@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: gitnexus-cli
|
||||
description: "Use when the user needs to run GitNexus CLI commands like analyze/index a repo, check status, clean the index, generate a wiki, or list indexed repos. Examples: \"Index this repo\", \"Reanalyze the codebase\", \"Generate a wiki\""
|
||||
---
|
||||
|
||||
# GitNexus CLI Commands
|
||||
|
||||
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 `bunx`, else `npx`), so no package-manager assumption and no global install is required — including on a bun-only machine, which has no npm, npx or pnpm at all.
|
||||
|
||||
> **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, or `bunx gitnexus@latest analyze` on a bun-only machine. 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 `bunx gitnexus@latest analyze`, or `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939).
|
||||
|
||||
## Commands
|
||||
|
||||
### analyze — Build or refresh the index
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
| Flag | Effect |
|
||||
| -------------- | ---------------------------------------------------------------- |
|
||||
| `--watch` | Keep a Git repository index current with serialized refreshes |
|
||||
| `--debounce <ms>` | Watch quiet period before refresh (default: 300 ms) |
|
||||
| `--force` | Force full re-index even if up to date |
|
||||
| `--embeddings` | Enable embedding generation for semantic search (off by default) |
|
||||
| `--drop-embeddings` | Drop existing embeddings on rebuild. By default, an `analyze` without `--embeddings` preserves them. |
|
||||
| `--pdg` | Build the program-dependence layers used by `explain` and `pdg_query` (taint, CDG, and REACHING_DEF). |
|
||||
| `--spring-actuator <path>` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. |
|
||||
| `--asyncapi-spec <path>` | Read opt-in AsyncAPI 3.x documents (directory or single file) and mint `Destination` nodes from their operations. 2.x is refused, not mapped. Unsupported with `--watch`. |
|
||||
|
||||
**When to run:** First time in a project, after major code changes, or when `gitnexus://repo/{name}/context` reports the index is stale. In Claude Code, a PostToolUse hook detects staleness after `git commit` and `git merge` and notifies the agent to run `analyze` — the hook does not run analyze itself, to avoid blocking the agent for up to 120s and risking KuzuDB corruption on timeout.
|
||||
|
||||
For Spring runtime enrichment, pass a JSON bundle, one endpoint JSON file, or a directory containing endpoint files. Route evidence is authoritative only when `runtimeConfirmed === true`; `runtimeSource` records provenance and may also accompany `handler-conflict`. Env/configprops values are never persisted.
|
||||
|
||||
## Index storage and retention
|
||||
|
||||
Default location is `<repo>/.gitnexus/`. Override with environment variables (also documented in README):
|
||||
|
||||
| Env | Effect |
|
||||
| --- | ------ |
|
||||
| `GITNEXUS_STORAGE_PATH` | One complete external index directory. Wins if both storage vars are set. |
|
||||
| `GITNEXUS_STORAGE_ROOT` | Absolute root; GitNexus creates an isolated `<repo-basename>-<12-hex>/` slot per repository. |
|
||||
| `GITNEXUS_CONTENT_RETENTION` | `full` (default) keeps file text; `symbol` keeps snippets; `none` keeps the graph only. |
|
||||
|
||||
`list_repos`, `gitnexus://repo/{name}/context`, and HTTP `GET /api/repos` / `GET /api/repo` expose `storagePath`, `contentRetention`, and `sourceAvailable`. HTTP `/api/file` and `/api/grep` return 410 unless retention is `full`. MCP `include_content` may still return symbol spans when retention is `symbol`.
|
||||
|
||||
Use `node .gitnexus/run.cjs analyze --watch` for a long-lived local Git repository. It performs an initial analysis, queues scanner-admitted file changes, and retries intact failed batches with bounded backoff. Watch refreshes update only the graph: they skip AGENTS.md / CLAUDE.md injection and standard skill installation, so run a one-shot `analyze` when those generated files need updating. Watch rejects one-shot or context-output flags including `--force`, embedding flags, `--skills`, `--default-branch`, `--skip-agents-md`, `--skip-skills`, `--no-stats`, `--self-commit`, `--index-only`, and `--skip-git`. It never pulls remotes. Scheduled remote clone/pull is a different command: `gitnexus auto-sync`. Bare `gitnexus watch` is reserved and does not start either job. Running MCP and `serve` processes periodically check for a published replacement and reopen it without a restart. MCP checks are throttled to once every five seconds, so a tool call before the next check can briefly use the previous index.
|
||||
|
||||
### status — Check index freshness
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
### clean — Delete the index
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
| Flag | Effect |
|
||||
| --------- | ------------------------------------------------- |
|
||||
| `--force` | Skip confirmation prompt |
|
||||
| `--all` | Clean all indexed repos, not just the current one |
|
||||
|
||||
### wiki — Generate documentation from the graph
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs wiki
|
||||
```
|
||||
|
||||
Generates repository documentation from the knowledge graph using an LLM. HTTP providers require an API key (saved to `~/.gitnexus/config.json` on first use). Local CLI providers (`--provider cursor|claude|codex|opencode|grok`) use your existing CLI login.
|
||||
|
||||
| Flag | Effect |
|
||||
| ------------------- | ----------------------------------------- |
|
||||
| `--force` | Force full regeneration, also required to re-generate an existing wiki in a different language |
|
||||
| `--provider <name>` | LLM provider: minimax, openai, openrouter, azure, custom, cursor, claude, codex, opencode, or grok (default: minimax). Local CLIs (`cursor`, `claude`, `codex`, `opencode`, `grok`) use your existing CLI login and skip `--api-key`. |
|
||||
| `--model <model>` | LLM model (default: MiniMax-M3) |
|
||||
| `--base-url <url>` | LLM API base URL |
|
||||
| `--api-key <key>` | LLM API key |
|
||||
| `--concurrency <n>` | Parallel LLM calls (default: 3) |
|
||||
| `--timeout <seconds>` | LLM request timeout in seconds (default: disabled) |
|
||||
| `--retries <n>` | Max LLM retry attempts per request (default: 3) |
|
||||
| `--lang <lang>` | Output language for generated documentation (e.g. english, chinese, spanish, japanese) |
|
||||
| `--gist` | Publish wiki as a public GitHub Gist |
|
||||
|
||||
### list — Show all indexed repos
|
||||
|
||||
```bash
|
||||
node .gitnexus/run.cjs list
|
||||
```
|
||||
|
||||
Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
|
||||
|
||||
## After Indexing
|
||||
|
||||
1. **Read `gitnexus://repo/{name}/context`** to verify the index loaded
|
||||
2. Use the other GitNexus skills (`exploring`, `debugging`, `impact-analysis`, `refactoring`) for your task
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **"Not inside a git repository"**: Run from a directory inside a git repo
|
||||
- **Index is stale after re-analyzing**: Wait for the next MCP tool call to reopen the published index; this normally takes no more than five seconds
|
||||
- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
name: gitnexus-debugging
|
||||
description: "Use when the user is debugging a bug, tracing an error, or asking why something fails. Examples: \"Why is X failing?\", \"Where does this error come from?\", \"Trace this bug\""
|
||||
---
|
||||
|
||||
# Debugging with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Why is this function failing?"
|
||||
- "Trace where this error comes from"
|
||||
- "Who calls this method?"
|
||||
- "This endpoint returns 500"
|
||||
- Investigating bugs, errors, or unexpected behavior
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
A root cause traced in the wrong repository is a wrong root cause.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask. This matters most for `cypher`, whose
|
||||
statement carries no in-band hint of which database it ran against.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
A stale index describes the code from before your bug, so refresh before
|
||||
trusting a trace, and state the repository and index freshness with the
|
||||
diagnosis.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo
|
||||
1. query({search_query: "<error or symptom>"}) → Find related execution flows
|
||||
2. context({name: "<suspect>"}) → See callers/callees/processes
|
||||
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
|
||||
4. cypher({statement: "MATCH path..."}) → Custom traces if needed
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] Understand the symptom (error message, unexpected behavior)
|
||||
- [ ] query for error text or related code
|
||||
- [ ] Identify the suspect function from returned processes
|
||||
- [ ] context to see callers and callees
|
||||
- [ ] Trace execution flow via process resource if applicable
|
||||
- [ ] cypher for custom call chain traces if needed
|
||||
- [ ] Read source files to confirm root cause
|
||||
- [ ] State the repository and index freshness with the diagnosis
|
||||
```
|
||||
|
||||
## Debugging Patterns
|
||||
|
||||
| Symptom | GitNexus Approach |
|
||||
| -------------------- | ---------------------------------------------------------- |
|
||||
| Error message | `query` for error text → `context` on throw sites |
|
||||
| Wrong return value | `context` on the function → trace callees for data flow |
|
||||
| Intermittent failure | `context` → look for external calls, async deps |
|
||||
| Performance issue | `context` → find symbols with many callers (hot paths) |
|
||||
| Recent regression | `detect_changes` to see what your changes affect — pass `worktree` for a linked worktree |
|
||||
| "How does A reach B?" | `trace` between the two symbols — shortest call chain in one call |
|
||||
|
||||
## Tools
|
||||
|
||||
**query** — find code related to error:
|
||||
|
||||
```
|
||||
query({search_query: "payment validation error", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, ErrorHandling
|
||||
→ Symbols: validatePayment, handlePaymentError, PaymentException
|
||||
```
|
||||
|
||||
**context** — full context for a suspect:
|
||||
|
||||
```
|
||||
context({name: "validatePayment", repo: "my-app"})
|
||||
→ Incoming calls: processCheckout, webhookHandler
|
||||
→ Outgoing calls: verifyCard, fetchRates (external API!)
|
||||
→ Processes: CheckoutFlow (step 3/7)
|
||||
```
|
||||
|
||||
**cypher** — custom call chain traces. Pass `repo` alongside the statement; the
|
||||
Cypher text itself names no repository, so the result is unattributable without
|
||||
it:
|
||||
|
||||
```cypher
|
||||
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
|
||||
RETURN [n IN nodes(path) | n.name] AS chain
|
||||
```
|
||||
|
||||
**trace** — shortest call chain between two symbols ("how does A reach B?"), one call instead of chaining `context` hops:
|
||||
|
||||
```
|
||||
trace({ from: "processCheckout", to: "fetchRates", repo: "my-app" })
|
||||
→ status: ok, hopCount: 3
|
||||
→ hops: processCheckout → validatePayment → verifyCard → fetchRates
|
||||
→ edges: CALLS (1.0), CALLS (0.95), CALLS (1.0)
|
||||
```
|
||||
|
||||
When no path exists, `trace` reports the furthest reachable node — exactly where the chain breaks (dynamic dispatch, reflection, or an external boundary).
|
||||
|
||||
## Example: "Payment endpoint returns 500 intermittently"
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — bind my-app explicitly on every call
|
||||
|
||||
1. query({search_query: "payment error handling", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, ErrorHandling
|
||||
→ Symbols: validatePayment, handlePaymentError
|
||||
|
||||
2. context({name: "validatePayment", repo: "my-app"})
|
||||
→ Outgoing calls: verifyCard, fetchRates (external API!)
|
||||
|
||||
3. READ gitnexus://repo/my-app/process/CheckoutFlow
|
||||
→ Step 3: validatePayment → calls fetchRates (external)
|
||||
|
||||
4. Root cause: fetchRates calls external API without proper timeout
|
||||
Repository: my-app Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
name: gitnexus-exploring
|
||||
description: "Use when the user asks how code works, wants to understand architecture, trace execution flows, or explore unfamiliar parts of the codebase. Examples: \"How does X work?\", \"What calls this function?\", \"Show me the auth flow\""
|
||||
---
|
||||
|
||||
# Exploring Codebases with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "How does authentication work?"
|
||||
- "What's the project structure?"
|
||||
- "Show me the main components"
|
||||
- "Where is the database logic?"
|
||||
- Understanding code you haven't seen before
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Step 1 discovers what is indexed; every call after it must say which of those
|
||||
it means. With one indexed repository, use the examples below as written. With
|
||||
more than one, pass `repo` on every call: an omitted `repo` normally errors,
|
||||
but under an MCP policy with a configured default it resolves to that default
|
||||
silently. If you cannot tell which repository is meant, stop and ask. Report
|
||||
the bound repository and index freshness alongside your explanation.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
1. list_repos {} or READ gitnexus://repos → Discover indexed repos
|
||||
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
|
||||
3. query({search_query: "<what you want to understand>"}) → Find related execution flows
|
||||
4. context({name: "<symbol>"}) → Deep dive on specific symbol
|
||||
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
|
||||
```
|
||||
|
||||
> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] READ gitnexus://repo/{name}/context
|
||||
- [ ] query for the concept you want to understand
|
||||
- [ ] Review returned processes (execution flows)
|
||||
- [ ] context on key symbols for callers/callees
|
||||
- [ ] READ process resource for full execution traces
|
||||
- [ ] Read source files for implementation details
|
||||
- [ ] State the repository and index freshness with the explanation
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | What you get |
|
||||
| --------------------------------------- | ------------------------------------------------------- |
|
||||
| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) |
|
||||
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) |
|
||||
| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) |
|
||||
| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) |
|
||||
|
||||
## Tools
|
||||
|
||||
**query** — find execution flows related to a concept:
|
||||
|
||||
```
|
||||
query({search_query: "payment processing", repo: "my-app"})
|
||||
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
|
||||
→ Symbols grouped by flow with file locations
|
||||
```
|
||||
|
||||
**context** — 360-degree view of a symbol:
|
||||
|
||||
```
|
||||
context({name: "validateUser", repo: "my-app"})
|
||||
→ Incoming calls: loginHandler, apiMiddleware
|
||||
→ Outgoing calls: checkToken, getUserById
|
||||
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
|
||||
```
|
||||
|
||||
`repo` is required once more than one repository is indexed, and may be omitted
|
||||
with a single one.
|
||||
|
||||
## Example: "How does payment processing work?"
|
||||
|
||||
```
|
||||
1. list_repos {} → total: 1 (my-app) — bind it
|
||||
READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
|
||||
2. query({search_query: "payment processing"})
|
||||
→ CheckoutFlow: processPayment → validateCard → chargeStripe
|
||||
→ RefundFlow: initiateRefund → calculateRefund → processRefund
|
||||
3. context({name: "processPayment"})
|
||||
→ Incoming: checkoutHandler, webhookHandler
|
||||
→ Outgoing: validateCard, chargeStripe, saveTransaction
|
||||
4. Read src/payments/processor.ts for implementation details
|
||||
5. Answer, noting: Repository my-app, index current
|
||||
```
|
||||
|
||||
Had step 1 returned two repositories, every call above would carry
|
||||
`repo: "my-app"`.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
name: gitnexus-guide
|
||||
description: "Use when the user asks about GitNexus itself — available tools, how to query the knowledge graph, MCP resources, graph schema, or workflow reference. Examples: \"What GitNexus tools are available?\", \"How do I use GitNexus?\""
|
||||
---
|
||||
|
||||
# GitNexus Guide
|
||||
|
||||
Quick reference for all GitNexus MCP tools, resources, and the knowledge graph schema.
|
||||
|
||||
## Always Start Here
|
||||
|
||||
For any task involving code understanding, debugging, impact analysis, or refactoring:
|
||||
|
||||
1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness
|
||||
2. **Match your task to a skill below** and **read that skill file**
|
||||
3. **Follow the skill's workflow and checklist**
|
||||
|
||||
> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first.
|
||||
|
||||
## Skills
|
||||
|
||||
| Task | Skill to read |
|
||||
| -------------------------------------------- | ------------------- |
|
||||
| Understand architecture / "How does X work?" | `gitnexus-exploring` |
|
||||
| Blast radius / "What breaks if I change X?" | `gitnexus-impact-analysis` |
|
||||
| Trace bugs / "Why is X failing?" | `gitnexus-debugging` |
|
||||
| Rename / extract / split / refactor | `gitnexus-refactoring` |
|
||||
| Tools, resources, schema reference | `gitnexus-guide` (this file) |
|
||||
| Index, status, clean, wiki CLI commands | `gitnexus-cli` |
|
||||
|
||||
## Tools Reference
|
||||
|
||||
| Tool | What it gives you |
|
||||
| ---------------- | ------------------------------------------------------------------------ |
|
||||
| `query` | Process-grouped code intelligence — execution flows related to a concept |
|
||||
| `context` | 360-degree symbol view — categorized refs, processes it participates in |
|
||||
| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence |
|
||||
| `trace` | Shortest path between two symbols — "how does A reach B?" in one call |
|
||||
| `detect_changes` | Git-diff impact — what do your current changes affect |
|
||||
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
|
||||
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
|
||||
| `explain` | Persisted taint findings — source→sink data flows (needs `analyze --pdg`) |
|
||||
| `pdg_query` | Control/data dependence — what gates X (CDG) / where Y flows (REACHING_DEF); needs `analyze --pdg` |
|
||||
| `check` | Check graph invariants such as circular imports |
|
||||
| `route_map` | API route map — which components/hooks fetch which endpoints, and the handler files that serve them |
|
||||
| `shape_check` | Response-shape drift — keys each route returns vs keys its consumers access (flags MISMATCH) |
|
||||
| `api_impact` | Pre-change report for an API route — consumers, middleware, shape mismatches, risk level |
|
||||
| `tool_map` | MCP/RPC tool definitions and the files that handle them |
|
||||
| `group_list` | List configured multi-repo groups, or one group's config |
|
||||
| `group_sync` | Rebuild a group's Contract Registry (cross-repo HTTP contract links); run after `group.yaml` changes or member re-index |
|
||||
| `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.
|
||||
|
||||
### Taint findings (`explain`)
|
||||
|
||||
`explain` returns taint findings recorded by `gitnexus analyze --pdg` — intra-procedural `TAINTED` edges plus cross-function `TAINT_PATH` hops where the interprocedural taint phase found a function-level source→sink chain. Each finding includes a sink category (command-injection, code-injection, path-traversal, sql-injection, xss), source/sink lines, and the ordered hop path with the variable carried on each hop.
|
||||
|
||||
- `explain {}` — enumerate all findings for the repo (bounded by `limit`, deterministic order)
|
||||
- `explain { target: "src/vuln.ts" }` — findings in a file (suffix path match accepted)
|
||||
- `explain { target: "runUserCommand" }` — findings in a function (resolved like `context`; ambiguous names return ranked candidates)
|
||||
|
||||
A repo indexed without `--pdg` returns a clear "no taint layer" note. Caveats: closure/callback, property/field, and implicit flows are not modeled, and interprocedural findings are function-level `TAINT_PATH` hops rather than statement-level path proof, so the absence of a finding is **not** proof of safety. `SANITIZES` (sanitizer-kill) edges are queryable via `cypher`.
|
||||
|
||||
### Control & data dependence (`pdg_query`)
|
||||
|
||||
`pdg_query` reads the control/data-dependence layers `gitnexus analyze --pdg` records (CDG + REACHING_DEF, basic-block granular) — the control/data analog of `explain`. It is **always anchored** (a `target` file path or symbol, resolved like `context`) and has two modes:
|
||||
|
||||
- `pdg_query { mode: "controls", target: "..." }` — CDG: "under what condition does X run?". Each edge is a controlling predicate block → dependent block with the branch sense (`'T'`/`'F'`) in `reason`; an edge into an early `return`/`throw` is flagged `guard: true` (guard-clause discovery — the sense depends on the predicate, so don't filter guards by a fixed label).
|
||||
- `pdg_query { mode: "flows", target: "...", variable?: "..." }` — REACHING_DEF def→use edges within the function; pass `variable` to trace one binding.
|
||||
|
||||
A repo indexed without `--pdg` returns a "no PDG layer" note (or "status unknown" when the layer can't be confirmed). Intra-procedural only — cross-function flow is taint's domain (`explain`). The raw CDG/REACHING_DEF edges are also queryable via `cypher`. See the `gitnexus-pdg-query` skill for the full query surface.
|
||||
|
||||
### Shortest path between two symbols (`trace`)
|
||||
|
||||
`trace` answers "how does A reach B?" in one call — the shortest directed path over `CALLS` (plus `HAS_METHOD`, so a class-rooted trace descends into its methods) instead of chaining 3–8 `context`/`impact` hops by hand.
|
||||
|
||||
- `trace { from: "validateUser", to: "executeQuery" }` — shortest path between two symbols.
|
||||
- Disambiguate common names with `from_uid`/`to_uid` (zero-ambiguity) or `from_file`/`to_file`; an ambiguous name returns ranked candidates.
|
||||
- `maxDepth` (default 10, max 30) bounds the search; `includeTests` (default false) lets the traversal pass through test-file symbols.
|
||||
|
||||
Returns ordered `hops` (each `{ name, filePath, startLine }`) and an aligned `edges[]` of `{ relType, confidence }`, so call hops and containment (`HAS_METHOD`) hops stay distinguishable. When no path exists it reports the **furthest** reachable node (where the chain breaks) and sets `truncated: true` if a traversal cap was hit first. Every result carries a `status`: `ok` / `no_path` / `ambiguous` / `not_found` / `error`.
|
||||
|
||||
Cross-repo (experimental): pass `repo: "@groupName"` to trace across a group's member repos — the path may cross **one** `ContractLink` boundary (reported as a `CONTRACT_LINK` hop with the bridged contract in `crossings[]`). Omit `to` entirely to follow `from`'s outgoing HTTP call to whatever provider endpoint it lands on. Groups are configured via `group_list` / `group_sync`.
|
||||
|
||||
## Resources Reference
|
||||
|
||||
Lightweight reads (~100-500 tokens) for navigation:
|
||||
|
||||
| Resource | Content |
|
||||
| ---------------------------------------------- | ----------------------------------------- |
|
||||
| `gitnexus://repo/{name}/context` | Stats, staleness check |
|
||||
| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores |
|
||||
| `gitnexus://repo/{name}/cluster/{clusterName}` | Area members |
|
||||
| `gitnexus://repo/{name}/processes` | All execution flows |
|
||||
| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace |
|
||||
| `gitnexus://repo/{name}/schema` | Graph schema for Cypher |
|
||||
|
||||
## Graph Schema
|
||||
|
||||
**Nodes:** File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, Route, Tool, plus language-specific types (Struct, Enum, Trait, Impl, Namespace, Module, …) and BasicBlock (`--pdg` indexes only). The full node list lives in `gitnexus://repo/{name}/schema`.
|
||||
**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, CONTAINS, MEMBER_OF, HAS_METHOD, HAS_PROPERTY, ACCESSES, METHOD_OVERRIDES, METHOD_IMPLEMENTS, STEP_IN_PROCESS, HANDLES_ROUTE, FETCHES, HANDLES_TOOL, ENTRY_POINT_OF, WRAPS, QUERIES, INJECTS, plus `--pdg`-only types (CFG, REACHING_DEF, TAINTED, SANITIZES, TAINT_PATH, CDG — zero rows on a default index).
|
||||
|
||||
Read `gitnexus://repo/{name}/schema` before writing Cypher — it is the authoritative schema for the indexed repo.
|
||||
|
||||
```cypher
|
||||
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"})
|
||||
RETURN caller.name, caller.filePath
|
||||
```
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
name: gitnexus-impact-analysis
|
||||
description: "Use when the user wants to know what will break if they change something, or needs safety analysis before editing code. Examples: \"Is it safe to change X?\", \"What depends on this?\", \"What will break?\""
|
||||
---
|
||||
|
||||
# Impact Analysis with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Is it safe to change this function?"
|
||||
- "What will break if I modify X?"
|
||||
- "Show me the blast radius"
|
||||
- "Who uses this code?"
|
||||
- Before making non-trivial code changes
|
||||
- Before committing — to understand what your changes affect
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Impact analysis is the gate that authorizes an edit, so it must answer for the
|
||||
repository you are about to edit.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask — every result below an ambiguous
|
||||
identity inherits the ambiguity. `list_repos` is paginated, so page with
|
||||
`offset: pagination.nextOffset` until `hasMore` is false before concluding a
|
||||
repository is absent.
|
||||
|
||||
`detect_changes` takes `worktree` when your changes are in a linked worktree
|
||||
the MCP server was not launched from. The server auto-detects a worktree only
|
||||
when it was launched from inside one; otherwise `git diff` runs in the wrong
|
||||
checkout and reports zero changed symbols — a false clean check that carries
|
||||
none of the degradation flags described below. In the CLI fallbacks, `--repo .`
|
||||
means the current checkout; pass the intended repository path instead when you
|
||||
are not standing in it.
|
||||
|
||||
State the bound identity with your risk report:
|
||||
|
||||
```
|
||||
Repository: <name> (<path>) Worktree: <path> Index: <commit>, <n> behind HEAD
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo (and worktree)
|
||||
1. impact({target: "X", direction: "upstream"}) or `node .gitnexus/run.cjs impact "X" --direction upstream --repo .`
|
||||
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
|
||||
3. detect_changes({scope: "all"}) or `node .gitnexus/run.cjs detect-changes --scope all --repo .`
|
||||
4. Assess risk and report to user, echoing repo/worktree/index identity
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
> If `.gitnexus/run.cjs` is missing, replace `node .gitnexus/run.cjs` with `npx gitnexus` in the fallback commands.
|
||||
|
||||
## Checklist
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] impact({target, direction: "upstream"}) or CLI fallback to find dependents
|
||||
- [ ] Review d=1 items first (these WILL BREAK)
|
||||
- [ ] Check high-confidence (>0.8) dependencies
|
||||
- [ ] READ processes to check affected execution flows
|
||||
- [ ] detect_changes({scope: "all"}) or CLI fallback for pre-commit check
|
||||
- [ ] Confirm the checkout you edited is the checkout that was diffed
|
||||
- [ ] Assess risk level and report, stating repo/worktree/index identity
|
||||
```
|
||||
|
||||
## Understanding Output
|
||||
|
||||
| Depth | Risk Level | Meaning |
|
||||
| ----- | ---------------- | ------------------------ |
|
||||
| d=1 | **WILL BREAK** | Direct callers/importers |
|
||||
| d=2 | LIKELY AFFECTED | Indirect dependencies |
|
||||
| d=3 | MAY NEED TESTING | Transitive effects |
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Affected | Risk |
|
||||
| ------------------------------ | -------- |
|
||||
| <5 symbols, few processes | LOW |
|
||||
| 5-15 symbols, 2-5 processes | MEDIUM |
|
||||
| >15 symbols or many processes | HIGH |
|
||||
| Critical path (auth, payments) | CRITICAL |
|
||||
| **Zero callers found** | **UNKNOWN** |
|
||||
|
||||
`UNKNOWN` is not a low rung on this scale — it means the walk could not answer.
|
||||
An empty caller set is equally consistent with "genuinely unused" and "the
|
||||
callers are not resolvable by the index" (plain-object property access, dynamic
|
||||
dispatch, cross-language calls), so few-callers ⇒ LOW does **not** apply. The
|
||||
result carries a `riskNote` saying so. Confirm with a text search before
|
||||
treating the symbol as safe to change or delete.
|
||||
|
||||
`risk` is the edit gate: warn on HIGH/CRITICAL and stop on UNKNOWN until the
|
||||
uncertainty is resolved. Within single-repo mode, compare File and symbol
|
||||
targets with local `riskSharedAxes` (direct/total only). Within group mode,
|
||||
compare only group results: their `riskSharedAxes` overlays resolved
|
||||
cross-repo crossings on that local value. Never use either field to waive the
|
||||
edit gate. Check `riskScale.unusedAxes` before comparing kinds: MCP File walks
|
||||
omit process/module axes, while web Graph-RAG expands File targets to in-file
|
||||
symbols before enrichment.
|
||||
|
||||
## Tools
|
||||
|
||||
**impact** — the primary tool for symbol blast radius. If MCP is unavailable, use `node .gitnexus/run.cjs impact <symbol> --direction upstream --repo .` instead:
|
||||
|
||||
```
|
||||
impact({
|
||||
target: "validateUser",
|
||||
repo: "my-app", // required once >1 repository is indexed
|
||||
direction: "upstream",
|
||||
minConfidence: 0.8,
|
||||
maxDepth: 3
|
||||
})
|
||||
|
||||
→ d=1 (WILL BREAK):
|
||||
- loginHandler (src/auth/login.ts:42) [CALLS, 100%]
|
||||
- apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%]
|
||||
|
||||
→ d=2 (LIKELY AFFECTED):
|
||||
- authRouter (src/routes/auth.ts:22) [CALLS, 95%]
|
||||
```
|
||||
|
||||
**detect_changes** — git-diff based impact analysis. If MCP is unavailable, use `node .gitnexus/run.cjs detect-changes --scope all --repo .` instead:
|
||||
|
||||
```
|
||||
detect_changes({scope: "all"})
|
||||
|
||||
→ Changed: 5 symbols in 3 files
|
||||
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
|
||||
→ Risk: MEDIUM
|
||||
```
|
||||
|
||||
Add `repo` once more than one repository is indexed, and `worktree: "<abs
|
||||
path>"` when your changes are in a linked worktree the server was not launched
|
||||
from.
|
||||
|
||||
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
|
||||
listing was capped) means the result is short of the truth, and reads like
|
||||
`UNKNOWN` above: a zero there means unseen, not unaffected. Re-run it rather
|
||||
than tick the pre-commit check.
|
||||
|
||||
A wrong-worktree zero carries neither flag and is shape-identical to a genuine
|
||||
clean result, so confirm the checkout you edited is the one that was diffed
|
||||
before treating an empty change set as a passed check.
|
||||
|
||||
## Example: "What breaks if I change validateUser?"
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
|
||||
|
||||
1. impact({target: "validateUser", repo: "my-app", direction: "upstream"}) or `node .gitnexus/run.cjs impact "validateUser" --direction upstream --repo .`
|
||||
→ d=1: loginHandler, apiMiddleware (WILL BREAK)
|
||||
→ d=2: authRouter, sessionManager (LIKELY AFFECTED)
|
||||
|
||||
2. READ gitnexus://repo/my-app/processes
|
||||
→ LoginFlow and TokenRefresh touch validateUser
|
||||
|
||||
3. Risk: 2 direct callers, 2 processes = MEDIUM
|
||||
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
name: gitnexus-refactoring
|
||||
description: "Use when the user wants to rename, extract, split, move, or restructure code safely. Examples: \"Rename this function\", \"Extract this into a module\", \"Refactor this class\", \"Move this to a separate file\""
|
||||
---
|
||||
|
||||
# Refactoring with GitNexus
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Rename this function safely"
|
||||
- "Extract this into a module"
|
||||
- "Split this service"
|
||||
- "Move this to a new file"
|
||||
- Any task involving renaming, extracting, splitting, or restructuring code
|
||||
|
||||
## Bind the repository first
|
||||
|
||||
Refactoring writes to disk. `rename` with `dry_run: false` edits files in
|
||||
whichever repository was resolved, so binding identity here is a safety gate,
|
||||
not bookkeeping.
|
||||
|
||||
Call `list_repos {}` before the first tool call. With one indexed repository,
|
||||
use the examples below as written. With more than one, pass `repo` on every
|
||||
call: an omitted `repo` normally errors, but under an MCP policy with a
|
||||
configured default it resolves to that default silently. If you cannot tell
|
||||
which repository is meant, stop and ask. Never run `rename` with
|
||||
`dry_run: false` until the preview in the same bound repository has been
|
||||
reviewed — its returned `file_path` values show which checkout is about to be
|
||||
written, so read them as a confirmation of identity.
|
||||
|
||||
`list_repos` is paginated, so page with `offset: pagination.nextOffset` until
|
||||
`hasMore` is false before concluding a repository is absent.
|
||||
|
||||
`detect_changes` takes `worktree` when you are editing a linked worktree the
|
||||
MCP server was not launched from; otherwise `git diff` runs in the wrong
|
||||
checkout and reports nothing changed, which reads as a verified refactor.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
0. list_repos {} → Bind repo (and worktree)
|
||||
1. impact({target: "X", direction: "upstream"}) → Map all dependents
|
||||
2. query({search_query: "X"}) → Find execution flows involving X
|
||||
3. context({name: "X"}) → See all incoming/outgoing refs
|
||||
4. Plan update order: interfaces → implementations → callers → tests
|
||||
```
|
||||
|
||||
> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal.
|
||||
|
||||
## Checklists
|
||||
|
||||
### Rename Symbol
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
|
||||
- [ ] Confirm the previewed file paths are in the bound repository/worktree
|
||||
- [ ] Review graph edits (high confidence) and text_search edits (review carefully)
|
||||
- [ ] If satisfied: rename({..., dry_run: false}) — apply edits
|
||||
- [ ] detect_changes() — verify only expected files changed
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
### Extract Module
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] context({name: target}) — see all incoming/outgoing refs
|
||||
- [ ] impact({target, direction: "upstream"}) — find all external callers
|
||||
- [ ] Define new module interface
|
||||
- [ ] Extract code, update imports
|
||||
- [ ] detect_changes() — verify affected scope
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
### Split Function/Service
|
||||
|
||||
```
|
||||
- [ ] list_repos {} — bind repo; explicit repo when >1 indexed, ask if ambiguous
|
||||
- [ ] context({name: target}) — understand all callees
|
||||
- [ ] Group callees by responsibility
|
||||
- [ ] impact({target, direction: "upstream"}) — map callers to update
|
||||
- [ ] Create new functions/services
|
||||
- [ ] Update callers
|
||||
- [ ] detect_changes() — verify affected scope
|
||||
- [ ] Run tests for affected processes
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
**rename** — automated multi-file rename:
|
||||
|
||||
```
|
||||
rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
|
||||
→ 12 edits across 8 files
|
||||
→ 10 graph edits (high confidence), 2 text_search edits (review)
|
||||
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
|
||||
```
|
||||
|
||||
**impact** — map all dependents first:
|
||||
|
||||
```
|
||||
impact({target: "validateUser", repo: "my-app", direction: "upstream"})
|
||||
→ d=1: loginHandler, apiMiddleware, testUtils
|
||||
→ Affected Processes: LoginFlow, TokenRefresh
|
||||
```
|
||||
|
||||
**detect_changes** — verify your changes after refactoring:
|
||||
|
||||
```
|
||||
detect_changes({scope: "all"})
|
||||
→ Changed: 8 files, 12 symbols
|
||||
→ Affected processes: LoginFlow, TokenRefresh
|
||||
→ Risk: MEDIUM
|
||||
```
|
||||
|
||||
`partial: true` (a graph query failed) or `truncated: true` (the changed-symbol
|
||||
listing was capped) means the result is short of the truth: a short or empty
|
||||
list is not proof that only the expected files changed. Re-run it rather than
|
||||
treat the refactor as verified.
|
||||
|
||||
A wrong-worktree zero carries neither flag and is indistinguishable from a
|
||||
clean verification, so confirm the diffed checkout is the one you edited.
|
||||
|
||||
**cypher** — custom reference queries:
|
||||
|
||||
```cypher
|
||||
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"})
|
||||
RETURN caller.name, caller.filePath ORDER BY caller.filePath
|
||||
```
|
||||
|
||||
## Risk Rules
|
||||
|
||||
| Risk Factor | Mitigation |
|
||||
| ------------------- | ----------------------------------------- |
|
||||
| Many callers (>5) | Use rename for automated updates |
|
||||
| Cross-area refs | Use detect_changes after to verify scope |
|
||||
| String/dynamic refs | query to find them |
|
||||
| External/public API | Version and deprecate properly |
|
||||
| Same name in another indexed repo | Bind `repo`; verify previewed paths before applying |
|
||||
|
||||
## Example: Rename `validateUser` to `authenticateUser`
|
||||
|
||||
```
|
||||
0. list_repos {}
|
||||
→ total: 2 (my-app, billing-api) — both define validateUser, so bind explicitly
|
||||
|
||||
1. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: true})
|
||||
→ 12 edits: 10 graph (safe), 2 text_search (review)
|
||||
→ Files: validator.ts, login.ts, middleware.ts, config.json...
|
||||
|
||||
2. Review text_search edits (config.json: dynamic reference!)
|
||||
|
||||
3. rename({symbol_name: "validateUser", new_name: "authenticateUser", repo: "my-app", dry_run: false})
|
||||
→ Applied 12 edits across 8 files
|
||||
|
||||
4. detect_changes({scope: "all", repo: "my-app"})
|
||||
→ Affected: LoginFlow, TokenRefresh
|
||||
→ Risk: MEDIUM — run tests for these flows
|
||||
Repository: my-app (/abs/path/my-app) Worktree: same Index: current
|
||||
```
|
||||
|
||||
With a single indexed repository, step 0 returns `total: 1` and the `repo`
|
||||
argument drops out of every call above.
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
run: node .gitea/scripts/rollback-nacos.mjs
|
||||
- name: 执行 SIT 应用回退
|
||||
shell: pwsh
|
||||
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art
|
||||
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.salon.yunail.art
|
||||
- name: 记录回退后的成功版本
|
||||
shell: bash
|
||||
run: node .gitea/scripts/record-rollback.mjs
|
||||
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
- name: 校验 PROD Nacos 发布记录
|
||||
shell: bash
|
||||
run: node .gitea/scripts/assert-nacos-release.mjs
|
||||
- name: 构建并固化 PROD 发布包
|
||||
- name: 构建并校验含 Flyway 迁移的 PROD 发布包
|
||||
shell: pwsh
|
||||
env:
|
||||
VITE_API_BASE_URL: https://salon.yunail.art/api
|
||||
|
||||
@@ -45,11 +45,11 @@ jobs:
|
||||
- name: 校验 SIT Nacos 发布记录
|
||||
shell: bash
|
||||
run: node .gitea/scripts/assert-nacos-release.mjs
|
||||
- name: 构建 SIT 发布包
|
||||
- name: 构建并校验含 Flyway 迁移的 SIT 发布包
|
||||
shell: pwsh
|
||||
env:
|
||||
VITE_API_BASE_URL: https://sit.yunail.art/api
|
||||
VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api
|
||||
VITE_API_BASE_URL: https://sit.salon.yunail.art/api
|
||||
VITE_ADMIN_API_BASE_URL: https://sit.salon.yunail.art/admin/api
|
||||
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
|
||||
- name: 持久化已校验发布包
|
||||
shell: bash
|
||||
@@ -69,7 +69,7 @@ jobs:
|
||||
printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json"
|
||||
- name: 执行 SIT 部署
|
||||
shell: pwsh
|
||||
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art
|
||||
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.salon.yunail.art
|
||||
- name: 记录成功部署
|
||||
shell: bash
|
||||
run: node .gitea/scripts/record-deploy.mjs
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
|
||||
|
||||
> 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).
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
|
||||
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
|
||||
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
|
||||
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
|
||||
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
|
||||
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
|
||||
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
|
||||
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
|
||||
- NEVER commit changes without running `detect_changes()` to check affected scope.
|
||||
- NEVER commit before MCP/CLI graph change analysis.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| --- | --- |
|
||||
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
|
||||
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
|
||||
@@ -32,21 +33,26 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat
|
||||
## 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` |
|
||||
| --- | --- |
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
|
||||
## Project Workflow Rules
|
||||
|
||||
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
|
||||
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
|
||||
- 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。
|
||||
- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。
|
||||
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
|
||||
- Salon Core 的数据库变更必须放在 `JC-Salon-Core/src/main/resources/db/migration/` 下,使用递增的 Flyway 版本文件(如 `V2__功能说明_20261024.sql`);已在任一环境成功执行的迁移文件不得修改或删除。
|
||||
- DEV、SIT、PROD 的数据库迁移由 Core 启动时的 Flyway 自动执行,Gitea 工作流不得直接连接数据库或绕过 Flyway 执行 SQL;合并到 SIT 前必须先在 DEV 验证迁移。
|
||||
- 应用回退不会自动回滚数据库;需要撤销或修正时,必须新增向前兼容的补偿迁移,禁止依赖 Flyway `clean`、自动 baseline 或重新执行初始化 SQL。
|
||||
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
|
||||
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。
|
||||
- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `docs/scripts/运行与发布配置总说明.md`,并在任务记录中写明新增或调整的版本化文件。
|
||||
|
||||
@@ -1,29 +1,30 @@
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **JayuCloud** (36096 symbols, 76216 relationships, 1267 execution flows).
|
||||
|
||||
> 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).
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze --index-only` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? Bootstrap with `npx`, `bunx`, or `pnpm dlx` — e.g. `bunx gitnexus@latest analyze` (npm 11 npx crash; #1939).
|
||||
|
||||
## Always Do
|
||||
|
||||
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
|
||||
- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`.
|
||||
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
|
||||
- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
|
||||
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
|
||||
- **MUST run impact before editing.** Use `impact({target: "symbolName", direction: "upstream"})` or `node .gitnexus/run.cjs impact "symbolName" --direction upstream --repo .`; report callers, processes, and risk. Never substitute grep for graph analysis.
|
||||
- **MUST analyze graph changes before committing.** Use `detect_changes({scope: "all"})` (MCP) or `node .gitnexus/run.cjs detect-changes --scope all --repo .` (CLI fallback). `partial: true` or `truncated: true` is not a clean check — a zero means unseen, not unaffected; re-run it. For regression review: `detect_changes({scope: "compare", base_ref: "prod"})` or `node .gitnexus/run.cjs detect-changes --scope compare --base-ref "prod" --repo .`.
|
||||
- MUST warn on HIGH/CRITICAL `risk` pre-edit; never use `riskSharedAxes` to waive a HIGH/CRITICAL `risk` warning. Compare File/symbol: MCP File omits axes; Graph-RAG expands File.
|
||||
- **MUST treat `risk: UNKNOWN` as unresolved, not as low.** An empty caller set is not evidence the symbol is unused — it can also mean the callers are not resolvable by the index (plain-object property access, dynamic dispatch, cross-language calls). `impact` pairs `UNKNOWN` with a `riskNote` saying so. Confirm with a text search before treating the symbol as safe to change or delete; do not proceed on the strength of a zero.
|
||||
- **MUST use `query({search_query: "concept"})` for concepts/flows, `context({name: "symbolName"})` for a named symbol, or `impact` for blast radius, on read-only callers, dependencies, imports, or execution flow.** Graph first; text search only for empty/`UNKNOWN`/literals.
|
||||
- For security review, `explain({target: "fileOrSymbol"})` lists taint findings (source→sink flows; needs `analyze --pdg`).
|
||||
|
||||
## Never Do
|
||||
|
||||
- NEVER edit a function, class, or method without first running `impact` on it.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
|
||||
- NEVER edit a function, class, or method before MCP/CLI impact analysis.
|
||||
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis, and never read `UNKNOWN` as an all-clear — it means the walk could not answer, which is the one verdict that requires confirming by other means.
|
||||
- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph.
|
||||
- NEVER commit changes without running `detect_changes()` to check affected scope.
|
||||
- NEVER commit before MCP/CLI graph change analysis.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Use for |
|
||||
|----------|---------|
|
||||
| --- | --- |
|
||||
| `gitnexus://repo/JayuCloud/context` | Codebase overview, check index freshness |
|
||||
| `gitnexus://repo/JayuCloud/clusters` | All functional areas |
|
||||
| `gitnexus://repo/JayuCloud/processes` | All execution flows |
|
||||
@@ -32,12 +33,17 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat
|
||||
## 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` |
|
||||
| --- | --- |
|
||||
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus-exploring/SKILL.md` |
|
||||
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus-impact-analysis/SKILL.md` |
|
||||
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus-debugging/SKILL.md` |
|
||||
| Rename / extract / split / refactor | `.claude/skills/gitnexus-refactoring/SKILL.md` |
|
||||
| Tools, resources, schema reference | `.claude/skills/gitnexus-guide/SKILL.md` |
|
||||
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus-cli/SKILL.md` |
|
||||
|
||||
<!-- gitnexus:end -->
|
||||
|
||||
## Project Workflow Rules
|
||||
|
||||
- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。
|
||||
- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。
|
||||
|
||||
@@ -57,7 +57,7 @@ export default defineConfig(({ mode }) => {
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
'2666.online',
|
||||
'wcy111.top'
|
||||
'wcsrv.top'
|
||||
]
|
||||
},
|
||||
build: {
|
||||
|
||||
@@ -110,6 +110,15 @@
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- Spring Boot manages the Flyway version; migrations run against the Nacos-configured datasource. -->
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-mysql</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
|
||||
+9
@@ -79,6 +79,15 @@ public class PermissionAspect {
|
||||
return Result.error(404, "用户不存在");
|
||||
}
|
||||
|
||||
// Salon 后台只有平台管理员,登录后台后的数据范围统一为全平台。
|
||||
// 权限表继续保留给小程序和兼容接口使用,但不再阻断管理员后台请求。
|
||||
String requestPath = request.getRequestURI();
|
||||
boolean adminPath = requestPath != null
|
||||
&& (requestPath.startsWith("/admin/") || requestPath.startsWith("/order/admin/"));
|
||||
if (adminPath && Integer.valueOf(4).equals(userDO.getType())) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
String permissionCode = requirePermission.value();
|
||||
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
|
||||
if (Integer.valueOf(4).equals(userDO.getType())
|
||||
|
||||
+5
-23
@@ -117,10 +117,13 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
}
|
||||
|
||||
boolean adminPath = isAdminPath(path);
|
||||
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
|
||||
if (adminPath && !Integer.valueOf(4).equals(currentUser.getType())) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "仅平台管理员可以访问后台管理系统");
|
||||
return false;
|
||||
}
|
||||
if (adminPath && Integer.valueOf(4).equals(currentUser.getType())) {
|
||||
currentShopId = null;
|
||||
}
|
||||
|
||||
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
|
||||
userId,
|
||||
@@ -139,14 +142,6 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (adminPath
|
||||
&& !Integer.valueOf(4).equals(currentUser.getType())
|
||||
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
|
||||
&& !isExpiredAdminAllowedPath(path)) {
|
||||
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (requiresSignature(request)) {
|
||||
try {
|
||||
requestSignatureService.validateRequest(request, token, userId);
|
||||
@@ -205,19 +200,6 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private boolean isExpiredAdminAllowedPath(String path) {
|
||||
return path.startsWith("/admin/auth/")
|
||||
|| path.equals("/admin/user/info")
|
||||
|| path.equals("/permission/list/user/current")
|
||||
|| path.equals("/api/permission/list/user/current")
|
||||
|| path.startsWith("/admin/planning/")
|
||||
|| path.startsWith("/admin/shops/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
|
||||
+10
-1
@@ -4,6 +4,8 @@ import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
/**
|
||||
* JWT 配置。
|
||||
*/
|
||||
@@ -15,7 +17,7 @@ public class JwtProperties {
|
||||
/**
|
||||
* HS512 密钥,生产环境请通过 Nacos 覆盖。
|
||||
*/
|
||||
private String secret = "jayucloud-salon-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
|
||||
private String secret;
|
||||
|
||||
/**
|
||||
* Token 发行者。
|
||||
@@ -41,4 +43,11 @@ public class JwtProperties {
|
||||
* 时钟偏移容忍,单位秒。
|
||||
*/
|
||||
private long clockSkewSeconds = 30;
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
if (secret == null || secret.trim().length() < 64) {
|
||||
throw new IllegalStateException("jayucloud-salon.security.jwt.secret 未配置或长度不足 64 位");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -21,6 +21,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
@Configuration
|
||||
@MapperScan({
|
||||
"com.xiaowang.jayucloud.salon.core.modules.artist.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.analytics.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.auth.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.content.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.file.mapper",
|
||||
@@ -32,6 +33,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
"com.xiaowang.jayucloud.salon.core.modules.payment.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.planning.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.product.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.privacy.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.registration.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.security.mapper",
|
||||
"com.xiaowang.jayucloud.salon.core.modules.shop.mapper",
|
||||
|
||||
+32
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
log.info("start insert fill ....");
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
fillPhoneIndexes(metaObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -37,5 +39,35 @@ public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
log.info("start update fill ....");
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
fillPhoneIndexes(metaObject);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populate searchable HMAC indexes for encrypted phone fields while keeping
|
||||
* this class as the single MyBatis-Plus MetaObjectHandler bean.
|
||||
*/
|
||||
private void fillPhoneIndexes(MetaObject metaObject) {
|
||||
setAccountIndex(metaObject);
|
||||
setIndex(metaObject, "phone", "phoneHash");
|
||||
setIndex(metaObject, "contactPhone", "contactPhoneHash");
|
||||
setIndex(metaObject, "customerPhoneSnapshot", "customerPhoneSnapshotHash");
|
||||
}
|
||||
|
||||
private void setAccountIndex(MetaObject metaObject) {
|
||||
if (!metaObject.hasGetter("account") || !metaObject.hasSetter("accountHash")) {
|
||||
return;
|
||||
}
|
||||
Object value = metaObject.getValue("account");
|
||||
String account = value == null ? null : String.valueOf(value);
|
||||
metaObject.setValue("accountHash", account == null ? null : PhoneCrypto.current().index(account));
|
||||
}
|
||||
|
||||
private void setIndex(MetaObject metaObject, String source, String target) {
|
||||
if (!metaObject.hasGetter(source) || !metaObject.hasSetter(target)) {
|
||||
return;
|
||||
}
|
||||
Object value = metaObject.getValue(source);
|
||||
String hash = value == null ? null : PhoneCrypto.current().index(String.valueOf(value));
|
||||
metaObject.setValue(target, hash);
|
||||
}
|
||||
}
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jayucloud-salon.privacy.phone-crypto")
|
||||
public class PhoneCryptoProperties {
|
||||
private String encryptionKey;
|
||||
private String indexKey;
|
||||
private boolean backfillEnabled;
|
||||
private int backfillPageSize = 500;
|
||||
}
|
||||
+1
-1
@@ -49,6 +49,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
"/user/wechat-mini/confirm-login",
|
||||
"/user/wechat-mini/status",
|
||||
"/user/wechat-mini/quick-login",
|
||||
"/integration/wechat/content-moderation/callback",
|
||||
"/user/workbench/register/**",
|
||||
"/user/workbench/shops/available",
|
||||
"/user/reset-password-by-phone",
|
||||
@@ -72,7 +73,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/login-shops/**",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
|
||||
+13
@@ -37,4 +37,17 @@ public class WechatMiniProperties {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Integer accessTokenBufferSeconds = 60;
|
||||
|
||||
/** 订阅消息发送开关。 */
|
||||
private Boolean subscribeMessageEnabled = true;
|
||||
/** DEV 使用 mock,SIT/PROD 使用 wechat。 */
|
||||
private String subscribeMessageProvider = "mock";
|
||||
/** 服务开始提醒提前分钟数。 */
|
||||
private Integer serviceStartReminderLeadMinutes = 30;
|
||||
/** 订阅消息点击后的默认页面。 */
|
||||
private String subscribeMessagePage = "/pages/planning/index";
|
||||
/** 微信小程序消息跳转环境。 */
|
||||
private String subscribeMessageMiniprogramState = "developer";
|
||||
/** 发送失败后的最大重试次数。 */
|
||||
private Integer subscribeMessageMaxRetries = 3;
|
||||
}
|
||||
|
||||
+164
@@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.analytics.service.OperationsAnalyticsService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
@@ -25,16 +26,35 @@ import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.DashboardStatsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.vo.HotProductVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.OperationsAnalyticsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.RecentActivityVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.analytics.vo.SalonDashboardOverviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.analytics.mapper.SalonDashboardMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.AfterSaleDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistChangeRequestDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.AfterSaleMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistChangeRequestMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.entity.AppointmentReservationDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.inventory.entity.InventoryItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.inventory.mapper.InventoryItemMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -44,6 +64,7 @@ import java.util.stream.Collectors;
|
||||
@RestController
|
||||
@RequestMapping("/admin/dashboard")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
/**
|
||||
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
|
||||
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
|
||||
@@ -90,6 +111,149 @@ public class DashboardController {
|
||||
*/
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
private final OperationsAnalyticsService operationsAnalyticsService;
|
||||
private final WorkbenchRegistrationApplicationMapper registrationMapper;
|
||||
private final ContentModerationRecordMapper contentModerationRecordMapper;
|
||||
private final AfterSaleMapper afterSaleMapper;
|
||||
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||
private final AppointmentReservationMapper appointmentReservationMapper;
|
||||
private final InventoryItemMapper inventoryItemMapper;
|
||||
private final SalonDashboardMapper salonDashboardMapper;
|
||||
|
||||
/**
|
||||
* Salon 平台管理员专用驾驶舱。旧 stats/analytics 接口保留兼容,但首页只使用本接口。
|
||||
*/
|
||||
@GetMapping("/overview")
|
||||
public Result<SalonDashboardOverviewVO> getOverview(
|
||||
@RequestParam(required = false) String date,
|
||||
@RequestParam(required = false, defaultValue = "7") Integer days) {
|
||||
LocalDate targetDate = parseOverviewDate(date);
|
||||
int rangeDays = days != null && days == 30 ? 30 : 7;
|
||||
try {
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
|
||||
String cacheKey = "cache:salon-dashboard:overview:" + targetDate + ":" + rangeDays;
|
||||
return Result.success(multiLevelCacheService.getOrLoad(
|
||||
cacheKey,
|
||||
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<SalonDashboardOverviewVO>() { },
|
||||
() -> buildSalonOverview(targetDate, rangeDays)
|
||||
));
|
||||
} catch (Exception exception) {
|
||||
log.warn("Salon 驾驶舱统计失败,返回空数据: date={}, days={}", targetDate, rangeDays, exception);
|
||||
SalonDashboardOverviewVO empty = emptySalonOverview(targetDate, rangeDays);
|
||||
empty.setDegraded(true);
|
||||
empty.setDegradedMessage("部分经营数据暂时不可用,刷新后重试");
|
||||
return Result.success(empty);
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate parseOverviewDate(String value) {
|
||||
if (value == null || value.isBlank()) return LocalDate.now();
|
||||
try {
|
||||
return LocalDate.parse(value);
|
||||
} catch (DateTimeParseException exception) {
|
||||
return LocalDate.now();
|
||||
}
|
||||
}
|
||||
|
||||
private SalonDashboardOverviewVO emptySalonOverview(LocalDate date, int days) {
|
||||
SalonDashboardOverviewVO overview = new SalonDashboardOverviewVO();
|
||||
overview.setDate(date.toString());
|
||||
for (int index = days - 1; index >= 0; index--) {
|
||||
SalonDashboardOverviewVO.TrendItem item = new SalonDashboardOverviewVO.TrendItem();
|
||||
item.setDate(date.minusDays(index).toString());
|
||||
overview.getTrend().add(item);
|
||||
}
|
||||
return overview;
|
||||
}
|
||||
|
||||
private SalonDashboardOverviewVO buildSalonOverview(LocalDate date, int days) {
|
||||
SalonDashboardOverviewVO overview = emptySalonOverview(date, days);
|
||||
SalonDashboardOverviewVO.Platform platform = overview.getPlatform();
|
||||
platform.setActiveShopCount(shopMapper.selectCount(new LambdaQueryWrapper<ShopDO>()
|
||||
.eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0)));
|
||||
platform.setActiveManagerCount(countUsersByType(2));
|
||||
platform.setActiveStaffCount(countUsersByType(3));
|
||||
platform.setCustomerCount(countUsersByType(0));
|
||||
platform.setStyleCount(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>()
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.eq(ProductDO::getFrontVisible, 1)
|
||||
.eq(ProductDO::getModerationStatus, "APPROVED")));
|
||||
|
||||
LocalDate rangeStart = date.minusDays(days - 1);
|
||||
List<Map<String, Object>> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date);
|
||||
Map<String, SalonDashboardOverviewVO.TrendItem> trendByDate = overview.getTrend().stream()
|
||||
.collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new));
|
||||
for (Map<String, Object> row : trendRows) {
|
||||
String rowDate = stringValue(row, "date");
|
||||
SalonDashboardOverviewVO.TrendItem item = trendByDate.get(rowDate);
|
||||
if (item == null) continue;
|
||||
item.setAppointmentCount(longValue(row, "appointmentCount"));
|
||||
item.setCompletedCount(longValue(row, "completedCount"));
|
||||
item.setAmount(decimalValue(row, "amount"));
|
||||
if (date.equals(LocalDate.parse(rowDate))) {
|
||||
overview.getToday().setServiceInProgressCount(longValue(row, "serviceInProgressCount"));
|
||||
overview.getToday().setPendingOrderCount(longValue(row, "pendingOrderCount"));
|
||||
overview.getToday().setCompletedServiceCount(longValue(row, "completedCount"));
|
||||
overview.getToday().setOrderAmount(decimalValue(row, "amount"));
|
||||
overview.getToday().setAppointmentCount(longValue(row, "appointmentCount"));
|
||||
}
|
||||
}
|
||||
List<SalonDashboardOverviewVO.ShopRankingItem> ranking = new ArrayList<>();
|
||||
for (Map<String, Object> row : salonDashboardMapper.selectShopRanking(rangeStart, date)) {
|
||||
SalonDashboardOverviewVO.ShopRankingItem item = new SalonDashboardOverviewVO.ShopRankingItem();
|
||||
item.setShopId(numberValue(row, "shopId"));
|
||||
item.setShopName(stringValue(row, "shopName"));
|
||||
item.setAppointmentCount(longValue(row, "appointmentCount"));
|
||||
item.setCompletedCount(longValue(row, "completedCount"));
|
||||
item.setAmount(decimalValue(row, "amount"));
|
||||
ranking.add(item);
|
||||
}
|
||||
overview.setShopRanking(ranking);
|
||||
|
||||
overview.getAttention().setRegistrationReviewCount(registrationMapper.selectCount(new LambdaQueryWrapper<WorkbenchRegistrationApplicationDO>()
|
||||
.eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0)
|
||||
.in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER)));
|
||||
overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper<ContentModerationRecordDO>()
|
||||
.in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY")));
|
||||
overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
|
||||
.eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING")));
|
||||
overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
|
||||
.eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING")));
|
||||
overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper<InventoryItemDO>()
|
||||
.eq(InventoryItemDO::getIsDelete, 0)
|
||||
.apply("stock_quantity <= warning_threshold")));
|
||||
return overview;
|
||||
}
|
||||
|
||||
private String stringValue(Map<String, Object> row, String key) {
|
||||
Object value = row.get(key);
|
||||
return value == null ? "" : value.toString();
|
||||
}
|
||||
|
||||
private long longValue(Map<String, Object> row, String key) {
|
||||
Object value = row.get(key);
|
||||
return value instanceof Number ? ((Number) value).longValue() : 0L;
|
||||
}
|
||||
|
||||
private Long numberValue(Map<String, Object> row, String key) {
|
||||
Object value = row.get(key);
|
||||
return value instanceof Number ? ((Number) value).longValue() : null;
|
||||
}
|
||||
|
||||
private BigDecimal decimalValue(Map<String, Object> row, String key) {
|
||||
Object value = row.get(key);
|
||||
if (value instanceof BigDecimal) return (BigDecimal) value;
|
||||
if (value instanceof Number) return BigDecimal.valueOf(((Number) value).doubleValue());
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private long countUsersByType(int type) {
|
||||
return userMapper.selectCount(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.eq(UserDO::getType, type)
|
||||
.eq(UserDO::getStatus, 1));
|
||||
}
|
||||
|
||||
@GetMapping("/stats")
|
||||
@RequirePermission("dashboard:view")
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.analytics.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Salon 驾驶舱趋势和门店排行聚合查询。 */
|
||||
@Mapper
|
||||
public interface SalonDashboardMapper {
|
||||
|
||||
String BUSINESS_ORDERS = "(SELECT o.id, o.shop_id, o.status, o.order_source, "
|
||||
+ "CASE WHEN o.order_source = 'HISTORICAL_BACKFILL' "
|
||||
+ "THEN COALESCE(item.service_date, DATE(o.create_time)) "
|
||||
+ "ELSE COALESCE(DATE(item.appointment_time), DATE(o.create_time)) END AS business_date, "
|
||||
+ "item.appointment_time, COALESCE(o.actual_amount, o.total_amount, 0) AS amount "
|
||||
+ "FROM t_order o LEFT JOIN (SELECT order_id, MIN(appointment_time) AS appointment_time, "
|
||||
+ "MIN(service_date) AS service_date FROM t_order_item WHERE is_delete = 0 GROUP BY order_id) item "
|
||||
+ "ON item.order_id = o.id WHERE o.is_delete = 0 AND o.status <> 3)";
|
||||
|
||||
@Select("SELECT DATE_FORMAT(business_date, '%Y-%m-%d') AS date, "
|
||||
+ "SUM(CASE WHEN order_source <> 'HISTORICAL_BACKFILL' AND appointment_time IS NOT NULL AND status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, "
|
||||
+ "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS completedCount, "
|
||||
+ "SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) AS serviceInProgressCount, "
|
||||
+ "SUM(CASE WHEN status IN (0, 1) THEN 1 ELSE 0 END) AS pendingOrderCount, "
|
||||
+ "SUM(amount) AS amount FROM " + BUSINESS_ORDERS + " business_orders"
|
||||
+ " WHERE business_date BETWEEN #{startDate} AND #{endDate} GROUP BY business_date ORDER BY business_date")
|
||||
List<Map<String, Object>> selectOrderTrend(@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate);
|
||||
|
||||
@Select("SELECT s.id AS shopId, s.shop_name AS shopName, "
|
||||
+ "SUM(CASE WHEN o.order_source <> 'HISTORICAL_BACKFILL' AND o.appointment_time IS NOT NULL AND o.status <> 3 THEN 1 ELSE 0 END) AS appointmentCount, "
|
||||
+ "SUM(CASE WHEN o.status = 2 THEN 1 ELSE 0 END) AS completedCount, SUM(o.amount) AS amount "
|
||||
+ "FROM " + BUSINESS_ORDERS + " o JOIN t_shop s ON s.id = o.shop_id AND s.is_delete = 0 "
|
||||
+ "WHERE o.business_date BETWEEN #{startDate} AND #{endDate} "
|
||||
+ "GROUP BY s.id, s.shop_name ORDER BY amount DESC LIMIT 10")
|
||||
List<Map<String, Object>> selectShopRanking(@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate);
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.analytics.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Salon 平台管理员驾驶舱数据。
|
||||
* 该 VO 只包含 Salon 经营口径,不复用 ArtList 的流量和电商指标。
|
||||
*/
|
||||
@Data
|
||||
public class SalonDashboardOverviewVO {
|
||||
private String date;
|
||||
private boolean degraded;
|
||||
private String degradedMessage;
|
||||
private Platform platform = new Platform();
|
||||
private Today today = new Today();
|
||||
private Attention attention = new Attention();
|
||||
private List<TrendItem> trend = new ArrayList<>();
|
||||
private List<ShopRankingItem> shopRanking = new ArrayList<>();
|
||||
|
||||
@Data
|
||||
public static class Platform {
|
||||
private long activeShopCount;
|
||||
private long activeManagerCount;
|
||||
private long activeStaffCount;
|
||||
private long customerCount;
|
||||
private long styleCount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Today {
|
||||
private long appointmentCount;
|
||||
private long serviceInProgressCount;
|
||||
private long completedServiceCount;
|
||||
private BigDecimal orderAmount = BigDecimal.ZERO;
|
||||
private long pendingOrderCount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Attention {
|
||||
private long registrationReviewCount;
|
||||
private long contentReviewCount;
|
||||
private long afterSaleCount;
|
||||
private long artistChangeCount;
|
||||
private long lowStockCount;
|
||||
|
||||
public long total() {
|
||||
return registrationReviewCount + contentReviewCount + afterSaleCount
|
||||
+ artistChangeCount + lowStockCount;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class TrendItem {
|
||||
private String date;
|
||||
private long appointmentCount;
|
||||
private long completedCount;
|
||||
private BigDecimal amount = BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ShopRankingItem {
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private long appointmentCount;
|
||||
private long completedCount;
|
||||
private BigDecimal amount = BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -136,7 +136,7 @@ public class AdminNailArtistController {
|
||||
}
|
||||
}
|
||||
|
||||
NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO);
|
||||
NailArtistInfoDTO saved = nailArtistInfoService.submitNailArtistInfo(nailArtistInfoDTO, currentUser.getId());
|
||||
return Result.success(saved);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -39,7 +39,7 @@ public class NailArtistController {
|
||||
|
||||
@GetMapping("/list/shop/{shopId}")
|
||||
public Result<List<NailArtistInfoDTO>> listByShopId(@PathVariable Long shopId) {
|
||||
return Result.success(nailArtistInfoService.getByShopId(shopId));
|
||||
return Result.success(nailArtistInfoService.listPublicByShopId(shopId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +47,7 @@ public class NailArtistController {
|
||||
*/
|
||||
@GetMapping("/get/{userId}")
|
||||
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId) {
|
||||
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
|
||||
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getPublicByUserId(userId);
|
||||
return Result.success(nailArtistInfoDTO);
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -39,6 +39,9 @@ public class NailArtistInfoDTO {
|
||||
*/
|
||||
private String skills;
|
||||
|
||||
/** 规划页使用的专属颜色。 */
|
||||
private String color;
|
||||
|
||||
/**
|
||||
* 评分
|
||||
*/
|
||||
@@ -79,6 +82,11 @@ public class NailArtistInfoDTO {
|
||||
*/
|
||||
private String portfolio;
|
||||
|
||||
/**
|
||||
* 对外资料审核状态,仅用于后台展示当前发布版本状态。
|
||||
*/
|
||||
private String moderationStatus;
|
||||
|
||||
/**
|
||||
* 美甲师姓名(从用户表获取)
|
||||
*/
|
||||
|
||||
+9
@@ -37,6 +37,9 @@ public class NailArtistInfoDO extends BaseEntity {
|
||||
*/
|
||||
private String skills;
|
||||
|
||||
/** 规划页使用的专属颜色。 */
|
||||
private String color;
|
||||
|
||||
/**
|
||||
* 评分
|
||||
*/
|
||||
@@ -70,6 +73,12 @@ public class NailArtistInfoDO extends BaseEntity {
|
||||
*/
|
||||
private String portfolio;
|
||||
|
||||
/**
|
||||
* 对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY。
|
||||
*/
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
|
||||
/**
|
||||
* 逻辑删除:0-未删,1-已删
|
||||
*/
|
||||
|
||||
+13
@@ -33,6 +33,11 @@ public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
|
||||
*/
|
||||
List<NailArtistInfoDTO> getByShopId(Long shopId);
|
||||
|
||||
/**
|
||||
* 获取对外展示的指定门店美甲师,只返回个人资料和门店审核通过的记录。
|
||||
*/
|
||||
List<NailArtistInfoDTO> listPublicByShopId(Long shopId);
|
||||
|
||||
/**
|
||||
* 保存或更新美甲师信息
|
||||
* @param nailArtistInfoDTO 美甲师信息DTO
|
||||
@@ -40,12 +45,20 @@ public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
|
||||
*/
|
||||
NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO);
|
||||
|
||||
/** 保存运营字段,并将美甲师对外展示资料提交审核。 */
|
||||
NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO, Long authorUserId);
|
||||
|
||||
/**
|
||||
* 获取所有可用的美甲师信息(前台使用)
|
||||
* @return 美甲师信息列表
|
||||
*/
|
||||
List<NailArtistInfoDTO> getAllAvailableNailArtists();
|
||||
|
||||
/**
|
||||
* 获取对外展示的指定美甲师资料。
|
||||
*/
|
||||
NailArtistInfoDTO getPublicByUserId(Long userId);
|
||||
|
||||
NailArtistProfileVO getPublicProfile(Long artistId);
|
||||
|
||||
List<NailArtistAvailabilityVO> getAvailability(Long artistId);
|
||||
|
||||
+248
-22
@@ -10,6 +10,8 @@ import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewD
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.TagDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper;
|
||||
@@ -31,7 +33,11 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistProfileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistReviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistWorkVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -51,6 +57,7 @@ import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@@ -109,6 +116,15 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
@Autowired
|
||||
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Autowired
|
||||
private TagMapper tagMapper;
|
||||
|
||||
@Autowired
|
||||
private ContentModerationService contentModerationService;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired(required = false)
|
||||
private ArtistScheduleMapper artistScheduleMapper;
|
||||
|
||||
@@ -188,6 +204,41 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<NailArtistInfoDTO> listPublicByShopId(Long shopId) {
|
||||
if (!isPublicShop(shopId)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<Long> serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
|
||||
if (serviceUserIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<UserDO> users = userMapper.selectList(new LambdaQueryWrapper<UserDO>()
|
||||
.in(UserDO::getId, serviceUserIds)
|
||||
.eq(UserDO::getType, 3)
|
||||
.eq(UserDO::getStatus, 1)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.eq(UserDO::getProfileModerationStatus, "APPROVED")
|
||||
.orderByAsc(UserDO::getCreateTime)
|
||||
.orderByAsc(UserDO::getId));
|
||||
List<NailArtistInfoDTO> result = new ArrayList<>();
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
for (UserDO user : users) {
|
||||
NailArtistInfoDTO dto = getByUserId(user.getId());
|
||||
if (dto == null) {
|
||||
dto = buildFallbackArtistInfo(user);
|
||||
}
|
||||
if (!isVisibleServiceUser(dto) || !"APPROVED".equals(dto.getModerationStatus())) {
|
||||
continue;
|
||||
}
|
||||
dto.setShopId(shopId);
|
||||
dto.setShopName(shop == null ? null : shop.getShopName());
|
||||
result.add(dto);
|
||||
}
|
||||
enrichScheduleSummaries(result, shopId);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Save submitted data.
|
||||
@@ -196,16 +247,50 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) {
|
||||
NailArtistInfoDO entity = new NailArtistInfoDO();
|
||||
BeanUtils.copyProperties(dto, entity);
|
||||
return saveNailArtistInfo(dto, null, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
|
||||
public NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO dto, Long authorUserId) {
|
||||
return saveNailArtistInfo(dto, authorUserId, true);
|
||||
}
|
||||
|
||||
private NailArtistInfoDTO saveNailArtistInfo(NailArtistInfoDTO dto, Long authorUserId, boolean moderatePublicProfile) {
|
||||
if (dto == null || dto.getUserId() == null) {
|
||||
throw new IllegalArgumentException("美甲师用户信息不能为空");
|
||||
}
|
||||
NailArtistInfoDO existing = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||
.eq(NailArtistInfoDO::getUserId, dto.getUserId())
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||
.last("LIMIT 1"));
|
||||
if (existing != null) {
|
||||
entity.setId(existing.getId());
|
||||
if (existing == null && moderatePublicProfile) {
|
||||
UserDO user = userMapper.selectById(dto.getUserId());
|
||||
if (user == null || isDeleted(user.getIsDelete())) {
|
||||
throw new IllegalArgumentException("美甲师信息不存在");
|
||||
}
|
||||
existing = new NailArtistInfoDO();
|
||||
existing.setUserId(dto.getUserId());
|
||||
existing.setIdentity("");
|
||||
existing.setExperience(0);
|
||||
existing.setSkills("");
|
||||
existing.setPortfolio("");
|
||||
existing.setStatus(1);
|
||||
existing.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
|
||||
existing.setModerationStatus("APPROVED");
|
||||
saveOrUpdate(existing);
|
||||
}
|
||||
|
||||
NailArtistInfoDO entity = new NailArtistInfoDO();
|
||||
if (existing != null) {
|
||||
// 后台编辑可能只提交部分资料。以已保存实体为基线,避免缺失字段被 BeanUtils 覆盖成 null。
|
||||
BeanUtils.copyProperties(existing, entity);
|
||||
mergeSubmittedFields(dto, entity);
|
||||
} else {
|
||||
BeanUtils.copyProperties(dto, entity);
|
||||
}
|
||||
entity.setModerationStatus(existing == null || !StringUtils.hasText(existing.getModerationStatus())
|
||||
? "APPROVED" : existing.getModerationStatus());
|
||||
if (entity.getStatus() == null) {
|
||||
entity.setStatus(1);
|
||||
}
|
||||
@@ -214,12 +299,17 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save submitted data.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param entity parameter `entity` supplied by the caller
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
boolean publicProfileChanged = moderatePublicProfile && existing != null && hasPublicProfileChanges(existing, entity);
|
||||
String moderationStatus = entity.getModerationStatus();
|
||||
if (publicProfileChanged) {
|
||||
moderationStatus = submitPublicProfileModeration(existing, entity, authorUserId);
|
||||
if (!"APPROVED".equals(moderationStatus)) {
|
||||
// 待审、拒绝或 Provider 故障都保持上一版公开资料,不允许新内容穿透。
|
||||
copyPublicProfileFields(existing, entity);
|
||||
} else {
|
||||
entity.setModerationStatus("APPROVED");
|
||||
}
|
||||
}
|
||||
saveOrUpdate(entity);
|
||||
/**
|
||||
* Run business method `convertToDTO`.
|
||||
@@ -227,7 +317,73 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
* @param entity parameter `entity` supplied by the caller
|
||||
* @return return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
return convertToDTO(entity);
|
||||
NailArtistInfoDTO result = convertToDTO(entity);
|
||||
result.setModerationStatus(moderationStatus);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a partial admin payload while preserving fields that the caller did not submit.
|
||||
* Explicit empty strings and zero values remain valid updates; only null means "unchanged".
|
||||
*/
|
||||
private void mergeSubmittedFields(NailArtistInfoDTO dto, NailArtistInfoDO target) {
|
||||
if (dto.getUserId() != null) target.setUserId(dto.getUserId());
|
||||
if (dto.getIdentity() != null) target.setIdentity(dto.getIdentity());
|
||||
if (dto.getExperience() != null) target.setExperience(dto.getExperience());
|
||||
if (dto.getSkills() != null) target.setSkills(dto.getSkills());
|
||||
if (dto.getColor() != null) target.setColor(dto.getColor());
|
||||
if (dto.getRating() != null) target.setRating(dto.getRating());
|
||||
if (dto.getStatus() != null) target.setStatus(dto.getStatus());
|
||||
if (dto.getParticipateProduction() != null) target.setParticipateProduction(dto.getParticipateProduction());
|
||||
if (dto.getWorkStartTime() != null) target.setWorkStartTime(dto.getWorkStartTime());
|
||||
if (dto.getWorkEndTime() != null) target.setWorkEndTime(dto.getWorkEndTime());
|
||||
if (dto.getPortfolio() != null) target.setPortfolio(dto.getPortfolio());
|
||||
}
|
||||
|
||||
private boolean hasPublicProfileChanges(NailArtistInfoDO current, NailArtistInfoDO candidate) {
|
||||
return !java.util.Objects.equals(current.getIdentity(), candidate.getIdentity())
|
||||
|| !java.util.Objects.equals(current.getExperience(), candidate.getExperience())
|
||||
|| !java.util.Objects.equals(current.getSkills(), candidate.getSkills())
|
||||
|| !java.util.Objects.equals(current.getPortfolio(), candidate.getPortfolio());
|
||||
}
|
||||
|
||||
private void copyPublicProfileFields(NailArtistInfoDO source, NailArtistInfoDO target) {
|
||||
target.setIdentity(source.getIdentity());
|
||||
target.setExperience(source.getExperience());
|
||||
target.setSkills(source.getSkills());
|
||||
target.setPortfolio(source.getPortfolio());
|
||||
}
|
||||
|
||||
private String buildArtistProfileModerationText(NailArtistInfoDO profile) {
|
||||
List<String> values = new ArrayList<>();
|
||||
if (StringUtils.hasText(profile.getIdentity())) values.add(profile.getIdentity().trim());
|
||||
if (profile.getExperience() != null) values.add(profile.getExperience() + "年从业经验");
|
||||
List<Long> tagIds = parseLongTokens(profile.getSkills());
|
||||
if (!tagIds.isEmpty()) {
|
||||
tagMapper.selectBatchIds(tagIds).stream()
|
||||
.filter(tag -> !isDeleted(tag.getIsDelete()))
|
||||
.map(TagDO::getTagName)
|
||||
.filter(StringUtils::hasText)
|
||||
.forEach(values::add);
|
||||
}
|
||||
return String.join("\n", values);
|
||||
}
|
||||
|
||||
private String submitPublicProfileModeration(NailArtistInfoDO current, NailArtistInfoDO candidate, Long authorUserId) {
|
||||
LinkedHashMap<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("identity", candidate.getIdentity());
|
||||
payload.put("experience", candidate.getExperience());
|
||||
payload.put("skills", candidate.getSkills());
|
||||
payload.put("portfolio", candidate.getPortfolio());
|
||||
String text = buildArtistProfileModerationText(candidate);
|
||||
try {
|
||||
ContentModerationResultVO result = contentModerationService.assessVersion(
|
||||
"NAIL_ARTIST_PROFILE", current.getId(), authorUserId, text,
|
||||
objectMapper.writeValueAsString(payload), java.util.Collections.emptyList());
|
||||
return result == null || !StringUtils.hasText(result.getStatus()) ? "PENDING" : result.getStatus();
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("美甲师公开资料审核任务创建失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -242,14 +398,25 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
.eq(NailArtistInfoDO::getStatus, 1)
|
||||
.eq(NailArtistInfoDO::getIsDelete, 0));
|
||||
for (NailArtistInfoDO record : records) {
|
||||
UserDO user = userMapper.selectById(record.getUserId());
|
||||
if (user == null || isDeleted(user.getIsDelete())
|
||||
|| !Integer.valueOf(1).equals(user.getStatus())
|
||||
|| !"APPROVED".equals(user.getProfileModerationStatus())) {
|
||||
continue;
|
||||
}
|
||||
NailArtistInfoDTO dto = convertToDTO(record);
|
||||
if (isBookableServiceUser(dto)) {
|
||||
if (isBookableServiceUser(dto) && "APPROVED".equals(dto.getModerationStatus()) && isPublicShop(dto.getShopId())) {
|
||||
result.add(dto);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NailArtistInfoDTO getPublicByUserId(Long userId) {
|
||||
return loadPublicArtistInfo(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NailArtistProfileVO getPublicProfile(Long artistId) {
|
||||
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
|
||||
@@ -263,7 +430,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
NailArtistProfileVO profile = new NailArtistProfileVO();
|
||||
profile.setArtistId(artistId);
|
||||
profile.setArtistName(resolveArtistName(artistInfo, artist));
|
||||
profile.setAvatar(artist.getAvatar());
|
||||
profile.setAvatar(artistInfo.getAvatar());
|
||||
profile.setIdentity(artistInfo.getIdentity());
|
||||
profile.setSignature(artistInfo.getSignature());
|
||||
profile.setExperience(artistInfo.getExperience());
|
||||
@@ -369,10 +536,16 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
if (artistId == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
|
||||
if (artistInfo == null || !isPublicShop(artistInfo.getShopId())) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
|
||||
.eq(OrderArtistReviewDO::getArtistId, artistId)
|
||||
.eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId())
|
||||
.eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED)
|
||||
.eq(OrderArtistReviewDO::getIsDelete, 0)
|
||||
.eq(OrderArtistReviewDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(OrderArtistReviewDO::getSubmittedAt)
|
||||
.orderByDesc(OrderArtistReviewDO::getId));
|
||||
if (reviews == null || reviews.isEmpty()) {
|
||||
@@ -386,6 +559,12 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
Map<Long, ProductDO> productMap = loadProducts(limitedReviews.stream()
|
||||
.map(OrderArtistReviewDO::getProductId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
limitedReviews = limitedReviews.stream()
|
||||
.filter(review -> {
|
||||
ProductDO product = productMap.get(review.getProductId());
|
||||
return product != null && isFrontVisible(product) && "APPROVED".equals(product.getModerationStatus());
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
Set<Long> imageIds = new LinkedHashSet<>();
|
||||
for (OrderArtistReviewDO review : limitedReviews) {
|
||||
imageIds.addAll(parseLongTokens(review.getImageFileIds()));
|
||||
@@ -447,6 +626,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
dto.setIdentity("美甲师");
|
||||
dto.setStatus(1);
|
||||
dto.setParticipateProduction(1);
|
||||
dto.setModerationStatus("APPROVED");
|
||||
dto.setShopId(user.getShopId());
|
||||
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
|
||||
if (!shopOptions.isEmpty()) {
|
||||
@@ -520,7 +700,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
return null;
|
||||
}
|
||||
String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar);
|
||||
return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar;
|
||||
return StringUtils.hasText(accessibleUrl) ? accessibleUrl : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -567,22 +747,67 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
if (artistId == null) {
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
NailArtistInfoDTO artistInfo = getByUserId(artistId);
|
||||
if (artistInfo != null && isVisibleServiceUser(artistInfo)) {
|
||||
return artistInfo;
|
||||
}
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null
|
||||
|| isDeleted(artist.getIsDelete())
|
||||
|| !Integer.valueOf(3).equals(artist.getType())
|
||||
|| !Integer.valueOf(1).equals(artist.getStatus())) {
|
||||
|| !Integer.valueOf(1).equals(artist.getStatus())
|
||||
|| !"APPROVED".equals(artist.getProfileModerationStatus())) {
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
return buildFallbackArtistInfo(artist);
|
||||
NailArtistInfoDTO artistInfo = getByUserId(artistId);
|
||||
if (artistInfo != null) {
|
||||
if (isVisibleServiceUser(artistInfo)
|
||||
&& "APPROVED".equals(artistInfo.getModerationStatus())
|
||||
&& isPublicShop(artistInfo.getShopId())) {
|
||||
return artistInfo;
|
||||
}
|
||||
throw new RuntimeException("美甲师信息暂不可公开展示");
|
||||
}
|
||||
NailArtistInfoDTO fallback = buildFallbackArtistInfo(artist);
|
||||
if (isVisibleServiceUser(fallback) && isPublicShop(fallback.getShopId())) {
|
||||
return fallback;
|
||||
}
|
||||
throw new RuntimeException("美甲师信息不存在");
|
||||
}
|
||||
|
||||
private boolean isPublicShop(Long shopId) {
|
||||
if (shopId == null) {
|
||||
return false;
|
||||
}
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
return shop != null
|
||||
&& !isDeleted(shop.getIsDelete())
|
||||
&& Integer.valueOf(1).equals(shop.getStatus())
|
||||
&& "APPROVED".equals(shop.getModerationStatus());
|
||||
}
|
||||
|
||||
private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) {
|
||||
BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
|
||||
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
|
||||
.eq(OrderArtistReviewDO::getArtistId, artistId)
|
||||
.eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId())
|
||||
.eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED)
|
||||
.eq(OrderArtistReviewDO::getIsDelete, 0)
|
||||
.eq(OrderArtistReviewDO::getModerationStatus, "APPROVED")
|
||||
.isNotNull(OrderArtistReviewDO::getRatingScore));
|
||||
Map<Long, ProductDO> products = loadProducts(reviews.stream()
|
||||
.map(OrderArtistReviewDO::getProductId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new)));
|
||||
BigDecimal averageRating = reviews.stream()
|
||||
.filter(review -> products.containsKey(review.getProductId()))
|
||||
.map(OrderArtistReviewDO::getRatingScore)
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
long ratingCount = reviews.stream()
|
||||
.filter(review -> products.containsKey(review.getProductId()))
|
||||
.map(OrderArtistReviewDO::getRatingScore)
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.count();
|
||||
if (ratingCount > 0) {
|
||||
averageRating = averageRating.divide(BigDecimal.valueOf(ratingCount), 1, RoundingMode.HALF_UP);
|
||||
} else {
|
||||
averageRating = null;
|
||||
}
|
||||
BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating;
|
||||
if (rating == null) {
|
||||
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
|
||||
@@ -822,7 +1047,8 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
|
||||
}
|
||||
|
||||
private boolean isFrontVisible(ProductDO product) {
|
||||
return product != null && Integer.valueOf(1).equals(product.getFrontVisible());
|
||||
return product != null && Integer.valueOf(1).equals(product.getFrontVisible())
|
||||
&& "APPROVED".equals(product.getModerationStatus());
|
||||
}
|
||||
|
||||
private LocalDateTime truncateToMinute(LocalDateTime value) {
|
||||
|
||||
+12
-38
@@ -3,15 +3,13 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.controller.admin;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.LoginRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningManagerRegisterDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.RefreshTokenRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.SwitchShopRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.admin.AdminAccountSecurityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -40,6 +38,7 @@ public class AdminAuthController {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final SecurityAuditLogService securityAuditLogService;
|
||||
private final AdminAccountSecurityService adminAccountSecurityService;
|
||||
|
||||
@PostMapping("/login")
|
||||
@OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
|
||||
@@ -64,37 +63,6 @@ public class AdminAuthController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
@OperationGuard(action = "admin-planning-register", ttlSeconds = 10, message = "注册处理中,请勿重复提交")
|
||||
public Result<LoginResponseVO> register(@RequestBody PlanningManagerRegisterDTO registerDTO) {
|
||||
return Result.success(userService.registerPlanningManager(registerDTO));
|
||||
}
|
||||
|
||||
@GetMapping("/login-shops/{account}")
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param account parameter `account` supplied by the caller
|
||||
* @return Result<LoginShopSelectionVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<LoginShopSelectionVO> getLoginShops(@PathVariable String account) {
|
||||
return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account)));
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
@OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作")
|
||||
/**
|
||||
* Run business method `switchShop`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller
|
||||
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId")));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5)
|
||||
/**
|
||||
@@ -115,10 +83,9 @@ public class AdminAuthController {
|
||||
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<LoginResponseVO> refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) {
|
||||
LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken());
|
||||
LoginResponseVO loginResponseVO = userService.adminRefreshToken(refreshTokenRequestDTO.getRefreshToken());
|
||||
if (loginResponseVO.getUserInfo() == null
|
||||
|| loginResponseVO.getUserInfo().getType() == null
|
||||
|| loginResponseVO.getUserInfo().getType() < 2) {
|
||||
|| !Integer.valueOf(4).equals(loginResponseVO.getUserInfo().getType())) {
|
||||
/**
|
||||
* Run business method `RuntimeException`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -128,4 +95,11 @@ public class AdminAuthController {
|
||||
}
|
||||
return Result.success(loginResponseVO);
|
||||
}
|
||||
|
||||
@PostMapping("/password")
|
||||
public Result<Boolean> changePassword(HttpServletRequest request,
|
||||
@Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest));
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.auth.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class AdminPasswordChangeRequestDTO {
|
||||
|
||||
@NotBlank(message = "当前密码不能为空")
|
||||
@Size(max = 128, message = "当前密码长度不能超过 128 位")
|
||||
private String currentPassword;
|
||||
|
||||
@NotBlank(message = "新密码不能为空")
|
||||
@Size(max = 128, message = "新密码长度不能超过 128 位")
|
||||
private String newPassword;
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ import lombok.Data;
|
||||
public class UpdatePhoneRequestDTO {
|
||||
|
||||
/**
|
||||
* 原手机号
|
||||
* 兼容旧客户端的原手机号字段;服务端不使用该字段进行身份校验。
|
||||
*/
|
||||
private String oldPhone;
|
||||
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.auth.service.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.AdminPasswordChangeRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAccountSecurityService {
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final UserSessionService userSessionService;
|
||||
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean changePassword(Long userId, AdminPasswordChangeRequestDTO request) {
|
||||
if (userId == null || request == null) {
|
||||
throw new RuntimeException("管理员账号信息无效");
|
||||
}
|
||||
|
||||
UserDO admin = userMapper.selectById(userId);
|
||||
if (admin == null || Integer.valueOf(1).equals(admin.getIsDelete())) {
|
||||
throw new RuntimeException("管理员账号不存在或已失效");
|
||||
}
|
||||
if (!Integer.valueOf(4).equals(admin.getType())) {
|
||||
throw new RuntimeException("仅平台管理员可以修改后台密码");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(admin.getStatus())) {
|
||||
throw new RuntimeException("管理员账号已被禁用");
|
||||
}
|
||||
if (!StringUtils.hasText(request.getCurrentPassword())
|
||||
|| !passwordEncoder.matches(request.getCurrentPassword(), admin.getPassword())) {
|
||||
throw new RuntimeException("当前密码不正确");
|
||||
}
|
||||
|
||||
String newPassword = request.getNewPassword();
|
||||
AdminDefaultPasswordSupport.validatePasswordStrength(newPassword);
|
||||
if (passwordEncoder.matches(newPassword, admin.getPassword())) {
|
||||
throw new RuntimeException("新密码不能与当前密码相同");
|
||||
}
|
||||
|
||||
admin.setPassword(passwordEncoder.encode(newPassword));
|
||||
if (userMapper.updateById(admin) <= 0) {
|
||||
throw new RuntimeException("密码保存失败,请重试");
|
||||
}
|
||||
|
||||
userSessionService.revokeAllUserSessions(userId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.service.impl;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
@@ -52,6 +53,10 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
*/
|
||||
private final MessageHubClientService messageHubClientService;
|
||||
|
||||
private String phoneKey(String phone) {
|
||||
return PhoneCrypto.current().index(phone);
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Run business method `generateVerificationCode`.
|
||||
@@ -94,14 +99,14 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
public void sendVerificationCode(String phone, String sceneCode) {
|
||||
String code = generateVerificationCode();
|
||||
|
||||
String codeKey = CODE_PREFIX + phone;
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phone;
|
||||
String codeKey = CODE_PREFIX + phoneKey(phone);
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone);
|
||||
|
||||
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
|
||||
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
|
||||
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
|
||||
Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode);
|
||||
log.info("验证码已发送,手机号: {}, sceneCode: {}", PhoneCrypto.current().mask(phone), sceneCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -113,21 +118,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean verifyCode(String phone, String code) {
|
||||
String codeKey = CODE_PREFIX + phone;
|
||||
String codeKey = CODE_PREFIX + phoneKey(phone);
|
||||
String storedCode = redisTemplate.opsForValue().get(codeKey);
|
||||
|
||||
if (storedCode == null) {
|
||||
log.warn("验证码不存在或已过期,手机号: {}", phone);
|
||||
log.warn("验证码不存在或已过期,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!storedCode.equals(code)) {
|
||||
log.warn("验证码错误,手机号: {}", phone);
|
||||
log.warn("验证码错误,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return false;
|
||||
}
|
||||
|
||||
redisTemplate.delete(codeKey);
|
||||
log.info("验证码验证成功,手机号: {}", phone);
|
||||
log.info("验证码验证成功,手机号: {}", PhoneCrypto.current().mask(phone));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -139,7 +144,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
* @return boolean result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public boolean canResend(String phone) {
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phone;
|
||||
String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone);
|
||||
String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
|
||||
return sendTime == null;
|
||||
}
|
||||
|
||||
+3
@@ -95,6 +95,9 @@ public class LoginResponseVO {
|
||||
* Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Boolean shopAuthorizationExpired;
|
||||
private LocalDateTime shopBusinessExpireTime;
|
||||
private Boolean shopBusinessExpired;
|
||||
private Integer shopBusinessRemainingDays;
|
||||
@JsonSerialize(contentUsing = ToStringSerializer.class)
|
||||
/**
|
||||
* Field `shopIds` (List<Long>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
|
||||
+3
@@ -71,4 +71,7 @@ public class CommentDO extends BaseEntity {
|
||||
*/
|
||||
@TableField("is_delete")
|
||||
private Integer isDelete;
|
||||
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
}
|
||||
|
||||
+10
@@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.content.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* 用户评论信息表 Mapper
|
||||
@@ -11,4 +13,12 @@ import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO;
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
public interface CommentMapper extends BaseMapper<CommentDO> {
|
||||
@Select("SELECT COUNT(1) FROM t_comment c "
|
||||
+ "LEFT JOIN t_product p ON p.id = NULLIF(c.product_id, 0) "
|
||||
+ "LEFT JOIN t_shop s ON s.id = COALESCE(NULLIF(c.shop_id, 0), p.shop_id) "
|
||||
+ "WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' "
|
||||
+ "AND (NULLIF(c.product_id, 0) IS NULL OR (p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED')) "
|
||||
+ "AND (COALESCE(NULLIF(c.shop_id, 0), p.shop_id) IS NULL OR (s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED')) "
|
||||
+ "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+65
-12
@@ -14,6 +14,10 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.service.CommentService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.vo.CommentVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -57,6 +61,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
private final ProductMapper productMapper;
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -155,7 +161,9 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
}
|
||||
commentDO.setLikeCount(0);
|
||||
commentDO.setIsDelete(0);
|
||||
commentDO.setModerationStatus("PENDING");
|
||||
commentMapper.insert(commentDO);
|
||||
moderateComment(commentDO, currentUserId);
|
||||
return commentDO.getId();
|
||||
}
|
||||
|
||||
@@ -172,9 +180,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
if (commentDO == null) {
|
||||
return false;
|
||||
}
|
||||
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
|
||||
commentDO.setUpdateTime(LocalDateTime.now());
|
||||
return commentMapper.updateById(commentDO) > 0;
|
||||
moderateComment(commentDO, commentDO.getUserId(), sanitizeContent(commentDTO.getCommentContent()), commentDO.getImageFileIds());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -204,7 +211,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
*/
|
||||
public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) {
|
||||
CommentDO commentDO = commentMapper.selectById(id);
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())
|
||||
|| !"APPROVED".equals(commentDO.getModerationStatus())) {
|
||||
return false;
|
||||
}
|
||||
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
|
||||
@@ -215,9 +223,10 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
*/
|
||||
throw new RuntimeException("只能修改自己的评论");
|
||||
}
|
||||
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
|
||||
commentDO.setUpdateTime(LocalDateTime.now());
|
||||
return commentMapper.updateById(commentDO) > 0;
|
||||
String nextContent = sanitizeContent(commentDTO.getCommentContent());
|
||||
String nextImages = joinImageFileIds(commentDTO.getImageFileIds());
|
||||
moderateComment(commentDO, currentUserId, nextContent, nextImages);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -230,7 +239,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
*/
|
||||
public boolean deleteComment(Long id, Long currentUserId) {
|
||||
CommentDO commentDO = commentMapper.selectById(id);
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) || !"APPROVED".equals(commentDO.getModerationStatus())) {
|
||||
return false;
|
||||
}
|
||||
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
|
||||
@@ -256,7 +265,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
*/
|
||||
public boolean adminDeleteComment(Long id, Long managedShopId) {
|
||||
CommentDO commentDO = commentMapper.selectById(id);
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
|
||||
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())
|
||||
|| !"APPROVED".equals(commentDO.getModerationStatus())) {
|
||||
return false;
|
||||
}
|
||||
if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) {
|
||||
@@ -315,6 +325,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getUserId, userId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.apply(publicVisibilitySql())
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -334,6 +346,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getShopId, shopId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.apply(publicVisibilitySql())
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -353,6 +367,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getProductId, productId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.apply(publicVisibilitySql())
|
||||
.orderByDesc(CommentDO::getCreateTime)
|
||||
);
|
||||
/**
|
||||
@@ -376,6 +392,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getParentCommentId, parentCommentId)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.apply(publicVisibilitySql())
|
||||
.orderByAsc(CommentDO::getCreateTime)
|
||||
);
|
||||
return commentDOs.stream()
|
||||
@@ -397,6 +415,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
List<CommentDO> commentDOs = commentMapper.selectList(
|
||||
Wrappers.lambdaQuery(CommentDO.class)
|
||||
.eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.eq(productId != null && productId > 0, CommentDO::getProductId, productId)
|
||||
.eq(userId != null && userId > 0, CommentDO::getUserId, userId)
|
||||
.eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId)
|
||||
@@ -540,8 +559,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
if (id > 0) {
|
||||
result.add(id);
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Ignore malformed legacy tokens.
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new IllegalArgumentException("评论图片必须引用已上传文件", exception);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(new LinkedHashSet<>(result));
|
||||
@@ -569,7 +588,41 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
|
||||
* @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> activeQuery() {
|
||||
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0);
|
||||
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0)
|
||||
.eq(CommentDO::getModerationStatus, "APPROVED")
|
||||
.apply(publicVisibilitySql());
|
||||
}
|
||||
|
||||
private String publicVisibilitySql() {
|
||||
return "(t_comment.shop_id IS NULL OR t_comment.shop_id = 0 OR EXISTS "
|
||||
+ "(SELECT 1 FROM t_shop visible_shop WHERE visible_shop.id = t_comment.shop_id "
|
||||
+ "AND visible_shop.is_delete = 0 AND visible_shop.status = 1 "
|
||||
+ "AND visible_shop.moderation_status = 'APPROVED')) "
|
||||
+ "AND (t_comment.product_id IS NULL OR t_comment.product_id = 0 OR EXISTS "
|
||||
+ "(SELECT 1 FROM t_product visible_product "
|
||||
+ "JOIN t_shop product_shop ON product_shop.id = visible_product.shop_id "
|
||||
+ "AND product_shop.is_delete = 0 AND product_shop.status = 1 "
|
||||
+ "AND product_shop.moderation_status = 'APPROVED' "
|
||||
+ "WHERE visible_product.id = t_comment.product_id "
|
||||
+ "AND visible_product.is_delete = 0 AND visible_product.front_visible = 1 "
|
||||
+ "AND visible_product.moderation_status = 'APPROVED'))";
|
||||
}
|
||||
|
||||
private void moderateComment(CommentDO comment, Long userId) {
|
||||
moderateComment(comment, userId, comment.getCommentContent(), comment.getImageFileIds());
|
||||
}
|
||||
|
||||
private void moderateComment(CommentDO comment, Long userId, String content, String imageFileIds) {
|
||||
try {
|
||||
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("commentContent", content);
|
||||
payload.put("imageFileIds", imageFileIds);
|
||||
List<Long> imageIds = parseImageFileIds(imageFileIds);
|
||||
contentModerationService.assessVersion("COMMENT", comment.getId(), userId, content,
|
||||
objectMapper.writeValueAsString(payload), imageIds);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new IllegalStateException("评论审核内容序列化失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+19
-2
@@ -22,6 +22,12 @@ public class MinioStorageConfig {
|
||||
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* Optional public endpoint used only when MinIO signs URLs for clients.
|
||||
* Internal uploads, downloads and deletes continue to use endpoint.
|
||||
*/
|
||||
private String publicEndpoint;
|
||||
|
||||
private String bucketName;
|
||||
|
||||
private String accessKey;
|
||||
@@ -34,13 +40,24 @@ public class MinioStorageConfig {
|
||||
@Bean
|
||||
@ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true")
|
||||
public MinioClient minioClient() {
|
||||
if (!StringUtils.hasText(endpoint)
|
||||
return buildClient(endpoint);
|
||||
}
|
||||
|
||||
public MinioClient createSigningClient() {
|
||||
if (!Boolean.TRUE.equals(enabled) || !StringUtils.hasText(publicEndpoint)) {
|
||||
return null;
|
||||
}
|
||||
return buildClient(publicEndpoint);
|
||||
}
|
||||
|
||||
private MinioClient buildClient(String clientEndpoint) {
|
||||
if (!StringUtils.hasText(clientEndpoint)
|
||||
|| !StringUtils.hasText(accessKey)
|
||||
|| !StringUtils.hasText(secretKey)) {
|
||||
throw new IllegalStateException("MinIO is enabled but endpoint/accessKey/secretKey is incomplete");
|
||||
}
|
||||
return MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.endpoint(clientEndpoint)
|
||||
.credentials(accessKey, secretKey)
|
||||
.build();
|
||||
}
|
||||
|
||||
+16
-1
@@ -4,6 +4,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.mapper.AnnouncementMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.mapper.SystemMessageMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
@@ -28,6 +33,11 @@ public class FrontendFileController {
|
||||
private final ProductMapper productMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final EffectDiagramMapper effectDiagramMapper;
|
||||
private final CommentMapper commentMapper;
|
||||
private final OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
private final AnnouncementMapper announcementMapper;
|
||||
private final SystemMessageMapper systemMessageMapper;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
/**
|
||||
* Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public.
|
||||
@@ -71,7 +81,12 @@ public class FrontendFileController {
|
||||
}
|
||||
return positive(productMapper.countPublicImageReference(fileId))
|
||||
|| positive(shopMapper.countPublicImageReference(fileId))
|
||||
|| positive(effectDiagramMapper.countPublicImageReference(fileId));
|
||||
|| positive(effectDiagramMapper.countPublicImageReference(fileId))
|
||||
|| positive(commentMapper.countPublicImageReference(fileId))
|
||||
|| positive(orderArtistReviewMapper.countPublicImageReference(fileId))
|
||||
|| positive(announcementMapper.countPublicImageReference(fileId))
|
||||
|| positive(systemMessageMapper.countPublicImageReference(fileId))
|
||||
|| positive(userMapper.countPublicImageReference(fileId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.file.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/object-storage-file")
|
||||
@RequiredArgsConstructor
|
||||
public class MiniProgramObjectStorageUploadController {
|
||||
|
||||
private final ObjectStorageDirectUploadService objectStorageDirectUploadService;
|
||||
|
||||
@PostMapping("/upload")
|
||||
@OperationGuard(action = "mini-program-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<ObjectStorageFileVO> uploadFile(HttpServletRequest request,
|
||||
@RequestParam("file") MultipartFile file) {
|
||||
Object userTypeValue = request.getAttribute("userType");
|
||||
if (!(userTypeValue instanceof Integer)
|
||||
|| (!Integer.valueOf(2).equals(userTypeValue) && !Integer.valueOf(3).equals(userTypeValue))) {
|
||||
return Result.error(403, "当前账号无权上传门店业务文件");
|
||||
}
|
||||
try {
|
||||
return Result.success(objectStorageDirectUploadService.upload(file));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("文件上传失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-29
@@ -10,6 +10,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageUploadOut
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
|
||||
@@ -46,6 +47,7 @@ public class ObjectStorageFileController {
|
||||
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final ObjectStorageDirectUploadService objectStorageDirectUploadService;
|
||||
/**
|
||||
* Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
@@ -156,35 +158,7 @@ public class ObjectStorageFileController {
|
||||
@OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
|
||||
public Result<ObjectStorageFileVO> uploadFile(@RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
uploadSecurityValidator.validate(file);
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
|
||||
file.getInputStream(),
|
||||
file.getSize(),
|
||||
file.getContentType(),
|
||||
objectName
|
||||
);
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName(originalFilename);
|
||||
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
|
||||
dto.setObjectName(objectName);
|
||||
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
|
||||
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
|
||||
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
|
||||
dto.setContentType(file.getContentType());
|
||||
dto.setFileSize(file.getSize());
|
||||
dto.setPrimaryUploadStatus(1);
|
||||
dto.setBackupUploadStatus(0);
|
||||
dto.setBackupRetryCount(0);
|
||||
dto.setUploadAttempts(uploadOutcome.getAttempts());
|
||||
dto.setStatus(1);
|
||||
|
||||
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
|
||||
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
|
||||
return Result.success(objectStorageDirectUploadService.upload(file));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return Result.error("文件上传失败: " + e.getMessage());
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.file.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.dto.ObjectStorageUploadOutcome;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.UploadSecurityValidator;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ObjectStorageDirectUploadService {
|
||||
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final ObjectStorageOrchestrationService objectStorageOrchestrationService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final UploadSecurityValidator uploadSecurityValidator;
|
||||
private final ObjectStorageProperties objectStorageProperties;
|
||||
|
||||
public ObjectStorageFileVO upload(MultipartFile file) throws Exception {
|
||||
uploadSecurityValidator.validate(file);
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
|
||||
|
||||
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
|
||||
file.getInputStream(),
|
||||
file.getSize(),
|
||||
file.getContentType(),
|
||||
objectName
|
||||
);
|
||||
|
||||
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
|
||||
dto.setFileName(originalFilename);
|
||||
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
|
||||
dto.setObjectName(objectName);
|
||||
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
|
||||
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
|
||||
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
|
||||
dto.setContentType(file.getContentType());
|
||||
dto.setFileSize(file.getSize());
|
||||
dto.setPrimaryUploadStatus(1);
|
||||
dto.setBackupUploadStatus(0);
|
||||
dto.setBackupRetryCount(0);
|
||||
dto.setUploadAttempts(uploadOutcome.getAttempts());
|
||||
dto.setStatus(1);
|
||||
|
||||
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
|
||||
return objectStorageFileService.getObjectStorageFileById(fileId);
|
||||
}
|
||||
}
|
||||
+4
@@ -75,4 +75,8 @@ public interface ObjectStorageFileService extends IService<ObjectStorageFileDO>
|
||||
List<ObjectStorageFileVO> listObjectStorageFilesByStatus(Integer status);
|
||||
|
||||
void evictObjectStorageFileCache(Long id);
|
||||
|
||||
Long findFileIdByReference(String reference);
|
||||
|
||||
String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes);
|
||||
}
|
||||
|
||||
+24
-3
@@ -9,9 +9,9 @@ import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import io.minio.http.Method;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@@ -20,15 +20,36 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MinioObjectStorageProvider implements ObjectStorageProvider {
|
||||
|
||||
private static final long UNKNOWN_SIZE_PART_SIZE = 10 * 1024 * 1024L;
|
||||
|
||||
private final ObjectProvider<MinioClient> minioClientProvider;
|
||||
private final MinioClient signingClient;
|
||||
private final MinioStorageConfig minioStorageConfig;
|
||||
private final ObjectStorageProperties objectStorageProperties;
|
||||
|
||||
@Autowired
|
||||
public MinioObjectStorageProvider(
|
||||
ObjectProvider<MinioClient> minioClientProvider,
|
||||
MinioStorageConfig minioStorageConfig,
|
||||
ObjectStorageProperties objectStorageProperties
|
||||
) {
|
||||
this(minioClientProvider, minioStorageConfig, objectStorageProperties, minioStorageConfig.createSigningClient());
|
||||
}
|
||||
|
||||
MinioObjectStorageProvider(
|
||||
ObjectProvider<MinioClient> minioClientProvider,
|
||||
MinioStorageConfig minioStorageConfig,
|
||||
ObjectStorageProperties objectStorageProperties,
|
||||
MinioClient signingClient
|
||||
) {
|
||||
this.minioClientProvider = minioClientProvider;
|
||||
this.minioStorageConfig = minioStorageConfig;
|
||||
this.objectStorageProperties = objectStorageProperties;
|
||||
this.signingClient = signingClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String providerCode() {
|
||||
return "MINIO";
|
||||
@@ -86,7 +107,7 @@ public class MinioObjectStorageProvider implements ObjectStorageProvider {
|
||||
if (!Boolean.TRUE.equals(minioStorageConfig.getPrivateBucket())) {
|
||||
return getFileUrl(objectName);
|
||||
}
|
||||
return requireClient().getPresignedObjectUrl(
|
||||
return (signingClient == null ? requireClient() : signingClient).getPresignedObjectUrl(
|
||||
GetPresignedObjectUrlArgs.builder()
|
||||
.method(Method.GET)
|
||||
.bucket(minioStorageConfig.getBucketName())
|
||||
|
||||
+27
@@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.mapper.ObjectStorageFileMa
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.mq.ObjectStorageBackupMessagePublisher;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -59,6 +60,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
|
||||
private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
|
||||
private final ObjectStorageProperties objectStorageProperties;
|
||||
private final ObjectStorageReplicaService objectStorageReplicaService;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -218,6 +220,31 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long findFileIdByReference(String reference) {
|
||||
if (!StringUtils.hasText(reference)) return null;
|
||||
String objectName = objectStorageUrlSupport.extractObjectName(reference);
|
||||
ObjectStorageFileDO file = objectStorageFileMapper.selectOne(Wrappers.lambdaQuery(ObjectStorageFileDO.class)
|
||||
.and(query -> query.eq(ObjectStorageFileDO::getFileUrl, reference)
|
||||
.or().eq(ObjectStorageFileDO::getPrimaryUrl, reference)
|
||||
.or().eq(StringUtils.hasText(objectName), ObjectStorageFileDO::getObjectName, objectName))
|
||||
.last("LIMIT 1"));
|
||||
return file == null ? null : file.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes) {
|
||||
ObjectStorageFileVO file = getObjectStorageFileById(fileId);
|
||||
if (file == null || !Integer.valueOf(1).equals(file.getStatus())) {
|
||||
throw new IllegalStateException("审核图片不存在或不可用");
|
||||
}
|
||||
String url = objectStorageUrlSupport.getSignedUrlOrThrow(file, expiryMinutes);
|
||||
if (!StringUtils.hasText(url) || !url.startsWith("https://")) {
|
||||
throw new IllegalStateException("审核图片必须通过 HTTPS 访问");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 DO 转换为 VO
|
||||
*
|
||||
|
||||
+65
-6
@@ -1,6 +1,8 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.file.support;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.config.AliyunOssConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.config.MinioStorageConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.config.QiniuKodoConfig;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.AliyunOssService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService;
|
||||
@@ -21,6 +23,8 @@ public class ObjectStorageUrlSupport {
|
||||
private static final int UPLOAD_STATUS_SUCCEEDED = 1;
|
||||
|
||||
private final PrimaryObjectStorageService primaryObjectStorageService;
|
||||
private final MinioStorageConfig minioStorageConfig;
|
||||
private final AliyunOssConfig aliyunOssConfig;
|
||||
private final QiniuKodoConfig qiniuKodoConfig;
|
||||
private final AliyunOssService aliyunOssService;
|
||||
private final ObjectStorageProperties objectStorageProperties;
|
||||
@@ -32,7 +36,7 @@ public class ObjectStorageUrlSupport {
|
||||
}
|
||||
String objectName = extractObjectName(fileUrl);
|
||||
if (!StringUtils.hasText(objectName)) {
|
||||
return fileUrl;
|
||||
return isKnownStorageUrl(fileUrl) ? null : fileUrl;
|
||||
}
|
||||
try {
|
||||
return objectStorageOrchestrationService.getPresignedUrl(
|
||||
@@ -116,6 +120,9 @@ public class ObjectStorageUrlSupport {
|
||||
}
|
||||
|
||||
String normalizedUrl = fileUrl.trim();
|
||||
if (normalizedUrl.startsWith("oss://")) {
|
||||
return extractBucketObjectName(normalizedUrl.substring("oss://".length()), aliyunOssConfig.getBucketName());
|
||||
}
|
||||
if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
|
||||
return stripQuery(stripLeadingSlash(normalizedUrl));
|
||||
}
|
||||
@@ -123,10 +130,17 @@ public class ObjectStorageUrlSupport {
|
||||
try {
|
||||
URI fileUri = URI.create(normalizedUrl);
|
||||
URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain()));
|
||||
if (!sameAuthority(fileUri, domainUri)) {
|
||||
return "";
|
||||
if (sameAuthority(fileUri, domainUri)) {
|
||||
return stripQuery(stripLeadingSlash(fileUri.getPath()));
|
||||
}
|
||||
return stripQuery(stripLeadingSlash(fileUri.getPath()));
|
||||
if (sameConfiguredAuthority(fileUri, minioStorageConfig.getEndpoint())
|
||||
|| sameConfiguredAuthority(fileUri, minioStorageConfig.getPublicEndpoint())) {
|
||||
return extractBucketObjectName(fileUri.getPath(), minioStorageConfig.getBucketName());
|
||||
}
|
||||
if (sameConfiguredAuthority(fileUri, aliyunOssConfig.getEndpoint())) {
|
||||
return extractBucketObjectName(fileUri.getPath(), aliyunOssConfig.getBucketName());
|
||||
}
|
||||
return "";
|
||||
} catch (Exception e) {
|
||||
log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e);
|
||||
return "";
|
||||
@@ -163,6 +177,9 @@ public class ObjectStorageUrlSupport {
|
||||
}
|
||||
|
||||
private String normalizeDomain(String domain) {
|
||||
if (!StringUtils.hasText(domain)) {
|
||||
return "";
|
||||
}
|
||||
String normalized = domain.trim();
|
||||
while (normalized.endsWith("/")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
@@ -174,13 +191,55 @@ public class ObjectStorageUrlSupport {
|
||||
}
|
||||
|
||||
private boolean sameAuthority(URI left, URI right) {
|
||||
return left.getScheme() != null
|
||||
&& left.getScheme().equalsIgnoreCase(right.getScheme())
|
||||
return right != null
|
||||
&& left.getHost() != null
|
||||
&& right.getHost() != null
|
||||
&& left.getHost().equalsIgnoreCase(right.getHost())
|
||||
&& normalizedPort(left) == normalizedPort(right);
|
||||
}
|
||||
|
||||
private boolean sameConfiguredAuthority(URI fileUri, String endpoint) {
|
||||
if (!StringUtils.hasText(endpoint)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return sameAuthority(fileUri, URI.create(normalizeDomain(endpoint)));
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String extractBucketObjectName(String rawPath, String bucketName) {
|
||||
String path = stripQuery(stripLeadingSlash(rawPath));
|
||||
if (!StringUtils.hasText(path) || !StringUtils.hasText(bucketName)) {
|
||||
return "";
|
||||
}
|
||||
String bucketPrefix = bucketName.trim() + "/";
|
||||
return path.startsWith(bucketPrefix) ? path.substring(bucketPrefix.length()) : path;
|
||||
}
|
||||
|
||||
private boolean isKnownStorageUrl(String fileUrl) {
|
||||
if (!StringUtils.hasText(fileUrl)) {
|
||||
return false;
|
||||
}
|
||||
String normalized = fileUrl.trim();
|
||||
if (normalized.startsWith("oss://")) {
|
||||
return true;
|
||||
}
|
||||
if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
URI uri = URI.create(normalized);
|
||||
return sameConfiguredAuthority(uri, qiniuKodoConfig.getDomain())
|
||||
|| sameConfiguredAuthority(uri, minioStorageConfig.getEndpoint())
|
||||
|| sameConfiguredAuthority(uri, minioStorageConfig.getPublicEndpoint())
|
||||
|| sameConfiguredAuthority(uri, aliyunOssConfig.getEndpoint());
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int normalizedPort(URI uri) {
|
||||
if (uri.getPort() >= 0) {
|
||||
return uri.getPort();
|
||||
|
||||
+8
-1
@@ -1,14 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.dto;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信小程序自动登录请求。
|
||||
*/
|
||||
@Data
|
||||
public class WechatMiniAutoLoginRequestDTO {
|
||||
public class WechatMiniAutoLoginRequestDTO implements AgreementAwareRequest {
|
||||
|
||||
@NotBlank(message = "微信登录凭证不能为空")
|
||||
/**
|
||||
@@ -20,4 +23,8 @@ public class WechatMiniAutoLoginRequestDTO {
|
||||
* Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private Long preferredShopId;
|
||||
|
||||
private Boolean agreementAccepted;
|
||||
private Map<String, String> agreementVersions;
|
||||
private String clientType;
|
||||
}
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 微信订阅消息发送记录。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_wechat_subscribe_message_log")
|
||||
public class WechatSubscribeMessageLogDO extends BaseEntity {
|
||||
private String eventKey;
|
||||
private String templateCode;
|
||||
private Long userId;
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private String openIdHash;
|
||||
private String status;
|
||||
private Integer retryCount;
|
||||
private Integer errCode;
|
||||
private String errMsg;
|
||||
private LocalDateTime nextRetryTime;
|
||||
private LocalDateTime sentTime;
|
||||
private Integer isDelete;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface WechatSubscribeMessageLogMapper extends BaseMapper<WechatSubscribeMessageLogDO> {
|
||||
@Select("SELECT * FROM t_wechat_subscribe_message_log WHERE is_delete = 0 AND ((status IN ('PENDING','RETRY') AND (next_retry_time IS NULL OR next_retry_time <= #{now})) OR (status = 'PROCESSING' AND update_time < DATE_SUB(#{now}, INTERVAL 10 MINUTE))) ORDER BY id ASC LIMIT #{limit}")
|
||||
List<WechatSubscribeMessageLogDO> selectDue(@Param("now") LocalDateTime now, @Param("limit") int limit);
|
||||
|
||||
@Update("UPDATE t_wechat_subscribe_message_log SET status = 'PROCESSING', update_time = NOW() WHERE id = #{id} AND is_delete = 0 AND (status IN ('PENDING','RETRY') OR (status = 'PROCESSING' AND update_time < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))")
|
||||
int claimForProcessing(@Param("id") Long id);
|
||||
}
|
||||
+8
@@ -21,6 +21,14 @@ public interface WechatMiniAuthService {
|
||||
|
||||
WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket);
|
||||
|
||||
WechatMiniRegistrationTicket validateRegistrationTicket(String ticket);
|
||||
|
||||
void transferRegistrationBinding(Long sourceUserId, Long targetUserId);
|
||||
|
||||
void rememberRegistrationAvatarUpload(String ticket, Long fileId);
|
||||
|
||||
void validateRegistrationAvatarUpload(String ticket, Long fileId);
|
||||
|
||||
/**
|
||||
* Run business method `autoLogin`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+10
@@ -1,5 +1,6 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信小程序开放接口客户端。
|
||||
@@ -29,6 +30,15 @@ public interface WechatMiniClientService {
|
||||
*/
|
||||
String getConfiguredAppId();
|
||||
|
||||
String getAccessTokenForContentModeration();
|
||||
|
||||
/** 发送微信小程序订阅消息。 */
|
||||
SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map<String, String> data,
|
||||
String page, String miniprogramState);
|
||||
|
||||
record SubscribeMessageResult(boolean success, int errCode, String errMsg) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `SessionInfo`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Salon 微信订阅消息业务服务。 */
|
||||
public interface WechatSubscribeMessageService {
|
||||
String TEMPLATE_SERVICE_START = "jURyVPL52qyUhm_c_OyvED5zivUZr_3LfAXjfV-KOJc";
|
||||
String TEMPLATE_CANCELLED = "0v80O2xaOS8D_aSrurqTo4fds8FmyMlEOsy66LXsjNQ";
|
||||
String TEMPLATE_APPOINTMENT = "Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo";
|
||||
|
||||
void enqueueAppointmentReminder(Long orderId, Long orderItemId);
|
||||
|
||||
void enqueueCancellationNotice(Long orderId, Long orderItemId);
|
||||
|
||||
void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime);
|
||||
|
||||
void processDueMessages();
|
||||
}
|
||||
+2
-1
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.xiaowang.jayucloud.salon.core.config.BrandProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.MessageHubPushConfigDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -138,7 +139,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken());
|
||||
rabbitTemplate.send(ingressExchange, ingressRoutingKey, message);
|
||||
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}",
|
||||
sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
sceneCode, PhoneCrypto.current().mask(phone), ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
} catch (Exception exception) {
|
||||
log.error("发送短信验证码失败", exception);
|
||||
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
|
||||
|
||||
+80
-14
@@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRe
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
|
||||
@@ -61,6 +62,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
*/
|
||||
private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:";
|
||||
private static final String REGISTRATION_TICKET_KEY_PREFIX = "user:wechat-mini:registration-ticket:";
|
||||
private static final String REGISTRATION_AVATAR_KEY_PREFIX = "user:wechat-mini:registration-avatar:";
|
||||
private static final Duration TICKET_TTL = Duration.ofMinutes(5);
|
||||
/**
|
||||
* Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
@@ -112,7 +114,9 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
}
|
||||
WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId());
|
||||
if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) {
|
||||
return applicationState(WechatMiniLoginResultVO.STATUS_REJECTED, "申请已被驳回,可修改后重新提交", application);
|
||||
WechatMiniLoginResultVO result = registrationResult(user.getId(), sessionInfo.openId(), application);
|
||||
result.setStatus(WechatMiniLoginResultVO.STATUS_REJECTED);
|
||||
return result;
|
||||
}
|
||||
if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus())
|
||||
|| WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) {
|
||||
@@ -154,7 +158,9 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
}
|
||||
WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId());
|
||||
if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) {
|
||||
return registrationResult(user.getId(), sessionInfo.openId(), application);
|
||||
WechatMiniLoginResultVO result = registrationResult(user.getId(), sessionInfo.openId(), application);
|
||||
result.setStatus(WechatMiniLoginResultVO.STATUS_REJECTED);
|
||||
return result;
|
||||
}
|
||||
if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus())
|
||||
|| WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) {
|
||||
@@ -192,14 +198,18 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
|
||||
@Override
|
||||
public WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket) {
|
||||
if (!StringUtils.hasText(ticket)) {
|
||||
throw new BusinessException("注册票据不能为空");
|
||||
}
|
||||
String key = REGISTRATION_TICKET_KEY_PREFIX + ticket;
|
||||
String payload = redisTemplate.opsForValue().get(key);
|
||||
if (!StringUtils.hasText(payload) || !Boolean.TRUE.equals(redisTemplate.delete(key))) {
|
||||
WechatMiniRegistrationTicket value = validateRegistrationTicket(ticket);
|
||||
if (!Boolean.TRUE.equals(redisTemplate.delete(REGISTRATION_TICKET_KEY_PREFIX + ticket))) {
|
||||
throw new BusinessException("注册票据已失效,请重新发起快捷登录");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WechatMiniRegistrationTicket validateRegistrationTicket(String ticket) {
|
||||
if (!StringUtils.hasText(ticket)) throw new BusinessException("注册票据不能为空");
|
||||
String payload = redisTemplate.opsForValue().get(REGISTRATION_TICKET_KEY_PREFIX + ticket);
|
||||
if (!StringUtils.hasText(payload)) throw new BusinessException("注册票据已失效,请重新发起快捷登录");
|
||||
try {
|
||||
WechatMiniRegistrationTicket value = objectMapper.readValue(payload, WechatMiniRegistrationTicket.class);
|
||||
WechatMiniBindingDO binding = findBindingByOpenId(value.getOpenId());
|
||||
@@ -213,6 +223,47 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void transferRegistrationBinding(Long sourceUserId, Long targetUserId) {
|
||||
if (sourceUserId == null || targetUserId == null || Objects.equals(sourceUserId, targetUserId)) {
|
||||
throw new BusinessException("微信身份关联目标不合法");
|
||||
}
|
||||
String appId = wechatMiniClientService.getConfiguredAppId();
|
||||
WechatMiniBindingDO source = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, sourceUserId)
|
||||
.eq(WechatMiniBindingDO::getStatus, 1).last("FOR UPDATE"));
|
||||
if (source == null) throw new BusinessException("注册申请的微信身份已失效");
|
||||
WechatMiniBindingDO occupied = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, targetUserId)
|
||||
.eq(WechatMiniBindingDO::getStatus, 1).last("FOR UPDATE"));
|
||||
if (occupied != null) throw new BusinessException("该美甲师已关联微信账号");
|
||||
WechatMiniBindingDO historical = wechatMiniBindingMapper.selectOne(new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, appId).eq(WechatMiniBindingDO::getUserId, targetUserId)
|
||||
.last("FOR UPDATE"));
|
||||
if (historical != null) wechatMiniBindingMapper.deleteById(historical.getId());
|
||||
source.setUserId(targetUserId);
|
||||
source.setUpdateTime(LocalDateTime.now());
|
||||
wechatMiniBindingMapper.updateById(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rememberRegistrationAvatarUpload(String ticket, Long fileId) {
|
||||
if (fileId == null || fileId <= 0) throw new BusinessException("头像文件无效");
|
||||
validateRegistrationTicket(ticket);
|
||||
Long ttl = redisTemplate.getExpire(REGISTRATION_TICKET_KEY_PREFIX + ticket);
|
||||
if (ttl == null || ttl <= 0) throw new BusinessException("注册票据已失效,请重新发起快捷登录");
|
||||
redisTemplate.opsForValue().set(REGISTRATION_AVATAR_KEY_PREFIX + ticket, String.valueOf(fileId), Duration.ofSeconds(ttl));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validateRegistrationAvatarUpload(String ticket, Long fileId) {
|
||||
if (fileId == null) return;
|
||||
validateRegistrationTicket(ticket);
|
||||
String uploadedFileId = redisTemplate.opsForValue().get(REGISTRATION_AVATAR_KEY_PREFIX + ticket);
|
||||
if (!String.valueOf(fileId).equals(uploadedFileId)) throw new BusinessException("请重新选择并上传头像");
|
||||
}
|
||||
|
||||
@Override
|
||||
/**
|
||||
* Run business method `autoLogin`.
|
||||
@@ -280,6 +331,9 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
|
||||
UserDO phoneUser = findActiveUserByPhone(phone);
|
||||
if (phoneUser != null) {
|
||||
if (requiresWechatIdentityForStaff(phoneUser)) {
|
||||
return WechatMiniLoginResultVO.needManualLogin("美甲师档案不能通过手机号关联,请使用关联微信身份或联系店长完成关联。");
|
||||
}
|
||||
if (userShopBindingSupport.listActiveShopIdsByUserId(phoneUser.getId()).isEmpty()) {
|
||||
return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone));
|
||||
}
|
||||
@@ -288,6 +342,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone));
|
||||
}
|
||||
|
||||
private boolean requiresWechatIdentityForStaff(UserDO user) {
|
||||
return user != null && Integer.valueOf(3).equals(user.getType())
|
||||
&& !StringUtils.hasText(user.getAccount());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
/**
|
||||
@@ -310,6 +369,10 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket());
|
||||
LoginResponseVO loginResponse;
|
||||
if (ticketPayload.getUserId() != null) {
|
||||
UserDO ticketUser = userMapper.selectById(ticketPayload.getUserId());
|
||||
if (requiresWechatIdentityForStaff(ticketUser)) {
|
||||
throw new BusinessException("美甲师档案尚未关联微信身份,请联系店长完成关联");
|
||||
}
|
||||
loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId);
|
||||
} else if (StringUtils.hasText(ticketPayload.getPhone())) {
|
||||
loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId);
|
||||
@@ -500,12 +563,15 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
if (!StringUtils.hasText(phone)) {
|
||||
return null;
|
||||
}
|
||||
return userMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
|
||||
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(phone.trim()))
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1"));
|
||||
if (user == null) {
|
||||
Long legacyId = userMapper.findLegacyIdByPhone(phone.trim());
|
||||
user = legacyId == null ? null : userMapper.selectById(legacyId);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+47
@@ -20,6 +20,7 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* WeChat mini program API client.
|
||||
@@ -201,6 +202,52 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
return properties.getAppId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAccessTokenForContentModeration() {
|
||||
return getAccessToken();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map<String, String> data,
|
||||
String page, String miniprogramState) {
|
||||
if (!StringUtils.hasText(openId) || !StringUtils.hasText(templateId)) {
|
||||
return new SubscribeMessageResult(false, 40001, "缺少订阅消息接收人或模板");
|
||||
}
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) {
|
||||
return new SubscribeMessageResult(false, 40002, "订阅消息已关闭");
|
||||
}
|
||||
if ("mock".equalsIgnoreCase(properties.getSubscribeMessageProvider())) {
|
||||
return new SubscribeMessageResult(true, 0, "MOCK_OK");
|
||||
}
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("touser", openId);
|
||||
request.put("template_id", templateId);
|
||||
request.put("page", StringUtils.hasText(page) ? page : "/pages/planning/index");
|
||||
request.put("miniprogram_state", StringUtils.hasText(miniprogramState) ? miniprogramState : "developer");
|
||||
request.put("lang", "zh_CN");
|
||||
Map<String, Map<String, String>> templateData = new HashMap<>();
|
||||
if (data != null) {
|
||||
data.forEach((key, value) -> templateData.put(key, Map.of("value", value == null ? "-" : value)));
|
||||
}
|
||||
request.put("data", templateData);
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
doPostForString(
|
||||
UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send")
|
||||
.queryParam("access_token", getAccessToken()).build(true).toUriString(),
|
||||
new HttpEntity<>(request, headers), "发送微信订阅消息失败"),
|
||||
"发送微信订阅消息失败");
|
||||
int errCode = (int) parseLong(response.get("errcode"), 0L);
|
||||
String errMsg = asText(response.get("errmsg"));
|
||||
return new SubscribeMessageResult(errCode == 0, errCode, errMsg);
|
||||
} catch (RuntimeException exception) {
|
||||
// 订阅消息属于异步通知,微信暂时不可用时交给 Outbox 重试,不影响预约主流程。
|
||||
return new SubscribeMessageResult(false, -1, "微信订阅消息服务暂时不可用");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatSubscribeMessageLogMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class WechatSubscribeMessageServiceImpl implements WechatSubscribeMessageService {
|
||||
/** 微信 date 类型使用中文日期格式;time 类型单独使用 HH:mm。 */
|
||||
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
|
||||
private static final DateTimeFormatter CLOCK_TIME = DateTimeFormatter.ofPattern("HH:mm");
|
||||
private static final String PENDING = "PENDING";
|
||||
private static final String RETRY = "RETRY";
|
||||
private static final String SENT = "SENT";
|
||||
private static final String FAILED = "FAILED";
|
||||
|
||||
private final WechatSubscribeMessageLogMapper logMapper;
|
||||
private final WechatMiniBindingMapper bindingMapper;
|
||||
private final WechatMiniClientService wechatMiniClientService;
|
||||
private final WechatMiniProperties properties;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
public void enqueueAppointmentReminder(Long orderId, Long orderItemId) {
|
||||
enqueue("APPOINTMENT", TEMPLATE_APPOINTMENT, orderId, orderItemId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueueCancellationNotice(Long orderId, Long orderItemId) {
|
||||
enqueue("CANCELLED", TEMPLATE_CANCELLED, orderId, orderItemId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime) {
|
||||
enqueue("SERVICE_START", TEMPLATE_SERVICE_START, orderId, orderItemId, appointmentTime);
|
||||
}
|
||||
|
||||
private void enqueue(String eventType, String templateCode, Long orderId, Long orderItemId, LocalDateTime dueTime) {
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled()) || orderItemId == null) return;
|
||||
OrderItemDO item = orderItemMapper.selectById(orderItemId);
|
||||
if (item == null || item.getArtistId() == null) return;
|
||||
String eventKey = eventType + ":" + orderItemId + ":" + item.getArtistId()
|
||||
+ (dueTime == null ? "" : ":" + dueTime);
|
||||
WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO();
|
||||
log.setEventKey(eventKey);
|
||||
log.setTemplateCode(templateCode);
|
||||
log.setOrderId(orderId);
|
||||
log.setOrderItemId(orderItemId);
|
||||
log.setUserId(item.getArtistId());
|
||||
log.setStatus(PENDING);
|
||||
log.setRetryCount(0);
|
||||
log.setNextRetryTime(dueTime == null ? LocalDateTime.now() : dueTime.minusMinutes(Math.max(1, properties.getServiceStartReminderLeadMinutes() == null ? 30 : properties.getServiceStartReminderLeadMinutes())));
|
||||
log.setIsDelete(0);
|
||||
try { logMapper.insert(log); } catch (DuplicateKeyException ignored) { }
|
||||
}
|
||||
|
||||
@Override
|
||||
@Scheduled(fixedDelayString = "${jayucloud-salon.wechat.mini.subscribe-message-scan-delay-millis:60000}")
|
||||
public void processDueMessages() {
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) return;
|
||||
List<WechatSubscribeMessageLogDO> logs = logMapper.selectDue(LocalDateTime.now(), 50);
|
||||
for (WechatSubscribeMessageLogDO log : logs) {
|
||||
if (logMapper.claimForProcessing(log.getId()) != 1) continue;
|
||||
try {
|
||||
processOne(log);
|
||||
} catch (RuntimeException exception) {
|
||||
retry(log, -1, "订阅消息处理暂时失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processOne(WechatSubscribeMessageLogDO log) {
|
||||
OrderItemDO item = orderItemMapper.selectById(log.getOrderItemId());
|
||||
OrderDO order = item == null ? null : orderMapper.selectById(item.getOrderId());
|
||||
if (item == null || order == null || Integer.valueOf(1).equals(item.getIsDelete()) || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||
mark(log, FAILED, 40004, "预约不存在", null); return;
|
||||
}
|
||||
if (log.getUserId() != null && !log.getUserId().equals(item.getArtistId())) {
|
||||
mark(log, FAILED, 40008, "预约承接美甲师已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && (item.getAppointmentTime() == null || !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()))) {
|
||||
mark(log, FAILED, 40005, "预约已取消或状态已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && !item.getAppointmentTime().isAfter(LocalDateTime.now())) {
|
||||
mark(log, FAILED, 40011, "预约已开始,跳过开始提醒", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode())
|
||||
&& !log.getEventKey().endsWith(String.valueOf(item.getAppointmentTime()))) {
|
||||
mark(log, FAILED, 40008, "预约时间已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_APPOINTMENT.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
|
||||
mark(log, FAILED, 40009, "预约已不在待服务状态", null); return;
|
||||
}
|
||||
if (TEMPLATE_CANCELLED.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) {
|
||||
mark(log, FAILED, 40010, "预约取消状态已变化", null); return;
|
||||
}
|
||||
Long artistId = item.getArtistId();
|
||||
if (artistId == null) { mark(log, FAILED, 40006, "预约尚未分配美甲师", null); return; }
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null) { mark(log, FAILED, 40007, "美甲师不存在", null); return; }
|
||||
LambdaQueryWrapper<WechatMiniBindingDO> bindingQuery = new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getUserId, artistId)
|
||||
.eq(WechatMiniBindingDO::getStatus, 1);
|
||||
if (StringUtils.hasText(properties.getAppId())) {
|
||||
bindingQuery.eq(WechatMiniBindingDO::getAppId, properties.getAppId());
|
||||
}
|
||||
WechatMiniBindingDO binding = bindingMapper.selectOne(bindingQuery.last("LIMIT 1"));
|
||||
if (binding == null || !StringUtils.hasText(binding.getOpenId())) { mark(log, FAILED, 43101, "美甲师未授权订阅消息", null); return; }
|
||||
log.setUserId(artistId);
|
||||
log.setOpenIdHash(phoneCrypto.index(binding.getOpenId()));
|
||||
logMapper.updateById(log);
|
||||
ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId());
|
||||
String productTitle = clip(product == null ? "预约服务" : product.getTitle(), 20);
|
||||
String customerName = clip(StringUtils.hasText(order.getCustomerNameSnapshot()) ? order.getCustomerNameSnapshot() : "到店客户", 20);
|
||||
String dateTime = item.getAppointmentTime() == null ? "待确认" : DATE_TIME.format(item.getAppointmentTime());
|
||||
String clockTime = item.getAppointmentTime() == null ? "待确认" : CLOCK_TIME.format(item.getAppointmentTime());
|
||||
Map<String, String> data = new LinkedHashMap<>();
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode())) {
|
||||
data.put("thing1", "预约即将开始,请提前准备"); data.put("date3", clip(dateTime, 20)); data.put("thing6", productTitle); data.put("thing7", customerName);
|
||||
} else if (TEMPLATE_CANCELLED.equals(log.getTemplateCode())) {
|
||||
data.put("name1", clip(customerName, 10)); data.put("thing2", productTitle); data.put("time4", clip(clockTime, 20)); data.put("thing6", clip(StringUtils.hasText(order.getCancelReason()) ? order.getCancelReason() : "门店取消预约", 20));
|
||||
} else {
|
||||
data.put("thing1", productTitle); data.put("time2", clip(clockTime, 20)); data.put("thing3", "请提前确认服务安排"); data.put("name5", clip(StringUtils.hasText(artist.getNickname()) ? artist.getNickname() : artist.getAccount(), 10)); data.put("name6", clip(customerName, 10));
|
||||
}
|
||||
WechatMiniClientService.SubscribeMessageResult result = wechatMiniClientService.sendSubscribeMessage(binding.getOpenId(), log.getTemplateCode(), data, properties.getSubscribeMessagePage(), properties.getSubscribeMessageMiniprogramState());
|
||||
if (result.success()) mark(log, SENT, 0, result.errMsg(), LocalDateTime.now());
|
||||
else if (isPermanentWechatError(result.errCode())) mark(log, FAILED, result.errCode(), result.errMsg(), null);
|
||||
else retry(log, result.errCode(), result.errMsg());
|
||||
}
|
||||
|
||||
private boolean isPermanentWechatError(int code) {
|
||||
return code == 40001 || code == 40003 || code == 40004 || code == 40037
|
||||
|| code == 41028 || code == 41030 || code == 43101 || code == 47003;
|
||||
}
|
||||
|
||||
private void retry(WechatSubscribeMessageLogDO log, int code, String message) {
|
||||
int count = log.getRetryCount() == null ? 0 : log.getRetryCount();
|
||||
int max = properties.getSubscribeMessageMaxRetries() == null ? 3 : properties.getSubscribeMessageMaxRetries();
|
||||
if (count >= max) { mark(log, FAILED, code, message, null); return; }
|
||||
mark(log, RETRY, code, message, LocalDateTime.now().plusSeconds(10L * (count + 1)));
|
||||
}
|
||||
|
||||
private void mark(WechatSubscribeMessageLogDO log, String status, int code, String message, LocalDateTime time) {
|
||||
log.setStatus(status); log.setErrCode(code); log.setErrMsg(clip(message, 500)); log.setNextRetryTime(time);
|
||||
if (SENT.equals(status)) log.setSentTime(LocalDateTime.now());
|
||||
log.setRetryCount(log.getRetryCount() == null ? 0 : log.getRetryCount() + (RETRY.equals(status) ? 1 : 0));
|
||||
logMapper.updateById(log);
|
||||
}
|
||||
|
||||
private static String clip(String value, int max) {
|
||||
if (!StringUtils.hasText(value)) return "-";
|
||||
String text = value.trim(); return text.length() <= max ? text : text.substring(0, max);
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -123,7 +123,7 @@ public class WechatMiniLoginResultVO {
|
||||
resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册");
|
||||
resultVO.setRegistrationRequired(true);
|
||||
resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket());
|
||||
resultVO.setPhone(loginResponse.getPhone());
|
||||
resultVO.setPhone(maskPhone(loginResponse.getPhone()));
|
||||
resultVO.setRegistrationReason(loginResponse.getRegistrationReason());
|
||||
resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus());
|
||||
resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason());
|
||||
@@ -131,6 +131,13 @@ public class WechatMiniLoginResultVO {
|
||||
return resultVO;
|
||||
}
|
||||
|
||||
private static String maskPhone(String phone) {
|
||||
if (phone == null || phone.length() != 11 || !phone.matches("1[3-9]\\d{9}")) {
|
||||
return phone;
|
||||
}
|
||||
return phone.substring(0, 3) + "****" + phone.substring(7);
|
||||
}
|
||||
|
||||
public static WechatMiniLoginResultVO selectShop(
|
||||
String message,
|
||||
String ticket,
|
||||
|
||||
+86
-14
@@ -27,8 +27,12 @@ import com.xiaowang.jayucloud.salon.core.modules.product.service.ProductService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
@@ -50,7 +54,7 @@ import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/manager")
|
||||
@RequestMapping({"/admin/manager", "/manager"})
|
||||
@RequiredArgsConstructor
|
||||
public class AdminManagerController {
|
||||
|
||||
@@ -141,6 +145,40 @@ public class AdminManagerController {
|
||||
return Result.success(result);
|
||||
}
|
||||
|
||||
@GetMapping("/customers/matches")
|
||||
@RequirePermission("user:view")
|
||||
public Result<List<UserVO>> customerMatches(HttpServletRequest request,
|
||||
@RequestParam String nickname,
|
||||
@RequestParam(required = false) String phone) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(userService.findCustomerMatches(nickname, phone, shopId));
|
||||
}
|
||||
|
||||
@GetMapping("/customers/identity-matches")
|
||||
@RequirePermission("user:view")
|
||||
public Result<List<AppointmentCustomerOptionVO>> customerIdentityMatches(HttpServletRequest request,
|
||||
@RequestParam String nickname,
|
||||
@RequestParam(required = false) String wechatId,
|
||||
@RequestParam(required = false) String phone) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requireShopContext(currentUser);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(userService.findCustomerIdentityMatches(nickname, wechatId, phone, shopId));
|
||||
}
|
||||
|
||||
@GetMapping("/customers/appointment-options")
|
||||
@RequirePermission("user:view")
|
||||
public Result<PageResultVO<AppointmentCustomerOptionVO>> appointmentCustomerOptions(HttpServletRequest request,
|
||||
@RequestParam(defaultValue = "1") Integer page,
|
||||
@RequestParam(defaultValue = "30") Integer size,
|
||||
@RequestParam(required = false) String keyword) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
adminScopeHelper.requireShopContext(currentUser);
|
||||
return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId));
|
||||
}
|
||||
|
||||
@GetMapping("/customers/{id}")
|
||||
@RequirePermission("user:view")
|
||||
public Result<UserVO> customer(HttpServletRequest request, @PathVariable Long id) {
|
||||
@@ -157,18 +195,7 @@ public class AdminManagerController {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再新增客户");
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
String phone = dto.getPhone().trim();
|
||||
UserDTO userDTO = new UserDTO();
|
||||
userDTO.setNickname(dto.getNickname().trim());
|
||||
userDTO.setPhone(phone);
|
||||
userDTO.setContactPhone(phone);
|
||||
userDTO.setAccount(phone);
|
||||
userDTO.setType(0);
|
||||
userDTO.setShopId(shopId);
|
||||
userDTO.setShopIds(List.of(shopId));
|
||||
userDTO.setLevel("普通");
|
||||
userDTO.setVipId(0L);
|
||||
return Result.success(userService.createUser(userDTO));
|
||||
return Result.success(userService.createManagerCustomer(dto.getNickname(), dto.getWechatId(), dto.getPhone(), shopId));
|
||||
}
|
||||
|
||||
@GetMapping("/employees")
|
||||
@@ -201,7 +228,7 @@ public class AdminManagerController {
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getUserId(), "无权编辑其他店铺员工");
|
||||
}
|
||||
return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(dto));
|
||||
return Result.success(nailArtistInfoService.submitNailArtistInfo(dto, currentUser.getId()));
|
||||
}
|
||||
|
||||
@PostMapping("/employees/users")
|
||||
@@ -220,6 +247,22 @@ public class AdminManagerController {
|
||||
return Result.success(userService.createUser(dto));
|
||||
}
|
||||
|
||||
@PostMapping("/employees/users/unlinked")
|
||||
@RequirePermission("user:create")
|
||||
@OperationGuard(action = "manager-user-create-unlinked", ttlSeconds = 10, message = "美甲师档案创建处理中,请勿重复提交")
|
||||
public Result<Long> createUnlinkedEmployee(HttpServletRequest request,
|
||||
@RequestBody UserDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
dto.setType(3);
|
||||
adminScopeHelper.ensureAssignableUserType(currentUser, dto.getType());
|
||||
if (!adminScopeHelper.isPlatformAdmin(currentUser)) {
|
||||
Long managedShopId = adminScopeHelper.getManagedShopId(currentUser);
|
||||
dto.setShopId(managedShopId);
|
||||
dto.setShopIds(List.of(managedShopId));
|
||||
}
|
||||
return Result.success(userService.createUnlinkedEmployee(dto, dto.getShopId()));
|
||||
}
|
||||
|
||||
@GetMapping("/employees/schedules")
|
||||
@RequirePermission("schedule:view")
|
||||
public Result<List<ArtistScheduleVO>> schedules(HttpServletRequest request,
|
||||
@@ -312,4 +355,33 @@ public class AdminManagerController {
|
||||
}
|
||||
return Result.success(shopService.updateShop(shopId, dto));
|
||||
}
|
||||
|
||||
@GetMapping("/shop/appointment-settings")
|
||||
@RequirePermission("shop:view")
|
||||
public Result<ShopAppointmentSettingsVO> appointmentSettings(HttpServletRequest request) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requireShopContext(currentUser);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(shopService.getAppointmentSettings(shopId));
|
||||
}
|
||||
|
||||
@PutMapping("/shop/appointment-settings")
|
||||
@RequirePermission("shop:edit")
|
||||
@OperationGuard(action = "manager-shop-appointment-settings-update", ttlSeconds = 10, message = "预约设置正在保存,请勿重复提交")
|
||||
public Result<Boolean> updateAppointmentSettings(HttpServletRequest request, @RequestBody ShopAppointmentSettingsDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requireShopContext(currentUser);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(shopService.updateAppointmentSettings(shopId, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/shop/name")
|
||||
@RequirePermission("shop:edit")
|
||||
@OperationGuard(action = "manager-shop-name-review", ttlSeconds = 10, message = "门店名称正在提交审核,请勿重复操作")
|
||||
public Result<Boolean> updateShopName(HttpServletRequest request, @RequestBody ShopNameUpdateDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
adminScopeHelper.requireShopContext(currentUser);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(shopService.updateShopName(shopId, dto));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-3
@@ -3,7 +3,6 @@ package com.xiaowang.jayucloud.salon.core.modules.manager.dto;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
@Data
|
||||
public class ManagerCustomerCreateDTO {
|
||||
@@ -11,7 +10,7 @@ public class ManagerCustomerCreateDTO {
|
||||
@NotBlank(message = "客户姓名不能为空")
|
||||
private String nickname;
|
||||
|
||||
@NotBlank(message = "手机号不能为空")
|
||||
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||
private String wechatId;
|
||||
|
||||
private String phone;
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.manager.vo;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class AppointmentCustomerOptionVO {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
private String name;
|
||||
private String phone;
|
||||
private String avatar;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CampaignDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CampaignService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CampaignVO;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/campaign")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminCampaignController {
|
||||
|
||||
private final CampaignService campaignService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("campaign:view")
|
||||
public Result<PageResultVO<CampaignVO>> list(HttpServletRequest request,
|
||||
@RequestParam(required = false) Integer status,
|
||||
@RequestParam(defaultValue = "1") Integer page,
|
||||
@RequestParam(defaultValue = "10") Integer size) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
|
||||
return Result.success(campaignService.listCampaigns(shopId, status, page, size));
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
@RequirePermission("campaign:manage")
|
||||
public Result<CampaignVO> save(HttpServletRequest request, @RequestBody CampaignDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()));
|
||||
try {
|
||||
CampaignVO result = campaignService.saveCampaign(dto);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId());
|
||||
return Result.success(result);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
-182
@@ -1,182 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 后台优惠券管理控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/admin/coupon")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminCouponController {
|
||||
/**
|
||||
* Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final CouponService couponService;
|
||||
/**
|
||||
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserService userService;
|
||||
/**
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建优惠券
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("coupon:create")
|
||||
@OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
|
||||
Long couponId = couponService.createCoupon(couponDTO, shopId);
|
||||
return Result.success(couponId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新优惠券
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("coupon:edit")
|
||||
@OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
|
||||
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券");
|
||||
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
|
||||
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除优惠券
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("coupon:delete")
|
||||
@OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.deleteCoupon(id, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取优惠券详情
|
||||
*/
|
||||
@GetMapping("/detail/{id}")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券");
|
||||
}
|
||||
return Result.success(couponVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取优惠券列表
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
|
||||
return Result.success(pageResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有优惠券
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<List<CouponVO>> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
List<CouponVO> coupons = couponService.listAllCoupons();
|
||||
Long resolvedShopId = shopId;
|
||||
if (resolvedShopId != null) {
|
||||
coupons = coupons.stream()
|
||||
.filter(coupon -> resolvedShopId.equals(coupon.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return Result.success(coupons);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为用户分配优惠券
|
||||
*/
|
||||
@PostMapping("/assign")
|
||||
@RequirePermission("coupon:assign")
|
||||
@OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发放优惠券
|
||||
*/
|
||||
@PostMapping("/distribute")
|
||||
@RequirePermission("coupon:assign")
|
||||
@OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交")
|
||||
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
for (Long userId : userIds) {
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
}
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
}
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.CouponDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.CouponVO;
|
||||
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.UserCouponVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 优惠券控制器
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/coupon")
|
||||
@RequiredArgsConstructor
|
||||
public class CouponController {
|
||||
/**
|
||||
* Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final CouponService couponService;
|
||||
/**
|
||||
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final UserService userService;
|
||||
/**
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
/**
|
||||
* 创建优惠券
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
@RequirePermission("coupon:create")
|
||||
public Result<Long> createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId());
|
||||
Long couponId = couponService.createCoupon(couponDTO, shopId);
|
||||
return Result.success(couponId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新优惠券
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
@RequirePermission("coupon:edit")
|
||||
public Result<Boolean> updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券");
|
||||
Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId());
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId);
|
||||
boolean success = couponService.updateCoupon(id, couponDTO, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除优惠券
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
@RequirePermission("coupon:delete")
|
||||
public Result<Boolean> deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.deleteCoupon(id, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取优惠券详情
|
||||
*/
|
||||
@GetMapping("/detail/{id}")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<CouponVO> getCouponById(HttpServletRequest request, @PathVariable Long id) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(id);
|
||||
if (couponVO != null) {
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券");
|
||||
}
|
||||
return Result.success(couponVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取优惠券列表
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
@RequirePermission("coupon:view")
|
||||
public Result<PageResultVO<CouponVO>> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
|
||||
PageResultVO<CouponVO> pageResult = couponService.listCoupons(page, size, shopId);
|
||||
return Result.success(pageResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为用户分配优惠券
|
||||
*/
|
||||
@PostMapping("/assign")
|
||||
@RequirePermission("coupon:assign")
|
||||
public Result<Boolean> assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.assignCouponToUser(userId, couponId, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户优惠券列表
|
||||
*/
|
||||
@GetMapping("/user/list")
|
||||
public Result<List<UserCouponVO>> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) {
|
||||
List<UserCouponVO> userCoupons = couponService.listUserCoupons(userId, status);
|
||||
return Result.success(userCoupons);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用优惠券
|
||||
*/
|
||||
@PostMapping("/use")
|
||||
public Result<Boolean> useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) {
|
||||
boolean success = couponService.useCoupon(userCouponId, userId);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取商品可用的优惠券
|
||||
*/
|
||||
@GetMapping("/available")
|
||||
public Result<List<UserCouponVO>> getAvailableCoupons(
|
||||
@RequestParam(required = false, defaultValue = "") String productTags,
|
||||
@RequestParam Double productPrice,
|
||||
@RequestParam(required = false) Long shopId,
|
||||
@RequestAttribute("userId") Long userId
|
||||
) {
|
||||
List<UserCouponVO> availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId);
|
||||
return Result.success(availableCoupons);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发放优惠券
|
||||
*/
|
||||
@PostMapping("/distribute")
|
||||
@RequirePermission("coupon:assign")
|
||||
public Result<Boolean> distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List<Long> userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
CouponVO couponVO = couponService.getCouponById(couponId);
|
||||
if (couponVO == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券");
|
||||
for (Long userId : userIds) {
|
||||
UserVO targetUser = userService.getUserById(userId);
|
||||
if (targetUser == null) {
|
||||
return Result.success(false);
|
||||
}
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券");
|
||||
}
|
||||
shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId());
|
||||
boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId);
|
||||
return Result.success(success);
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.GrowthService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.GrowthSummaryVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/growth")
|
||||
@RequiredArgsConstructor
|
||||
public class GrowthController {
|
||||
|
||||
private final GrowthService growthService;
|
||||
|
||||
@GetMapping("/summary")
|
||||
public Result<GrowthSummaryVO> summary(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(growthService.getSummary(userId));
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.ProductLikeService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* 商品点赞控制器
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-03-05
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/product-like")
|
||||
@RequiredArgsConstructor
|
||||
public class ProductLikeController {
|
||||
/**
|
||||
* Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ProductLikeService productLikeService;
|
||||
|
||||
/**
|
||||
* 点赞商品
|
||||
*
|
||||
* @param userId 当前用户ID
|
||||
* @param productId 商品ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
@PostMapping("/like/{productId}")
|
||||
@OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Boolean> likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
|
||||
productLikeService.addLike(userId, productId);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消点赞商品
|
||||
*
|
||||
* @param userId 当前用户ID
|
||||
* @param productId 商品ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
@PostMapping("/unlike/{productId}")
|
||||
@OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Boolean> unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
|
||||
productLikeService.removeLike(userId, productId);
|
||||
return Result.success(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否已点赞商品
|
||||
*
|
||||
* @param userId 当前用户ID
|
||||
* @param productId 商品ID
|
||||
* @return 是否已点赞
|
||||
*/
|
||||
@GetMapping("/check/{productId}")
|
||||
public Result<Boolean> checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) {
|
||||
boolean isLiked = productLikeService.isProductLiked(userId, productId);
|
||||
return Result.success(isLiked);
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipBenefitDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipBenefitVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipBenefitService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* VIP权益信息表 Controller
|
||||
* 对应数据库表 t_vip_benefit
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping({"/vip-benefit", "/api/vip-benefit"})
|
||||
@RequiredArgsConstructor
|
||||
public class VipBenefitController {
|
||||
/**
|
||||
* Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final VipBenefitService vipBenefitService;
|
||||
|
||||
/**
|
||||
* 创建VIP权益
|
||||
*
|
||||
* @param vipBenefitDTO VIP权益DTO
|
||||
* @return VIP权益ID
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
public Result<Long> createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) {
|
||||
Long id = vipBenefitService.createVipBenefit(vipBenefitDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新VIP权益
|
||||
*
|
||||
* @param id VIP权益ID
|
||||
* @param vipBenefitDTO VIP权益DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
public Result<Boolean> updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) {
|
||||
boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除VIP权益
|
||||
*
|
||||
* @param id VIP权益ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public Result<Boolean> deleteVipBenefit(@PathVariable Long id) {
|
||||
boolean success = vipBenefitService.deleteVipBenefit(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询VIP权益
|
||||
*
|
||||
* @param id VIP权益ID
|
||||
* @return VIP权益VO
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<VipBenefitVO> getVipBenefitById(@PathVariable Long id) {
|
||||
VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id);
|
||||
return Result.success(vipBenefitVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有VIP权益
|
||||
*
|
||||
* @return VIP权益VO列表
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
public Result<List<VipBenefitVO>> listAllVipBenefits() {
|
||||
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listAllVipBenefits();
|
||||
return Result.success(vipBenefitVOs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据所需VIP等级查询VIP权益
|
||||
*
|
||||
* @param requiredVipLevel 所需VIP等级
|
||||
* @return VIP权益VO列表
|
||||
*/
|
||||
@GetMapping("/list/requiredVipLevel/{requiredVipLevel}")
|
||||
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) {
|
||||
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel);
|
||||
return Result.success(vipBenefitVOs);
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipInfoDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipInfoVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipInfoService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户VIP信息表 Controller
|
||||
* 对应数据库表 t_vip_info
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping({"/vip-info", "/api/vip-info"})
|
||||
@RequiredArgsConstructor
|
||||
public class VipInfoController {
|
||||
/**
|
||||
* Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final VipInfoService vipInfoService;
|
||||
|
||||
/**
|
||||
* 创建VIP信息
|
||||
*
|
||||
* @param vipInfoDTO VIP信息DTO
|
||||
* @return VIP信息ID
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
public Result<Long> createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) {
|
||||
Long id = vipInfoService.createVipInfo(vipInfoDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新VIP信息
|
||||
*
|
||||
* @param id VIP信息ID
|
||||
* @param vipInfoDTO VIP信息DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
public Result<Boolean> updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) {
|
||||
boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除VIP信息
|
||||
*
|
||||
* @param id VIP信息ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public Result<Boolean> deleteVipInfo(@PathVariable Long id) {
|
||||
boolean success = vipInfoService.deleteVipInfo(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询VIP信息
|
||||
*
|
||||
* @param id VIP信息ID
|
||||
* @return VIP信息VO
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<VipInfoVO> getVipInfoById(@PathVariable Long id) {
|
||||
VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id);
|
||||
return Result.success(vipInfoVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有VIP信息
|
||||
*
|
||||
* @return VIP信息VO列表
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
public Result<List<VipInfoVO>> listAllVipInfos() {
|
||||
List<VipInfoVO> vipInfoVOs = vipInfoService.listAllVipInfos();
|
||||
return Result.success(vipInfoVOs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据VIP等级查询VIP信息
|
||||
*
|
||||
* @param vipLevel VIP等级
|
||||
* @return VIP信息VO列表
|
||||
*/
|
||||
@GetMapping("/list/vipLevel/{vipLevel}")
|
||||
public Result<List<VipInfoVO>> listVipInfosByVipLevel(@PathVariable String vipLevel) {
|
||||
List<VipInfoVO> vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel);
|
||||
return Result.success(vipInfoVOs);
|
||||
}
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.VipRechargePlanDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.VipRechargePlanService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.VipRechargePlanVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"})
|
||||
/**
|
||||
* VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
|
||||
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
|
||||
*/
|
||||
public class VipRechargePlanController {
|
||||
/**
|
||||
* Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final VipRechargePlanService vipRechargePlanService;
|
||||
/**
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
|
||||
@GetMapping("/admin/list")
|
||||
@RequirePermission("user:vip:manage")
|
||||
/**
|
||||
* Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<List<VipRechargePlanVO>> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId));
|
||||
}
|
||||
|
||||
@PostMapping("/admin/create")
|
||||
@RequirePermission("user:vip:manage")
|
||||
@OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交")
|
||||
/**
|
||||
* Create a new record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @param dto parameter `dto` supplied by the caller
|
||||
* @return Result<Long> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Long> create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
return Result.success(vipRechargePlanService.createPlan(currentUser, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/admin/{id}")
|
||||
@RequirePermission("user:vip:manage")
|
||||
@OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交")
|
||||
/**
|
||||
* Update an existing record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @param id parameter `id` supplied by the caller
|
||||
* @param dto parameter `dto` supplied by the caller
|
||||
* @return Result<Boolean> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Boolean> update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/admin/{id}/status")
|
||||
@RequirePermission("user:vip:manage")
|
||||
/**
|
||||
* Change the enabled/status flag of one record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @param id parameter `id` supplied by the caller
|
||||
* @param status parameter `status` supplied by the caller
|
||||
* @return Result<Boolean> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Boolean> updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status));
|
||||
}
|
||||
|
||||
@GetMapping("/my/list")
|
||||
/**
|
||||
* List records for the current query or current user scope.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<List<VipRechargePlanVO>> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<List<VipRechargePlanVO>> listMy(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(vipRechargePlanService.listMyPlans(userId));
|
||||
}
|
||||
|
||||
@GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"})
|
||||
/**
|
||||
* Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role.
|
||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
public Result<List<String>> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId));
|
||||
}
|
||||
}
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.marketing.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistAddWithGroupDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistGroupDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.dto.WishlistMoveDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.WishlistService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistGroupVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.vo.WishlistInspirationVO;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/wishlist")
|
||||
public class WishlistController {
|
||||
|
||||
@Autowired
|
||||
private WishlistService wishlistService;
|
||||
|
||||
@PostMapping("/add")
|
||||
@OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<?> addToWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
|
||||
wishlistService.addToWishlist(userId, request.get("productId"));
|
||||
return Result.success("ok");
|
||||
}
|
||||
|
||||
@PostMapping("/add-with-group")
|
||||
@OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<?> addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) {
|
||||
wishlistService.addToWishlist(userId, request);
|
||||
return Result.success("ok");
|
||||
}
|
||||
|
||||
@PostMapping("/remove")
|
||||
@OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<?> removeFromWishlist(@RequestBody Map<String, Long> request, @RequestAttribute("userId") Long userId) {
|
||||
wishlistService.removeFromWishlist(userId, request.get("productId"));
|
||||
return Result.success("ok");
|
||||
}
|
||||
|
||||
@GetMapping("/check")
|
||||
public Result<Boolean> checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.isInWishlist(userId, productId));
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public Result<List<WishlistDTO>> getWishlist(@RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.getWishlistByUserId(userId));
|
||||
}
|
||||
|
||||
@GetMapping("/groups")
|
||||
public Result<List<WishlistGroupVO>> listGroups(@RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.listGroups(userId));
|
||||
}
|
||||
|
||||
@PostMapping("/groups")
|
||||
public Result<Long> createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.createGroup(userId, request));
|
||||
}
|
||||
|
||||
@PutMapping("/groups/{id}")
|
||||
public Result<Boolean> updateGroup(
|
||||
@PathVariable Long id,
|
||||
@RequestBody WishlistGroupDTO request,
|
||||
@RequestAttribute("userId") Long userId
|
||||
) {
|
||||
return Result.success(wishlistService.updateGroup(userId, id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/groups/{id}")
|
||||
public Result<Boolean> deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.deleteGroup(userId, id));
|
||||
}
|
||||
|
||||
@PostMapping("/move")
|
||||
@OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
public Result<Boolean> moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.moveWishlist(userId, request));
|
||||
}
|
||||
|
||||
@GetMapping("/inspiration")
|
||||
public Result<WishlistInspirationVO> getInspiration(@RequestAttribute("userId") Long userId) {
|
||||
return Result.success(wishlistService.getInspiration(userId));
|
||||
}
|
||||
}
|
||||
+3
@@ -27,6 +27,9 @@ public class AnnouncementCreateDTO {
|
||||
*/
|
||||
private String content;
|
||||
|
||||
/** 公告图片文件ID集合,多个ID以逗号分隔。 */
|
||||
private String imageFileIds;
|
||||
|
||||
@NotBlank(message = "公告范围不能为空")
|
||||
/**
|
||||
* Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
|
||||
+6
@@ -30,6 +30,9 @@ public class AnnouncementDO extends BaseEntity {
|
||||
*/
|
||||
private String content;
|
||||
|
||||
@TableField("image_file_ids")
|
||||
private String imageFileIds;
|
||||
|
||||
@TableField("publisher_id")
|
||||
/**
|
||||
* Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
@@ -66,6 +69,9 @@ public class AnnouncementDO extends BaseEntity {
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
|
||||
@TableField("sort_order")
|
||||
/**
|
||||
* Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
|
||||
+3
@@ -106,6 +106,9 @@ public class SystemMessageDO extends BaseEntity {
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
|
||||
@TableField("publish_time")
|
||||
/**
|
||||
* Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
|
||||
+4
@@ -2,10 +2,14 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows.
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
*/
|
||||
public interface AnnouncementMapper extends BaseMapper<AnnouncementDO> {
|
||||
@Select("SELECT COUNT(1) FROM t_announcement WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+4
@@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
@Mapper
|
||||
/**
|
||||
@@ -10,4 +12,6 @@ import org.apache.ibatis.annotations.Mapper;
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
*/
|
||||
public interface SystemMessageMapper extends BaseMapper<SystemMessageDO> {
|
||||
@Select("SELECT COUNT(1) FROM t_system_message WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND image_file_id = #{fileId}")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+52
-2
@@ -13,8 +13,11 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.service.AnnouncementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.AnnouncementVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -83,6 +86,9 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -99,16 +105,28 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
AnnouncementDO announcement = new AnnouncementDO();
|
||||
announcement.setTitle(dto.getTitle().trim());
|
||||
announcement.setContent(dto.getContent().trim());
|
||||
announcement.setImageFileIds(normalizeImageFileIds(dto.getImageFileIds()));
|
||||
announcement.setPublisherId(currentUser.getId());
|
||||
announcement.setPublisherName(resolvePublisherName(currentUser));
|
||||
announcement.setPublisherType(currentUser.getType());
|
||||
announcement.setTargetType(targetType);
|
||||
announcement.setTargetIds(joinIds(targetIds));
|
||||
announcement.setStatus(1);
|
||||
announcement.setStatus(0);
|
||||
announcement.setModerationStatus("PENDING");
|
||||
announcement.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder());
|
||||
announcement.setPublishTime(LocalDateTime.now());
|
||||
announcement.setIsDelete(0);
|
||||
announcementMapper.insert(announcement);
|
||||
try {
|
||||
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("title", announcement.getTitle()); payload.put("content", announcement.getContent());
|
||||
payload.put("imageFileIds", announcement.getImageFileIds()); payload.put("status", 1);
|
||||
contentModerationService.assessVersion("ANNOUNCEMENT", announcement.getId(), currentUser.getId(),
|
||||
announcement.getTitle() + "\n" + announcement.getContent(), objectMapper.writeValueAsString(payload),
|
||||
parseImageFileIds(announcement.getImageFileIds()));
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("公告审核任务创建失败", exception);
|
||||
}
|
||||
return announcement.getId();
|
||||
}
|
||||
|
||||
@@ -212,7 +230,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setNickname(user.getNickname());
|
||||
vo.setAccount(user.getAccount());
|
||||
vo.setAccount(phoneCrypto.mask(user.getAccount()));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
@@ -233,6 +251,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
return announcementMapper.selectList(new LambdaQueryWrapper<AnnouncementDO>()
|
||||
.eq(AnnouncementDO::getIsDelete, 0)
|
||||
.eq(AnnouncementDO::getStatus, 1)
|
||||
.eq(AnnouncementDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(AnnouncementDO::getSortOrder)
|
||||
.orderByDesc(AnnouncementDO::getPublishTime))
|
||||
.stream()
|
||||
@@ -373,6 +392,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
vo.setId(item.getId());
|
||||
vo.setTitle(item.getTitle());
|
||||
vo.setContent(item.getContent());
|
||||
vo.setImageFileIds(parseImageFileIds(item.getImageFileIds()));
|
||||
vo.setPublisherId(item.getPublisherId());
|
||||
vo.setPublisherName(item.getPublisherName());
|
||||
vo.setPublisherType(item.getPublisherType());
|
||||
@@ -475,6 +495,36 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
|
||||
return ids.stream().map(String::valueOf).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
private String normalizeImageFileIds(String value) {
|
||||
return parseImageFileIdsStrict(value).stream().map(String::valueOf).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
private List<Long> parseImageFileIdsStrict(String value) {
|
||||
if (!StringUtils.hasText(value)) return List.of();
|
||||
return java.util.Arrays.stream(value.split(","))
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(token -> {
|
||||
try {
|
||||
long id = Long.parseLong(token);
|
||||
if (id <= 0) throw new NumberFormatException("file id must be positive");
|
||||
return id;
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new IllegalArgumentException("公告图片必须引用已上传文件", exception);
|
||||
}
|
||||
})
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<Long> parseImageFileIds(String value) {
|
||||
if (!StringUtils.hasText(value)) return List.of();
|
||||
return java.util.Arrays.stream(value.split(","))
|
||||
.map(String::trim).filter(StringUtils::hasText)
|
||||
.map(token -> { try { return Long.valueOf(token); } catch (NumberFormatException ignored) { return null; } })
|
||||
.filter(id -> id != null && id > 0).distinct().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `targetTypeName`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+23
-4
@@ -16,10 +16,13 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapp
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.service.SystemMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.message.vo.SystemMessageVO;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -97,10 +100,13 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
/**
|
||||
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -153,14 +159,26 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
message.setPublisherType(currentUser.getType());
|
||||
message.setTargetType(targetType);
|
||||
message.setTargetIds(joinIds(targetIds));
|
||||
message.setBusinessType(trimToNull(dto.getBusinessType()));
|
||||
message.setBusinessId(dto.getBusinessId());
|
||||
// Business metadata is reserved for server-created transaction messages.
|
||||
// Never let an admin request mark an arbitrary message as an auto-approved event.
|
||||
message.setBusinessType(null);
|
||||
message.setBusinessId(null);
|
||||
message.setActionPath(trimToNull(dto.getActionPath()));
|
||||
message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1);
|
||||
message.setStatus(1);
|
||||
message.setStatus(0);
|
||||
message.setModerationStatus("PENDING");
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
message.setIsDelete(0);
|
||||
systemMessageMapper.insert(message);
|
||||
try {
|
||||
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("title", title); payload.put("content", content); payload.put("imageFileId", dto.getImageFileId()); payload.put("status", 1);
|
||||
List<Long> imageIds = dto.getImageFileId() == null ? List.of() : List.of(dto.getImageFileId());
|
||||
contentModerationService.assessVersion("SYSTEM_MESSAGE", message.getId(), currentUser.getId(),
|
||||
title + "\n" + content, objectMapper.writeValueAsString(payload), imageIds);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("站内消息审核任务创建失败", exception);
|
||||
}
|
||||
return message.getId();
|
||||
}
|
||||
|
||||
@@ -267,7 +285,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
|
||||
vo.setId(user.getId());
|
||||
vo.setNickname(user.getNickname());
|
||||
vo.setAccount(user.getAccount());
|
||||
vo.setAccount(phoneCrypto.mask(user.getAccount()));
|
||||
vo.setShopId(user.getShopId());
|
||||
vo.setShopName(shopNameMap.get(user.getShopId()));
|
||||
vo.setType(user.getType());
|
||||
@@ -427,6 +445,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
||||
return systemMessageMapper.selectList(new LambdaQueryWrapper<SystemMessageDO>()
|
||||
.eq(SystemMessageDO::getIsDelete, 0)
|
||||
.eq(SystemMessageDO::getStatus, 1)
|
||||
.eq(SystemMessageDO::getModerationStatus, "APPROVED")
|
||||
.orderByDesc(SystemMessageDO::getPublishTime))
|
||||
.stream()
|
||||
.filter(message -> isMessageVisibleToUser(message, user))
|
||||
|
||||
+1
@@ -23,6 +23,7 @@ public class AnnouncementVO {
|
||||
* Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
private String content;
|
||||
private List<Long> imageFileIds;
|
||||
/**
|
||||
* Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||
*/
|
||||
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.order.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CartDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.CartService;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.OperationGuardStrategy;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CartVO;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/cart")
|
||||
/**
|
||||
* CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
|
||||
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
|
||||
*/
|
||||
public class CartController {
|
||||
|
||||
@Resource
|
||||
/**
|
||||
* Purpose: cartService supports CartController.java by holding or executing the cart service business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private CartService cartService;
|
||||
|
||||
@PostMapping("/add")
|
||||
@OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
|
||||
/**
|
||||
* Add a new record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param cartDTO parameter `cartDTO` supplied by the caller
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.addToCart(userId, cartDTO);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@DeleteMapping("/remove/{productId}")
|
||||
@OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
/**
|
||||
* Remove a record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param productId parameter `productId` supplied by the caller
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> removeFromCart(@PathVariable Long productId, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.removeFromCart(userId, productId);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PostMapping("/batch-remove")
|
||||
@OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
/**
|
||||
* Run business method `batchRemoveFromCart`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param cartItemIds parameter `cartItemIds` supplied by the caller
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> batchRemoveFromCart(@RequestBody List<Long> cartItemIds, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.batchRemoveFromCart(userId, cartItemIds);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PutMapping("/update")
|
||||
@OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作")
|
||||
/**
|
||||
* Update an existing record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param cartDTO parameter `cartDTO` supplied by the caller
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.updateCartQuantity(userId, cartDTO);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<List<CartVO>> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<List<CartVO>> getCartList(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
List<CartVO> cartList = cartService.getCartList(userId);
|
||||
return Result.success(cartList);
|
||||
}
|
||||
|
||||
@DeleteMapping("/clear")
|
||||
@OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10)
|
||||
/**
|
||||
* Run business method `clearCart`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> clearCart(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
cartService.clearCart(userId);
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
+4
-10
@@ -3,7 +3,6 @@ package com.xiaowang.jayucloud.salon.core.modules.order.controller.front;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO;
|
||||
@@ -14,7 +13,6 @@ import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO;
|
||||
@@ -73,12 +71,6 @@ public class OrderController {
|
||||
return Result.success(orderVO);
|
||||
}
|
||||
|
||||
@PostMapping("/checkout-preview")
|
||||
public Result<CheckoutPreviewVO> checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO));
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
@@ -115,9 +107,11 @@ public class OrderController {
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> cancelOrder(@PathVariable Long orderId, HttpServletRequest request) {
|
||||
public Result<Void> cancelOrder(@PathVariable Long orderId,
|
||||
@RequestParam(required = false) String cancelReason,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
orderService.cancelOrder(orderId, userId);
|
||||
orderService.cancelOrder(orderId, userId, cancelReason);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -67,6 +67,9 @@ public class OrderArtistReviewDO extends BaseEntity {
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
@TableField("moderation_status")
|
||||
private String moderationStatus;
|
||||
|
||||
@TableField("rating_score")
|
||||
/**
|
||||
* Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role.
|
||||
|
||||
+8
-1
@@ -1,6 +1,9 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.order.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -8,7 +11,7 @@ import java.time.LocalDateTime;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
@Data
|
||||
@TableName("t_order")
|
||||
@TableName(value = "t_order", autoResultMap = true)
|
||||
/**
|
||||
* OrderDO maps to a database table row. Mapper classes persist and query this object.
|
||||
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
|
||||
@@ -54,8 +57,12 @@ public class OrderDO extends BaseEntity {
|
||||
private String paymentOrderNo;
|
||||
private String refundStatus;
|
||||
private String customerRemark;
|
||||
private String cancelReason;
|
||||
private String customerNameSnapshot;
|
||||
@TableField(typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String customerPhoneSnapshot;
|
||||
@TableField(value = "customer_phone_snapshot_hash", fill = FieldFill.INSERT_UPDATE)
|
||||
private String customerPhoneSnapshotHash;
|
||||
private String quoteStatus;
|
||||
private String orderSource;
|
||||
private Integer quoteUserConfirmed;
|
||||
|
||||
+19
-1
@@ -25,6 +25,24 @@ public interface OrderArtistReviewMapper extends BaseMapper<OrderArtistReviewDO>
|
||||
@Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1")
|
||||
OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId);
|
||||
|
||||
@Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0")
|
||||
@Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0 AND moderation_status = 'APPROVED'")
|
||||
BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId);
|
||||
|
||||
@Select("SELECT COUNT(1) FROM t_order_artist_review r "
|
||||
+ "LEFT JOIN t_product p ON p.id = r.product_id "
|
||||
+ "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) "
|
||||
+ "WHERE r.id = #{reviewId} AND r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' "
|
||||
+ "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' "
|
||||
+ "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' "
|
||||
+ "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("reviewId") Long reviewId, @Param("fileId") Long fileId);
|
||||
|
||||
@Select("SELECT COUNT(1) FROM t_order_artist_review r "
|
||||
+ "LEFT JOIN t_product p ON p.id = r.product_id "
|
||||
+ "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) "
|
||||
+ "WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' "
|
||||
+ "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' "
|
||||
+ "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' "
|
||||
+ "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0")
|
||||
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||
}
|
||||
|
||||
+5
-8
@@ -1,14 +1,12 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.order.service;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistReviewSubmitDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteReplyDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderQuoteSubmitDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistCalendarAppointmentVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO;
|
||||
@@ -31,11 +29,6 @@ public interface OrderService {
|
||||
*/
|
||||
OrderVO createOrder(Long userId, OrderDTO orderDTO);
|
||||
|
||||
/**
|
||||
* Preview checkout pricing and coupon explanations without creating an order.
|
||||
*/
|
||||
CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO);
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -57,7 +50,11 @@ public interface OrderService {
|
||||
* @param orderId parameter `orderId` supplied by the caller
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
*/
|
||||
void cancelOrder(Long orderId, Long userId);
|
||||
default void cancelOrder(Long orderId, Long userId) {
|
||||
cancelOrder(orderId, userId, null);
|
||||
}
|
||||
|
||||
void cancelOrder(Long orderId, Long userId, String cancelReason);
|
||||
/**
|
||||
* Run business method `processOrder`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+1
@@ -145,6 +145,7 @@ public class AfterSaleServiceImpl implements AfterSaleService {
|
||||
message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId());
|
||||
message.setPopupEnabled(1);
|
||||
message.setStatus(1);
|
||||
message.setModerationStatus("APPROVED");
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
message.setIsDelete(0);
|
||||
systemMessageMapper.insert(message);
|
||||
|
||||
+73
-109
@@ -3,8 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.order.service.impl;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.CheckoutPreviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRejectDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistChangeRequestDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderArtistReviewSubmitDTO;
|
||||
@@ -41,20 +41,25 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.BusinessEventOutboxService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.service.TagService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStateMachine;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistCalendarAppointmentVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutCouponPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO.CheckoutIssueVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeOptionsVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutCouponPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.CheckoutPreviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistChangeRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderArtistReviewVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderItemVO;
|
||||
@@ -284,6 +289,15 @@ public class OrderServiceImpl implements OrderService {
|
||||
*/
|
||||
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||
|
||||
@Resource
|
||||
private ContentModerationService contentModerationService;
|
||||
|
||||
@Resource
|
||||
private ObjectStorageFileService objectStorageFileService;
|
||||
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Resource
|
||||
/**
|
||||
* Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role.
|
||||
@@ -419,6 +433,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
@Resource
|
||||
private WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
|
||||
@PreDestroy
|
||||
/**
|
||||
* Run business method `shutdownOrderLockRenewExecutor`.
|
||||
@@ -530,53 +547,6 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) {
|
||||
OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO);
|
||||
CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO);
|
||||
List<CheckoutIssueVO> bookingIssues = collectCheckoutBookingIssues(userId, orderDTO);
|
||||
List<UserCouponVO> availableCouponOptions = couponService.getAvailableCoupons(
|
||||
userId,
|
||||
pricingContext.getProductTagNames(),
|
||||
pricingContext.getTotalAmount().doubleValue(),
|
||||
pricingContext.getShopId()
|
||||
);
|
||||
if (availableCouponOptions == null) {
|
||||
availableCouponOptions = List.of();
|
||||
}
|
||||
|
||||
List<CheckoutCouponPreviewVO> availableCoupons = availableCouponOptions.stream()
|
||||
.map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount()))
|
||||
.sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed()
|
||||
.thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo)))
|
||||
.toList();
|
||||
|
||||
CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons);
|
||||
if (bestCoupon != null) {
|
||||
bestCoupon.setBest(true);
|
||||
}
|
||||
|
||||
CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon);
|
||||
BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount());
|
||||
BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount);
|
||||
if (payableAmount.compareTo(BigDecimal.ZERO) < 0) {
|
||||
payableAmount = BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
CheckoutPreviewVO preview = new CheckoutPreviewVO();
|
||||
preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount()));
|
||||
preview.setSavedAmount(scaleMoney(savedAmount));
|
||||
preview.setPayableAmount(scaleMoney(payableAmount));
|
||||
preview.setBestCoupon(bestCoupon);
|
||||
preview.setAvailableCoupons(availableCoupons);
|
||||
preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext));
|
||||
preview.setBookingAvailable(bookingIssues.isEmpty());
|
||||
preview.setBookingIssues(bookingIssues);
|
||||
preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons));
|
||||
preview.setSummaryText(buildCheckoutSummaryText(preview));
|
||||
return preview;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new record.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -836,63 +806,6 @@ public class OrderServiceImpl implements OrderService {
|
||||
return buildOrderVO(order);
|
||||
}
|
||||
|
||||
private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) {
|
||||
OrderDTO orderDTO = new OrderDTO();
|
||||
if (checkoutPreviewDTO == null) {
|
||||
return orderDTO;
|
||||
}
|
||||
orderDTO.setCouponId(checkoutPreviewDTO.getCouponId());
|
||||
orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType());
|
||||
orderDTO.setRemark(checkoutPreviewDTO.getRemark());
|
||||
orderDTO.setItems(checkoutPreviewDTO.getItems());
|
||||
return orderDTO;
|
||||
}
|
||||
|
||||
private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) {
|
||||
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
|
||||
throw new RuntimeException("订单项不能为空");
|
||||
}
|
||||
|
||||
List<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
|
||||
Map<Long, Integer> requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs);
|
||||
BigDecimal totalAmount = BigDecimal.ZERO;
|
||||
Set<String> selectedTagNames = new LinkedHashSet<>();
|
||||
Long shopId = null;
|
||||
|
||||
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
|
||||
validateOrderQuantity(orderItemDTO.getQuantity());
|
||||
ProductDO product = productMapper.selectById(orderItemDTO.getProductId());
|
||||
if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) {
|
||||
throw new RuntimeException("商品不存在或已下架");
|
||||
}
|
||||
|
||||
CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId());
|
||||
Integer requestedQuantity = requestedQuantityByProductId.get(product.getId());
|
||||
if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) {
|
||||
throw new RuntimeException("请先将商品加入购物车后再结算");
|
||||
}
|
||||
if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) {
|
||||
throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试");
|
||||
}
|
||||
|
||||
if (shopId == null) {
|
||||
shopId = product.getShopId();
|
||||
validateUserCanCreateOrderInShop(userId, shopId);
|
||||
} else if (!shopId.equals(product.getShopId())) {
|
||||
throw new RuntimeException("跨店铺商品请分开下单");
|
||||
}
|
||||
|
||||
collectPreviewTagNames(selectedTagNames, product.getTags());
|
||||
BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice();
|
||||
totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity())));
|
||||
}
|
||||
|
||||
if (totalAmount.compareTo(BigDecimal.ZERO) == 0) {
|
||||
throw new RuntimeException("订单金额无效");
|
||||
}
|
||||
return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames));
|
||||
}
|
||||
|
||||
private List<CheckoutIssueVO> collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) {
|
||||
List<CheckoutIssueVO> issues = new ArrayList<>();
|
||||
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
|
||||
@@ -1454,6 +1367,12 @@ public class OrderServiceImpl implements OrderService {
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
*/
|
||||
public void cancelOrder(Long orderId, Long userId) {
|
||||
cancelOrder(orderId, userId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void cancelOrder(Long orderId, Long userId, String cancelReason) {
|
||||
OrderDO order = orderMapper.selectById(orderId);
|
||||
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||
/**
|
||||
@@ -1483,6 +1402,8 @@ public class OrderServiceImpl implements OrderService {
|
||||
|
||||
OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode());
|
||||
order.setStatus(3);
|
||||
String normalizedReason = StringUtils.hasText(cancelReason) ? cancelReason.trim() : "客户取消预约";
|
||||
order.setCancelReason(normalizedReason.length() > 255 ? normalizedReason.substring(0, 255) : normalizedReason);
|
||||
if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) {
|
||||
order.setQuoteStatus(QUOTE_STATUS_EXPIRED);
|
||||
order.setQuoteUserConfirmed(0);
|
||||
@@ -1491,6 +1412,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
appointmentCapacityService.releaseByOrder(orderId);
|
||||
enqueueCancellationMessages(orderId);
|
||||
/**
|
||||
* Run business method `restoreUserCoupon`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -1550,12 +1472,17 @@ public class OrderServiceImpl implements OrderService {
|
||||
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||
}
|
||||
order.setStatus(status);
|
||||
if (targetStatus == OrderStatus.CANCELLED && !StringUtils.hasText(order.getCancelReason())) {
|
||||
order.setCancelReason("门店取消预约");
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
if (targetStatus == OrderStatus.COMPLETED) {
|
||||
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||
}
|
||||
if (targetStatus == OrderStatus.CANCELLED) {
|
||||
appointmentCapacityService.releaseByOrder(order.getId());
|
||||
restoreUserCoupon(order, order.getUserId());
|
||||
enqueueCancellationMessages(order.getId());
|
||||
if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) {
|
||||
order.setQuoteStatus(QUOTE_STATUS_EXPIRED);
|
||||
order.setQuoteUserConfirmed(0);
|
||||
@@ -1566,6 +1493,21 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
private void enqueueCancellationMessages(Long orderId) {
|
||||
if (orderId == null) {
|
||||
return;
|
||||
}
|
||||
List<OrderItemDO> items = orderItemMapper.selectByOrderId(orderId);
|
||||
if (items == null) {
|
||||
return;
|
||||
}
|
||||
for (OrderItemDO item : items) {
|
||||
if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) {
|
||||
wechatSubscribeMessageService.enqueueCancellationNotice(orderId, item.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
/**
|
||||
@@ -1791,9 +1733,25 @@ public class OrderServiceImpl implements OrderService {
|
||||
review.setRatingScore(rating);
|
||||
review.setContent(trimToNull(dto == null ? null : dto.getContent()));
|
||||
review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds()));
|
||||
review.setModerationStatus("PENDING");
|
||||
review.setStatus(REVIEW_STATUS_SUBMITTED);
|
||||
review.setSubmittedAt(LocalDateTime.now());
|
||||
orderArtistReviewMapper.updateById(review);
|
||||
try {
|
||||
java.util.Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("content", review.getContent());
|
||||
payload.put("imageFileIds", review.getImageFileIds());
|
||||
List<Long> imageIds = parseIdSet(review.getImageFileIds()).stream().toList();
|
||||
ContentModerationResultVO moderation = contentModerationService.assessVersion(
|
||||
"ORDER_ARTIST_REVIEW", review.getId(), userId, review.getContent(),
|
||||
objectMapper.writeValueAsString(payload), imageIds);
|
||||
if (moderation != null && "APPROVED".equals(moderation.getStatus())) {
|
||||
review.setModerationStatus("APPROVED");
|
||||
orderArtistReviewMapper.updateById(review);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("评价审核任务创建失败", exception);
|
||||
}
|
||||
refreshArtistRating(review.getArtistId());
|
||||
return buildArtistReviewVO(review);
|
||||
}
|
||||
@@ -2144,6 +2102,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
review.setArtistId(item.getArtistId());
|
||||
review.setCustomerId(order.getUserId());
|
||||
review.setStatus(REVIEW_STATUS_PENDING);
|
||||
review.setModerationStatus("APPROVED");
|
||||
review.setIsDelete(0);
|
||||
review = insertPendingArtistReview(review);
|
||||
if (review == null || review.getId() == null) {
|
||||
@@ -2220,8 +2179,11 @@ public class OrderServiceImpl implements OrderService {
|
||||
vo.setCustomerId(review.getCustomerId());
|
||||
vo.setRating(review.getRatingScore());
|
||||
vo.setRatingScore(review.getRatingScore());
|
||||
vo.setContent(review.getContent());
|
||||
vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds())));
|
||||
boolean moderationApproved = "APPROVED".equals(review.getModerationStatus());
|
||||
vo.setContent(moderationApproved ? review.getContent() : null);
|
||||
vo.setImageFileIds(moderationApproved
|
||||
? new ArrayList<>(parseIdSet(review.getImageFileIds()))
|
||||
: new ArrayList<>());
|
||||
vo.setStatus(review.getStatus());
|
||||
vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价");
|
||||
vo.setReminderMessageId(review.getReminderMessageId());
|
||||
@@ -3063,6 +3025,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
message.setActionPath(actionPath);
|
||||
message.setPopupEnabled(1);
|
||||
message.setStatus(1);
|
||||
message.setModerationStatus("APPROVED");
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
message.setIsDelete(0);
|
||||
systemMessageMapper.insert(message);
|
||||
@@ -3102,6 +3065,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
message.setIdempotencyKey(idempotencyKey);
|
||||
message.setPopupEnabled(1);
|
||||
message.setStatus(1);
|
||||
message.setModerationStatus("APPROVED");
|
||||
message.setPublishTime(LocalDateTime.now());
|
||||
message.setIsDelete(0);
|
||||
try {
|
||||
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.RefundOrderVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/payment")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminPaymentController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final SecurityAuditSupport securityAuditSupport;
|
||||
|
||||
@PostMapping("/order/{orderId}/manual-confirm")
|
||||
@RequirePermission("payment:manage")
|
||||
public Result<PaymentOrderVO> manualConfirm(HttpServletRequest request,
|
||||
@PathVariable Long orderId,
|
||||
@RequestParam(required = false) String remark) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
try {
|
||||
PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId);
|
||||
return Result.success(result);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/order/{orderId}/manual-refund")
|
||||
@RequirePermission("refund:manage")
|
||||
public Result<RefundOrderVO> manualRefund(HttpServletRequest request,
|
||||
@PathVariable Long orderId,
|
||||
@RequestParam(required = false) Long afterSaleId,
|
||||
@RequestParam(required = false) String remark) {
|
||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||
try {
|
||||
RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark);
|
||||
securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId);
|
||||
return Result.success(result);
|
||||
} catch (RuntimeException exception) {
|
||||
securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage());
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceChangeDetailDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceChangeDetailService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户余额变动明细表 Controller
|
||||
* 对应数据库表 t_balance_change_detail
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"})
|
||||
@RequiredArgsConstructor
|
||||
public class BalanceChangeDetailController {
|
||||
/**
|
||||
* Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final BalanceChangeDetailService balanceChangeDetailService;
|
||||
|
||||
/**
|
||||
* 创建余额变动明细
|
||||
*
|
||||
* @param balanceChangeDetailDTO 余额变动明细DTO
|
||||
* @return 余额变动明细ID
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
public Result<Long> createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) {
|
||||
Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新余额变动明细
|
||||
*
|
||||
* @param id 余额变动明细ID
|
||||
* @param balanceChangeDetailDTO 余额变动明细DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
public Result<Boolean> updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) {
|
||||
boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除余额变动明细
|
||||
*
|
||||
* @param id 余额变动明细ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public Result<Boolean> deleteBalanceChangeDetail(@PathVariable Long id) {
|
||||
boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询余额变动明细
|
||||
*
|
||||
* @param id 余额变动明细ID
|
||||
* @return 余额变动明细VO
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<BalanceChangeDetailVO> getBalanceChangeDetailById(@PathVariable Long id) {
|
||||
BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id);
|
||||
return Result.success(balanceChangeDetailVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有余额变动明细
|
||||
*
|
||||
* @return 余额变动明细VO列表
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
public Result<List<BalanceChangeDetailVO>> listAllBalanceChangeDetails() {
|
||||
List<BalanceChangeDetailVO> balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails();
|
||||
return Result.success(balanceChangeDetailVOs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户ID查询余额变动明细
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 余额变动明细VO列表
|
||||
*/
|
||||
@GetMapping("/list/user/{userId}")
|
||||
public Result<List<BalanceChangeDetailVO>> listBalanceChangeDetailsByUserId(@PathVariable Long userId) {
|
||||
List<BalanceChangeDetailVO> balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId);
|
||||
return Result.success(balanceChangeDetailVOs);
|
||||
}
|
||||
}
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.dto.BalanceDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.service.BalanceService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户余额信息表 Controller
|
||||
* 对应数据库表 t_balance
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping({"/balance", "/api/balance"})
|
||||
@RequiredArgsConstructor
|
||||
public class BalanceController {
|
||||
/**
|
||||
* Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final BalanceService balanceService;
|
||||
|
||||
/**
|
||||
* 创建余额
|
||||
*
|
||||
* @param balanceDTO 余额DTO
|
||||
* @return 余额ID
|
||||
*/
|
||||
@PostMapping("/create")
|
||||
public Result<Long> createBalance(@RequestBody BalanceDTO balanceDTO) {
|
||||
Long id = balanceService.createBalance(balanceDTO);
|
||||
return Result.success(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新余额
|
||||
*
|
||||
* @param id 余额ID
|
||||
* @param balanceDTO 余额DTO
|
||||
* @return 是否更新成功
|
||||
*/
|
||||
@PutMapping("/update/{id}")
|
||||
public Result<Boolean> updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) {
|
||||
boolean success = balanceService.updateBalance(id, balanceDTO);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除余额
|
||||
*
|
||||
* @param id 余额ID
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public Result<Boolean> deleteBalance(@PathVariable Long id) {
|
||||
boolean success = balanceService.deleteBalance(id);
|
||||
return Result.success(success);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询余额
|
||||
*
|
||||
* @param id 余额ID
|
||||
* @return 余额VO
|
||||
*/
|
||||
@GetMapping("/get/{id}")
|
||||
public Result<BalanceVO> getBalanceById(@PathVariable Long id) {
|
||||
BalanceVO balanceVO = balanceService.getBalanceById(id);
|
||||
return Result.success(balanceVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有余额
|
||||
*
|
||||
* @return 余额VO列表
|
||||
*/
|
||||
@GetMapping("/list/all")
|
||||
public Result<List<BalanceVO>> listAllBalances() {
|
||||
List<BalanceVO> balanceVOs = balanceService.listAllBalances();
|
||||
return Result.success(balanceVOs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户ID查询余额
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 余额VO
|
||||
*/
|
||||
@GetMapping("/get/user/{userId}")
|
||||
public Result<BalanceVO> getBalanceByUserId(@PathVariable Long userId) {
|
||||
BalanceVO balanceVO = balanceService.getBalanceByUserId(userId);
|
||||
return Result.success(balanceVO);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/payment")
|
||||
@RequiredArgsConstructor
|
||||
public class PaymentController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
@PostMapping("/order/{orderId}/prepare")
|
||||
public Result<PaymentOrderVO> prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(paymentService.prepareOrderPayment(userId, orderId));
|
||||
}
|
||||
|
||||
@PostMapping("/order/{orderId}/mock-success")
|
||||
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
|
||||
}
|
||||
}
|
||||
+3
@@ -8,6 +8,7 @@ import java.math.BigDecimal;
|
||||
public class PlanningAppointmentCreateDTO {
|
||||
private Long customerUserId;
|
||||
private String customerName;
|
||||
private String wechatId;
|
||||
private String phone;
|
||||
private Long productId;
|
||||
private Integer quantity;
|
||||
@@ -16,6 +17,8 @@ public class PlanningAppointmentCreateDTO {
|
||||
private String appointmentTime;
|
||||
private String appointmentStartTime;
|
||||
private Integer durationMinutes;
|
||||
private BigDecimal amount;
|
||||
private Boolean createCustomerRecord;
|
||||
private String manualProductTitle;
|
||||
private BigDecimal manualProductPrice;
|
||||
private String manualProductDescription;
|
||||
|
||||
+1
@@ -5,4 +5,5 @@ import lombok.Data;
|
||||
@Data
|
||||
public class PlanningAppointmentStatusDTO {
|
||||
private Integer status;
|
||||
private String cancelReason;
|
||||
}
|
||||
|
||||
+7
@@ -9,8 +9,15 @@ public class PlanningBackfillOrderCreateDTO {
|
||||
private Long productId;
|
||||
private String manualProductTitle;
|
||||
private BigDecimal manualProductPrice;
|
||||
private Integer durationMinutes;
|
||||
private String manualProductDescription;
|
||||
private String manualProductTags;
|
||||
private String manualProductTargetAudience;
|
||||
private String manualProductPrecautions;
|
||||
private String manualProductImageFileIds;
|
||||
private Long customerUserId;
|
||||
private String customerName;
|
||||
private String wechatId;
|
||||
private String phone;
|
||||
private String serviceDate;
|
||||
private String serviceTime;
|
||||
|
||||
+153
-63
@@ -22,12 +22,16 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.PlanningService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningCalendarSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningTodayOverviewSupport;
|
||||
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
@@ -39,10 +43,12 @@ import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningDaySummaryV
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningScheduleVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningTodayOverviewVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -71,7 +77,6 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
private static final String RESERVATION_UNASSIGNED = "UNASSIGNED";
|
||||
private static final String ASSIGNMENT_ASSIGNED = "ASSIGNED";
|
||||
private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT";
|
||||
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW";
|
||||
private static final List<String> ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED);
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
private static final List<String> ARTIST_COLORS = List.of(
|
||||
@@ -80,6 +85,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
|
||||
private final AdminScopeHelper adminScopeHelper;
|
||||
private final UserMapper userMapper;
|
||||
private final UserService userService;
|
||||
private final NailArtistInfoMapper nailArtistInfoMapper;
|
||||
private final ArtistScheduleMapper artistScheduleMapper;
|
||||
private final ArtistScheduleExceptionMapper artistScheduleExceptionMapper;
|
||||
@@ -88,9 +94,12 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final ShopBusinessExpiryService shopBusinessExpiryService;
|
||||
private final AppointmentCapacityService appointmentCapacityService;
|
||||
private final OrderService orderService;
|
||||
private final WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@Override
|
||||
public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) {
|
||||
@@ -105,9 +114,9 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
|
||||
Long shopId = requirePlanningShopId(currentUser);
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours(
|
||||
shop == null ? null : shop.getBusinessHours()
|
||||
);
|
||||
PlanningCalendarSupport.BusinessHours businessHours = parseConfiguredBusinessHours(
|
||||
shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours())
|
||||
? shop.getAppointmentBusinessHours() : shop.getBusinessHours()));
|
||||
|
||||
List<PlanningArtistVO> artists = listArtists(shopId, artistId);
|
||||
List<ArtistScheduleDO> schedules = listSchedules(shopId, start, end, artistId);
|
||||
@@ -129,8 +138,10 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue()));
|
||||
|
||||
PlanningCalendarVO vo = new PlanningCalendarVO();
|
||||
vo.setBusinessStartTime(businessHours.start().toString());
|
||||
vo.setBusinessEndTime(businessHours.end().toString());
|
||||
vo.setBusinessStartTime(businessHours == null ? null : businessHours.start().toString());
|
||||
vo.setBusinessEndTime(businessHours == null ? null : businessHours.end().toString());
|
||||
vo.setDefaultAppointmentDurationMinutes(shop == null || shop.getDefaultAppointmentDurationMinutes() == null
|
||||
|| shop.getDefaultAppointmentDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes());
|
||||
vo.setSlotMinutes(DEFAULT_SLOT_MINUTES);
|
||||
vo.setArtists(artists);
|
||||
vo.setSchedules(scheduleVos);
|
||||
@@ -170,23 +181,38 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
throw new RuntimeException("美甲师账号只能查看预约,不能新建预约");
|
||||
}
|
||||
Long shopId = requirePlanningShopId(currentUser);
|
||||
requireAppointmentDuration(dto.getDurationMinutes());
|
||||
ProductDO product = resolveAppointmentProduct(dto, shopId);
|
||||
UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId);
|
||||
UserDO customer = resolveCustomer(shopId, dto);
|
||||
|
||||
shopBusinessExpiryService.assertShopActive(shopId);
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
int shopDefaultDuration = resolveShopDefaultDuration(shop);
|
||||
int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity();
|
||||
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity;
|
||||
ProductDO product = dto.getProductId() == null ? null : requireActiveProduct(dto.getProductId(), shopId);
|
||||
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity;
|
||||
LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime());
|
||||
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
|
||||
ensureFutureAppointmentTime(startTime);
|
||||
ensureWithinBusinessHours(shopId, startTime, endTime);
|
||||
if (product == null) {
|
||||
product = createManualAppointmentProduct(dto, shopId, shopDefaultDuration);
|
||||
durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity;
|
||||
endTime = startTime.plusMinutes(durationMinutes);
|
||||
ensureWithinBusinessHours(shopId, startTime, endTime);
|
||||
}
|
||||
UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId);
|
||||
UserDO customer = resolveCustomer(currentUser, shopId, dto);
|
||||
|
||||
BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice();
|
||||
BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity));
|
||||
BigDecimal amount = dto.getAmount() == null
|
||||
? unitPrice.multiply(BigDecimal.valueOf(quantity))
|
||||
: dto.getAmount();
|
||||
if (amount.compareTo(BigDecimal.ZERO) < 0) {
|
||||
throw new RuntimeException("成交金额不能小于0");
|
||||
}
|
||||
|
||||
OrderDO order = new OrderDO();
|
||||
order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString());
|
||||
order.setUserId(customer.getId());
|
||||
order.setUserId(customer == null ? null : customer.getId());
|
||||
order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null);
|
||||
order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null);
|
||||
order.setShopId(shopId);
|
||||
order.setTotalAmount(amount);
|
||||
order.setActualAmount(amount);
|
||||
@@ -207,7 +233,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
item.setOrderId(order.getId());
|
||||
item.setProductId(product.getId());
|
||||
item.setQuantity(quantity);
|
||||
item.setPrice(unitPrice);
|
||||
item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP));
|
||||
item.setArtistId(artist == null ? null : artist.getId());
|
||||
item.setAppointmentTime(startTime);
|
||||
item.setIsDelete(0);
|
||||
@@ -224,6 +250,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
endTime,
|
||||
trimToNull(dto.getClientRequestId())
|
||||
);
|
||||
wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId());
|
||||
wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime);
|
||||
}
|
||||
|
||||
return getAppointment(currentUser, item.getId());
|
||||
@@ -248,6 +276,14 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice();
|
||||
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) throw new RuntimeException("项目金额不能小于0");
|
||||
product = new ProductDO(); product.setShopId(shopId); product.setTitle(title); product.setPrice(price);
|
||||
product.setDescription(trimToNull(dto.getManualProductDescription()));
|
||||
product.setTags(trimToNull(dto.getManualProductTags()));
|
||||
product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience()));
|
||||
product.setPrecautions(trimToNull(dto.getManualProductPrecautions()));
|
||||
product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds()));
|
||||
int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : dto.getDurationMinutes();
|
||||
product.setApproximateDuration(durationMinutes + "分钟");
|
||||
product.setBookableArtists(String.valueOf(dto.getArtistId()));
|
||||
product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); product.setFrontVisible(0);
|
||||
product.setLikeCount(0); product.setCollectCount(0); product.setIsDelete(0); productMapper.insert(product);
|
||||
}
|
||||
@@ -294,7 +330,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
Map<Long, PlanningArtistVO> artistMap = listArtists(order.getShopId(), item.getArtistId()).stream()
|
||||
.collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a));
|
||||
Map<Long, UserDO> customerMap = order.getUserId() == null ? Map.of() : loadUsers(Set.of(order.getUserId()));
|
||||
return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap);
|
||||
UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId());
|
||||
return toAppointmentVO(reservation, item, order, product, customer, artistMap);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -311,7 +348,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId());
|
||||
Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId();
|
||||
UserDO artist = requireActiveArtist(targetArtistId, order.getShopId());
|
||||
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) *
|
||||
ShopDO shop = shopMapper.selectById(order.getShopId());
|
||||
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), resolveShopDefaultDuration(shop)) *
|
||||
Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity());
|
||||
LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime())
|
||||
? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime())
|
||||
@@ -320,6 +358,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
throw new RuntimeException("预约时间不能为空");
|
||||
}
|
||||
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
|
||||
ensureFutureAppointmentTime(startTime);
|
||||
ensureWithinBusinessHours(order.getShopId(), startTime, endTime);
|
||||
|
||||
appointmentCapacityService.moveReservationForArtistChange(
|
||||
@@ -336,6 +375,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
item.setArtistId(artist.getId());
|
||||
item.setAppointmentTime(startTime);
|
||||
orderItemMapper.updateById(item);
|
||||
wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId());
|
||||
wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime);
|
||||
return getAppointment(currentUser, item.getId());
|
||||
}
|
||||
|
||||
@@ -356,6 +397,13 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (targetStatus == OrderStatus.CANCELLED.getCode()) {
|
||||
order.setCancelReason(StringUtils.hasText(dto.getCancelReason()) ? dto.getCancelReason().trim() : "门店取消预约");
|
||||
if (order.getCancelReason().length() > 255) {
|
||||
order.setCancelReason(order.getCancelReason().substring(0, 255));
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
}
|
||||
orderService.processOrder(orderId, targetStatus);
|
||||
return true;
|
||||
}
|
||||
@@ -392,8 +440,9 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1)));
|
||||
vo.setShortName(PlanningCalendarSupport.shortName(vo.getName()));
|
||||
vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), ""));
|
||||
vo.setAvatar(user.getAvatar());
|
||||
vo.setColor(colorForArtist(user.getId(), i));
|
||||
vo.setAvatar(objectStorageUrlSupport.toAccessibleUrl(user.getAvatar()));
|
||||
vo.setColor(info != null && StringUtils.hasText(info.getColor())
|
||||
? info.getColor() : colorForArtist(user.getId(), i));
|
||||
vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus());
|
||||
vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约");
|
||||
vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString());
|
||||
@@ -515,7 +564,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
continue;
|
||||
}
|
||||
ProductDO product = item == null ? null : productMap.get(item.getProductId());
|
||||
UserDO customer = customerMap.get(order.getUserId());
|
||||
UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId());
|
||||
result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap));
|
||||
if (reservation.getOrderItemId() != null) {
|
||||
reservationItemIds.add(reservation.getOrderItemId());
|
||||
@@ -530,7 +579,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
continue;
|
||||
}
|
||||
ProductDO product = productMap.get(item.getProductId());
|
||||
UserDO customer = customerMap.get(order.getUserId());
|
||||
UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId());
|
||||
result.add(toAppointmentVO(null, item, order, product, customer, artistMap));
|
||||
}
|
||||
result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo))
|
||||
@@ -544,7 +593,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
if (start == null && item != null) {
|
||||
start = item.getAppointmentTime();
|
||||
}
|
||||
int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity());
|
||||
ShopDO shop = order == null || order.getShopId() == null ? null : shopMapper.selectById(order.getShopId());
|
||||
int durationMinutes = resolveDurationMinutes(product, null, resolveShopDefaultDuration(shop)) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity());
|
||||
LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime();
|
||||
if (end == null && start != null) {
|
||||
end = start.plusMinutes(durationMinutes);
|
||||
@@ -721,23 +771,31 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
return product;
|
||||
}
|
||||
|
||||
private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
|
||||
private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) {
|
||||
if (dto.getProductId() != null) {
|
||||
return requireActiveProduct(dto.getProductId(), shopId);
|
||||
}
|
||||
return createManualAppointmentProduct(dto, shopId);
|
||||
return createManualAppointmentProduct(dto, shopId, defaultDurationMinutes);
|
||||
}
|
||||
|
||||
private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
|
||||
private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) {
|
||||
String title = trimToNull(dto.getManualProductTitle());
|
||||
String imageFileIds = trimToNull(dto.getManualProductImageFileIds());
|
||||
if (!hasText(title)) {
|
||||
throw new RuntimeException("请选择预约作品或填写手动作品名称");
|
||||
title = firstNonBlank(dto.getCustomerName(), hasText(imageFileIds) ? "散客款式" : null);
|
||||
}
|
||||
BigDecimal price = dto.getManualProductPrice();
|
||||
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
|
||||
throw new RuntimeException("手动作品价格不能小于0");
|
||||
if (!hasText(title) && !hasText(imageFileIds)) {
|
||||
throw new RuntimeException("请填写美甲款式名称或上传款式图片");
|
||||
}
|
||||
int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes());
|
||||
BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice();
|
||||
if (price == null) {
|
||||
throw new RuntimeException("成交金额不能为空");
|
||||
}
|
||||
if (price.compareTo(BigDecimal.ZERO) < 0) {
|
||||
throw new RuntimeException("成交金额不能小于0");
|
||||
}
|
||||
int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0
|
||||
? defaultDurationMinutes : dto.getDurationMinutes();
|
||||
ProductDO product = new ProductDO();
|
||||
product.setShopId(shopId);
|
||||
product.setTitle(title);
|
||||
@@ -745,7 +803,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
product.setTags(trimToNull(dto.getManualProductTags()));
|
||||
product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience()));
|
||||
product.setPrecautions(trimToNull(dto.getManualProductPrecautions()));
|
||||
product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds()));
|
||||
product.setImageFileIds(imageFileIds);
|
||||
product.setPrice(price);
|
||||
product.setLikeCount(0);
|
||||
product.setCollectCount(0);
|
||||
@@ -758,13 +816,6 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
return product;
|
||||
}
|
||||
|
||||
private int requireAppointmentDuration(Integer durationMinutes) {
|
||||
if (durationMinutes == null || durationMinutes <= 0) {
|
||||
throw new RuntimeException("预约时长不能为空且必须大于0分钟");
|
||||
}
|
||||
return durationMinutes;
|
||||
}
|
||||
|
||||
private UserDO requireActiveArtist(Long artistId, Long shopId) {
|
||||
if (artistId == null) {
|
||||
throw new RuntimeException("请选择美甲师");
|
||||
@@ -777,37 +828,37 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
return artist;
|
||||
}
|
||||
|
||||
private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) {
|
||||
private UserDO resolveCustomer(UserDO currentUser, Long shopId, PlanningAppointmentCreateDTO dto) {
|
||||
if (dto.getCustomerUserId() != null) {
|
||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getCustomerUserId(), "客户不属于当前店铺");
|
||||
UserDO customer = userMapper.selectById(dto.getCustomerUserId());
|
||||
if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) {
|
||||
if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete()) || !Integer.valueOf(0).equals(customer.getType())) {
|
||||
throw new RuntimeException("客户不存在");
|
||||
}
|
||||
return customer;
|
||||
}
|
||||
if (!hasText(dto.getPhone())) {
|
||||
throw new RuntimeException("客户手机号不能为空");
|
||||
String customerName = trimToNull(dto.getCustomerName());
|
||||
String wechatId = trimToNull(dto.getWechatId());
|
||||
String phone = trimToNull(dto.getPhone());
|
||||
if (!hasText(customerName) && hasText(phone)) {
|
||||
throw new RuntimeException("填写手机号时请同时填写客户姓名");
|
||||
}
|
||||
QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("is_delete", 0)
|
||||
.and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone()))
|
||||
.last("LIMIT 1");
|
||||
UserDO existing = userMapper.selectOne(wrapper);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
if (Boolean.FALSE.equals(dto.getCreateCustomerRecord())) {
|
||||
return null;
|
||||
}
|
||||
UserDO customer = new UserDO();
|
||||
customer.setShopId(shopId);
|
||||
customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone()));
|
||||
customer.setPhone(dto.getPhone());
|
||||
customer.setContactPhone(dto.getPhone());
|
||||
customer.setAccount(dto.getPhone());
|
||||
customer.setPassword(ENCODED_UNSET_PASSWORD);
|
||||
customer.setType(0);
|
||||
customer.setStatus(1);
|
||||
customer.setIsDelete(0);
|
||||
userMapper.insert(customer);
|
||||
return customer;
|
||||
if (!hasText(customerName)) {
|
||||
return null;
|
||||
}
|
||||
List<com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO> matches =
|
||||
userService.findCustomerIdentityMatches(customerName, dto.getWechatId(), phone, shopId);
|
||||
if (matches.size() > 1) {
|
||||
throw new RuntimeException("存在多个匹配客户,请先选择已有客户");
|
||||
}
|
||||
if (!matches.isEmpty()) {
|
||||
return userMapper.selectById(matches.get(0).getId());
|
||||
}
|
||||
Long customerId = userService.createManagerCustomer(customerName, wechatId, phone, shopId);
|
||||
return userMapper.selectById(customerId);
|
||||
}
|
||||
|
||||
private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) {
|
||||
@@ -831,7 +882,14 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
|
||||
private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) {
|
||||
ShopDO shop = shopMapper.selectById(shopId);
|
||||
PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours());
|
||||
String configuredHours = shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours())
|
||||
? shop.getAppointmentBusinessHours() : shop.getBusinessHours());
|
||||
PlanningCalendarSupport.BusinessHours hours = parseConfiguredBusinessHours(configuredHours);
|
||||
if (hours == null) {
|
||||
throw new RuntimeException(StringUtils.hasText(configuredHours)
|
||||
? "门店营业时间格式无效,请先完成设置"
|
||||
: "门店营业时间未设置,请先完成设置");
|
||||
}
|
||||
LocalTime start = startTime.toLocalTime();
|
||||
LocalTime end = endTime.toLocalTime();
|
||||
if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) {
|
||||
@@ -839,6 +897,34 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
}
|
||||
}
|
||||
|
||||
private PlanningCalendarSupport.BusinessHours parseConfiguredBusinessHours(String value) {
|
||||
if (!StringUtils.hasText(value)) return null;
|
||||
String[] parts = value.trim().split("-");
|
||||
if (parts.length != 2) return null;
|
||||
try {
|
||||
LocalTime start = LocalTime.parse(parts[0].trim());
|
||||
LocalTime end = LocalTime.parse(parts[1].trim());
|
||||
return start.isBefore(end) ? new PlanningCalendarSupport.BusinessHours(start, end) : null;
|
||||
} catch (RuntimeException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureFutureAppointmentTime(LocalDateTime startTime) {
|
||||
LocalDate today = LocalDate.now();
|
||||
if (startTime.toLocalDate().isBefore(today)) {
|
||||
throw new RuntimeException("历史日期请使用历史补单");
|
||||
}
|
||||
if (!startTime.isAfter(LocalDateTime.now())) {
|
||||
throw new RuntimeException("预约时间已过,请使用历史补单");
|
||||
}
|
||||
}
|
||||
|
||||
private int resolveShopDefaultDuration(ShopDO shop) {
|
||||
return shop == null || shop.getDefaultAppointmentDurationMinutes() == null || shop.getDefaultAppointmentDurationMinutes() <= 0
|
||||
? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes();
|
||||
}
|
||||
|
||||
private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) {
|
||||
if (hasText(appointmentStartTime)) {
|
||||
String normalized = appointmentStartTime.trim().replace('T', ' ');
|
||||
@@ -860,10 +946,14 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
}
|
||||
|
||||
private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) {
|
||||
return resolveDurationMinutes(product, overrideMinutes, DEFAULT_DURATION_MINUTES);
|
||||
}
|
||||
|
||||
private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes, int defaultMinutes) {
|
||||
if (overrideMinutes != null && overrideMinutes > 0) {
|
||||
return overrideMinutes;
|
||||
}
|
||||
return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES);
|
||||
return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), defaultMinutes);
|
||||
}
|
||||
|
||||
private boolean isVisibleOrder(OrderDO order, Long shopId) {
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ import java.util.List;
|
||||
public class PlanningCalendarVO {
|
||||
private String businessStartTime;
|
||||
private String businessEndTime;
|
||||
private Integer defaultAppointmentDurationMinutes;
|
||||
private Integer slotMinutes;
|
||||
private List<PlanningArtistVO> artists;
|
||||
private List<PlanningScheduleVO> schedules;
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "jayucloud-salon.privacy.content-moderation")
|
||||
public class ContentModerationProperties {
|
||||
private Boolean allowMock = false;
|
||||
private Integer scene = 2;
|
||||
private Integer imageUrlExpireMinutes = 5;
|
||||
private Integer requestTimeoutMillis = 8000;
|
||||
private Integer maxRetries = 3;
|
||||
private String retryCron = "0 */2 * * * *";
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
public class WechatContentModerationHttpConfig {
|
||||
@Bean("wechatContentModerationRestTemplate")
|
||||
public RestTemplate wechatContentModerationRestTemplate(ContentModerationProperties properties) {
|
||||
int timeoutMillis = properties.getRequestTimeoutMillis() == null
|
||||
? 8000 : Math.max(1000, properties.getRequestTimeoutMillis());
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(timeoutMillis);
|
||||
requestFactory.setReadTimeout(timeoutMillis);
|
||||
return new RestTemplate(requestFactory);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ClosureSuccessorManagerVO;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin/privacy/account-closure")
|
||||
public class AdminAccountClosureController {
|
||||
private final AccountClosureService accountClosureService;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@GetMapping("/pending")
|
||||
public Result<List<AccountClosureRequestVO>> pending(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(accountClosureService.listPending());
|
||||
}
|
||||
|
||||
@GetMapping("/successor-managers")
|
||||
public Result<List<ClosureSuccessorManagerVO>> successorManagers(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
List<ClosureSuccessorManagerVO> managers = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class)
|
||||
.eq(UserDO::getType, 2).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0)
|
||||
.select(UserDO::getId, UserDO::getNickname, UserDO::getShopId)
|
||||
.orderByAsc(UserDO::getNickname))
|
||||
.stream().map(user -> new ClosureSuccessorManagerVO(user.getId(), user.getNickname(), user.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
return Result.success(managers);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/process")
|
||||
@OperationGuard(action = "admin-account-closure-process", ttlSeconds = 10, message = "申请处理中,请勿重复提交")
|
||||
public Result<Boolean> process(HttpServletRequest request, @PathVariable Long id,
|
||||
@RequestBody AccountClosureProcessDTO dto) {
|
||||
Long reviewerId = requirePlatformAdmin(request);
|
||||
return Result.success(accountClosureService.process(reviewerId, id, dto));
|
||||
}
|
||||
|
||||
private Long requirePlatformAdmin(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
Long userId = (Long) value;
|
||||
UserDO actor = userMapper.selectById(userId);
|
||||
if (actor == null || !Integer.valueOf(4).equals(actor.getType())) throw new IllegalArgumentException("无权处理注销申请");
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
|
||||
|
||||
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.ContentModerationReviewDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
@RequestMapping("/admin/privacy/content-moderation")
|
||||
public class AdminContentModerationController {
|
||||
private final ContentModerationService contentModerationService;
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@GetMapping("/pending")
|
||||
public Result<List<ContentModerationRecordVO>> pending(HttpServletRequest request) {
|
||||
requirePlatformAdmin(request);
|
||||
return Result.success(contentModerationService.listPending());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/review")
|
||||
@OperationGuard(action = "admin-content-moderation-review", ttlSeconds = 5, message = "复核处理中,请勿重复提交")
|
||||
public Result<Boolean> review(HttpServletRequest request, @PathVariable Long id,
|
||||
@Valid @RequestBody ContentModerationReviewDTO dto) {
|
||||
Long reviewerId = requirePlatformAdmin(request);
|
||||
if (dto.getApproved() == null) throw new IllegalArgumentException("请选择通过或拒绝");
|
||||
return Result.success(contentModerationService.review(reviewerId, id, dto.getApproved(), dto.getReason()));
|
||||
}
|
||||
|
||||
private Long requirePlatformAdmin(HttpServletRequest request) {
|
||||
Object value = request.getAttribute("userId");
|
||||
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
|
||||
Long userId = (Long) value;
|
||||
UserDO actor = userMapper.selectById(userId);
|
||||
if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) {
|
||||
throw new IllegalArgumentException("无权处理内容复核");
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user