diff --git a/.claude/skills/gitnexus-cli/SKILL.md b/.claude/skills/gitnexus-cli/SKILL.md new file mode 100644 index 00000000..3a00ab54 --- /dev/null +++ b/.claude/skills/gitnexus-cli/SKILL.md @@ -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 ` — 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 ` | 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 ` | Import opt-in Spring Boot Actuator mappings, beans, conditions, configprops, and env snapshots. Forces a full rebuild; unsupported with `--watch`. | +| `--asyncapi-spec ` | 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 `/.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 `-<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 ` | 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 ` | LLM model (default: MiniMax-M3) | +| `--base-url ` | LLM API base URL | +| `--api-key ` | LLM API key | +| `--concurrency ` | Parallel LLM calls (default: 3) | +| `--timeout ` | LLM request timeout in seconds (default: disabled) | +| `--retries ` | Max LLM retry attempts per request (default: 3) | +| `--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 diff --git a/.claude/skills/gitnexus-debugging/SKILL.md b/.claude/skills/gitnexus-debugging/SKILL.md new file mode 100644 index 00000000..41fb568f --- /dev/null +++ b/.claude/skills/gitnexus-debugging/SKILL.md @@ -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: ""}) → Find related execution flows +2. context({name: ""}) → 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. diff --git a/.claude/skills/gitnexus-exploring/SKILL.md b/.claude/skills/gitnexus-exploring/SKILL.md new file mode 100644 index 00000000..46fc187c --- /dev/null +++ b/.claude/skills/gitnexus-exploring/SKILL.md @@ -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: ""}) → Find related execution flows +4. context({name: ""}) → Deep dive on specific symbol +5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow +``` + +> If step 2 says "Index is stale" → run `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"`. diff --git a/.claude/skills/gitnexus-guide/SKILL.md b/.claude/skills/gitnexus-guide/SKILL.md new file mode 100644 index 00000000..c9661613 --- /dev/null +++ b/.claude/skills/gitnexus-guide/SKILL.md @@ -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 +``` diff --git a/.claude/skills/gitnexus-impact-analysis/SKILL.md b/.claude/skills/gitnexus-impact-analysis/SKILL.md new file mode 100644 index 00000000..85d90c90 --- /dev/null +++ b/.claude/skills/gitnexus-impact-analysis/SKILL.md @@ -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: () Worktree: Index: , 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 --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: ""` 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. diff --git a/.claude/skills/gitnexus-refactoring/SKILL.md b/.claude/skills/gitnexus-refactoring/SKILL.md new file mode 100644 index 00000000..9d63eb6e --- /dev/null +++ b/.claude/skills/gitnexus-refactoring/SKILL.md @@ -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. diff --git a/.gitea/workflows/sit环境回退上一个版本.yml b/.gitea/workflows/sit环境回退上一个版本.yml index 4c786543..84b1b043 100644 --- a/.gitea/workflows/sit环境回退上一个版本.yml +++ b/.gitea/workflows/sit环境回退上一个版本.yml @@ -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 diff --git a/.gitea/workflows/自动部署prod环境.yml b/.gitea/workflows/自动部署prod环境.yml index 2b6c4c51..ab68d1b9 100644 --- a/.gitea/workflows/自动部署prod环境.yml +++ b/.gitea/workflows/自动部署prod环境.yml @@ -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 diff --git a/.gitea/workflows/自动部署sit环境.yml b/.gitea/workflows/自动部署sit环境.yml index be7c88ca..316e30ad 100644 --- a/.gitea/workflows/自动部署sit环境.yml +++ b/.gitea/workflows/自动部署sit环境.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 5636c33d..5164818f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,30 @@ # 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` | ## 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`,并在任务记录中写明新增或调整的版本化文件。 diff --git a/CLAUDE.md b/CLAUDE.md index b53a6048..26eaebc7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,29 +1,30 @@ # 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` | + +## Project Workflow Rules + +- 用户未明确要求设计文档或方案确认时,实施类请求直接基于现有代码修改,不额外编写设计文档,也不以设计确认流程阻塞实现。 +- 修改前如工作区已有未提交改动,先创建中文 Git 回溯提交,再开始本次任务;提交后只暂存和提交本次任务涉及的文件,保留其他新产生或并行改动。 diff --git a/JC-ArtList-Frontend/vite.config.ts b/JC-ArtList-Frontend/vite.config.ts index e1fc04bd..b439431f 100644 --- a/JC-ArtList-Frontend/vite.config.ts +++ b/JC-ArtList-Frontend/vite.config.ts @@ -57,7 +57,7 @@ export default defineConfig(({ mode }) => { 'localhost', '127.0.0.1', '2666.online', - 'wcy111.top' + 'wcsrv.top' ] }, build: { diff --git a/JC-Salon-Core/pom.xml b/JC-Salon-Core/pom.xml index 5e00698b..1e6901cd 100644 --- a/JC-Salon-Core/pom.xml +++ b/JC-Salon-Core/pom.xml @@ -110,6 +110,15 @@ mysql-connector-j runtime + + + org.flywaydb + flyway-core + + + org.flywaydb + flyway-mysql + com.baomidou mybatis-plus-boot-starter diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java index 47955e0f..fd9885f8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/aspect/PermissionAspect.java @@ -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()) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java index a5c15828..4fb2635a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AuthInterceptor.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java index 27018ef0..20d49713 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/JwtProperties.java @@ -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 位"); + } + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java index 28153d12..ab15be83 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyBatisPlusConfig.java @@ -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", diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java index 9db357b0..a0432f08 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/MyMetaObjectHandler.java @@ -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); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java new file mode 100644 index 00000000..3ed1ee75 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/PhoneCryptoProperties.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java index 174cf00c..64d4bb98 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java @@ -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/**" diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java index 9e69d4dc..351655d4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WechatMiniProperties.java @@ -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; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java index 1c15872b..7912bae6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/controller/front/DashboardController.java @@ -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 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() { }, + () -> 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() + .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() + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, 1) + .eq(ProductDO::getModerationStatus, "APPROVED"))); + + LocalDate rangeStart = date.minusDays(days - 1); + List> trendRows = salonDashboardMapper.selectOrderTrend(rangeStart, date); + Map trendByDate = overview.getTrend().stream() + .collect(Collectors.toMap(SalonDashboardOverviewVO.TrendItem::getDate, item -> item, (left, right) -> left, LinkedHashMap::new)); + for (Map 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 ranking = new ArrayList<>(); + for (Map 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() + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .in(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN, WorkbenchRegistrationStatus.PENDING_MANAGER))); + overview.getAttention().setContentReviewCount(contentModerationRecordMapper.selectCount(new LambdaQueryWrapper() + .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY"))); + overview.getAttention().setAfterSaleCount(afterSaleMapper.selectCount(new LambdaQueryWrapper() + .eq(AfterSaleDO::getIsDelete, 0).eq(AfterSaleDO::getStatus, "PENDING"))); + overview.getAttention().setArtistChangeCount(orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() + .eq(OrderArtistChangeRequestDO::getIsDelete, 0).eq(OrderArtistChangeRequestDO::getStatus, "PENDING"))); + overview.getAttention().setLowStockCount(inventoryItemMapper.selectCount(new LambdaQueryWrapper() + .eq(InventoryItemDO::getIsDelete, 0) + .apply("stock_quantity <= warning_threshold"))); + return overview; + } + + private String stringValue(Map row, String key) { + Object value = row.get(key); + return value == null ? "" : value.toString(); + } + + private long longValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : 0L; + } + + private Long numberValue(Map row, String key) { + Object value = row.get(key); + return value instanceof Number ? ((Number) value).longValue() : null; + } + + private BigDecimal decimalValue(Map 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() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getType, type) + .eq(UserDO::getStatus, 1)); + } @GetMapping("/stats") @RequirePermission("dashboard:view") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java new file mode 100644 index 00000000..83647b03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/mapper/SalonDashboardMapper.java @@ -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> 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> selectShopRanking(@Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java new file mode 100644 index 00000000..ebecd94d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/analytics/vo/SalonDashboardOverviewVO.java @@ -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 trend = new ArrayList<>(); + private List 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; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java index cadd683f..552d4aa3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java @@ -136,7 +136,7 @@ public class AdminNailArtistController { } } - NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + NailArtistInfoDTO saved = nailArtistInfoService.submitNailArtistInfo(nailArtistInfoDTO, currentUser.getId()); return Result.success(saved); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java index 7ec61a67..985cd848 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java @@ -39,7 +39,7 @@ public class NailArtistController { @GetMapping("/list/shop/{shopId}") public Result> 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 getNailArtistInfo(@PathVariable Long userId) { - NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getPublicByUserId(userId); return Result.success(nailArtistInfoDTO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java index ce46e421..ce20916d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java @@ -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; + /** * 美甲师姓名(从用户表获取) */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java index 039eadee..28f6ba48 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java @@ -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-已删 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java index 4b5fc1a7..d89b45f7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java @@ -33,6 +33,11 @@ public interface NailArtistInfoService extends IService { */ List getByShopId(Long shopId); + /** + * 获取对外展示的指定门店美甲师,只返回个人资料和门店审核通过的记录。 + */ + List listPublicByShopId(Long shopId); + /** * 保存或更新美甲师信息 * @param nailArtistInfoDTO 美甲师信息DTO @@ -40,12 +45,20 @@ public interface NailArtistInfoService extends IService { */ NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); + /** 保存运营字段,并将美甲师对外展示资料提交审核。 */ + NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO, Long authorUserId); + /** * 获取所有可用的美甲师信息(前台使用) * @return 美甲师信息列表 */ List getAllAvailableNailArtists(); + /** + * 获取对外展示的指定美甲师资料。 + */ + NailArtistInfoDTO getPublicByUserId(Long userId); + NailArtistProfileVO getPublicProfile(Long artistId); List getAvailability(Long artistId); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java index e0aa81a4..6f136c9c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -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 listPublicByShopId(Long shopId) { + if (!isPublicShop(shopId)) { + return new ArrayList<>(); + } + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { + return new ArrayList<>(); + } + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .eq(UserDO::getType, 3) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getProfileModerationStatus, "APPROVED") + .orderByAsc(UserDO::getCreateTime) + .orderByAsc(UserDO::getId)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto == null) { + dto = buildFallbackArtistInfo(user); + } + 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() .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 values = new ArrayList<>(); + if (StringUtils.hasText(profile.getIdentity())) values.add(profile.getIdentity().trim()); + if (profile.getExperience() != null) values.add(profile.getExperience() + "年从业经验"); + List 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 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(); } + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (artistInfo == null || !isPublicShop(artistInfo.getShopId())) { + return new ArrayList<>(); + } List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() .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 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 imageIds = new LinkedHashSet<>(); for (OrderArtistReviewDO review : limitedReviews) { imageIds.addAll(parseLongTokens(review.getImageFileIds())); @@ -447,6 +626,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); if (!shopOptions.isEmpty()) { @@ -520,7 +700,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .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 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 register(@RequestBody PlanningManagerRegisterDTO registerDTO) { - return Result.success(userService.registerPlanningManager(registerDTO)); - } - - @GetMapping("/login-shops/{account}") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param account parameter `account` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getLoginShops(@PathVariable String account) { - return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account))); - } - - @PostMapping("/switch-shop") - @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") - /** - * Run business method `switchShop`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); - } - @PostMapping("/logout") @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) /** @@ -115,10 +83,9 @@ public class AdminAuthController { * @return Result result consumed by the caller or returned to the frontend */ public Result 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 changePassword(HttpServletRequest request, + @Valid @RequestBody AdminPasswordChangeRequestDTO passwordChangeRequest) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(adminAccountSecurityService.changePassword(userId, passwordChangeRequest)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java new file mode 100644 index 00000000..1b9a7ebf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/AdminPasswordChangeRequestDTO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java index e2234b69..76c65ec8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/dto/UpdatePhoneRequestDTO.java @@ -13,7 +13,7 @@ import lombok.Data; public class UpdatePhoneRequestDTO { /** - * 原手机号 + * 兼容旧客户端的原手机号字段;服务端不使用该字段进行身份校验。 */ private String oldPhone; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java new file mode 100644 index 00000000..84ed1de5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/admin/AdminAccountSecurityService.java @@ -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; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index 8b78796f..ec76f1b7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -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; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java index 1e418b46..b0533321 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/auth/vo/LoginResponseVO.java @@ -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): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java index 8eecf13b..23bc1b4a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/entity/CommentDO.java @@ -71,4 +71,7 @@ public class CommentDO extends BaseEntity { */ @TableField("is_delete") private Integer isDelete; + + @TableField("moderation_status") + private String moderationStatus; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java index b22e4acd..0339d134 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/mapper/CommentMapper.java @@ -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 { + @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); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java index 70a3cf98..7ee77356 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java @@ -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 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 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 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 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 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 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 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 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 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 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 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 im List 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 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 im * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend */ private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { - return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); + 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 payload = new java.util.LinkedHashMap<>(); + payload.put("commentContent", content); + payload.put("imageFileIds", imageFileIds); + List imageIds = parseImageFileIds(imageFileIds); + contentModerationService.assessVersion("COMMENT", comment.getId(), userId, content, + objectMapper.writeValueAsString(payload), imageIds); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("评论审核内容序列化失败", exception); + } } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java index d9779869..2d1045f0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/config/MinioStorageConfig.java @@ -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(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java index 7d9bbfc5..621a0622 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java @@ -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)); } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java new file mode 100644 index 00000000..535fcdde --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadController.java @@ -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 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()); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java index ed328e55..51d03a2f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileController.java @@ -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 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()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java new file mode 100644 index 00000000..17381419 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java @@ -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); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java index 3112446a..da393bc2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java @@ -75,4 +75,8 @@ public interface ObjectStorageFileService extends IService List listObjectStorageFilesByStatus(Integer status); void evictObjectStorageFileCache(Long id); + + Long findFileIdByReference(String reference); + + String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java index 9e1e2168..2fdd8957 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProvider.java @@ -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 minioClientProvider; + private final MinioClient signingClient; private final MinioStorageConfig minioStorageConfig; private final ObjectStorageProperties objectStorageProperties; + @Autowired + public MinioObjectStorageProvider( + ObjectProvider minioClientProvider, + MinioStorageConfig minioStorageConfig, + ObjectStorageProperties objectStorageProperties + ) { + this(minioClientProvider, minioStorageConfig, objectStorageProperties, minioStorageConfig.createSigningClient()); + } + + MinioObjectStorageProvider( + ObjectProvider 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()) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java index 33243a25..e1e845c3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -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 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 * diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java index 4ca6e791..3691eeb2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupport.java @@ -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(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java index 13c12e77..1d85f25c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java @@ -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 agreementVersions; + private String clientType; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java new file mode 100644 index 00000000..89c569c2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/entity/WechatSubscribeMessageLogDO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java new file mode 100644 index 00000000..81cca550 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/mapper/WechatSubscribeMessageLogMapper.java @@ -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 { + @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 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); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java index 9044cc7a..9bbf4fe8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniAuthService.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java index ba9e7435..b9ce7b89 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java @@ -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 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java new file mode 100644 index 00000000..29e777fe --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatSubscribeMessageService.java @@ -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(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 03c42c24..d490a8dc 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -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); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java index 7bf5ee0a..f2e41c64 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -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() + .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() + .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() + .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() - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO user = userMapper.selectOne(new LambdaQueryWrapper() + .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; } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java index 0733d6ac..3bb5fb73 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java @@ -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 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 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> templateData = new HashMap<>(); + if (data != null) { + data.forEach((key, value) -> templateData.put(key, Map.of("value", value == null ? "-" : value))); + } + request.put("data", templateData); + Map 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java new file mode 100644 index 00000000..aba1f4f8 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImpl.java @@ -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 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 bindingQuery = new LambdaQueryWrapper() + .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 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); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java index 22b5f3e3..4f0d1b2a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/vo/WechatMiniLoginResultVO.java @@ -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, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java index 2474ec4e..81194408 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java @@ -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> 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> 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> 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 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 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> 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 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 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 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)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java index 396e8700..f129a4c2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/dto/ManagerCustomerCreateDTO.java @@ -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; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java new file mode 100644 index 00000000..3831ab2f --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java deleted file mode 100644 index 4373969b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCampaignController.java +++ /dev/null @@ -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> list(HttpServletRequest request, - @RequestParam(required = false) Integer status, - @RequestParam(defaultValue = "1") Integer page, - @RequestParam(defaultValue = "10") Integer size) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); - return Result.success(campaignService.listCampaigns(shopId, status, page, size)); - } - - @PostMapping("/save") - @RequirePermission("campaign:manage") - public Result save(HttpServletRequest request, @RequestBody CampaignDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); - try { - CampaignVO result = campaignService.saveCampaign(dto); - securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId()); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java deleted file mode 100644 index 882fa9c3..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/admin/AdminCouponController.java +++ /dev/null @@ -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 createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - @OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - @OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 获取所有优惠券 - */ - @GetMapping("/list/all") - @RequirePermission("coupon:view") - public Result> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - List coupons = couponService.listAllCoupons(); - Long resolvedShopId = shopId; - if (resolvedShopId != null) { - coupons = coupons.stream() - .filter(coupon -> resolvedShopId.equals(coupon.getShopId())) - .collect(Collectors.toList()); - } - return Result.success(coupons); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - @OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java deleted file mode 100644 index e437ed39..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/CouponController.java +++ /dev/null @@ -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 createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); - Long couponId = couponService.createCoupon(couponDTO, shopId); - return Result.success(couponId); - } - - /** - * 更新优惠券 - */ - @PutMapping("/update/{id}") - @RequirePermission("coupon:edit") - public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); - Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); - shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); - boolean success = couponService.updateCoupon(id, couponDTO, shopId); - return Result.success(success); - } - - /** - * 删除优惠券 - */ - @DeleteMapping("/delete/{id}") - @RequirePermission("coupon:delete") - public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.deleteCoupon(id, shopId); - return Result.success(success); - } - - /** - * 获取优惠券详情 - */ - @GetMapping("/detail/{id}") - @RequirePermission("coupon:view") - public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(id); - if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); - } - return Result.success(couponVO); - } - - /** - * 获取优惠券列表 - */ - @GetMapping("/list") - @RequirePermission("coupon:view") - public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO pageResult = couponService.listCoupons(page, size, shopId); - return Result.success(pageResult); - } - - /** - * 为用户分配优惠券 - */ - @PostMapping("/assign") - @RequirePermission("coupon:assign") - public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.assignCouponToUser(userId, couponId, shopId); - return Result.success(success); - } - - /** - * 获取用户优惠券列表 - */ - @GetMapping("/user/list") - public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { - List userCoupons = couponService.listUserCoupons(userId, status); - return Result.success(userCoupons); - } - - /** - * 使用优惠券 - */ - @PostMapping("/use") - public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { - boolean success = couponService.useCoupon(userCouponId, userId); - return Result.success(success); - } - - /** - * 获取商品可用的优惠券 - */ - @GetMapping("/available") - public Result> getAvailableCoupons( - @RequestParam(required = false, defaultValue = "") String productTags, - @RequestParam Double productPrice, - @RequestParam(required = false) Long shopId, - @RequestAttribute("userId") Long userId - ) { - List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); - return Result.success(availableCoupons); - } - - /** - * 发放优惠券 - */ - @PostMapping("/distribute") - @RequirePermission("coupon:assign") - public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - CouponVO couponVO = couponService.getCouponById(couponId); - if (couponVO == null) { - return Result.success(false); - } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); - for (Long userId : userIds) { - UserVO targetUser = userService.getUserById(userId); - if (targetUser == null) { - return Result.success(false); - } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); - } - shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); - boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); - return Result.success(success); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java deleted file mode 100644 index 125fde8a..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/GrowthController.java +++ /dev/null @@ -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 summary(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(growthService.getSummary(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java deleted file mode 100644 index dd000704..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/ProductLikeController.java +++ /dev/null @@ -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 likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.addLike(userId, productId); - return Result.success(true); - } - - /** - * 取消点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否成功 - */ - @PostMapping("/unlike/{productId}") - @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - productLikeService.removeLike(userId, productId); - return Result.success(true); - } - - /** - * 检查用户是否已点赞商品 - * - * @param userId 当前用户ID - * @param productId 商品ID - * @return 是否已点赞 - */ - @GetMapping("/check/{productId}") - public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { - boolean isLiked = productLikeService.isProductLiked(userId, productId); - return Result.success(isLiked); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java deleted file mode 100644 index 0fc71ff0..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipBenefitController.java +++ /dev/null @@ -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 createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { - Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); - return Result.success(id); - } - - /** - * 更新VIP权益 - * - * @param id VIP权益ID - * @param vipBenefitDTO VIP权益DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { - boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); - return Result.success(success); - } - - /** - * 删除VIP权益 - * - * @param id VIP权益ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipBenefit(@PathVariable Long id) { - boolean success = vipBenefitService.deleteVipBenefit(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP权益 - * - * @param id VIP权益ID - * @return VIP权益VO - */ - @GetMapping("/get/{id}") - public Result getVipBenefitById(@PathVariable Long id) { - VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); - return Result.success(vipBenefitVO); - } - - /** - * 查询所有VIP权益 - * - * @return VIP权益VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipBenefits() { - List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); - return Result.success(vipBenefitVOs); - } - - /** - * 根据所需VIP等级查询VIP权益 - * - * @param requiredVipLevel 所需VIP等级 - * @return VIP权益VO列表 - */ - @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") - public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { - List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); - return Result.success(vipBenefitVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java deleted file mode 100644 index c98795da..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipInfoController.java +++ /dev/null @@ -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 createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { - Long id = vipInfoService.createVipInfo(vipInfoDTO); - return Result.success(id); - } - - /** - * 更新VIP信息 - * - * @param id VIP信息ID - * @param vipInfoDTO VIP信息DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { - boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); - return Result.success(success); - } - - /** - * 删除VIP信息 - * - * @param id VIP信息ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteVipInfo(@PathVariable Long id) { - boolean success = vipInfoService.deleteVipInfo(id); - return Result.success(success); - } - - /** - * 根据ID查询VIP信息 - * - * @param id VIP信息ID - * @return VIP信息VO - */ - @GetMapping("/get/{id}") - public Result getVipInfoById(@PathVariable Long id) { - VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); - return Result.success(vipInfoVO); - } - - /** - * 查询所有VIP信息 - * - * @return VIP信息VO列表 - */ - @GetMapping("/list/all") - public Result> listAllVipInfos() { - List vipInfoVOs = vipInfoService.listAllVipInfos(); - return Result.success(vipInfoVOs); - } - - /** - * 根据VIP等级查询VIP信息 - * - * @param vipLevel VIP等级 - * @return VIP信息VO列表 - */ - @GetMapping("/list/vipLevel/{vipLevel}") - public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { - List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); - return Result.success(vipInfoVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java deleted file mode 100644 index a8a5a343..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/VipRechargePlanController.java +++ /dev/null @@ -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> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); - } - - @PostMapping("/admin/create") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Create a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); - } - - @PutMapping("/admin/{id}") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param dto parameter `dto` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); - } - - @PutMapping("/admin/{id}/status") - @RequirePermission("user:vip:manage") - /** - * Change the enabled/status flag of one record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @param status parameter `status` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); - } - - @GetMapping("/my/list") - /** - * List records for the current query or current user scope. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> listMy(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(vipRechargePlanService.listMyPlans(userId)); - } - - @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) - /** - * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java deleted file mode 100644 index f1b850fb..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/marketing/controller/front/WishlistController.java +++ /dev/null @@ -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 request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @PostMapping("/add-with-group") - @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { - wishlistService.addToWishlist(userId, request); - return Result.success("ok"); - } - - @PostMapping("/remove") - @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - wishlistService.removeFromWishlist(userId, request.get("productId")); - return Result.success("ok"); - } - - @GetMapping("/check") - public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.isInWishlist(userId, productId)); - } - - @GetMapping("/list") - public Result> getWishlist(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getWishlistByUserId(userId)); - } - - @GetMapping("/groups") - public Result> listGroups(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.listGroups(userId)); - } - - @PostMapping("/groups") - public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.createGroup(userId, request)); - } - - @PutMapping("/groups/{id}") - public Result updateGroup( - @PathVariable Long id, - @RequestBody WishlistGroupDTO request, - @RequestAttribute("userId") Long userId - ) { - return Result.success(wishlistService.updateGroup(userId, id, request)); - } - - @DeleteMapping("/groups/{id}") - public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.deleteGroup(userId, id)); - } - - @PostMapping("/move") - @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.moveWishlist(userId, request)); - } - - @GetMapping("/inspiration") - public Result getInspiration(@RequestAttribute("userId") Long userId) { - return Result.success(wishlistService.getInspiration(userId)); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java index dbe4fe58..f73e22e3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java index 833bca6b..3075823e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java index d0667a59..76ec67cd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java index 8e71d620..ca978c9f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java @@ -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 { + @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); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java index 43a7b814..6c5caebf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java @@ -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 { + @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); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java index 3a7143df..360e2998 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -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 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() .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 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 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java index dd69afcf..2e966913 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java @@ -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 payload = new java.util.LinkedHashMap<>(); + payload.put("title", title); payload.put("content", content); payload.put("imageFileId", dto.getImageFileId()); payload.put("status", 1); + List 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() .eq(SystemMessageDO::getIsDelete, 0) .eq(SystemMessageDO::getStatus, 1) + .eq(SystemMessageDO::getModerationStatus, "APPROVED") .orderByDesc(SystemMessageDO::getPublishTime)) .stream() .filter(message -> isMessageVisibleToUser(message, user)) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java index d068d8a7..11ec1597 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java @@ -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 imageFileIds; /** * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java deleted file mode 100644 index 029b3630..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/CartController.java +++ /dev/null @@ -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 result consumed by the caller or returned to the frontend - */ - public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.addToCart(userId, cartDTO); - return Result.success(); - } - - @DeleteMapping("/remove/{productId}") - @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param productId parameter `productId` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.removeFromCart(userId, productId); - return Result.success(); - } - - @PostMapping("/batch-remove") - @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `batchRemoveFromCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartItemIds parameter `cartItemIds` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.batchRemoveFromCart(userId, cartItemIds); - return Result.success(); - } - - @PutMapping("/update") - @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") - /** - * Update an existing record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param cartDTO parameter `cartDTO` supplied by the caller - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.updateCartQuantity(userId, cartDTO); - return Result.success(); - } - - @GetMapping("/list") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getCartList(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - List cartList = cartService.getCartList(userId); - return Result.success(cartList); - } - - @DeleteMapping("/clear") - @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Run business method `clearCart`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result clearCart(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - cartService.clearCart(userId); - return Result.success(); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java index 6f4b3663..137822d0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/controller/front/OrderController.java @@ -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 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 result consumed by the caller or returned to the frontend */ - public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { + public Result 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(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java index a64c727d..f48299e7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java index f32076e7..221ab3b1 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderDO.java @@ -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; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java index 63e2fef3..4a9e6eed 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java @@ -25,6 +25,24 @@ public interface OrderArtistReviewMapper extends BaseMapper @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); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java index 228bf9fe..f07dae11 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/OrderService.java @@ -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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java index d5f6f88e..175759af 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java @@ -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); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java index 64c6f469..6f9e4e74 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java @@ -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 bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); - List availableCouponOptions = couponService.getAvailableCoupons( - userId, - pricingContext.getProductTagNames(), - pricingContext.getTotalAmount().doubleValue(), - pricingContext.getShopId() - ); - if (availableCouponOptions == null) { - availableCouponOptions = List.of(); - } - - List availableCoupons = availableCouponOptions.stream() - .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) - .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() - .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) - .toList(); - - CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); - if (bestCoupon != null) { - bestCoupon.setBest(true); - } - - CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); - BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); - BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); - if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { - payableAmount = BigDecimal.ZERO; - } - - CheckoutPreviewVO preview = new CheckoutPreviewVO(); - preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); - preview.setSavedAmount(scaleMoney(savedAmount)); - preview.setPayableAmount(scaleMoney(payableAmount)); - preview.setBestCoupon(bestCoupon); - preview.setAvailableCoupons(availableCoupons); - preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); - preview.setBookingAvailable(bookingIssues.isEmpty()); - preview.setBookingIssues(bookingIssues); - preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); - preview.setSummaryText(buildCheckoutSummaryText(preview)); - return preview; - } - /** * Create a new record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -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 orderItemDTOs = orderDTO.getItems(); - Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); - BigDecimal totalAmount = BigDecimal.ZERO; - Set selectedTagNames = new LinkedHashSet<>(); - Long shopId = null; - - for (OrderItemDTO orderItemDTO : orderItemDTOs) { - validateOrderQuantity(orderItemDTO.getQuantity()); - ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); - if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { - throw new RuntimeException("商品不存在或已下架"); - } - - CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); - Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); - if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { - throw new RuntimeException("请先将商品加入购物车后再结算"); - } - if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { - throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); - } - - if (shopId == null) { - shopId = product.getShopId(); - validateUserCanCreateOrderInShop(userId, shopId); - } else if (!shopId.equals(product.getShopId())) { - throw new RuntimeException("跨店铺商品请分开下单"); - } - - collectPreviewTagNames(selectedTagNames, product.getTags()); - BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); - } - - if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { - throw new RuntimeException("订单金额无效"); - } - return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); - } - private List collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) { List issues = new ArrayList<>(); if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { @@ -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 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 payload = new java.util.LinkedHashMap<>(); + payload.put("content", review.getContent()); + payload.put("imageFileIds", review.getImageFileIds()); + List 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 { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java deleted file mode 100644 index 45e4fc77..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/admin/AdminPaymentController.java +++ /dev/null @@ -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 manualConfirm(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark); - securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/order/{orderId}/manual-refund") - @RequirePermission("refund:manage") - public Result manualRefund(HttpServletRequest request, - @PathVariable Long orderId, - @RequestParam(required = false) Long afterSaleId, - @RequestParam(required = false) String remark) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - try { - RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark); - securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId); - return Result.success(result); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); - throw exception; - } - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java deleted file mode 100644 index 87f1c49b..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceChangeDetailController.java +++ /dev/null @@ -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 createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); - return Result.success(id); - } - - /** - * 更新余额变动明细 - * - * @param id 余额变动明细ID - * @param balanceChangeDetailDTO 余额变动明细DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { - boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); - return Result.success(success); - } - - /** - * 删除余额变动明细 - * - * @param id 余额变动明细ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalanceChangeDetail(@PathVariable Long id) { - boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); - return Result.success(success); - } - - /** - * 根据ID查询余额变动明细 - * - * @param id 余额变动明细ID - * @return 余额变动明细VO - */ - @GetMapping("/get/{id}") - public Result getBalanceChangeDetailById(@PathVariable Long id) { - BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); - return Result.success(balanceChangeDetailVO); - } - - /** - * 查询所有余额变动明细 - * - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalanceChangeDetails() { - List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); - return Result.success(balanceChangeDetailVOs); - } - - /** - * 根据用户ID查询余额变动明细 - * - * @param userId 用户ID - * @return 余额变动明细VO列表 - */ - @GetMapping("/list/user/{userId}") - public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { - List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); - return Result.success(balanceChangeDetailVOs); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java deleted file mode 100644 index c625c430..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/BalanceController.java +++ /dev/null @@ -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 createBalance(@RequestBody BalanceDTO balanceDTO) { - Long id = balanceService.createBalance(balanceDTO); - return Result.success(id); - } - - /** - * 更新余额 - * - * @param id 余额ID - * @param balanceDTO 余额DTO - * @return 是否更新成功 - */ - @PutMapping("/update/{id}") - public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { - boolean success = balanceService.updateBalance(id, balanceDTO); - return Result.success(success); - } - - /** - * 删除余额 - * - * @param id 余额ID - * @return 是否删除成功 - */ - @DeleteMapping("/delete/{id}") - public Result deleteBalance(@PathVariable Long id) { - boolean success = balanceService.deleteBalance(id); - return Result.success(success); - } - - /** - * 根据ID查询余额 - * - * @param id 余额ID - * @return 余额VO - */ - @GetMapping("/get/{id}") - public Result getBalanceById(@PathVariable Long id) { - BalanceVO balanceVO = balanceService.getBalanceById(id); - return Result.success(balanceVO); - } - - /** - * 查询所有余额 - * - * @return 余额VO列表 - */ - @GetMapping("/list/all") - public Result> listAllBalances() { - List balanceVOs = balanceService.listAllBalances(); - return Result.success(balanceVOs); - } - - /** - * 根据用户ID查询余额 - * - * @param userId 用户ID - * @return 余额VO - */ - @GetMapping("/get/user/{userId}") - public Result getBalanceByUserId(@PathVariable Long userId) { - BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); - return Result.success(balanceVO); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java deleted file mode 100644 index 09e832e5..00000000 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/payment/controller/front/PaymentController.java +++ /dev/null @@ -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 prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.prepareOrderPayment(userId, orderId)); - } - - @PostMapping("/order/{orderId}/mock-success") - public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } -} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java index b11e4eea..0c7c28fd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -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; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java index 62f84b9d..6bfa9163 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentStatusDTO.java @@ -5,4 +5,5 @@ import lombok.Data; @Data public class PlanningAppointmentStatusDTO { private Integer status; + private String cancelReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java index cf6247a7..e4596e53 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java @@ -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; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index 21a076f2..e00062b8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -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 ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final List ARTIST_COLORS = List.of( @@ -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 artists = listArtists(shopId, artistId); List 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 artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); Map 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 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 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) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java index 26f412c1..0370d736 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java @@ -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 artists; private List schedules; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java new file mode 100644 index 00000000..6cefdac5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java @@ -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 * * * *"; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java new file mode 100644 index 00000000..33eccf7c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java @@ -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); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java new file mode 100644 index 00000000..004748bf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminAccountClosureController.java @@ -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> pending(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(accountClosureService.listPending()); + } + + @GetMapping("/successor-managers") + public Result> successorManagers(HttpServletRequest request) { + requirePlatformAdmin(request); + List 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 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; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java new file mode 100644 index 00000000..e8facf1a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java @@ -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> pending(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(contentModerationService.listPending()); + } + + @PostMapping("/{id}/review") + @OperationGuard(action = "admin-content-moderation-review", ttlSeconds = 5, message = "复核处理中,请勿重复提交") + public Result 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; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java new file mode 100644 index 00000000..aa4b8cbd --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminPhoneBackfillController.java @@ -0,0 +1,43 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin; + +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.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneBackfillReport; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneDataBackfillService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +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 +@RequiredArgsConstructor +@RequestMapping("/admin/privacy/phone-backfill") +public class AdminPhoneBackfillController { + private final PhoneDataBackfillService backfillService; + private final UserMapper userMapper; + + @GetMapping("/report") + public Result report(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(backfillService.backfill(true)); + } + + @PostMapping("/run") + public Result run(HttpServletRequest request) { + requirePlatformAdmin(request); + return Result.success(backfillService.backfill(false)); + } + + private void requirePlatformAdmin(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + UserDO actor = userMapper.selectById((Long) value); + if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) { + throw new IllegalArgumentException("无权执行手机号数据处理"); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java new file mode 100644 index 00000000..19e74bff --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/AccountClosureController.java @@ -0,0 +1,44 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.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.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +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 +@RequiredArgsConstructor +@RequestMapping("/user/account-closure") +public class AccountClosureController { + private final AccountClosureService accountClosureService; + + @PostMapping + @OperationGuard(action = "account-closure-request", ttlSeconds = 10, message = "注销申请处理中,请勿重复提交") + public Result request(HttpServletRequest request) { + return Result.success(accountClosureService.request(userId(request))); + } + + @GetMapping("/me") + public Result getMine(HttpServletRequest request) { + return Result.success(accountClosureService.getMine(userId(request))); + } + + @DeleteMapping("/me") + @OperationGuard(action = "account-closure-withdraw", ttlSeconds = 10, message = "撤回处理中,请勿重复操作") + public Result withdraw(HttpServletRequest request) { + return Result.success(accountClosureService.withdraw(userId(request))); + } + + private Long userId(HttpServletRequest request) { + Object value = request.getAttribute("userId"); + if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效"); + return (Long) value; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java new file mode 100644 index 00000000..b0ee033d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -0,0 +1,114 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/integration/wechat/content-moderation") +public class WechatContentModerationCallbackController { + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final WechatMiniProperties wechatProperties; + private final WechatCallbackCrypto crypto; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; + + @GetMapping("/callback") + public String verifyEndpoint(@RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @RequestParam("echostr") String echoString) { + ModerationRuntimeConfig config = requireCallbackConfig(); + if ("aes".equalsIgnoreCase(encryptType)) { + if (!crypto.verify(config.getCallbackToken(), timestamp, nonce, echoString, messageSignature)) { + throw new IllegalArgumentException("微信审核回调 AES 握手校验失败"); + } + return crypto.decrypt(echoString, config.getEncodingAesKey(), wechatProperties.getAppId()); + } + if (!crypto.verifyPlain(config.getCallbackToken(), timestamp, nonce, signature)) { + throw new IllegalArgumentException("微信审核回调明文握手校验失败"); + } + return echoString; + } + + @PostMapping(value = "/callback", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE}) + public String callback(@RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @org.springframework.web.bind.annotation.RequestBody String body) throws Exception { + ModerationRuntimeConfig config = requireWechatConfig(); + String encrypted = crypto.encryptedValue(body); + String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature; + if (!crypto.verify(config.getCallbackToken(), timestamp, nonce, + "aes".equalsIgnoreCase(encryptType) ? encrypted : "", expectedSignature)) { + throw new IllegalArgumentException("微信审核回调签名校验失败"); + } + if (!"aes".equalsIgnoreCase(encryptType) || !StringUtils.hasText(config.getEncodingAesKey())) { + throw new IllegalArgumentException("微信审核回调仅接受 AES 加密消息"); + } + String decoded = crypto.decrypt(encrypted, config.getEncodingAesKey(), wechatProperties.getAppId()); + String taskId; + String suggest; + String reason; + if (decoded.trim().startsWith("<")) { + taskId = firstNonBlank(crypto.value(decoded, "trace_id"), crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id")); + suggest = firstNonBlank(crypto.value(decoded, "suggest"), crypto.value(decoded, "Suggest"), "review"); + reason = firstNonBlank(crypto.value(decoded, "errmsg"), crypto.value(decoded, "label"), "微信异步图片审核回调"); + } else { + JsonNode root = objectMapper.readTree(decoded); + taskId = firstText(root, "trace_id", "traceId", "task_id"); + suggest = firstText(root.path("result"), "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + reason = firstText(root, "errmsg", "reason"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + } + if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); + contentModerationService.handleWechatImageResult(taskId, suggest, reason); + return "success"; + } + + private String firstText(JsonNode node, String... keys) { + for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText(); + return null; + } + + private String firstNonBlank(String... values) { + for (String value : values) if (StringUtils.hasText(value)) return value; + return null; + } + + private ModerationRuntimeConfig requireWechatConfig() { + ModerationRuntimeConfig config = requireCallbackConfig(); + if (!"WECHAT".equals(config.getProvider())) { + throw new IllegalStateException("微信内容审核回调尚未启用或配置不完整"); + } + return config; + } + + private ModerationRuntimeConfig requireCallbackConfig() { + ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationCallbackConfig(); + if (config == null || !config.isReady() + || !StringUtils.hasText(config.getCallbackToken()) + || !StringUtils.hasText(config.getEncodingAesKey())) { + throw new IllegalStateException("微信内容审核回调凭据尚未配置完整"); + } + return config; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java new file mode 100644 index 00000000..25e9a019 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/AccountClosureProcessDTO.java @@ -0,0 +1,13 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class AccountClosureProcessDTO { + private String decision; + private Long successorManagerId; + private List archiveShopIds; + private String note; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java new file mode 100644 index 00000000..162ae123 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dto/ContentModerationReviewDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +public class ContentModerationReviewDTO { + private Boolean approved; + @NotBlank + private String reason; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java new file mode 100644 index 00000000..64eb74d4 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/AccountClosureRequestDO.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_account_closure_request") +public class AccountClosureRequestDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private Long userId; + private String status; + private LocalDateTime requestedAt; + private LocalDateTime processedAt; + private Long reviewerId; + private String reviewerNote; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java new file mode 100644 index 00000000..ec535536 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java @@ -0,0 +1,26 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_content_moderation_image_task") +public class ContentModerationImageTaskDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private Long recordId; + private Long fileId; + private String providerTaskId; + private String status; + private String resultCode; + private String reason; + private Integer attemptCount; + private LocalDateTime nextRetryAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java new file mode 100644 index 00000000..0d6f093b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java @@ -0,0 +1,34 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_content_moderation_record") +public class ContentModerationRecordDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private String contentType; + private Long businessId; + private Long userId; + private Integer versionNo; + private Integer imageCount; + private String textStatus; + private String textContent; + private String status; + private String provider; + private String resultCode; + private String reason; + private String payloadJson; + private Long reviewedBy; + private LocalDateTime reviewedAt; + private Integer attemptCount; + private LocalDateTime nextRetryAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java new file mode 100644 index 00000000..2f219aa3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/AccountClosureRequestMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO; + +public interface AccountClosureRequestMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java new file mode 100644 index 00000000..f4d8e8bc --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; + +public interface ContentModerationImageTaskMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java new file mode 100644 index 00000000..00d420c7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationRecordMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; + +public interface ContentModerationRecordMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java new file mode 100644 index 00000000..4b92f09d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +public interface ContentModerationProvider { + String providerName(); + + ModerationOutcome reviewText(String contentType, String content, String openId); + + ModerationOutcome submitImage(String contentType, String imageUrl, String openId); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java new file mode 100644 index 00000000..5a5838f4 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java @@ -0,0 +1,36 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import org.springframework.stereotype.Component; + +@Component +public class LocalMockContentModerationProvider implements ContentModerationProvider { + @Override + public String providerName() { + return "LOCAL_MOCK"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return result(content); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return result(imageUrl); + } + + private ModerationOutcome result(String content) { + String value = content == null ? "" : content; + if (value.contains("[[MOCK:FAIL]]")) throw new IllegalStateException("本地模拟审核故障"); + if (value.contains("[[MOCK:REJECT]]")) { + return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "MOCK_REJECT", "本地模拟命中拒绝场景"); + } + if (value.contains("[[MOCK:PENDING]]")) { + return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_PENDING", "本地模拟进入人工复核"); + } + if (value.contains("[[MOCK:APPROVE]]")) { + return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_APPROVE", "本地模拟通过场景"); + } + return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_UNMATCHED", "开发环境模拟审核默认通过"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java new file mode 100644 index 00000000..b4ea0e4b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +public record ModerationOutcome(Status status, String code, String reason, String remoteTaskId) { + public ModerationOutcome(Status status, String code, String reason) { + this(status, code, reason, null); + } + + public enum Status { APPROVED, PENDING, REJECTED, RETRY } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java new file mode 100644 index 00000000..549e254b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java @@ -0,0 +1,46 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Slf4j +@Primary +@Component +@RequiredArgsConstructor +public class RoutingContentModerationProvider implements ContentModerationProvider { + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final LocalMockContentModerationProvider mockProvider; + private final UnconfiguredContentModerationProvider unconfiguredProvider; + private final WechatContentModerationProvider wechatProvider; + + @Override + public String providerName() { + return resolveProvider().providerName(); + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return resolveProvider().reviewText(contentType, content, openId); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return resolveProvider().submitImage(contentType, imageUrl, openId); + } + + private ContentModerationProvider resolveProvider() { + try { + ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationRuntimeConfig(); + if (config == null || !config.isReady()) return unconfiguredProvider; + if ("MOCK".equals(config.getProvider())) return mockProvider; + if ("WECHAT".equals(config.getProvider())) return wechatProvider; + } catch (RuntimeException exception) { + log.warn("无法读取内容审核安全配置,保持失败关闭", exception); + } + return unconfiguredProvider; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java new file mode 100644 index 00000000..8b561b02 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import org.springframework.stereotype.Component; + +@Component +public class UnconfiguredContentModerationProvider implements ContentModerationProvider { + @Override + public String providerName() { + return "UNCONFIGURED"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return new ModerationOutcome( + ModerationOutcome.Status.RETRY, + "PROVIDER_NOT_CONFIGURED", + "内容审核平台尚未接入,内容已隔离等待人工复核" + ); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return reviewText(contentType, imageUrl, openId); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java new file mode 100644 index 00000000..a3d1da87 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -0,0 +1,118 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Component +public class WechatContentModerationProvider implements ContentModerationProvider { + private static final String TEXT_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check"; + private static final String IMAGE_CHECK_URL = "https://api.weixin.qq.com/wxa/media_check_async"; + + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ContentModerationProperties properties; + + public WechatContentModerationProvider( + @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, + ObjectMapper objectMapper, + WechatMiniClientService wechatMiniClientService, + ContentModerationProperties properties) { + this.restTemplate = restTemplate; + this.objectMapper = objectMapper; + this.wechatMiniClientService = wechatMiniClientService; + this.properties = properties; + } + + @Override + public String providerName() { + return "WECHAT"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(content)) return approved("EMPTY_TEXT"); + Map payload = new LinkedHashMap<>(); + payload.put("content", content); + payload.put("version", 2); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(TEXT_CHECK_URL, payload), false); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { + return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址"); + } + Map payload = new LinkedHashMap<>(); + payload.put("media_url", imageUrl); + payload.put("media_type", 2); + payload.put("version", 2); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(IMAGE_CHECK_URL, payload), true); + } + + private Map post(String endpoint, Map payload) { + String url = UriComponentsBuilder.fromHttpUrl(endpoint) + .queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration()) + .toUriString(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + try { + String response = restTemplate.postForObject(url, new HttpEntity<>(payload, headers), String.class); + if (!StringUtils.hasText(response)) throw new IllegalStateException("微信审核服务返回空响应"); + return objectMapper.readValue(response, new TypeReference>() {}); + } catch (RestClientException | java.io.IOException exception) { + throw new IllegalStateException("微信内容审核请求失败", exception); + } + } + + private ModerationOutcome parseResult(Map response, boolean asynchronous) { + int errorCode = number(response.get("errcode")); + if (errorCode != 0) return errorCode == 87014 + ? new ModerationOutcome(ModerationOutcome.Status.REJECTED, String.valueOf(errorCode), "微信内容安全接口判定内容违规") + : retry(String.valueOf(errorCode), "微信内容安全接口暂不可用"); + if (asynchronous) { + String taskId = text(response.get("trace_id")); + return StringUtils.hasText(taskId) + ? new ModerationOutcome(ModerationOutcome.Status.PENDING, "WECHAT_ASYNC", "等待微信图片审核回调", taskId) + : retry("TRACE_ID_MISSING", "微信图片审核未返回任务标识"); + } + Object resultRaw = response.get("result"); + if (resultRaw instanceof Map) { + Object suggest = ((Map) resultRaw).get("suggest"); + if ("pass".equalsIgnoreCase(text(suggest))) return approved("WECHAT_PASS"); + if ("review".equalsIgnoreCase(text(suggest))) return pending("WECHAT_REVIEW", "微信要求人工复核"); + if ("risky".equalsIgnoreCase(text(suggest))) return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "WECHAT_RISKY", "微信内容安全接口判定内容违规"); + } + return retry("RESULT_MISSING", "微信内容安全接口未返回明确审核结论"); + } + + private int number(Object value) { + try { return value == null ? -1 : Integer.parseInt(String.valueOf(value)); } + catch (NumberFormatException ignored) { return -1; } + } + + private String text(Object value) { return value == null ? null : String.valueOf(value); } + private ModerationOutcome approved(String code) { return new ModerationOutcome(ModerationOutcome.Status.APPROVED, code, "审核通过"); } + private ModerationOutcome pending(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.PENDING, code, reason); } + private ModerationOutcome retry(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.RETRY, code, reason); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java new file mode 100644 index 00000000..fd0f650a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.scheduler; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ContentModerationRetryScheduler { + private final ContentModerationService contentModerationService; + + @Scheduled(cron = "${jayucloud-salon.privacy.content-moderation.retry-cron:0 */2 * * * *}") + public void retryFailedImageTasks() { + int count = contentModerationService.retryFailedImageTasks(); + if (count > 0) log.info("内容审核图片重试任务完成, count={}", count); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java new file mode 100644 index 00000000..77092474 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/AccountClosureService.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO; + +import java.util.List; + +public interface AccountClosureService { + AccountClosureRequestVO request(Long userId); + AccountClosureRequestVO getMine(Long userId); + boolean withdraw(Long userId); + List listPending(); + boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java new file mode 100644 index 00000000..8b5360c0 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; + +import java.util.List; + +public interface ContentModerationService { + ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson); + ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds); + List listPending(); + boolean review(Long reviewerId, Long recordId, boolean approved, String reason); + boolean handleWechatImageResult(String providerTaskId, String suggest, String reason); + int retryFailedImageTasks(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java new file mode 100644 index 00000000..68282375 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/AccountClosureServiceImpl.java @@ -0,0 +1,297 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.AccountClosureRequestMapper; +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.security.entity.UserShopRoleDO; +import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserRelationDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper; +import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class AccountClosureServiceImpl implements AccountClosureService { + private static final String PENDING = "PENDING"; + private static final String WITHDRAWN = "WITHDRAWN"; + private static final String APPROVED = "APPROVED"; + private static final String REJECTED = "REJECTED"; + + private final AccountClosureRequestMapper requestMapper; + private final UserMapper userMapper; + private final ShopMapper shopMapper; + private final UserShopBindingMapper bindingMapper; + private final UserShopRoleMapper shopRoleMapper; + private final UserRelationMapper relationMapper; + private final WechatMiniBindingMapper wechatBindingMapper; + private final UserAgreementConsentMapper consentMapper; + private final SecurityAuditLogMapper securityAuditLogMapper; + private final OrderMapper orderMapper; + private final UserSessionService sessionService; + + @Override + @Transactional(rollbackFor = Exception.class) + public AccountClosureRequestVO request(Long userId) { + UserDO user = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getId, userId).eq(UserDO::getIsDelete, 0).last("FOR UPDATE")); + if (user == null) throw new IllegalStateException("账号不存在或已注销"); + if (Integer.valueOf(4).equals(user.getType())) throw new IllegalStateException("管理员账号不能申请注销"); + AccountClosureRequestDO pending = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (pending != null) return toVO(pending, user); + + AccountClosureRequestDO request = new AccountClosureRequestDO(); + request.setUserId(userId); + request.setStatus(PENDING); + request.setRequestedAt(LocalDateTime.now()); + requestMapper.insert(request); + return toVO(request, user); + } + + @Override + public AccountClosureRequestVO getMine(Long userId) { + AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (request == null) return null; + UserDO user = userMapper.selectById(userId); + return toVO(request, user); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean withdraw(Long userId) { + AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getUserId, userId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByDesc(AccountClosureRequestDO::getRequestedAt) + .last("limit 1")); + if (request == null) return false; + request.setStatus(WITHDRAWN); + request.setProcessedAt(LocalDateTime.now()); + return requestMapper.updateById(request) > 0; + } + + @Override + public List listPending() { + return requestMapper.selectList(new LambdaQueryWrapper() + .eq(AccountClosureRequestDO::getStatus, PENDING) + .orderByAsc(AccountClosureRequestDO::getRequestedAt)) + .stream() + .map(request -> toVO(request, userMapper.selectById(request.getUserId()))) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto) { + if (dto == null || (!"APPROVE".equals(dto.getDecision()) && !"REJECT".equals(dto.getDecision()))) { + throw new IllegalArgumentException("请选择批准或驳回"); + } + AccountClosureRequestDO request = requestMapper.selectById(requestId); + if (request == null || !PENDING.equals(request.getStatus())) throw new IllegalStateException("注销申请已处理或不存在"); + int claimed = requestMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountClosureRequestDO::getId, requestId) + .eq(AccountClosureRequestDO::getStatus, PENDING) + .set(AccountClosureRequestDO::getStatus, "PROCESSING")); + if (claimed != 1) throw new IllegalStateException("注销申请已处理或正在处理中"); + UserDO user = requireActiveUser(request.getUserId()); + if ("REJECT".equals(dto.getDecision())) { + if (!StringUtils.hasText(dto.getNote())) throw new IllegalArgumentException("驳回原因不能为空"); + request.setStatus(REJECTED); + request.setReviewerNote(dto.getNote().trim()); + } else { + transferOrArchiveShops(user, dto); + anonymizeUser(user); + request.setStatus(APPROVED); + request.setReviewerNote(StringUtils.hasText(dto.getNote()) ? dto.getNote().trim() : "已完成资料清理与会话撤销"); + } + request.setReviewerId(reviewerId); + request.setProcessedAt(LocalDateTime.now()); + return requestMapper.updateById(request) > 0; + } + + private void transferOrArchiveShops(UserDO user, AccountClosureProcessDTO dto) { + List bindings = bindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + if (bindings.isEmpty()) return; + if (!Integer.valueOf(2).equals(user.getType())) { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0) + .set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + return; + } + if (dto.getSuccessorManagerId() != null) { + UserDO successor = requireActiveUser(dto.getSuccessorManagerId()); + if (!Integer.valueOf(2).equals(successor.getType()) || Objects.equals(successor.getId(), user.getId())) { + throw new IllegalArgumentException("接手账号必须是其他已启用店长"); + } + for (UserShopBindingDO binding : bindings) { + UserShopBindingDO successorBinding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, successor.getId()) + .eq(UserShopBindingDO::getShopId, binding.getShopId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .last("limit 1")); + if (successorBinding == null) { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getId, binding.getId()) + .set(UserShopBindingDO::getUserId, successor.getId()) + .set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + } else { + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getId, binding.getId()) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + } + } + List roles = shopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)); + for (UserShopRoleDO role : roles) { + UserShopRoleDO existing = shopRoleMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, successor.getId()) + .eq(UserShopRoleDO::getShopId, role.getShopId()) + .eq(UserShopRoleDO::getRoleId, role.getRoleId()) + .eq(UserShopRoleDO::getIsDelete, 0) + .last("limit 1")); + if (existing == null) { + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getId, role.getId()) + .set(UserShopRoleDO::getUserId, successor.getId()) + .set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } else { + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getId, role.getId()) + .set(UserShopRoleDO::getIsDelete, 1) + .set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } + } + return; + } + + Set shopIds = bindings.stream().map(UserShopBindingDO::getShopId).collect(Collectors.toSet()); + if (dto.getArchiveShopIds() == null || !dto.getArchiveShopIds().containsAll(shopIds)) { + throw new IllegalArgumentException("必须明确归档该账号关联的全部门店"); + } + shopMapper.update(null, new LambdaUpdateWrapper() + .in(ShopDO::getId, shopIds) + .set(ShopDO::getStatus, 0) + .set(ShopDO::getUpdateTime, LocalDateTime.now())); + bindingMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now())); + shopRoleMapper.update(null, new LambdaUpdateWrapper() + .eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0) + .set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now())); + } + + private void anonymizeUser(UserDO user) { + Long userId = user.getId(); + sessionService.revokeAllUserSessions(userId); + wechatBindingMapper.delete(new LambdaQueryWrapper().eq(WechatMiniBindingDO::getUserId, userId)); + relationMapper.update(null, new LambdaUpdateWrapper() + .eq(UserRelationDO::getUserId, userId).eq(UserRelationDO::getIsDelete, 0) + .set(UserRelationDO::getIsDelete, 1).set(UserRelationDO::getUpdateTime, LocalDateTime.now())); + relationMapper.update(null, new LambdaUpdateWrapper() + .eq(UserRelationDO::getParentUserId, userId).eq(UserRelationDO::getIsDelete, 0) + .set(UserRelationDO::getParentUserId, null).set(UserRelationDO::getUpdateTime, LocalDateTime.now())); + orderMapper.update(null, new LambdaUpdateWrapper() + .eq(OrderDO::getUserId, userId) + .set(OrderDO::getUserId, null) + .set(OrderDO::getCustomerNameSnapshot, "已注销用户") + .set(OrderDO::getCustomerPhoneSnapshot, null) + .set(OrderDO::getCustomerPhoneSnapshotHash, null) + .set(OrderDO::getUpdateTime, LocalDateTime.now())); + consentMapper.update(null, new LambdaUpdateWrapper() + .eq(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, userId) + .set(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, null)); + securityAuditLogMapper.update(null, new LambdaUpdateWrapper() + .eq(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, userId) + .set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, null) + .set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getAccount, "已注销用户")); + user.setNickname("已注销用户"); + user.setAccount(null); + user.setAccountHash(null); + user.setPassword(null); + user.setPhone(null); + user.setPhoneHash(null); + user.setContactPhone(null); + user.setContactPhoneHash(null); + user.setPhoneVerified(0); + user.setEmail(null); + user.setEmailVerified(0); + user.setBirthday(null); + user.setWechatId(null); + user.setWechatQrCode(null); + user.setAvatar(null); + user.setSignature(null); + user.setShopId(null); + user.setStatus(0); + user.setIsDelete(1); + user.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(user); + } + + private UserDO requireActiveUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new IllegalStateException("账号不存在或已注销"); + return user; + } + + private AccountClosureRequestVO toVO(AccountClosureRequestDO request, UserDO user) { + AccountClosureRequestVO vo = new AccountClosureRequestVO(); + vo.setId(request.getId()); + vo.setUserId(request.getUserId()); + vo.setNickname(user == null ? "已注销用户" : user.getNickname()); + vo.setUserType(user == null ? null : user.getType()); + vo.setStatus(request.getStatus()); + vo.setRequestedAt(request.getRequestedAt()); + vo.setProcessingTargetText("目标:15个工作日内完成,具体时长视门店移交或归档流程而定。"); + if (user != null && Integer.valueOf(2).equals(user.getType())) { + List bindings = bindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + List shopIds = bindings.stream().map(UserShopBindingDO::getShopId).distinct().collect(Collectors.toList()); + vo.setShopIds(shopIds); + vo.setShopNames(shopIds.isEmpty() ? List.of() : shopMapper.selectBatchIds(shopIds).stream().map(ShopDO::getShopName).collect(Collectors.toList())); + } + vo.setProcessedAt(request.getProcessedAt()); + vo.setReviewerNote(request.getReviewerNote()); + return vo; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java new file mode 100644 index 00000000..886f5094 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java @@ -0,0 +1,540 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO; +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.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationImageTaskMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +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.privacy.vo.ContentModerationResultVO; +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.product.entity.EffectDiagramDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.Comparator; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ContentModerationServiceImpl implements ContentModerationService { + private final ContentModerationProvider provider; + private final ContentModerationRecordMapper recordMapper; + private final ContentModerationImageTaskMapper imageTaskMapper; + private final ProductMapper productMapper; + private final EffectDiagramMapper effectDiagramMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + private final CommentMapper commentMapper; + private final ShopMapper shopMapper; + private final AnnouncementMapper announcementMapper; + private final SystemMessageMapper systemMessageMapper; + private final UserMapper userMapper; + private final WechatMiniBindingMapper bindingMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ObjectStorageFileService objectStorageFileService; + private final ContentModerationProperties properties; + private final ObjectMapper objectMapper; + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson) { + return assessVersion(contentType, businessId, userId, content, payloadJson, Collections.emptyList()); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds) { + List normalizedImageIds = imageFileIds == null ? Collections.emptyList() : imageFileIds.stream() + .filter(fileId -> fileId != null && fileId > 0) + .collect(java.util.stream.Collectors.collectingAndThen( + java.util.stream.Collectors.toCollection(LinkedHashSet::new), ArrayList::new)); + ContentModerationRecordDO record = new ContentModerationRecordDO(); + record.setContentType(contentType); + record.setBusinessId(businessId); + record.setUserId(userId); + record.setVersionNo(nextVersion(contentType, businessId, userId)); + record.setTextContent(text); + record.setImageCount(normalizedImageIds.size()); + record.setProvider(provider.providerName()); + record.setPayloadJson(payloadJson); + record.setAttemptCount(1); + int maxRetries = Math.max(0, properties.getMaxRetries() == null ? 3 : properties.getMaxRetries()); + + String openId = resolveOpenId(userId); + ModerationOutcome textOutcome = StringUtils.hasText(openId) + ? safeTextReview(contentType, text, openId) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean textRetryExhausted = exhausted(textOutcome, 1, maxRetries); + record.setTextStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setResultCode(textOutcome.code()); + record.setReason(textRetryExhausted ? "自动重试已关闭,转人工复核" : textOutcome.reason()); + record.setStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setNextRetryAt(textOutcome.status() == ModerationOutcome.Status.RETRY && !textRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); + recordMapper.insert(record); + + if (!normalizedImageIds.isEmpty()) { + for (Long fileId : normalizedImageIds) { + ContentModerationImageTaskDO task = new ContentModerationImageTaskDO(); + task.setRecordId(record.getId()); + task.setFileId(fileId); + task.setAttemptCount(1); + ModerationOutcome imageOutcome = StringUtils.hasText(openId) + ? safeImageReview(contentType, fileId, openId) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean imageRetryExhausted = exhausted(imageOutcome, 1, maxRetries); + task.setStatus(imageRetryExhausted ? "PENDING" : imageOutcome.status().name()); + task.setResultCode(imageOutcome.code()); + task.setReason(imageRetryExhausted ? "自动重试已关闭,转人工复核" : imageOutcome.reason()); + task.setProviderTaskId(imageOutcome.remoteTaskId()); + task.setNextRetryAt(imageOutcome.status() == ModerationOutcome.Status.RETRY && !imageRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.insert(task); + } + } + refreshAggregate(record); + return result(record); + } + + @Override + public List listPending() { + List records = recordMapper.selectList(new LambdaQueryWrapper() + .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY") + .orderByAsc(ContentModerationRecordDO::getCreateTime)); + List result = new ArrayList<>(); + for (ContentModerationRecordDO record : records) { + ContentModerationRecordVO vo = new ContentModerationRecordVO(); + vo.setId(record.getId()); + vo.setContentType(record.getContentType()); + vo.setBusinessId(record.getBusinessId()); + vo.setStatus(record.getStatus()); + vo.setResultCode(record.getResultCode()); + vo.setReason(record.getReason()); + vo.setTextPreview(record.getTextContent()); + vo.setAttemptCount(record.getAttemptCount()); + vo.setCreateTime(record.getCreateTime()); + UserDO author = record.getUserId() == null ? null : userMapper.selectById(record.getUserId()); + vo.setAuthorName(author == null ? "后台/未知发布者" : author.getNickname()); + vo.setImages(loadImagePreviews(record)); + result.add(vo); + } + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean review(Long reviewerId, Long recordId, boolean approved, String reason) { + if (!StringUtils.hasText(reason)) throw new IllegalArgumentException("复核说明不能为空"); + ContentModerationRecordDO record = lockVersionRecord(recordId); + if (record == null || !isReviewable(record.getStatus())) throw new IllegalStateException("该内容已复核或不存在"); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, recordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("FOR UPDATE")); + if (approved && tasks.size() != (record.getImageCount() == null ? 0 : record.getImageCount())) { + throw new IllegalStateException("图片审核任务不完整,不能通过复核"); + } + if (approved) { + for (ContentModerationImageTaskDO task : tasks) { + try { + objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes()); + } catch (RuntimeException exception) { + throw new IllegalStateException("存在无法安全预览的图片,不能通过复核"); + } + } + } + for (ContentModerationImageTaskDO task : tasks) { + task.setStatus(approved ? "APPROVED" : "REJECTED"); + task.setReason("由管理员人工复核"); + task.setProviderTaskId(null); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + } + record.setTextStatus(approved ? "APPROVED" : "REJECTED"); + record.setStatus(approved ? "APPROVED" : "REJECTED"); + record.setReviewedBy(reviewerId); + record.setReviewedAt(LocalDateTime.now()); + record.setReason(reason.trim()); + record.setNextRetryAt(null); + if (approved && isCurrentVersionLocked(record)) applyApprovedPayload(record); + record.setPayloadJson(null); + return recordMapper.updateById(record) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) { + if (!StringUtils.hasText(providerTaskId)) return false; + ContentModerationImageTaskDO candidate = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId).last("LIMIT 1")); + if (candidate == null) return false; + if (!isReviewable(candidate.getStatus())) return true; + + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + if (record == null || !isReviewable(record.getStatus())) return true; + + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId) + .last("FOR UPDATE")); + if (task == null || !isReviewable(task.getStatus())) return task != null; + if ("pass".equalsIgnoreCase(suggest)) task.setStatus("APPROVED"); + else if ("risky".equalsIgnoreCase(suggest)) task.setStatus("REJECTED"); + else task.setStatus("PENDING"); + task.setResultCode("WECHAT_CALLBACK_" + (suggest == null ? "UNKNOWN" : suggest.toUpperCase())); + task.setReason(reason); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int retryFailedImageTasks() { + int maxRetries = properties.getMaxRetries() == null ? 3 : properties.getMaxRetries(); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationImageTaskDO::getRecordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("LIMIT 100")); + int attempted = 0; + for (ContentModerationImageTaskDO candidate : tasks) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + String openId = record == null ? null : resolveOpenId(record.getUserId()); + if (record == null || !isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .last("FOR UPDATE")); + if (task == null) continue; + attempted++; + task.setProviderTaskId(null); + ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId); + task.setAttemptCount((task.getAttemptCount() == null ? 0 : task.getAttemptCount()) + 1); + task.setStatus(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "PENDING" : outcome.status().name()); + task.setResultCode(outcome.code()); + task.setReason(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + task.setProviderTaskId(outcome.remoteTaskId()); + task.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted(outcome, task.getAttemptCount(), maxRetries) ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + } + List records = recordMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getTextStatus, "RETRY") + .le(ContentModerationRecordDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationRecordDO::getNextRetryAt) + .or().le(ContentModerationRecordDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationRecordDO::getId) + .last("LIMIT 100")); + for (ContentModerationRecordDO candidate : records) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getId()); + if (record == null || !"RETRY".equals(record.getTextStatus()) + || (record.getNextRetryAt() != null && record.getNextRetryAt().isAfter(LocalDateTime.now()))) continue; + String openId = resolveOpenId(record.getUserId()); + if (!isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + attempted++; + ModerationOutcome outcome = safeTextReview(record.getContentType(), record.getTextContent(), openId); + record.setAttemptCount((record.getAttemptCount() == null ? 0 : record.getAttemptCount()) + 1); + boolean exhausted = exhausted(outcome, record.getAttemptCount(), maxRetries); + record.setTextStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setResultCode(outcome.code()); + record.setReason(exhausted ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + record.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted ? LocalDateTime.now().plusMinutes(2) : null); + recordMapper.updateById(record); + refreshAggregate(record); + } + return attempted; + } + + private void refreshAggregate(ContentModerationRecordDO record) { + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, record.getId())); + boolean rejected = "REJECTED".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "REJECTED".equals(task.getStatus())); + boolean retry = "RETRY".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "RETRY".equals(task.getStatus())); + boolean allImagesApproved = tasks.stream().allMatch(task -> "APPROVED".equals(task.getStatus())); + boolean pending = "PENDING".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "PENDING".equals(task.getStatus())); + int expectedImageCount = record.getImageCount() == null ? 0 : record.getImageCount(); + if (tasks.size() != expectedImageCount) pending = true; + if (rejected) record.setStatus("REJECTED"); + else if (retry) record.setStatus("RETRY"); + else if (pending) record.setStatus("PENDING"); + else if (allImagesApproved && "APPROVED".equals(record.getTextStatus())) { + if (isCurrentVersionLocked(record)) { + applyApprovedPayload(record); + } + record.setStatus("APPROVED"); + record.setPayloadJson(null); + record.setReason("文字及全部图片审核通过"); + record.setNextRetryAt(null); + } + recordMapper.updateById(record); + } + + private boolean isCurrentVersionLocked(ContentModerationRecordDO record) { + ContentModerationRecordDO latest = currentVersion(record, true); + return latest != null && record.getId().equals(latest.getId()); + } + + private ContentModerationRecordDO currentVersion(ContentModerationRecordDO record, boolean lock) { + return latestVersion(versionScope(record, lock)); + } + + private ContentModerationRecordDO lockVersionRecord(Long recordId) { + if (recordId == null) return null; + ContentModerationRecordDO snapshot = recordMapper.selectById(recordId); + if (snapshot == null) return null; + return versionScope(snapshot, true).stream() + .filter(record -> recordId.equals(record.getId())) + .findFirst() + .orElse(null); + } + + private List versionScope(ContentModerationRecordDO record, boolean lock) { + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getContentType, record.getContentType()); + if (record.getBusinessId() != null) { + query.eq(ContentModerationRecordDO::getBusinessId, record.getBusinessId()); + } else if (record.getUserId() != null) { + query.isNull(ContentModerationRecordDO::getBusinessId).eq(ContentModerationRecordDO::getUserId, record.getUserId()); + } else { + query.isNull(ContentModerationRecordDO::getBusinessId).isNull(ContentModerationRecordDO::getUserId); + } + query.orderByAsc(ContentModerationRecordDO::getId); + if (lock) query.last("FOR UPDATE"); + return recordMapper.selectList(query); + } + + private ContentModerationRecordDO latestVersion(List records) { + if (records == null || records.isEmpty()) return null; + return records.stream() + .max(Comparator.comparing(ContentModerationRecordDO::getVersionNo, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .orElse(null); + } + + private void applyApprovedPayload(ContentModerationRecordDO record) { + if (!StringUtils.hasText(record.getPayloadJson())) return; + try { + JsonNode payload = objectMapper.readTree(record.getPayloadJson()); + switch (record.getContentType()) { + case "PRODUCT": applyProduct(record.getBusinessId(), payload); break; + case "EFFECT_DIAGRAM": applyEffectDiagram(record.getBusinessId(), payload); break; + case "COMMENT": applyComment(record.getBusinessId(), payload); break; + case "ORDER_ARTIST_REVIEW": applyOrderArtistReview(record.getBusinessId(), payload); break; + case "USER_PROFILE": case "USER_AVATAR": applyUser(record.getBusinessId() == null ? record.getUserId() : record.getBusinessId(), payload); break; + case "NAIL_ARTIST_PROFILE": applyNailArtistProfile(record.getBusinessId(), payload); break; + case "SHOP": applyShop(record.getBusinessId(), payload); break; + case "ANNOUNCEMENT": applyAnnouncement(record.getBusinessId(), payload); break; + case "SYSTEM_MESSAGE": applySystemMessage(record.getBusinessId(), payload); break; + default: throw new IllegalStateException("不支持的审核内容类型: " + record.getContentType()); + } + } catch (Exception exception) { + throw new IllegalStateException("隔离内容快照无法应用", exception); + } + } + + private void applyProduct(Long id, JsonNode p) { + ProductDO row = productMapper.selectById(id); if (row == null) return; + if (p.has("shopId")) row.setShopId(p.path("shopId").asLong()); + if (p.has("title")) row.setTitle(p.path("title").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("targetAudience")) row.setTargetAudience(p.path("targetAudience").asText(null)); + if (p.has("precautions")) row.setPrecautions(p.path("precautions").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").decimalValue()); + if (p.has("tags")) row.setTags(p.path("tags").asText(null)); + if (p.has("approximateDuration")) row.setApproximateDuration(p.path("approximateDuration").asText(null)); + if (p.has("bookableArtists")) row.setBookableArtists(p.path("bookableArtists").asText(null)); + if (p.has("availableCoupons")) row.setAvailableCoupons(p.path("availableCoupons").asText(null)); + row.setFrontVisible(p.path("frontVisible").asInt(1)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); productMapper.updateById(row); + } + + private void applyEffectDiagram(Long id, JsonNode p) { + EffectDiagramDO row = effectDiagramMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("productId")) row.setProductId(p.path("productId").asLong()); + if (p.has("category")) row.setCategory(p.path("category").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").isNull() ? null : p.path("price").decimalValue()); + if (p.has("duration")) row.setDuration(p.path("duration").asText(null)); + if (p.has("tag")) row.setTag(p.path("tag").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + effectDiagramMapper.updateById(row); + } + + private void applyComment(Long id, JsonNode p) { + CommentDO row = commentMapper.selectById(id); if (row == null) return; + row.setCommentContent(p.path("commentContent").asText(row.getCommentContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); commentMapper.updateById(row); + } + + private void applyOrderArtistReview(Long id, JsonNode p) { + OrderArtistReviewDO row = orderArtistReviewMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("content")) row.setContent(p.path("content").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + orderArtistReviewMapper.updateById(row); + } + + private void applyUser(Long id, JsonNode p) { + UserDO row = userMapper.selectById(id); if (row == null) return; + if (p.hasNonNull("nickname")) row.setNickname(p.path("nickname").asText()); + if (p.has("signature")) row.setSignature(p.path("signature").asText(null)); + if (p.has("avatar")) row.setAvatar(p.path("avatar").asText(null)); + if (p.has("wechatQrCode")) row.setWechatQrCode(p.path("wechatQrCode").asText(null)); + row.setProfileModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); userMapper.updateById(row); + } + + private void applyNailArtistProfile(Long id, JsonNode p) { + NailArtistInfoDO row = nailArtistInfoMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("identity")) row.setIdentity(p.path("identity").asText(null)); + if (p.has("experience")) row.setExperience(p.path("experience").isNull() ? null : p.path("experience").asInt()); + if (p.has("skills")) row.setSkills(p.path("skills").asText(null)); + if (p.has("portfolio")) row.setPortfolio(p.path("portfolio").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + nailArtistInfoMapper.updateById(row); + } + + private void applyShop(Long id, JsonNode p) { + ShopDO row = shopMapper.selectById(id); if (row == null) return; + if (p.has("shopName")) row.setShopName(p.path("shopName").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("address")) row.setAddress(p.path("address").asText()); + if (p.has("mapProvider")) row.setMapProvider(p.path("mapProvider").asText(null)); + if (p.has("longitude")) row.setLongitude(p.path("longitude").isNull() ? null : p.path("longitude").decimalValue()); + if (p.has("latitude")) row.setLatitude(p.path("latitude").isNull() ? null : p.path("latitude").decimalValue()); + if (p.has("businessHours")) row.setBusinessHours(p.path("businessHours").asText(null)); + if (p.has("coverImageFileId")) row.setCoverImageFileId(p.path("coverImageFileId").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("themeBackgroundImageFileId")) row.setThemeBackgroundImageFileId(p.path("themeBackgroundImageFileId").asText(null)); + if (p.has("themePrimaryColor")) row.setThemePrimaryColor(p.path("themePrimaryColor").asText(null)); + if (p.has("themeSecondaryColor")) row.setThemeSecondaryColor(p.path("themeSecondaryColor").asText(null)); + if (p.has("themeAccentColor")) row.setThemeAccentColor(p.path("themeAccentColor").asText(null)); + if (p.has("themePageBgColor")) row.setThemePageBgColor(p.path("themePageBgColor").asText(null)); + if (p.has("themeCardBgColor")) row.setThemeCardBgColor(p.path("themeCardBgColor").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); shopMapper.updateById(row); + } + + private void applyAnnouncement(Long id, JsonNode p) { + AnnouncementDO row = announcementMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); announcementMapper.updateById(row); + } + + private void applySystemMessage(Long id, JsonNode p) { + SystemMessageDO row = systemMessageMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileId")) row.setImageFileId(p.path("imageFileId").isNull() ? null : p.path("imageFileId").asLong()); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); systemMessageMapper.updateById(row); + } + + private List loadImagePreviews(ContentModerationRecordDO record) { + List previews = new ArrayList<>(); + for (ContentModerationImageTaskDO task : imageTaskMapper.selectList(new LambdaQueryWrapper().eq(ContentModerationImageTaskDO::getRecordId, record.getId()))) { + ContentModerationRecordVO.ImagePreview image = new ContentModerationRecordVO.ImagePreview(); image.setFileId(task.getFileId()); image.setStatus(task.getStatus()); + try { image.setUrl(objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes())); } + catch (RuntimeException exception) { log.warn("审核图片安全预览生成失败, taskId={}", task.getId()); } + previews.add(image); + } + return previews; + } + + private ModerationOutcome safeTextReview(String type, String text, String openId) { + try { return provider.reviewText(type, text, openId); } + catch (RuntimeException exception) { return outcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); } + } + + private ModerationOutcome safeImageReview(String type, Long fileId, String openId) { + try { + String url = objectStorageFileService.createTemporaryModerationUrl(fileId, properties.getImageUrlExpireMinutes()); + return provider.submitImage(type, url, openId); + } catch (RuntimeException exception) { + return outcome(ModerationOutcome.Status.RETRY, "IMAGE_REVIEW_FAILURE", "图片审核暂不可用,内容已隔离等待重试"); + } + } + + private String resolveOpenId(Long userId) { + if (userId == null) return null; + try { + String appId = wechatMiniClientService.getConfiguredAppId(); + WechatMiniBindingDO binding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getUserId, userId).eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getStatus, 1).last("LIMIT 1")); + return binding == null ? null : binding.getOpenId(); + } catch (RuntimeException exception) { return null; } + } + + private int nextVersion(String type, Long businessId, Long userId) { + ContentModerationRecordDO scope = new ContentModerationRecordDO(); + scope.setContentType(type); + scope.setBusinessId(businessId); + scope.setUserId(userId); + ContentModerationRecordDO latest = latestVersion(versionScope(scope, true)); + return latest == null || latest.getVersionNo() == null ? 1 : latest.getVersionNo() + 1; + } + + private ContentModerationResultVO result(ContentModerationRecordDO record) { + ContentModerationResultVO vo = new ContentModerationResultVO(); vo.setRecordId(record.getId()); vo.setStatus(record.getStatus()); vo.setReason(record.getReason()); return vo; + } + private boolean isReviewable(String status) { return "PENDING".equals(status) || "RETRY".equals(status); } + private boolean exhausted(ModerationOutcome outcome, int attempts, int maxRetries) { + return outcome.status() == ModerationOutcome.Status.RETRY && attempts > Math.max(0, maxRetries); + } + private ModerationOutcome outcome(ModerationOutcome.Status status, String code, String reason) { return new ModerationOutcome(status, code, reason); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java new file mode 100644 index 00000000..0fa13211 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java @@ -0,0 +1,82 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class WechatCallbackCrypto { + public boolean verifyPlain(String token, String timestamp, String nonce, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) + || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce), signature); + } + + public boolean verify(String token, String timestamp, String nonce, String encrypted, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) + || !StringUtils.hasText(encrypted) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce, encrypted), signature); + } + + private boolean sha1Equals(List values, String signature) { + try { + String source = values.stream().sorted().collect(Collectors.joining()); + byte[] digest = MessageDigest.getInstance("SHA-1").digest(source.getBytes(StandardCharsets.UTF_8)); + return MessageDigest.isEqual(HexFormat.of().formatHex(digest).getBytes(StandardCharsets.US_ASCII), signature.getBytes(StandardCharsets.US_ASCII)); + } catch (Exception exception) { return false; } + } + + public String encryptedValue(String xml) { + return element(xml, "Encrypt"); + } + + public String decrypt(String encrypted, String encodingAesKey, String expectedAppId) { + try { + byte[] aesKey = Base64.getDecoder().decode(encodingAesKey + "="); + byte[] cipherText = Base64.getDecoder().decode(encrypted); + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(Arrays.copyOf(aesKey, 16))); + byte[] padded = cipher.doFinal(cipherText); + int messageLength = ByteBuffer.wrap(padded, 16, 4).getInt(); + if (messageLength < 0 || messageLength > padded.length - 20) throw new IllegalArgumentException("微信回调密文长度无效"); + String appId = new String(padded, 20 + messageLength, padded.length - 20 - messageLength, StandardCharsets.UTF_8).trim(); + if (!expectedAppId.equals(appId)) throw new IllegalArgumentException("微信回调 AppID 不匹配"); + return new String(padded, 20, messageLength, StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalArgumentException("微信审核回调解密失败", exception); + } + } + + public String value(String xml, String key) { + return element(xml, key); + } + + public String element(String xml, String key) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); + factory.setExpandEntityReferences(false); + Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))); + return document.getElementsByTagName(key).item(0) == null ? null : document.getElementsByTagName(key).item(0).getTextContent(); + } catch (Exception exception) { throw new IllegalArgumentException("微信审核回调 XML 无效", exception); } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java new file mode 100644 index 00000000..c050fe07 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/AccountClosureRequestVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class AccountClosureRequestVO { + private Long id; + private Long userId; + private String nickname; + private Integer userType; + private List shopIds; + private List shopNames; + private String status; + private LocalDateTime requestedAt; + private String processingTargetText; + private LocalDateTime processedAt; + private String reviewerNote; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java new file mode 100644 index 00000000..2152752b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ClosureSuccessorManagerVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ClosureSuccessorManagerVO { + private Long id; + private String nickname; + private Long shopId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java new file mode 100644 index 00000000..edea2ff7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class ContentModerationRecordVO { + private Long id; + private String contentType; + private Long businessId; + private String authorName; + private String status; + private String resultCode; + private String reason; + private String textPreview; + private List images; + private Integer attemptCount; + private LocalDateTime createTime; + + @Data + public static class ImagePreview { + private Long fileId; + private String url; + private String status; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java new file mode 100644 index 00000000..f3301075 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationResultVO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +@Data +public class ContentModerationResultVO { + private Long recordId; + private String status; + private String reason; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java index cf634963..3e764305 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java @@ -64,6 +64,7 @@ public class AdminProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -82,6 +83,7 @@ public class AdminProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java index cc04a7f4..3bdea3e0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java @@ -72,6 +72,7 @@ public class ProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -89,6 +90,7 @@ public class ProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java index bbd80343..38e66360 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java @@ -88,4 +88,7 @@ public class ProductDTO { * 来源类型 */ private String sourceType; + + /** Server-populated author id; never trust a client-supplied value. */ + private Long publisherUserId; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java index ccb2a9b1..7cb2b926 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java @@ -62,6 +62,9 @@ public class EffectDiagramDO extends BaseEntity { @TableField("tag") private String tag; + @TableField("moderation_status") + private String moderationStatus; + /** * 效果图点赞数 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java index 738d62dd..5739e23b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java @@ -105,6 +105,9 @@ public class ProductDO extends BaseEntity { @TableField("front_visible") private Integer frontVisible; + @TableField("moderation_status") + private String moderationStatus; + /** * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java index 4a238076..bfe5f63a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface EffectDiagramMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE e.is_delete = 0 AND e.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java index 40115dab..bfe1e148 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java @@ -51,6 +51,6 @@ public interface ProductMapper extends BaseMapper { @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") int decrementLikeCount(@Param("productId") Long productId); - @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java index 46ab151c..cd7dcbee 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java @@ -7,10 +7,26 @@ import com.xiaowang.jayucloud.salon.core.modules.product.entity.EffectDiagramDO; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; import com.xiaowang.jayucloud.salon.core.modules.product.service.EffectDiagramService; import com.xiaowang.jayucloud.salon.core.modules.product.vo.EffectDiagramVO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +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 org.springframework.util.StringUtils; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Collections; +import java.util.Arrays; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import java.util.stream.Collectors; /** @@ -27,6 +43,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl 0; + EffectDiagramDO candidate = copy(source); + candidate.setProductId(effectDiagramDTO.getProductId()); + candidate.setCategory(effectDiagramDTO.getCategory()); + candidate.setImageFileIds(effectDiagramDTO.getImageFileIds()); + candidate.setDescription(effectDiagramDTO.getDescription()); + candidate.setPrice(effectDiagramDTO.getPrice()); + candidate.setDuration(effectDiagramDTO.getDuration()); + candidate.setTag(effectDiagramDTO.getTag()); + candidate.setModerationStatus("PENDING"); + ContentModerationResultVO moderation = assess(candidate); + return "APPROVED".equals(moderation.getStatus()) && effectDiagramMapper.updateById(candidate) > 0; } @Override @@ -81,7 +110,7 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend */ public List listAllEffectDiagrams() { - List effectDiagramDOs = effectDiagramMapper.selectList(null); + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class).eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED")); return effectDiagramDOs.stream() + .filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -133,8 +166,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getProductId, productId) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -150,8 +185,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getCategory, category) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -177,4 +214,66 @@ public class EffectDiagramServiceImpl extends ServiceImpl payload = new LinkedHashMap<>(); + payload.put("productId", effect.getProductId()); payload.put("category", effect.getCategory()); + payload.put("imageFileIds", effect.getImageFileIds()); payload.put("description", effect.getDescription()); + payload.put("price", effect.getPrice()); payload.put("duration", effect.getDuration()); payload.put("tag", effect.getTag()); + String text = String.join("\n", safe(effect.getCategory()), safe(effect.getDescription()), safe(effect.getTag())); + return contentModerationService.assessVersion("EFFECT_DIAGRAM", effect.getId(), currentUserId(), text, + objectMapper.writeValueAsString(payload), parseImageFileIds(effect.getImageFileIds())); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("效果图审核内容序列化失败", exception); + } + } + + private EffectDiagramDO copy(EffectDiagramDO source) { + EffectDiagramDO target = new EffectDiagramDO(); + target.setId(source.getId()); target.setProductId(source.getProductId()); target.setCategory(source.getCategory()); + target.setImageFileIds(source.getImageFileIds()); target.setDescription(source.getDescription()); target.setPrice(source.getPrice()); + target.setDuration(source.getDuration()); target.setTag(source.getTag()); target.setLikeCount(source.getLikeCount()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private boolean isPublic(EffectDiagramDO effect) { + ProductDO product = effect.getProductId() == null ? null : productMapper.selectById(effect.getProductId()); + ShopDO shop = product == null || product.getShopId() == null ? null : shopMapper.selectById(product.getShopId()); + return product != null && shop != null + && Integer.valueOf(0).equals(product.getIsDelete()) + && Integer.valueOf(1).equals(product.getFrontVisible()) + && "APPROVED".equals(product.getModerationStatus()) + && Integer.valueOf(0).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("效果图必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(java.util.stream.Collectors.toList()); + } + + private String safe(String value) { return value == null ? "" : value; } + + private Long currentUserId() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) return null; + Object value = attributes.getRequest().getAttribute("userId"); + return value instanceof Long ? (Long) value : null; + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java index 84d3dd52..6f990bc3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java @@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; import com.xiaowang.jayucloud.salon.core.modules.product.dto.ProductDTO; import com.xiaowang.jayucloud.salon.core.modules.marketing.entity.CouponDO; @@ -24,8 +26,11 @@ import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO; import com.xiaowang.jayucloud.salon.core.modules.product.vo.TagInfo; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.Duration; @@ -113,6 +118,8 @@ public class ProductServiceImpl extends ServiceImpl im * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final AppCacheProperties appCacheProperties; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override /** @@ -121,6 +128,7 @@ public class ProductServiceImpl extends ServiceImpl im * @param productDTO parameter `productDTO` supplied by the caller * @return Long result consumed by the caller or returned to the frontend */ + @Transactional(rollbackFor = Exception.class) public Long createProduct(ProductDTO productDTO) { validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); @@ -138,10 +146,18 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setApproximateDuration(productDTO.getApproximateDuration()); productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible())); + Integer requestedFrontVisible = resolveFrontVisible(productDTO.getFrontVisible()); + productDO.setFrontVisible(0); productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); productDO.setIsDelete(0); + productDO.setModerationStatus("PENDING"); productMapper.insert(productDO); + ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible, productDTO.getPublisherUserId()); + if ("APPROVED".equals(moderation.getStatus())) { + productDO.setFrontVisible(requestedFrontVisible); + productDO.setModerationStatus("APPROVED"); + productMapper.updateById(productDO); + } evictPublicProductCaches(productDO.getId()); return productDO.getId(); } @@ -154,6 +170,7 @@ public class ProductServiceImpl extends ServiceImpl im * @param productDTO parameter `productDTO` supplied by the caller * @return boolean result consumed by the caller or returned to the frontend */ + @Transactional(rollbackFor = Exception.class) public boolean updateProduct(Long id, ProductDTO productDTO) { ProductDO productDO = productMapper.selectById(id); if (productDO == null) { @@ -161,26 +178,35 @@ public class ProductServiceImpl extends ServiceImpl im } validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); - productDO.setShopId(productDTO.getShopId()); - productDO.setTitle(productDTO.getTitle()); - productDO.setDescription(productDTO.getDescription()); - productDO.setTargetAudience(productDTO.getTargetAudience()); - productDO.setPrecautions(productDTO.getPrecautions()); - productDO.setImageFileIds(productDTO.getImageFileIds()); - productDO.setPrice(productDTO.getPrice()); - productDO.setTags(productDTO.getTags()); + ProductDO candidate = copyProduct(productDO); + candidate.setShopId(productDTO.getShopId()); + candidate.setTitle(productDTO.getTitle()); + candidate.setDescription(productDTO.getDescription()); + candidate.setTargetAudience(productDTO.getTargetAudience()); + candidate.setPrecautions(productDTO.getPrecautions()); + candidate.setImageFileIds(productDTO.getImageFileIds()); + candidate.setPrice(productDTO.getPrice()); + candidate.setTags(productDTO.getTags()); if (productDTO.getLikeCount() != null) { - productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + candidate.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); } if (productDTO.getCollectCount() != null) { - productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + candidate.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + } + candidate.setApproximateDuration(productDTO.getApproximateDuration()); + candidate.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + candidate.setAvailableCoupons(productDTO.getAvailableCoupons()); + Integer requestedFrontVisible = resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible()); + candidate.setFrontVisible(productDO.getFrontVisible()); + candidate.setModerationStatus("PENDING"); + candidate.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); + ContentModerationResultVO moderation = assessProduct(candidate, requestedFrontVisible, productDTO.getPublisherUserId()); + boolean updated = true; + if ("APPROVED".equals(moderation.getStatus())) { + candidate.setFrontVisible(requestedFrontVisible); + candidate.setModerationStatus("APPROVED"); + updated = productMapper.updateById(candidate) > 0; } - productDO.setApproximateDuration(productDTO.getApproximateDuration()); - productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); - productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible())); - productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); - boolean updated = productMapper.updateById(productDO) > 0; if (updated) { /** * Run business method `evictPublicProductCaches`. @@ -193,6 +219,59 @@ public class ProductServiceImpl extends ServiceImpl im return updated; } + private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible, Long publisherUserId) { + try { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("shopId", product.getShopId()); snapshot.put("title", product.getTitle()); + snapshot.put("description", product.getDescription()); snapshot.put("targetAudience", product.getTargetAudience()); + snapshot.put("precautions", product.getPrecautions()); snapshot.put("imageFileIds", product.getImageFileIds()); + snapshot.put("price", product.getPrice()); snapshot.put("tags", product.getTags()); + snapshot.put("approximateDuration", product.getApproximateDuration()); snapshot.put("bookableArtists", product.getBookableArtists()); + snapshot.put("availableCoupons", product.getAvailableCoupons()); snapshot.put("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible); + String content = String.join("\n", List.of(safe(product.getTitle()), safe(product.getDescription()), + safe(product.getTargetAudience()), safe(product.getPrecautions()), safe(product.getTags()))); + return contentModerationService.assessVersion("PRODUCT", product.getId(), publisherUserId, + content, objectMapper.writeValueAsString(snapshot), parseImageFileIds(product.getImageFileIds())); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("作品审核内容序列化失败", exception); + } + } + + private ProductDO copyProduct(ProductDO source) { + ProductDO target = new ProductDO(); + target.setId(source.getId()); target.setShopId(source.getShopId()); target.setTitle(source.getTitle()); + target.setDescription(source.getDescription()); target.setTargetAudience(source.getTargetAudience()); + target.setPrecautions(source.getPrecautions()); target.setImageFileIds(source.getImageFileIds()); + target.setPrice(source.getPrice()); target.setTags(source.getTags()); target.setLikeCount(source.getLikeCount()); + target.setCollectCount(source.getCollectCount()); target.setApproximateDuration(source.getApproximateDuration()); + target.setBookableArtists(source.getBookableArtists()); target.setAvailableCoupons(source.getAvailableCoupons()); + target.setFrontVisible(source.getFrontVisible()); target.setSourceType(source.getSourceType()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("作品图片必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(Collectors.toList()); + } + + private String safe(String value) { + return value == null ? "" : value; + } + @Override /** * Delete, revoke, or logically remove a record. @@ -305,7 +384,9 @@ public class ProductServiceImpl extends ServiceImpl im ProductDO productDO = productMapper.selectById(id); if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete()) - || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { + || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible()) + || !"APPROVED".equals(productDO.getModerationStatus()) + || !isPublicShop(productDO.getShopId())) { return null; } return convertToVO(productDO); @@ -887,6 +968,7 @@ public class ProductServiceImpl extends ServiceImpl im LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED") .orderByDesc(ProductDO::getCreateTime); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); @@ -984,7 +1066,11 @@ public class ProductServiceImpl extends ServiceImpl im private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED"); + wrapper.apply("EXISTS (SELECT 1 FROM t_shop public_product_shop WHERE public_product_shop.id = t_product.shop_id " + + "AND public_product_shop.is_delete = 0 AND public_product_shop.status = 1 " + + "AND public_product_shop.moderation_status = 'APPROVED')"); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); } @@ -1006,12 +1092,22 @@ public class ProductServiceImpl extends ServiceImpl im return wrapper; } + private boolean isPublicShop(Long shopId) { + if (shopId == null || shopId <= 0) return false; + ShopDO shop = shopMapper.selectById(shopId); + return shop != null && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + private Integer resolveFrontVisible(Integer frontVisible) { return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; } private String resolveSourceType(String sourceType) { - return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; + // MANAGER_APPOINTMENT products are created only by the planning domain. A public + // product endpoint must never trust a client-provided source to bypass moderation. + return SOURCE_TYPE_BACKEND; } private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { @@ -1022,10 +1118,8 @@ public class ProductServiceImpl extends ServiceImpl im } private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { - if (StringUtils.hasText(nextSourceType)) { - return resolveSourceType(nextSourceType); - } - return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; + return "MANAGER_APPOINTMENT".equals(currentSourceType) + ? currentSourceType : SOURCE_TYPE_BACKEND; } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java index f058ca6f..97bb3b87 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java @@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.controller; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRejectDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationAssociateDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchRegistrationService; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; @@ -18,7 +20,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController -@RequestMapping("/admin/user/workbench/registration") +@RequestMapping({"/admin/user/workbench/registration", "/user/workbench/registration"}) public class AdminWorkbenchRegistrationController { private final WorkbenchRegistrationService registrationService; private final UserMapper userMapper; @@ -40,11 +42,29 @@ public class AdminWorkbenchRegistrationController { return Result.success(registrationService.getReviewSummary(requireUserId(request))); } + @GetMapping("/unassociated") + public Result> unassociatedApplications(HttpServletRequest request) { + return Result.success(registrationService.listUnassociatedApplications(requireUserId(request))); + } + @PostMapping("/{id}/approve") - public Result approve(HttpServletRequest request, @PathVariable Long id) { + public Result approve(HttpServletRequest request, @PathVariable Long id, + @RequestBody(required = false) WorkbenchRegistrationApproveDTO requestDTO) { Long userId = requireUserId(request); UserDO user = userMapper.selectById(userId); - return Result.success(registrationService.approve(userId, isPlatformAdmin(user), id)); + return Result.success(registrationService.approve(userId, isPlatformAdmin(user), id, requestDTO)); + } + + @GetMapping("/{id}/unbound-artists") + public Result unboundArtists(HttpServletRequest request, @PathVariable Long id) { + return Result.success(registrationService.listUnboundArtists(requireUserId(request), id)); + } + + @PostMapping("/{id}/pre-associate") + public Result preAssociate(HttpServletRequest request, @PathVariable Long id, + @RequestBody WorkbenchRegistrationAssociateDTO requestDTO) { + return Result.success(registrationService.preAssociate(requireUserId(request), id, + requestDTO == null ? null : requestDTO.getTargetArtistUserId())); } @PostMapping("/{id}/reject") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java new file mode 100644 index 00000000..257f023d --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationAvatarController.java @@ -0,0 +1,56 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.controller; + +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 com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationAvatarVO; +import org.springframework.util.StringUtils; +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 java.util.Locale; + +@RestController +@RequestMapping("/user/workbench/register") +public class WorkbenchRegistrationAvatarController { + + private static final long MAX_AVATAR_SIZE = 5L * 1024 * 1024; + + private final WechatMiniAuthService wechatMiniAuthService; + private final ObjectStorageDirectUploadService objectStorageDirectUploadService; + + public WorkbenchRegistrationAvatarController(WechatMiniAuthService wechatMiniAuthService, + ObjectStorageDirectUploadService objectStorageDirectUploadService) { + this.wechatMiniAuthService = wechatMiniAuthService; + this.objectStorageDirectUploadService = objectStorageDirectUploadService; + } + + @PostMapping("/avatar") + public Result uploadAvatar( + @RequestParam("registrationTicket") String registrationTicket, + @RequestParam("file") MultipartFile file) { + if (!StringUtils.hasText(registrationTicket)) return Result.error("注册票据不能为空"); + if (file == null || file.isEmpty() || file.getSize() > MAX_AVATAR_SIZE) { + return Result.error("头像不能为空且不能超过5MB"); + } + String contentType = file.getContentType() == null ? "" : file.getContentType().toLowerCase(Locale.ROOT); + String filename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename().toLowerCase(Locale.ROOT); + boolean supportedImage = ("image/jpeg".equals(contentType) && (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))) + || ("image/png".equals(contentType) && filename.endsWith(".png")) + || ("image/webp".equals(contentType) && filename.endsWith(".webp")); + if (!supportedImage) return Result.error("头像仅支持 JPG、PNG 或 WebP 图片"); + + try { + wechatMiniAuthService.validateRegistrationTicket(registrationTicket); + ObjectStorageFileVO fileVO = objectStorageDirectUploadService.upload(file); + wechatMiniAuthService.rememberRegistrationAvatarUpload(registrationTicket, fileVO.getId()); + return Result.success(new WorkbenchRegistrationAvatarVO(fileVO.getId())); + } catch (Exception error) { + return Result.error(error.getMessage() == null ? "头像上传失败" : error.getMessage()); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java index 848c0128..d1b9dba1 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/controller/WorkbenchRegistrationController.java @@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; 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 org.springframework.web.bind.annotation.*; import java.util.List; @@ -38,7 +39,14 @@ public class WorkbenchRegistrationController { @GetMapping("/register/status") public Result status(@RequestParam String phone) { - UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone).eq(UserDO::getIsDelete, 0).last("limit 1")); + String normalizedPhone = phone == null ? "" : phone.trim(); + UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone)) + .eq(UserDO::getIsDelete, 0).last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } if (user == null) { throw new IllegalArgumentException("未找到注册申请"); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java new file mode 100644 index 00000000..af856e55 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationApproveDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationApproveDTO { + private Long targetArtistUserId; + private Boolean useApplicantNickname; + private Boolean useApplicantAvatar; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java new file mode 100644 index 00000000..3f996b87 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationAssociateDTO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationAssociateDTO { + private Long targetArtistUserId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java index f2714893..b64ec349 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java @@ -13,4 +13,6 @@ public class WorkbenchRegistrationRequestDTO { private String shopName; private String shopAddress; private Boolean agreementAccepted; + private String applicantNickname; + private Long applicantAvatarFileId; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java index 522b8b3f..3a1d7abf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java @@ -43,6 +43,18 @@ public class WorkbenchRegistrationApplicationDO extends BaseEntity { @TableField("reject_reason") private String rejectReason; + @TableField("content_moderation_record_id") + private Long contentModerationRecordId; + + @TableField("target_artist_user_id") + private Long targetArtistUserId; + + @TableField("applicant_nickname") + private String applicantNickname; + + @TableField("applicant_avatar_file_id") + private Long applicantAvatarFileId; + @TableField("is_delete") private Integer isDelete; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java new file mode 100644 index 00000000..9e17d9f1 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/scheduler/ManagerRegistrationModerationScheduler.java @@ -0,0 +1,23 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.scheduler; + +import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchRegistrationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ManagerRegistrationModerationScheduler { + private final WorkbenchRegistrationService registrationService; + + @Scheduled(fixedDelay = 30000L) + public void processPendingApplications() { + try { + registrationService.processPendingManagerModeration(); + } catch (RuntimeException exception) { + log.warn("店长注册内容审核补偿处理失败", exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java index fe41e0a0..91d1f9e4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/WorkbenchRegistrationService.java @@ -1,9 +1,11 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.service; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationArtistVO; import java.util.List; @@ -14,5 +16,10 @@ public interface WorkbenchRegistrationService { List listForReviewer(Long reviewerId, boolean platformAdmin); WorkbenchRegistrationReviewSummaryVO getReviewSummary(Long reviewerId); boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId); + boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId, WorkbenchRegistrationApproveDTO request); boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason); + List listUnboundArtists(Long reviewerId, Long applicationId); + List listUnassociatedApplications(Long reviewerId); + boolean preAssociate(Long reviewerId, Long applicationId, Long targetArtistUserId); + void processPendingManagerModeration(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java index fdab6898..87b7e038 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.dto.WorkbenchRegistrationApproveDTO; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationRole; import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRegistrationStatus; @@ -10,6 +11,9 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.service.WorkbenchR import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationArtistVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniRegistrationTicket; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; @@ -17,16 +21,27 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +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.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; 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.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +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; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.LocalDateTime; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; @@ -44,6 +59,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe private final UserShopBindingMapper userShopBindingMapper; private final WechatMiniAuthService wechatMiniAuthService; private final SystemParameterConfigService systemParameterConfigService; + private final ContentModerationService contentModerationService; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final ShopBusinessExpiryService shopBusinessExpiryService; + private final TransactionTemplate transactionTemplate; + private final WechatMiniBindingMapper wechatMiniBindingMapper; + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; public WorkbenchRegistrationServiceImpl( WorkbenchRegistrationApplicationMapper applicationMapper, @@ -53,7 +75,14 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe UserShopBindingSupport userShopBindingSupport, UserShopBindingMapper userShopBindingMapper, WechatMiniAuthService wechatMiniAuthService, - SystemParameterConfigService systemParameterConfigService + SystemParameterConfigService systemParameterConfigService, + ContentModerationService contentModerationService, + ContentModerationRecordMapper contentModerationRecordMapper, + ShopBusinessExpiryService shopBusinessExpiryService, + PlatformTransactionManager transactionManager, + WechatMiniBindingMapper wechatMiniBindingMapper, + ObjectStorageFileService objectStorageFileService, + ObjectStorageUrlSupport objectStorageUrlSupport ) { this.applicationMapper = applicationMapper; this.userMapper = userMapper; @@ -63,6 +92,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe this.userShopBindingMapper = userShopBindingMapper; this.wechatMiniAuthService = wechatMiniAuthService; this.systemParameterConfigService = systemParameterConfigService; + this.contentModerationService = contentModerationService; + this.contentModerationRecordMapper = contentModerationRecordMapper; + this.shopBusinessExpiryService = shopBusinessExpiryService; + this.transactionTemplate = new TransactionTemplate(transactionManager); + this.wechatMiniBindingMapper = wechatMiniBindingMapper; + this.objectStorageFileService = objectStorageFileService; + this.objectStorageUrlSupport = objectStorageUrlSupport; } @Override @@ -82,8 +118,11 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe require(selectedStaffShop != null, "店铺不存在或暂未营业"); } - WechatMiniRegistrationTicket ticket = wechatMiniAuthService.consumeRegistrationTicket( - requireText(request.getRegistrationTicket(), "注册票据不能为空")); + String registrationTicket = requireText(request.getRegistrationTicket(), "注册票据不能为空"); + if (WorkbenchRegistrationRole.STAFF.equals(roleType) && request.getApplicantAvatarFileId() != null) { + wechatMiniAuthService.validateRegistrationAvatarUpload(registrationTicket, request.getApplicantAvatarFileId()); + } + WechatMiniRegistrationTicket ticket = wechatMiniAuthService.consumeRegistrationTicket(registrationTicket); UserDO user = userMapper.selectById(ticket.getUserId()); require(user != null && !Integer.valueOf(1).equals(user.getIsDelete()), "注册用户不存在"); @@ -109,6 +148,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe shop.setBusinessHours("10:00-22:00"); shop.setStatus(0); shop.setIsDelete(0); + shop.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDateTime.now().toLocalDate())); if (shop.getId() == null) { shopMapper.insert(shop); } else { @@ -142,6 +182,11 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe application.setShopName(shop.getShopName()); application.setShopAddress(shop.getAddress()); application.setStatus(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? WorkbenchRegistrationStatus.PENDING_ADMIN : WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setTargetArtistUserId(null); + application.setApplicantNickname(WorkbenchRegistrationRole.STAFF.equals(roleType) && StringUtils.hasText(request.getApplicantNickname()) + ? request.getApplicantNickname().trim() : null); + application.setApplicantAvatarFileId(WorkbenchRegistrationRole.STAFF.equals(roleType) ? request.getApplicantAvatarFileId() : null); + application.setContentModerationRecordId(null); application.setRejectReason(null); application.setReviewerId(null); application.setReviewedAt(null); @@ -151,6 +196,21 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe } else { applicationMapper.updateById(application); } + if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) { + String reviewText = "门店名称:" + shop.getShopName() + "\n门店地址:" + (shop.getAddress() == null ? "未填写" : shop.getAddress()); + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "SHOP", null, user.getId(), reviewText, null, Collections.emptyList()); + application.setContentModerationRecordId(moderation.getRecordId()); + applicationMapper.updateById(application); + processManagerModeration(application.getId()); + application = applicationMapper.selectById(application.getId()); + } else if (application.getApplicantNickname() != null || application.getApplicantAvatarFileId() != null) { + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "STAFF_REGISTRATION", application.getId(), user.getId(), application.getApplicantNickname(), null, + application.getApplicantAvatarFileId() == null ? Collections.emptyList() : List.of(application.getApplicantAvatarFileId())); + application.setContentModerationRecordId(moderation.getRecordId()); + applicationMapper.updateById(application); + } return toStatus(application); } @@ -172,7 +232,10 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe public List listForReviewer(Long reviewerId, boolean platformAdmin) { List applications; if (platformAdmin) { - applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getRoleType, WorkbenchRegistrationRole.MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime)); } else { UserDO reviewer = requireManager(reviewerId); applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER).eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); @@ -186,8 +249,17 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe ? Map.of() : userMapper.selectBatchIds(applicantIds).stream() .collect(Collectors.toMap(UserDO::getId, Function.identity())); + List moderationIds = applications.stream() + .map(WorkbenchRegistrationApplicationDO::getContentModerationRecordId) + .filter(Objects::nonNull).distinct().collect(Collectors.toList()); + Map moderationById = moderationIds.isEmpty() + ? Map.of() + : contentModerationRecordMapper.selectBatchIds(moderationIds).stream() + .collect(Collectors.toMap(ContentModerationRecordDO::getId, Function.identity())); return applications.stream() - .map(application -> toReviewVO(application, applicants.get(application.getUserId()))) + .map(application -> toReviewVO(application, applicants.get(application.getUserId()), + application.getContentModerationRecordId() == null + ? null : moderationById.get(application.getContentModerationRecordId()))) .collect(Collectors.toList()); } @@ -206,20 +278,72 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe @Override @Transactional(rollbackFor = Exception.class) public boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId) { + return approve(reviewerId, platformAdmin, applicationId, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId, WorkbenchRegistrationApproveDTO request) { WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, platformAdmin, applicationId); + if (WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType())) { + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + require(moderation != null && "APPROVED".equals(moderation.getStatus()), "门店资料内容审核通过后才能审核注册申请"); + } + if (WorkbenchRegistrationRole.STAFF.equals(application.getRoleType())) { + Long targetArtistUserId = request != null && request.getTargetArtistUserId() != null + ? request.getTargetArtistUserId() : application.getTargetArtistUserId(); + require(targetArtistUserId != null, "请选择要关联的美甲师"); + require(targetArtistUserId > 0, "目标美甲师不合法"); + UserDO target = loadActiveArtistForUpdate(targetArtistUserId, application.getShopId()); + require(!hasActiveWechatBinding(target.getId()), "目标美甲师已关联微信账号"); + require(!hasPendingAssociation(target.getId(), applicationId), "该美甲师已被其他申请预关联"); + application.setTargetArtistUserId(target.getId()); + return approveApplication(application, reviewerId, request); + } + return approveApplication(application, reviewerId, request); + } + + private boolean approveApplication(WorkbenchRegistrationApplicationDO application, Long reviewerId) { + return approveApplication(application, reviewerId, null); + } + + private boolean approveApplication(WorkbenchRegistrationApplicationDO application, Long reviewerId, WorkbenchRegistrationApproveDTO request) { UserDO user = userMapper.selectById(application.getUserId()); require(user != null, "申请用户不存在"); if (WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType())) { - require(platformAdmin && WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()), "无权审核该申请"); ShopDO shop = shopMapper.selectById(application.getShopId()); require(shop != null, "申请店铺不存在"); shop.setStatus(1); shopMapper.updateById(shop); + shopBusinessExpiryService.startDefaultValidity(shop.getId(), LocalDateTime.now().toLocalDate()); + } + if (WorkbenchRegistrationRole.STAFF.equals(application.getRoleType())) { + Long targetId = application.getTargetArtistUserId(); + UserDO target = loadActiveArtistForUpdate(targetId, application.getShopId()); + if (request != null && Boolean.TRUE.equals(request.getUseApplicantNickname()) && StringUtils.hasText(application.getApplicantNickname())) { + requireApplicantProfileApproved(application); + target.setNickname(application.getApplicantNickname()); + } + if (request != null && Boolean.TRUE.equals(request.getUseApplicantAvatar()) && application.getApplicantAvatarFileId() != null) { + requireApplicantProfileApproved(application); + ObjectStorageFileVO file = contentModerationFile(application.getApplicantAvatarFileId()); + target.setAvatar(objectStorageUrlSupport.toStoredUrl(StringUtils.hasText(file.getObjectName()) + ? file.getObjectName() : file.getFileUrl())); + } + target.setStatus(1); + userMapper.updateById(target); + wechatMiniAuthService.transferRegistrationBinding(application.getUserId(), target.getId()); + userShopBindingSupport.updateBindingStatus(target.getId(), application.getShopId(), 1); + userService.syncManagedPermissions(target.getId()); + user.setStatus(0); + userMapper.updateById(user); + } else { + user.setStatus(1); + userMapper.updateById(user); + userShopBindingSupport.updateBindingStatus(user.getId(), application.getShopId(), 1); + userService.syncManagedPermissions(user.getId()); } - user.setStatus(1); - userMapper.updateById(user); - userShopBindingSupport.updateBindingStatus(user.getId(), application.getShopId(), 1); - userService.syncManagedPermissions(user.getId()); application.setStatus(WorkbenchRegistrationStatus.APPROVED); application.setReviewerId(reviewerId); application.setReviewedAt(LocalDateTime.now()); @@ -227,6 +351,114 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe return true; } + private ObjectStorageFileVO contentModerationFile(Long fileId) { + ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId); + require(file != null && Integer.valueOf(1).equals(file.getStatus()), "申请头像文件不可用"); + return file; + } + + private void requireApplicantProfileApproved(WorkbenchRegistrationApplicationDO application) { + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + require(moderation != null && "STAFF_REGISTRATION".equals(moderation.getContentType()) + && Objects.equals(application.getId(), moderation.getBusinessId()) + && "APPROVED".equals(moderation.getStatus()), "申请昵称或头像尚未通过内容审核"); + } + + @Override + public List listUnboundArtists(Long reviewerId, Long applicationId) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, false, applicationId); + List users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getType, 3).eq(UserDO::getShopId, application.getShopId()).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0).orderByAsc(UserDO::getNickname)); + return users.stream() + .filter(user -> !hasActiveWechatBinding(user.getId())) + .filter(user -> !hasPendingAssociation(user.getId(), applicationId)) + .map(user -> new WorkbenchRegistrationArtistVO(user.getId(), user.getNickname(), + objectStorageUrlSupport.toAccessibleUrl(user.getAvatar()))) + .collect(Collectors.toList()); + } + + @Override + public List listUnassociatedApplications(Long reviewerId) { + return listForReviewer(reviewerId, false).stream().filter(item -> item.getTargetArtistUserId() == null).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean preAssociate(Long reviewerId, Long applicationId, Long targetArtistUserId) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, false, applicationId); + require(targetArtistUserId != null, "请选择美甲师"); + UserDO target = loadActiveArtistForUpdate(targetArtistUserId, application.getShopId()); + require(!hasActiveWechatBinding(target.getId()), "目标美甲师已关联微信账号"); + require(!hasPendingAssociation(targetArtistUserId, applicationId), "该美甲师已被其他申请预关联"); + application.setTargetArtistUserId(targetArtistUserId); + return applicationMapper.updateById(application) > 0; + } + + private UserDO loadActiveArtistForUpdate(Long userId, Long shopId) { + UserDO artist = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getId, userId) + .eq(UserDO::getType, 3) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .last("FOR UPDATE")); + require(artist != null, "目标美甲师不属于当前门店或已停用"); + return artist; + } + + private boolean hasPendingAssociation(Long artistUserId, Long currentApplicationId) { + WorkbenchRegistrationApplicationDO occupied = applicationMapper.selectOne(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getTargetArtistUserId, artistUserId) + .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .last("LIMIT 1 FOR UPDATE")); + return occupied != null && !Objects.equals(occupied.getId(), currentApplicationId); + } + + private boolean hasActiveWechatBinding(Long userId) { + return wechatMiniBindingMapper.selectCount(Wrappers.lambdaQuery(WechatMiniBindingDO.class).eq(WechatMiniBindingDO::getUserId, userId).eq(WechatMiniBindingDO::getStatus, 1)) > 0; + } + + public void processPendingManagerModeration() { + List pending = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getRoleType, WorkbenchRegistrationRole.MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .isNotNull(WorkbenchRegistrationApplicationDO::getContentModerationRecordId) + .orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime) + .last("LIMIT 100")); + for (WorkbenchRegistrationApplicationDO application : pending) { + try { + transactionTemplate.executeWithoutResult(status -> processManagerModeration(application.getId())); + } catch (RuntimeException ignored) { + // Roll back only this application; the next pass retries it independently. + } + } + } + + @Transactional(rollbackFor = Exception.class) + public void processManagerModeration(Long applicationId) { + WorkbenchRegistrationApplicationDO application = applicationMapper.selectByIdForUpdate(applicationId); + if (application == null || !WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType()) + || !WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || application.getContentModerationRecordId() == null) return; + ContentModerationRecordDO moderation = contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + if (moderation == null || !"SHOP".equals(moderation.getContentType()) || moderation.getBusinessId() != null + || !Objects.equals(moderation.getUserId(), application.getUserId())) return; + if ("REJECTED".equals(moderation.getStatus())) { + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setRejectReason(StringUtils.hasText(moderation.getReason()) ? moderation.getReason() : "门店资料内容未通过审核"); + application.setReviewedAt(LocalDateTime.now()); + applicationMapper.updateById(application); + return; + } + boolean autoApproveEnabled = "true".equalsIgnoreCase(systemParameterConfigService.getEnabledValue( + "WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")); + if (autoApproveEnabled && "APPROVED".equals(moderation.getStatus())) { + approveApplication(application, null); + } + } + @Override @Transactional(rollbackFor = Exception.class) public boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason) { @@ -235,6 +467,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe application.setReviewerId(reviewerId); application.setReviewedAt(LocalDateTime.now()); application.setRejectReason(requireText(reason, "驳回原因不能为空")); + application.setTargetArtistUserId(null); applicationMapper.updateById(application); return true; } @@ -259,17 +492,31 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe } private WorkbenchRegistrationStatusVO toStatus(WorkbenchRegistrationApplicationDO application) { - return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName()); + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), + application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName(), + moderation == null ? null : moderation.getStatus(), moderation == null ? null : moderation.getReason()); } - private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant) { + private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant, + ContentModerationRecordDO moderation) { WorkbenchRegistrationReviewVO review = new WorkbenchRegistrationReviewVO(); BeanUtils.copyProperties(application, review); if (applicant != null) { - review.setApplicantNickname(applicant.getNickname()); - review.setApplicantAvatar(applicant.getAvatar()); + boolean approved = moderation != null + && "STAFF_REGISTRATION".equals(moderation.getContentType()) + && Objects.equals(application.getId(), moderation.getBusinessId()) + && Objects.equals(application.getUserId(), moderation.getUserId()) + && "APPROVED".equals(moderation.getStatus()); + review.setApplicantNickname(approved ? (StringUtils.hasText(application.getApplicantNickname()) ? application.getApplicantNickname() : applicant.getNickname()) : null); + review.setApplicantAvatar(approved && application.getApplicantAvatarFileId() != null + ? objectStorageFileService.createTemporaryModerationUrl(application.getApplicantAvatarFileId(), 30) : null); review.setApplicantMaskedPhone(maskPhone(applicant.getPhone())); } + review.setContentModerationStatus(moderation == null ? "MISSING" : moderation.getStatus()); + review.setContentModerationReason(moderation == null ? "未关联内容审核记录" : moderation.getReason()); + review.setTargetArtistUserId(application.getTargetArtistUserId()); return review; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java new file mode 100644 index 00000000..7ed59b99 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationArtistVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationArtistVO { + private Long userId; + private String nickname; + private String avatar; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java new file mode 100644 index 00000000..41729448 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationAvatarVO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationAvatarVO { + private Long fileId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java index 16ab3fb0..714b6477 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java @@ -24,4 +24,7 @@ public class WorkbenchRegistrationReviewVO { private String applicantNickname; private String applicantAvatar; private String applicantMaskedPhone; + private Long targetArtistUserId; + private String contentModerationStatus; + private String contentModerationReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java index d23342fa..133d0e1c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java @@ -13,4 +13,6 @@ public class WorkbenchRegistrationStatusVO { private String rejectReason; private Long shopId; private String shopName; + private String contentModerationStatus; + private String contentModerationReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java index 9e371877..ca1aaada 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/entity/SecurityAuditLogDO.java @@ -60,13 +60,6 @@ public class SecurityAuditLogDO extends BaseEntity { */ private String ipAddress; - @TableField("device_id") - /** - * Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - @TableField("operate_time") /** * Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java index 29e580c0..b4b32fc5 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java @@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO; import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper; 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.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.security.vo.SecurityAuditLogVO; import lombok.RequiredArgsConstructor; @@ -38,12 +37,11 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { try { SecurityAuditLogDO log = new SecurityAuditLogDO(); log.setUserId(userId); - log.setAccount(limit(account, 80)); + log.setAccount(maskPhoneAccount(account)); log.setAction(limit(action, 80)); log.setResult(limit(result, 20)); log.setReason(limit(reason, 500)); log.setIpAddress(limit(resolveClientIp(request), 80)); - log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); log.setOperateTime(LocalDateTime.now()); auditLogMapper.insert(log); } catch (Exception ignored) { @@ -101,7 +99,6 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { vo.setResult(log.getResult()); vo.setReason(log.getReason()); vo.setIpAddress(log.getIpAddress()); - vo.setDeviceId(log.getDeviceId()); vo.setOperateTime(log.getOperateTime()); return vo; } @@ -132,4 +129,12 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { } return value.substring(0, max); } + + private String maskPhoneAccount(String value) { + if (value == null) return null; + String normalized = value.trim(); + return normalized.matches("1[3-9]\\d{9}") + ? normalized.substring(0, 3) + "****" + normalized.substring(7) + : limit(normalized, 80); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java index ef1b430f..a581544f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java @@ -107,6 +107,7 @@ public final class SecurityAuditActions { public static final String CAMPAIGN_PUBLISH = "CAMPAIGN_PUBLISH"; public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; + public static final String SECURE_CONFIG_UPDATE = "SECURE_CONFIG_UPDATE"; private SecurityAuditActions() { } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java index c8352bb1..ed48ae7c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/vo/SecurityAuditLogVO.java @@ -46,11 +46,6 @@ public class SecurityAuditLogVO { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private String ipAddress; - /** - * Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; /** * Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java index 32b20c54..7c0c9aa7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/admin/AdminShopController.java @@ -6,6 +6,8 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO; 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; @@ -17,6 +19,7 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.time.LocalDate; @RestController @RequestMapping("/admin/shops") @@ -39,6 +42,7 @@ public class AdminShopController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SecurityAuditSupport securityAuditSupport; + private final ShopBusinessExpiryService shopBusinessExpiryService; @GetMapping("/list") @RequirePermission("shop:view") @@ -180,6 +184,33 @@ public class AdminShopController { return Result.success(shop); } + @GetMapping("/business-expiries") + @RequirePermission("shop:view") + public Result> listBusinessExpiries( + HttpServletRequest request, @RequestParam String shopIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅平台管理员可以管理门店经营有效期"); + List ids = java.util.Arrays.stream(shopIds.split(",")) + .map(String::trim) + .filter(value -> !value.isEmpty()) + .map(Long::valueOf) + .distinct() + .limit(100) + .collect(java.util.stream.Collectors.toList()); + return Result.success(shopBusinessExpiryService.listExpiries(ids)); + } + + @PutMapping("/{id}/business-expiry") + @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-business-expiry", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateBusinessExpiry( + HttpServletRequest request, @PathVariable Long id, @RequestBody BusinessExpiryRequest body) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅平台管理员可以管理门店经营有效期"); + return Result.success(shopBusinessExpiryService.updateExpiry(id, + body == null || body.getExpireDate() == null ? null : LocalDate.parse(body.getExpireDate()))); + } + @Data /** * Purpose: StatusRequest supports AdminShopController.java by holding or executing the status request business role. @@ -192,4 +223,9 @@ public class AdminShopController { */ private Integer status; } + + @Data + public static class BusinessExpiryRequest { + private String expireDate; + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java index 5753348e..ab8cd7fe 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java @@ -115,7 +115,7 @@ public class ShopController { * @return Result result consumed by the caller or returned to the frontend */ public Result getShopById(@PathVariable Long id) { - ShopVO shopVO = shopService.getShopById(id); + ShopVO shopVO = shopService.getPublicShopById(id); return Result.success(shopVO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java new file mode 100644 index 00000000..8ea218ea --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopAppointmentSettingsDTO { + private String businessHours; + private Integer defaultAppointmentDurationMinutes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java new file mode 100644 index 00000000..1c43a3f5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopNameUpdateDTO { + private String shopName; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java index 67535d1e..1540d7d2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java @@ -76,6 +76,12 @@ public class ShopDO extends BaseEntity { @TableField("business_hours") private String businessHours; + @TableField("appointment_business_hours") + private String appointmentBusinessHours; + + @TableField("default_appointment_duration_minutes") + private Integer defaultAppointmentDurationMinutes; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ @@ -136,6 +142,9 @@ public class ShopDO extends BaseEntity { @TableField("status") private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("authorization_start_date") /** * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. @@ -156,6 +165,9 @@ public class ShopDO extends BaseEntity { @TableField("authorization_expire_time") private LocalDateTime authorizationExpireTime; + @TableField("business_expire_time") + private LocalDateTime businessExpireTime; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java index 1b5792dc..5cec65eb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface ShopMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") + @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java new file mode 100644 index 00000000..58aa45c2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessExpiryService.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service; + +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO; + +import java.time.LocalDate; +import java.util.List; + +public interface ShopBusinessExpiryService { + int getDefaultValidDays(); + java.time.LocalDateTime defaultExpireTime(LocalDate startDate); + void startDefaultValidity(Long shopId, LocalDate startDate); + void assertShopActive(Long shopId); + ShopBusinessExpiryVO getExpiry(Long shopId); + List listExpiries(List shopIds); + ShopBusinessExpiryVO updateExpiry(Long shopId, LocalDate expireDate); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java index 1006a133..43fb26fb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java @@ -6,6 +6,9 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +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.vo.ShopAppointmentSettingsVO; import java.util.List; @@ -51,6 +54,15 @@ public interface ShopService extends IService { */ ShopVO getShopById(Long id); + ShopAppointmentSettingsVO getAppointmentSettings(Long id); + + boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings); + + boolean updateShopName(Long id, ShopNameUpdateDTO request); + + /** Public shop detail with the approved-content visibility gate applied. */ + ShopVO getPublicShopById(Long id); + /** * Purpose: getShopTrustProfile aggregates public shop confidence signals. * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java new file mode 100644 index 00000000..d22c1560 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopBusinessExpiryServiceImpl.java @@ -0,0 +1,113 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +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.shop.vo.ShopBusinessExpiryVO; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +public class ShopBusinessExpiryServiceImpl implements ShopBusinessExpiryService { + private static final int DEFAULT_VALID_DAYS = 30; + private static final String EXPIRED_MESSAGE = "门店经营有效期已到期,暂不能新增预约,请联系平台管理员办理续期"; + + private final ShopMapper shopMapper; + private final SystemParameterConfigService systemParameterConfigService; + + @Override + public int getDefaultValidDays() { + String value = systemParameterConfigService.getEnabledValue("SHOP", "SHOP_DEFAULT_VALID_DAYS"); + if (!StringUtils.hasText(value)) return DEFAULT_VALID_DAYS; + try { + int days = Integer.parseInt(value.trim()); + return days > 0 && days <= 3650 ? days : DEFAULT_VALID_DAYS; + } catch (NumberFormatException ignored) { + return DEFAULT_VALID_DAYS; + } + } + + @Override + public LocalDateTime defaultExpireTime(LocalDate startDate) { + LocalDate start = startDate == null ? LocalDate.now() : startDate; + return start.plusDays(getDefaultValidDays() - 1L).atTime(23, 59, 59); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void startDefaultValidity(Long shopId, LocalDate startDate) { + ShopDO shop = requireShop(shopId); + shop.setBusinessExpireTime(defaultExpireTime(startDate)); + shopMapper.updateById(shop); + } + + @Override + public void assertShopActive(Long shopId) { + ShopDO shop = requireShop(shopId); + if (shop.getBusinessExpireTime() == null) { + throw new IllegalStateException("门店经营有效期未设置,暂不能新增预约,请联系平台管理员设置有效期"); + } + if (LocalDateTime.now().isAfter(shop.getBusinessExpireTime())) { + throw new IllegalStateException(EXPIRED_MESSAGE); + } + } + + @Override + public ShopBusinessExpiryVO getExpiry(Long shopId) { + return toVO(requireShop(shopId)); + } + + @Override + public List listExpiries(List shopIds) { + if (shopIds == null || shopIds.isEmpty()) return Collections.emptyList(); + List ids = shopIds.stream().filter(Objects::nonNull).distinct().limit(100).toList(); + if (ids.isEmpty()) return Collections.emptyList(); + return shopMapper.selectList(Wrappers.lambdaQuery(ShopDO.class) + .in(ShopDO::getId, ids) + .eq(ShopDO::getIsDelete, 0)) + .stream().map(this::toVO).toList(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public ShopBusinessExpiryVO updateExpiry(Long shopId, LocalDate expireDate) { + if (expireDate == null) throw new IllegalArgumentException("请选择门店到期日期"); + if (expireDate.isBefore(LocalDate.now())) throw new IllegalArgumentException("到期日期不能早于今天"); + ShopDO shop = requireShop(shopId); + shop.setBusinessExpireTime(expireDate.atTime(23, 59, 59)); + shopMapper.updateById(shop); + return toVO(shop); + } + + private ShopDO requireShop(Long shopId) { + ShopDO shop = shopId == null ? null : shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在或已删除"); + } + return shop; + } + + private ShopBusinessExpiryVO toVO(ShopDO shop) { + ShopBusinessExpiryVO vo = new ShopBusinessExpiryVO(); + vo.setShopId(shop.getId()); + vo.setBusinessExpireTime(shop.getBusinessExpireTime()); + LocalDateTime now = LocalDateTime.now(); + boolean expired = shop.getBusinessExpireTime() != null && now.isAfter(shop.getBusinessExpireTime()); + vo.setBusinessExpired(expired); + vo.setBusinessRemainingDays(shop.getBusinessExpireTime() == null ? null + : expired ? 0 : (int) Math.max(1, ChronoUnit.DAYS.between(now.toLocalDate(), shop.getBusinessExpireTime().toLocalDate()) + 1)); + return vo; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java index 2778fc8f..99f8e165 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java @@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.core.type.TypeReference; import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; 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.order.entity.OrderArtistReviewDO; import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; @@ -23,14 +25,20 @@ import com.xiaowang.jayucloud.salon.core.modules.integration.service.MapService; import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.support.ShopThemeSupport; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; 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.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -41,6 +49,8 @@ import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -85,6 +95,8 @@ public class ShopServiceImpl extends ServiceImpl implements * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ShopMapper shopMapper; + private final ContentModerationRecordMapper contentModerationRecordMapper; + private final ShopBusinessExpiryService shopBusinessExpiryService; /** * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -139,6 +151,8 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final MapService mapService; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override @Transactional(rollbackFor = Exception.class) @@ -150,20 +164,23 @@ public class ShopServiceImpl extends ServiceImpl implements */ public Long createShop(ShopDTO shopDTO) { ShopDO shopDO = new ShopDO(); - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); + shopDO.setShopName(""); + shopDO.setDescription(null); + shopDO.setAddress(""); shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); shopDO.setLongitude(shopDTO.getLongitude()); shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); + shopDO.setBusinessHours(null); + shopDO.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDate.now())); + shopDO.setCoverImageFileId(null); + shopDO.setImageFileIds(null); + shopDO.setModerationStatus("PENDING"); applyTheme(shopDO, shopDTO); applyAuthorization(shopDO, shopDTO); shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); shopDO.setIsDelete(0); shopMapper.insert(shopDO); + submitShopSnapshot(shopDO, shopDTO); couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); evictShopCaches(shopDO.getId()); return shopDO.getId(); @@ -185,21 +202,8 @@ public class ShopServiceImpl extends ServiceImpl implements if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); } - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); - shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); - shopDO.setLongitude(shopDTO.getLongitude()); - shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); - applyTheme(shopDO, shopDTO); - applyAuthorization(shopDO, shopDTO); - if (shopDTO.getStatus() != null) { - shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); - } - boolean updated = shopMapper.updateById(shopDO) > 0; + boolean updated = updateShopOperationalFields(shopDO, shopDTO); + submitShopSnapshot(shopDO, shopDTO); if (updated) { /** * Run business method `evictShopCaches`. @@ -212,6 +216,166 @@ public class ShopServiceImpl extends ServiceImpl implements return updated; } + @Override + public ShopAppointmentSettingsVO getAppointmentSettings(Long id) { + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopAppointmentSettingsVO result = new ShopAppointmentSettingsVO(); + result.setShopName(shop.getShopName()); + ContentModerationRecordDO latestReview = contentModerationRecordMapper.selectOne(Wrappers.lambdaQuery(ContentModerationRecordDO.class) + .eq(ContentModerationRecordDO::getContentType, "SHOP") + .eq(ContentModerationRecordDO::getBusinessId, id) + .orderByDesc(ContentModerationRecordDO::getVersionNo) + .last("limit 1")); + result.setShopNameModerationStatus(latestReview == null ? shop.getModerationStatus() : latestReview.getStatus()); + if (latestReview != null && StringUtils.hasText(latestReview.getPayloadJson())) { + try { + result.setPendingShopName(objectMapper.readTree(latestReview.getPayloadJson()).path("shopName").asText(null)); + } catch (Exception ignored) { + result.setPendingShopName(null); + } + } + result.setBusinessHours(StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); + result.setDefaultAppointmentDurationMinutes(shop.getDefaultAppointmentDurationMinutes() == null + || shop.getDefaultAppointmentDurationMinutes() <= 0 ? 60 : shop.getDefaultAppointmentDurationMinutes()); + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings) { + if (settings == null) throw new IllegalArgumentException("预约设置不能为空"); + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + String businessHours = normalizeAppointmentBusinessHours(settings.getBusinessHours()); + Integer duration = settings.getDefaultAppointmentDurationMinutes(); + if (duration == null || duration < 15 || duration > 720) { + throw new IllegalArgumentException("默认预约时长需在15至720分钟之间"); + } + shop.setAppointmentBusinessHours(businessHours); + shop.setDefaultAppointmentDurationMinutes(duration); + return shopMapper.updateById(shop) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateShopName(Long id, ShopNameUpdateDTO request) { + if (request == null || !StringUtils.hasText(request.getShopName())) { + throw new IllegalArgumentException("门店名称不能为空"); + } + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopDTO profile = new ShopDTO(); + profile.setShopName(request.getShopName().trim()); + profile.setDescription(shop.getDescription()); + profile.setAddress(shop.getAddress()); + profile.setMapProvider(shop.getMapProvider()); + profile.setLongitude(shop.getLongitude()); + profile.setLatitude(shop.getLatitude()); + profile.setBusinessHours(shop.getBusinessHours()); + profile.setCoverImageFileId(shop.getCoverImageFileId()); + profile.setImageFileIds(shop.getImageFileIds()); + profile.setThemePrimaryColor(shop.getThemePrimaryColor()); + profile.setThemeSecondaryColor(shop.getThemeSecondaryColor()); + profile.setThemeAccentColor(shop.getThemeAccentColor()); + profile.setThemePageBgColor(shop.getThemePageBgColor()); + profile.setThemeCardBgColor(shop.getThemeCardBgColor()); + profile.setThemeBackgroundImageFileId(shop.getThemeBackgroundImageFileId()); + submitShopSnapshot(shop, profile); + return true; + } + + private String normalizeAppointmentBusinessHours(String value) { + if (!StringUtils.hasText(value)) throw new IllegalArgumentException("请设置门店营业时间"); + String[] parts = value.trim().split("-"); + if (parts.length != 2) throw new IllegalArgumentException("营业时间格式不正确"); + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + if (!start.isBefore(end)) throw new IllegalArgumentException("营业结束时间必须晚于开始时间"); + return start + "-" + end; + } catch (DateTimeParseException exception) { + throw new IllegalArgumentException("营业时间格式不正确,请使用小时和分钟"); + } + } + + private boolean updateShopOperationalFields(ShopDO current, ShopDTO dto) { + boolean changed = false; + if (dto.getStatus() != null) { + current.setStatus(normalizeStatus(dto.getStatus())); + changed = true; + } + if (dto.getAuthorizationStartDate() != null || dto.getAuthorizationDays() != null || dto.getAuthorizationExpireTime() != null) { + applyAuthorization(current, dto); + changed = true; + } + return !changed || shopMapper.updateById(current) > 0; + } + + private ShopDO copyShop(ShopDO source) { + ShopDO target = new ShopDO(); + target.setId(source.getId()); target.setShopName(source.getShopName()); target.setDescription(source.getDescription()); + target.setAddress(source.getAddress()); target.setMapProvider(source.getMapProvider()); target.setLongitude(source.getLongitude()); + target.setLatitude(source.getLatitude()); target.setBusinessHours(source.getBusinessHours()); target.setCoverImageFileId(source.getCoverImageFileId()); + target.setAppointmentBusinessHours(source.getAppointmentBusinessHours()); target.setDefaultAppointmentDurationMinutes(source.getDefaultAppointmentDurationMinutes()); + target.setImageFileIds(source.getImageFileIds()); target.setThemePrimaryColor(source.getThemePrimaryColor()); + target.setThemeSecondaryColor(source.getThemeSecondaryColor()); target.setThemeAccentColor(source.getThemeAccentColor()); + target.setThemePageBgColor(source.getThemePageBgColor()); target.setThemeCardBgColor(source.getThemeCardBgColor()); + target.setThemeBackgroundImageFileId(source.getThemeBackgroundImageFileId()); target.setStatus(source.getStatus()); + target.setAuthorizationStartDate(source.getAuthorizationStartDate()); target.setAuthorizationDays(source.getAuthorizationDays()); + target.setAuthorizationExpireTime(source.getAuthorizationExpireTime()); target.setIsDelete(source.getIsDelete()); + target.setModerationStatus(source.getModerationStatus()); target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private void submitShopSnapshot(ShopDO current, ShopDTO dto) { + try { + ShopDO candidate = copyShop(current); + candidate.setShopName(dto.getShopName()); candidate.setDescription(dto.getDescription()); candidate.setAddress(dto.getAddress()); + candidate.setMapProvider(mapService.normalizeProvider(dto.getMapProvider())); + candidate.setLongitude(dto.getLongitude()); candidate.setLatitude(dto.getLatitude()); + candidate.setBusinessHours(dto.getBusinessHours()); candidate.setCoverImageFileId(dto.getCoverImageFileId()); + candidate.setImageFileIds(dto.getImageFileIds()); applyTheme(candidate, dto); + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("shopName", candidate.getShopName()); payload.put("description", candidate.getDescription()); + payload.put("address", candidate.getAddress()); payload.put("businessHours", candidate.getBusinessHours()); + payload.put("mapProvider", candidate.getMapProvider()); payload.put("longitude", candidate.getLongitude()); + payload.put("latitude", candidate.getLatitude()); + payload.put("coverImageFileId", candidate.getCoverImageFileId()); payload.put("imageFileIds", candidate.getImageFileIds()); + payload.put("themePrimaryColor", candidate.getThemePrimaryColor()); + payload.put("themeSecondaryColor", candidate.getThemeSecondaryColor()); + payload.put("themeAccentColor", candidate.getThemeAccentColor()); + payload.put("themePageBgColor", candidate.getThemePageBgColor()); + payload.put("themeCardBgColor", candidate.getThemeCardBgColor()); + payload.put("themeBackgroundImageFileId", candidate.getThemeBackgroundImageFileId()); + String text = String.join("\n", java.util.Arrays.asList(candidate.getShopName(), candidate.getDescription(), candidate.getAddress(), candidate.getBusinessHours())); + java.util.List images = new java.util.ArrayList<>(); + addImageIds(images, candidate.getCoverImageFileId()); addImageIds(images, candidate.getImageFileIds()); addImageIds(images, candidate.getThemeBackgroundImageFileId()); + contentModerationService.assessVersion("SHOP", current.getId(), null, text, objectMapper.writeValueAsString(payload), images); + } catch (Exception exception) { + throw new IllegalStateException("门店展示资料审核任务创建失败", exception); + } + } + + private void addImageIds(java.util.List ids, String value) { + if (!StringUtils.hasText(value)) return; + for (String token : value.split(",")) { + if (!StringUtils.hasText(token)) continue; + Long fileId = objectStorageFileService.findFileIdByReference(token.trim()); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("门店图片必须引用已上传文件"); + } + if (!ids.contains(fileId)) ids.add(fileId); + } + } + @Override @Transactional(rollbackFor = Exception.class) /** @@ -282,6 +446,18 @@ public class ShopServiceImpl extends ServiceImpl implements ); } + @Override + public ShopVO getPublicShopById(Long id) { + ShopDO shop = id == null ? null : shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete()) + || !Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + || !"APPROVED".equals(shop.getModerationStatus()) + || !isAuthorizationValid(shop)) { + return null; + } + return convertToVO(shop); + } + @Override /** * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. @@ -292,7 +468,8 @@ public class ShopServiceImpl extends ServiceImpl implements return null; } ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) + || !"APPROVED".equals(shopDO.getModerationStatus()) || !isAuthorizationValid(shopDO)) { return null; } @@ -358,6 +535,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .orderByDesc(ShopDO::getCreateTime) ).stream() .filter(this::isAuthorizationValid) @@ -404,6 +582,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .like(ShopDO::getShopName, normalizedShopName) ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); return shopDOs.stream() @@ -456,7 +635,8 @@ public class ShopServiceImpl extends ServiceImpl implements private long countActiveProducts(Long shopId) { Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)); + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED")); return count == null ? 0L : count; } @@ -476,6 +656,7 @@ public class ShopServiceImpl extends ServiceImpl implements return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED") .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) .orderByDesc(ProductDO::getCollectCount) .orderByDesc(ProductDO::getLikeCount) @@ -530,14 +711,24 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: only status=1 reviews should feed public trust display. */ private List listSubmittedReviews(Long shopId, int limit) { - return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return Collections.emptyList(); + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .orderByDesc(OrderArtistReviewDO::getSubmittedAt) - .orderByDesc(OrderArtistReviewDO::getCreateTime) - .last("LIMIT " + Math.max(1, limit))) - .stream() + .orderByDesc(OrderArtistReviewDO::getCreateTime)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .limit(Math.max(1, limit)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @@ -547,11 +738,20 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: render it beside average rating so customers can judge sample size. */ private long countSubmittedReviews(Long shopId) { - Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return 0L; + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0)); - return count == null ? 0L : count; + .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED")); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream().filter(review -> approvedProductIds.contains(review.getProductId())).count(); } /** @@ -559,11 +759,23 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: use submitted reviews only and return zero when no rating exists. */ private BigDecimal calculateAverageRating(Long shopId) { + if (!isPublicShop(shopId)) { + return BigDecimal.ZERO; + } List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .isNotNull(OrderArtistReviewDO::getRatingScore)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + reviews = reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .collect(Collectors.toList()); if (reviews == null || reviews.isEmpty()) { return BigDecimal.ZERO; } @@ -578,6 +790,32 @@ public class ShopServiceImpl extends ServiceImpl implements return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); } + private boolean isPublicShop(Long shopId) { + if (shopId == null) { + return false; + } + ShopDO shop = shopMapper.selectById(shopId); + return shop != null + && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + && "APPROVED".equals(shop.getModerationStatus()) + && isAuthorizationValid(shop); + } + + private Set listApprovedProductIds(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return Collections.emptySet(); + } + return productMapper.selectBatchIds(productIds).stream() + .filter(Objects::nonNull) + .filter(product -> !Integer.valueOf(1).equals(product.getIsDelete())) + .filter(product -> Integer.valueOf(1).equals(product.getFrontVisible())) + .filter(product -> "APPROVED".equals(product.getModerationStatus())) + .map(ProductDO::getId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + /** * Purpose: buildFeaturedProduct converts a product row into a compact trust card. * Usage: keep this card small and do not include unpublished product internals. @@ -764,6 +1002,7 @@ public class ShopServiceImpl extends ServiceImpl implements shopVO.setLatitude(shopDO.getLatitude()); shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); shopVO.setBusinessHours(shopDO.getBusinessHours()); + shopVO.setModerationStatus(shopDO.getModerationStatus()); shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); shopVO.setCoverImageUrls(new java.util.ArrayList<>()); shopVO.setImageFileIds(shopDO.getImageFileIds()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java new file mode 100644 index 00000000..2a039666 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.vo; + +import lombok.Data; + +@Data +public class ShopAppointmentSettingsVO { + private String shopName; + private String shopNameModerationStatus; + private String pendingShopName; + private String businessHours; + private Integer defaultAppointmentDurationMinutes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java new file mode 100644 index 00000000..99d0bfba --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessExpiryVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.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 ShopBusinessExpiryVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + private LocalDateTime businessExpireTime; + private Boolean businessExpired; + private Integer businessRemainingDays; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java index 34bcb7c4..d3ebbd5b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java @@ -70,6 +70,8 @@ public class ShopVO { */ private String businessHours; + private String moderationStatus; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java new file mode 100644 index 00000000..a03c6149 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -0,0 +1,77 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.controller.admin; + +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.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.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/system-settings/secure-integration") +public class AdminSecureIntegrationConfigController { + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping + @RequirePermission("messagehub:config:manage") + public Result getConfig(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + } + + @GetMapping("/map-runtime") + @RequirePermission("messagehub:config:manage") + public Result> getMapRuntimeConfig(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(secureIntegrationConfigService.getMapRuntimeConfig(currentUser)); + } + + @PostMapping("/map") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-map-config-save", ttlSeconds = 5, message = "地图设置正在保存,请勿重复提交") + public Result saveMapConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveMapConfig(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=MAP"); + return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=MAP"); + throw exception; + } + } + + @PostMapping("/content-moderation") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-moderation-config-save", ttlSeconds = 5, message = "内容审核设置正在保存,请勿重复提交") + public Result saveModerationConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveModerationConfig(currentUser, dto); + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION"); + return Result.success(secureIntegrationConfigService.getAdminConfig(currentUser)); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION"); + throw exception; + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java index 0b1d02cf..b7da2b76 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/SystemParameterConfigController.java @@ -58,34 +58,6 @@ public class SystemParameterConfigController { return Result.success(configService.saveConfig(currentUser, dto)); } - @GetMapping("/admin/tencent-map") - /** - * Purpose: getTencentMapKey supports SystemParameterConfigController.java by holding or executing the get tencent map key business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getTencentMapKey(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - return Result.success(result); - } - - @GetMapping("/admin/map-config") - /** - * Purpose: getMapConfig supports SystemParameterConfigController.java by holding or executing the get map config business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public Result> getMapConfig(HttpServletRequest request) { - adminScopeHelper.getCurrentUser(request); - Map result = new HashMap<>(); - String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER"); - result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT"); - result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); - result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY")); - result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY")); - return Result.success(result); - } - @GetMapping("/admin/user-default-password") @RequirePermission("user:create") public Result> getUserDefaultPassword(HttpServletRequest request) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java new file mode 100644 index 00000000..23c58956 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java @@ -0,0 +1,22 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.dto; + +import lombok.Data; + +@Data +public class SecureIntegrationConfigDTO { + private String mapProvider; + private Boolean mapEnabled; + private String tencentWebKey; + private String amapWebKey; + private String amapMiniKey; + private Boolean clearTencentWebKey; + private Boolean clearAmapWebKey; + private Boolean clearAmapMiniKey; + + private String moderationProvider; + private String moderationCallbackUrl; + private String moderationCallbackToken; + private String moderationEncodingAesKey; + private Boolean clearModerationCallbackToken; + private Boolean clearModerationEncodingAesKey; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java new file mode 100644 index 00000000..01affe03 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/SecureIntegrationConfigDO.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_secure_integration_config") +public class SecureIntegrationConfigDO extends BaseEntity { + @TableField("config_group") + private String configGroup; + + @TableField("config_key") + private String configKey; + + @TableField("config_value") + private String configValue; + + @TableField("is_secret") + private Integer secret; + + @TableField("enabled") + private Integer enabled; + + @TableField("updated_by") + private Long updatedBy; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java new file mode 100644 index 00000000..0724b3ab --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/SecureIntegrationConfigMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SecureIntegrationConfigMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java new file mode 100644 index 00000000..ea04a176 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationRuntimeConfig.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ModerationRuntimeConfig { + private String provider; + private String callbackUrl; + private String callbackToken; + private String encodingAesKey; + private boolean ready; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java new file mode 100644 index 00000000..65f6b4bc --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureConfigEncryptionService.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; + +@Component +public class SecureConfigEncryptionService { + private static final String PREFIX = "v1:"; + private static final int NONCE_LENGTH = 12; + private static final int TAG_LENGTH_BITS = 128; + private static final SecureRandom RANDOM = new SecureRandom(); + + private final String encodedMasterKey; + + @Autowired + public SecureConfigEncryptionService() { + this(System.getenv("SALON_SECURE_CONFIG_MASTER_KEY")); + } + + SecureConfigEncryptionService(String encodedMasterKey) { + this.encodedMasterKey = encodedMasterKey; + } + + public boolean isConfigured() { + try { + decodeKey(); + return true; + } catch (IllegalStateException exception) { + return false; + } + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value)) return null; + byte[] nonce = new byte[NONCE_LENGTH]; + RANDOM.nextBytes(nonce); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, decodeKey(), new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + byte[] encrypted = cipher.doFinal(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + byte[] payload = new byte[nonce.length + encrypted.length]; + System.arraycopy(nonce, 0, payload, 0, nonce.length); + System.arraycopy(encrypted, 0, payload, nonce.length, encrypted.length); + return PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("安全配置加密失败", exception); + } + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value)) return ""; + if (!value.startsWith(PREFIX)) throw new IllegalStateException("安全配置密文版本不受支持"); + byte[] payload; + try { + payload = Base64.getDecoder().decode(value.substring(PREFIX.length())); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("安全配置密文格式错误", exception); + } + if (payload.length <= NONCE_LENGTH) throw new IllegalStateException("安全配置密文长度错误"); + byte[] nonce = Arrays.copyOfRange(payload, 0, NONCE_LENGTH); + byte[] ciphertext = Arrays.copyOfRange(payload, NONCE_LENGTH, payload.length); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, decodeKey(), new GCMParameterSpec(TAG_LENGTH_BITS, nonce)); + return new String(cipher.doFinal(ciphertext), java.nio.charset.StandardCharsets.UTF_8); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("安全配置无法解密,请检查环境主密钥是否与写入时一致", exception); + } + } + + private SecretKeySpec decodeKey() { + if (!StringUtils.hasText(encodedMasterKey)) { + throw new IllegalStateException("尚未配置安全接入加密主密钥"); + } + try { + byte[] key = Base64.getDecoder().decode(encodedMasterKey.trim()); + if (key.length != 32) throw new IllegalStateException("安全接入加密主密钥必须是 Base64 编码的 32 字节密钥"); + return new SecretKeySpec(key, "AES"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("安全接入加密主密钥必须是有效的 Base64 字符串", exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java new file mode 100644 index 00000000..1fd7f59f --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import java.util.Map; + +public interface SecureIntegrationConfigService { + SecureIntegrationConfigVO getAdminConfig(UserDO currentUser); + + void saveMapConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + Map getMapRuntimeConfig(UserDO currentUser); + + ModerationRuntimeConfig getModerationRuntimeConfig(); + + ModerationRuntimeConfig getModerationCallbackConfig(); + + void migrateLegacyMapConfig(); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java index 694d7861..dff0a9ed 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java @@ -201,8 +201,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { version, entry, clientType, - resolveClientIp(httpRequest), - httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) + resolveClientIp(httpRequest) )); } @@ -225,7 +224,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { * Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { + private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip) { if (!StringUtils.hasText(version)) { return; } @@ -240,7 +239,6 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { consent.setEntry(entry); consent.setClientType(clientType); consent.setIpAddress(ip); - consent.setDeviceId(deviceId); consent.setConsentTime(LocalDateTime.now()); if (existing == null) { consentMapper.insert(consent); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java new file mode 100644 index 00000000..a1930a6b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java @@ -0,0 +1,372 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.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.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.SecureConfigEncryptionService; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService { + private static final String MAP = "MAP"; + private static final String MODERATION = "CONTENT_MODERATION"; + private static final String SYSTEM = "SYSTEM"; + private static final String LEGACY_MAP_MIGRATED = "LEGACY_MAP_MIGRATED"; + private static final String WECHAT_CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + + private final SecureIntegrationConfigMapper secureConfigMapper; + private final SystemParameterConfigMapper systemParameterConfigMapper; + private final SecureConfigEncryptionService encryptionService; + private final ContentModerationProperties moderationProperties; + private final WechatMiniProperties wechatMiniProperties; + + @Override + @Transactional + public SecureIntegrationConfigVO getAdminConfig(UserDO currentUser) { + requirePlatformAdmin(currentUser); + migrateLegacyMapConfig(); + SecureIntegrationConfigVO result = new SecureIntegrationConfigVO(); + result.setEncryptionKeyConfigured(encryptionService.isConfigured()); + result.setMapLegacyMigrationPending(hasLegacyMapValues() && !isLegacyMapMigrationComplete()); + result.setMapProvider(readValue(MAP, "PROVIDER", "TENCENT")); + result.setMapEnabled(Boolean.parseBoolean(readValue(MAP, "ENABLED", "false"))); + result.setTencentWebKeyConfigured(hasStoredValue(MAP, "TENCENT_WEB_KEY")); + result.setAmapWebKeyConfigured(hasStoredValue(MAP, "AMAP_WEB_KEY")); + result.setAmapMiniKeyConfigured(hasStoredValue(MAP, "AMAP_MINI_KEY")); + + boolean moderationProviderReadable = encryptionService.isConfigured() + || !hasStoredValue(MODERATION, "PROVIDER"); + String moderationProvider = moderationProviderReadable + ? normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider())) + : "DISABLED"; + boolean tokenConfigured = hasStoredValue(MODERATION, "CALLBACK_TOKEN"); + boolean aesConfigured = hasStoredValue(MODERATION, "ENCODING_AES_KEY"); + boolean callbackConfigured = isValidCallbackUrl(readValue(MODERATION, "CALLBACK_URL", "")); + boolean appConfigured = isWechatMiniConfigured(); + boolean callbackReady = encryptionService.isConfigured() + && tokenConfigured && aesConfigured && callbackConfigured && appConfigured; + boolean moderationReady = "MOCK".equals(moderationProvider) + ? isMockAllowed() + : "WECHAT".equals(moderationProvider) && callbackReady; + + result.setModerationProvider(moderationProvider); + result.setModerationCallbackUrl(readValue(MODERATION, "CALLBACK_URL", "")); + result.setModerationCallbackTokenConfigured(tokenConfigured); + result.setModerationEncodingAesKeyConfigured(aesConfigured); + result.setModerationCallbackReady(callbackReady); + result.setModerationReady(moderationReady); + result.setWechatMiniAppConfigured(appConfigured); + result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId()) + ? wechatMiniProperties.getAppId() : ""); + result.setMockProviderAllowed(isMockAllowed()); + result.setUpdatedAt(latestUpdateTime()); + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveMapConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + migrateLegacyMapConfig(); + + String provider = upper(dto.getMapProvider(), "TENCENT"); + if (!"TENCENT".equals(provider) && !"AMAP".equals(provider)) { + throw new IllegalArgumentException("地图渠道仅支持腾讯地图或高德地图"); + } + updateSecret(MAP, "TENCENT_WEB_KEY", dto.getTencentWebKey(), dto.getClearTencentWebKey(), currentUser.getId()); + updateSecret(MAP, "AMAP_WEB_KEY", dto.getAmapWebKey(), dto.getClearAmapWebKey(), currentUser.getId()); + updateSecret(MAP, "AMAP_MINI_KEY", dto.getAmapMiniKey(), dto.getClearAmapMiniKey(), currentUser.getId()); + + boolean enabled = Boolean.TRUE.equals(dto.getMapEnabled()); + if (enabled) { + String selectedKey = "AMAP".equals(provider) + ? resolveUpdatedSecret(MAP, "AMAP_WEB_KEY", dto.getAmapWebKey(), dto.getClearAmapWebKey()) + : resolveUpdatedSecret(MAP, "TENCENT_WEB_KEY", dto.getTencentWebKey(), dto.getClearTencentWebKey()); + if (!StringUtils.hasText(selectedKey)) { + throw new IllegalArgumentException("请先填写当前地图渠道对应的 Web Key,或关闭地图服务"); + } + } + writeValue(MAP, "PROVIDER", provider, false, currentUser.getId()); + writeValue(MAP, "ENABLED", String.valueOf(enabled), false, currentUser.getId()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + + String provider = normalizedProvider(dto.getModerationProvider()); + if (!Arrays.asList("DISABLED", "WECHAT", "MOCK").contains(provider)) { + throw new IllegalArgumentException("内容审核渠道不受支持"); + } + if ("MOCK".equals(provider) && !isMockAllowed()) { + throw new IllegalArgumentException("当前环境不允许启用模拟审核"); + } + + String callbackUrl = StringUtils.trimWhitespace(dto.getModerationCallbackUrl()); + String token = resolveUpdatedSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(), + dto.getClearModerationCallbackToken()); + String aesKey = resolveUpdatedSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(), + dto.getClearModerationEncodingAesKey()); + if (StringUtils.hasText(token) && !token.matches("[A-Za-z0-9]{3,32}")) { + throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字"); + } + if (StringUtils.hasText(aesKey) && !aesKey.matches("[A-Za-z0-9+/]{43}")) { + throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥"); + } + String effectiveCallbackUrl = StringUtils.hasText(callbackUrl) + ? callbackUrl : readValue(MODERATION, "CALLBACK_URL", ""); + if ("WECHAT".equals(provider)) { + if (!StringUtils.hasText(token) || token.length() < 3 || token.length() > 32) { + throw new IllegalArgumentException("微信回调 Token 需要为 3-32 位英文字母或数字"); + } + if (!StringUtils.hasText(aesKey) || !aesKey.matches("[A-Za-z0-9+/]{43}")) { + throw new IllegalArgumentException("微信 EncodingAESKey 需要填写 43 位密钥"); + } + if (!isValidCallbackUrl(effectiveCallbackUrl)) { + throw new IllegalArgumentException("微信回调地址必须使用公网域名 HTTPS,并精确指向 /api/integration/wechat/content-moderation/callback"); + } + if (!isWechatMiniConfigured()) { + throw new IllegalArgumentException("当前环境未同时配置微信小程序 AppID 和 AppSecret,请先完成环境配置"); + } + } + if (StringUtils.hasText(callbackUrl)) { + writeValue(MODERATION, "CALLBACK_URL", callbackUrl, false, currentUser.getId()); + } + updateSecret(MODERATION, "CALLBACK_TOKEN", dto.getModerationCallbackToken(), + dto.getClearModerationCallbackToken(), currentUser.getId()); + updateSecret(MODERATION, "ENCODING_AES_KEY", dto.getModerationEncodingAesKey(), + dto.getClearModerationEncodingAesKey(), currentUser.getId()); + writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId()); + } + + @Override + @Transactional + public Map getMapRuntimeConfig(UserDO currentUser) { + requirePlatformAdmin(currentUser); + migrateLegacyMapConfig(); + String provider = upper(readValue(MAP, "PROVIDER", "TENCENT"), "TENCENT"); + boolean enabled = Boolean.parseBoolean(readValue(MAP, "ENABLED", "false")); + String keyName = "AMAP".equals(provider) ? "AMAP_WEB_KEY" : "TENCENT_WEB_KEY"; + String key = enabled && encryptionService.isConfigured() ? readValue(MAP, keyName, "") : ""; + Map result = new HashMap<>(); + result.put("provider", provider); + result.put("enabled", String.valueOf(enabled)); + result.put("key", key); + return result; + } + + @Override + public ModerationRuntimeConfig getModerationRuntimeConfig() { + ModerationRuntimeConfig callbackConfig = getModerationCallbackConfig(); + if ("WECHAT".equals(callbackConfig.getProvider()) && callbackConfig.isReady()) return callbackConfig; + if ("MOCK".equals(callbackConfig.getProvider()) && isMockAllowed()) { + return new ModerationRuntimeConfig("MOCK", "", "", "", true); + } + return new ModerationRuntimeConfig("DISABLED", "", "", "", false); + } + + @Override + public ModerationRuntimeConfig getModerationCallbackConfig() { + if (!encryptionService.isConfigured()) { + if (!hasStoredValue(MODERATION, "PROVIDER") && isMockAllowed()) { + return new ModerationRuntimeConfig("MOCK", "", "", "", true); + } + return new ModerationRuntimeConfig("DISABLED", "", "", "", false); + } + String provider = normalizedProvider(readValue(MODERATION, "PROVIDER", defaultModerationProvider())); + String callbackUrl = readValue(MODERATION, "CALLBACK_URL", ""); + String token = readValue(MODERATION, "CALLBACK_TOKEN", ""); + String aesKey = readValue(MODERATION, "ENCODING_AES_KEY", ""); + boolean allowedMock = !"MOCK".equals(provider) || isMockAllowed(); + boolean configured = StringUtils.hasText(token) && StringUtils.hasText(aesKey) + && isValidCallbackUrl(callbackUrl) && isWechatMiniConfigured(); + if (!allowedMock) provider = "DISABLED"; + return new ModerationRuntimeConfig(provider, callbackUrl, token, aesKey, configured); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void migrateLegacyMapConfig() { + if (!encryptionService.isConfigured() || isLegacyMapMigrationComplete()) return; + List legacyConfigs = systemParameterConfigMapper.selectList( + new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, MAP) + .eq(SystemParameterConfigDO::getIsDelete, 0)); + Map legacyByKey = new HashMap<>(); + for (SystemParameterConfigDO legacy : legacyConfigs) { + legacyByKey.put(upper(legacy.getConfigKey(), ""), legacy); + } + moveLegacyValue(legacyByKey, "MAP_PROVIDER", MAP, "PROVIDER", false); + moveLegacyValue(legacyByKey, "TENCENT_MAP_KEY", MAP, "TENCENT_WEB_KEY", true); + moveLegacyValue(legacyByKey, "AMAP_WEB_KEY", MAP, "AMAP_WEB_KEY", true); + moveLegacyValue(legacyByKey, "AMAP_MINI_KEY", MAP, "AMAP_MINI_KEY", true); + SystemParameterConfigDO oldProvider = legacyByKey.get("MAP_PROVIDER"); + if (oldProvider != null) { + String provider = upper(oldProvider.getConfigValue(), "TENCENT"); + String activeKeyName = "AMAP".equals(provider) ? "AMAP_WEB_KEY" : "TENCENT_MAP_KEY"; + SystemParameterConfigDO activeKey = legacyByKey.get(activeKeyName); + boolean enabled = Integer.valueOf(1).equals(oldProvider.getEnabled()) + && activeKey != null + && Integer.valueOf(1).equals(activeKey.getEnabled()) + && StringUtils.hasText(activeKey.getConfigValue()); + writeValue(MAP, "ENABLED", String.valueOf(enabled), false, null); + } + for (SystemParameterConfigDO legacy : legacyConfigs) { + legacy.setConfigValue(""); + legacy.setEnabled(0); + systemParameterConfigMapper.updateById(legacy); + } + writeValue(SYSTEM, LEGACY_MAP_MIGRATED, "true", false, null); + } + + private void moveLegacyValue(Map legacyByKey, String oldKey, + String group, String newKey, boolean secret) { + SystemParameterConfigDO legacy = legacyByKey.get(oldKey); + if (legacy == null || !StringUtils.hasText(legacy.getConfigValue()) || hasStoredValue(group, newKey)) return; + writeValue(group, newKey, legacy.getConfigValue(), secret, null); + } + + private void updateSecret(String group, String key, String submittedValue, Boolean clear, Long updatedBy) { + if (Boolean.TRUE.equals(clear)) { + writeValue(group, key, "", true, updatedBy); + } else if (StringUtils.hasText(submittedValue)) { + writeValue(group, key, submittedValue.trim(), true, updatedBy); + } + } + + private String resolveUpdatedSecret(String group, String key, String submittedValue, Boolean clear) { + if (Boolean.TRUE.equals(clear)) return ""; + return StringUtils.hasText(submittedValue) ? submittedValue.trim() : readValue(group, key, ""); + } + + private void writeValue(String group, String key, String value, boolean secret, Long updatedBy) { + SecureIntegrationConfigDO record = select(group, key); + if (record == null) { + record = new SecureIntegrationConfigDO(); + record.setConfigGroup(group); + record.setConfigKey(key); + } + record.setConfigValue(StringUtils.hasText(value) ? encryptionService.encrypt(value) : null); + record.setSecret(secret ? 1 : 0); + record.setEnabled(StringUtils.hasText(value) ? 1 : 0); + record.setUpdatedBy(updatedBy); + if (record.getId() == null) secureConfigMapper.insert(record); + else secureConfigMapper.updateById(record); + } + + private String readValue(String group, String key, String fallback) { + SecureIntegrationConfigDO record = select(group, key); + if (record == null || !Integer.valueOf(1).equals(record.getEnabled()) + || !StringUtils.hasText(record.getConfigValue()) || !encryptionService.isConfigured()) return fallback; + return encryptionService.decrypt(record.getConfigValue()); + } + + private boolean hasStoredValue(String group, String key) { + SecureIntegrationConfigDO record = select(group, key); + return record != null && Integer.valueOf(1).equals(record.getEnabled()) && StringUtils.hasText(record.getConfigValue()); + } + + private SecureIntegrationConfigDO select(String group, String key) { + return secureConfigMapper.selectOne(new LambdaQueryWrapper() + .eq(SecureIntegrationConfigDO::getConfigGroup, group) + .eq(SecureIntegrationConfigDO::getConfigKey, key) + .last("LIMIT 1")); + } + + private boolean hasLegacyMapValues() { + return systemParameterConfigMapper.selectCount(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, MAP) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .apply("config_value IS NOT NULL AND config_value <> ''")) > 0; + } + + private boolean isLegacyMapMigrationComplete() { + return "true".equalsIgnoreCase(readValue(SYSTEM, LEGACY_MAP_MIGRATED, "false")); + } + + private java.time.LocalDateTime latestUpdateTime() { + List rows = secureConfigMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(SecureIntegrationConfigDO::getUpdateTime).last("LIMIT 1")); + return rows == null || rows.isEmpty() ? null : rows.get(0).getUpdateTime(); + } + + private void requireEncryptionKey() { + if (!encryptionService.isConfigured()) { + throw new IllegalStateException("安全接入加密主密钥未配置,请先由部署维护人员设置 SALON_SECURE_CONFIG_MASTER_KEY 并重启 Core"); + } + } + + private void requirePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理安全接入配置"); + } + } + + private boolean isMockAllowed() { + return Boolean.TRUE.equals(moderationProperties.getAllowMock()); + } + + private String defaultModerationProvider() { + return isMockAllowed() ? "MOCK" : "DISABLED"; + } + + private boolean isWechatMiniConfigured() { + return StringUtils.hasText(wechatMiniProperties.getAppId()) + && StringUtils.hasText(wechatMiniProperties.getAppSecret()); + } + + private boolean isValidCallbackUrl(String value) { + if (!StringUtils.hasText(value)) return false; + try { + URI uri = new URI(value.trim()); + String host = uri.getHost(); + if (!"https".equalsIgnoreCase(uri.getScheme()) || !StringUtils.hasText(host) + || uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null + || !WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) { + return false; + } + String normalizedHost = host.toLowerCase(Locale.ROOT); + if (normalizedHost.endsWith(".")) normalizedHost = normalizedHost.substring(0, normalizedHost.length() - 1); + if ("localhost".equals(normalizedHost) || normalizedHost.endsWith(".localhost") + || normalizedHost.endsWith(".local") || normalizedHost.endsWith(".internal") + || normalizedHost.contains(":") || normalizedHost.matches("\\d{1,3}(\\.\\d{1,3}){3}")) { + return false; + } + return uri.getPort() == -1 || uri.getPort() == 443; + } catch (URISyntaxException exception) { + return false; + } + } + + private String normalizedProvider(String value) { + return upper(value, "DISABLED"); + } + + private String upper(String value, String fallback) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java index 545bfe3e..ea6ec63a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -16,6 +16,7 @@ import org.springframework.util.StringUtils; import java.util.List; import java.util.Locale; +import java.util.Collections; import java.util.stream.Collectors; @Service @@ -40,12 +41,17 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe */ public List listConfigs(UserDO currentUser, String configGroup) { ensurePlatformAdmin(currentUser); + if (StringUtils.hasText(configGroup) && "MAP".equalsIgnoreCase(configGroup.trim())) { + return Collections.emptyList(); + } LambdaQueryWrapper wrapper = new LambdaQueryWrapper() .eq(SystemParameterConfigDO::getIsDelete, 0) .orderByAsc(SystemParameterConfigDO::getConfigGroup) .orderByAsc(SystemParameterConfigDO::getConfigKey); if (StringUtils.hasText(configGroup)) { wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); + } else { + wrapper.ne(SystemParameterConfigDO::getConfigGroup, "MAP"); } return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); } @@ -60,6 +66,9 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe ensurePlatformAdmin(currentUser); String group = normalize(dto.getConfigGroup()); String key = normalize(dto.getConfigKey()); + if ("MAP".equals(group)) { + throw new IllegalArgumentException("地图密钥已迁移至安全接入配置,不允许通过通用参数接口读写"); + } if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) { AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue()); } @@ -98,6 +107,7 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { return ""; } + if ("MAP".equalsIgnoreCase(configGroup.trim())) return ""; SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java new file mode 100644 index 00000000..4c3be1a1 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class SecureIntegrationConfigVO { + private String mapProvider; + private Boolean mapEnabled; + private Boolean tencentWebKeyConfigured; + private Boolean amapWebKeyConfigured; + private Boolean amapMiniKeyConfigured; + private Boolean mapLegacyMigrationPending; + + private String moderationProvider; + private String moderationCallbackUrl; + private Boolean moderationCallbackTokenConfigured; + private Boolean moderationEncodingAesKeyConfigured; + private Boolean moderationCallbackReady; + private Boolean moderationReady; + private Boolean wechatMiniAppConfigured; + private String wechatMiniAppId; + private Boolean mockProviderAllowed; + + private Boolean encryptionKeyConfigured; + private LocalDateTime updatedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java index 938c6780..b2ff295e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/admin/AdminUserController.java @@ -3,22 +3,17 @@ package com.xiaowang.jayucloud.salon.core.modules.user.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.user.dto.AdminUserBalanceChangeDTO; -import com.xiaowang.jayucloud.salon.core.modules.user.dto.AdminUserVipOverrideDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserRelationUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport; 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.BalanceChangeDetailVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import lombok.Data; @@ -42,10 +37,6 @@ public class AdminUserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -334,101 +325,6 @@ public class AdminUserController { } } - @GetMapping("/{id}/asset") - @RequirePermission("user:balance:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getUserAsset(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产"); - UserAssetVO assetVO = userAssetService.getUserAsset(targetUser.getId()); - return Result.success(assetVO); - } - - @GetMapping("/{id}/balance/history") - @RequirePermission("user:balance:view") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水"); - List history = userAssetService.listBalanceHistory(targetUser.getId()); - return Result.success(history); - } - - @PostMapping("/{id}/balance/change") - @RequirePermission("user:balance:manage") - @OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result changeUserBalance( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserBalanceChangeDTO balanceChangeDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额"); - try { - UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/override") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - public Result overrideUserVip( - HttpServletRequest request, - @PathVariable Long id, - @RequestBody AdminUserVipOverrideDTO vipOverrideDTO - ) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - - @PostMapping("/{id}/vip/recalculate") - @RequirePermission("user:vip:manage") - @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") - /** - * Run business method `recalculateUserVip`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @param id parameter `id` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); - try { - UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId()); - securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id); - return Result.success(assetVO); - } catch (RuntimeException exception) { - securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage()); - throw exception; - } - } - @GetMapping("/info") /** * Load data by the supplied parameter. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java index 5d18605d..975cb151 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java @@ -10,21 +10,20 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp import com.xiaowang.jayucloud.salon.core.modules.file.vo.ChunkUploadSessionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; -import com.xiaowang.jayucloud.salon.core.modules.payment.vo.BalanceChangeDetailVO; -import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAssetVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.InviteCodeVO; import com.xiaowang.jayucloud.salon.core.modules.integration.vo.WechatMiniLoginResultVO; import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; -import com.xiaowang.jayucloud.salon.core.modules.user.service.UserAssetService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils; @@ -75,10 +74,6 @@ public class UserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; - /** - * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final UserAssetService userAssetService; /** * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -124,6 +119,7 @@ public class UserController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final LegalAgreementService legalAgreementService; + private final AccountClosureService accountClosureService; /** * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -226,30 +222,6 @@ public class UserController { return Result.success(success); } - @GetMapping("/asset/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result result consumed by the caller or returned to the frontend - */ - public Result getMyAsset(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.getUserAsset(userId)); - } - - @GetMapping("/balance/history/me") - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param request parameter `request` supplied by the caller - * @return Result> result consumed by the caller or returned to the frontend - */ - public Result> getMyBalanceHistory(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(userAssetService.listBalanceHistory(userId)); - } - /** * 根据ID查询用户 * @@ -343,10 +315,7 @@ public class UserController { */ public Result checkAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); String message = available ? "账号可用" : "账号已被注册"; return Result.success(new AvailabilityVO(available, message)); @@ -361,12 +330,7 @@ public class UserController { */ public Result checkLoginAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); boolean exists = userDO != null; String nickname = exists ? userDO.getNickname() : null; String message = exists @@ -405,11 +369,14 @@ public class UserController { * @return Result result consumed by the caller or returned to the frontend */ public Result checkPhoneAvailability(@PathVariable String phone) { - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - ); + String normalizedPhone = phone == null ? "" : phone.trim(); + UserDO userDO = userMapper.selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone)) + .eq(UserDO::getIsDelete, 0)); + if (userDO == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone); + userDO = legacyId == null ? null : userMapper.selectById(legacyId); + } boolean available = userDO == null; String message = available ? "手机号可用" : "该手机号已被注册"; return Result.success(new AvailabilityVO(available, message)); @@ -473,13 +440,18 @@ public class UserController { * @param requestDTO parameter `requestDTO` supplied by the caller * @return Result result consumed by the caller or returned to the frontend */ - public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { - return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); + public Result wechatMiniAutoLogin(HttpServletRequest request, + @Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.autoLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_AUTO_LOGIN", request); + return Result.success(result); } @PostMapping("/wechat-mini/status") @OperationGuard(action = "wechat-mini-status", ttlSeconds = 2, message = "状态检测中,请稍后重试") public Result wechatMiniStatus(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + legalAgreementService.requireAccepted(requestDTO); return Result.success(wechatMiniAuthService.status(requestDTO)); } @@ -553,12 +525,7 @@ public class UserController { legalAgreementService.requireAccepted(registerRequestDTO); try { boolean success = userService.register(registerRequestDTO); - UserDO userDO = userMapper.selectOne( - com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())); if (userDO != null) { legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); @@ -616,6 +583,30 @@ public class UserController { return Result.success(true); } + @PostMapping("/send-current-password-code") + @OperationGuard(action = "send-current-password-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作") + public Result sendCurrentPasswordVerificationCode(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + throw new RuntimeException("请登录后操作"); + } + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) + || (user.getStatus() != null && !Integer.valueOf(1).equals(user.getStatus())) + || !org.springframework.util.StringUtils.hasText(user.getPhone()) + || !Integer.valueOf(1).equals(user.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + + String phone = user.getPhone(); + requestThrottleService.checkSendCode(request, phone); + if (!verificationCodeService.canResend(phone)) { + throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); + } + verificationCodeService.sendVerificationCode(phone, "USER_CHANGE_PASSWORD_SMS_CODE"); + return Result.success(true); + } + /** * 通过手机号验证码重置密码 * @@ -682,8 +673,7 @@ public class UserController { */ @GetMapping("/info") public Result getCurrentUserInfo(HttpServletRequest request) { - Long userId = (Long) request.getAttribute("userId"); - UserVO userVO = userService.getUserById(userId); + UserVO userVO = userService.getCurrentUserInfo(); return Result.success(userVO); } @@ -715,6 +705,20 @@ public class UserController { return Result.success(success); } + @PostMapping("/unbind-phone") + @OperationGuard(action = "user-unbind-phone", ttlSeconds = 10, message = "手机号解绑处理中,请勿重复提交") + public Result unbindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.unbindPhone(userId, requestDTO == null ? null : requestDTO.getVerificationCode())); + } + + @PostMapping("/unbind-phone/send-code") + @OperationGuard(action = "user-unbind-phone-send-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作") + public Result sendUnbindPhoneCode(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.sendUnbindPhoneCode(userId)); + } + @PostMapping("/wechat-mini/bind-phone") @OperationGuard(action = "wechat-mini-bind-phone", ttlSeconds = 10, message = "手机号绑定处理中,请勿重复提交") public Result bindWechatMiniPhone(HttpServletRequest request, @@ -981,8 +985,8 @@ public class UserController { return Result.error("管理员账号无法注销"); } - boolean success = userService.deleteUser(userId); - return Result.success(success); + accountClosureService.request(userId); + return Result.success(true); } /** @@ -1029,6 +1033,22 @@ public class UserController { return sanitized; } + private UserDO findUserByAccount(String account) { + String normalized = account == null ? "" : account.trim(); + boolean phoneAccount = PhoneCrypto.current().isMobilePhone(normalized); + com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper query = + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .last("limit 1"); + query.eq(UserDO::getAccountHash, PhoneCrypto.current().index(normalized)); + UserDO user = userMapper.selectOne(query); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByAccount(normalized); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } + @Data /** * Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java index adfb021c..3c5d7349 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java @@ -88,6 +88,9 @@ public class UserDTO { */ private String wechatId; + /** 美甲师在规划页展示的专属颜色(#RRGGBB)。 */ + private String color; + /** * 微信二维码 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java index 8e7b2bb8..e1205a2a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserAgreementConsentDO.java @@ -59,13 +59,6 @@ public class UserAgreementConsentDO extends BaseEntity { */ private String ipAddress; - @TableField("device_id") - /** - * Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String deviceId; - @TableField("consent_time") /** * Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java index 48845495..d00a31a0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java @@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler; +import com.xiaowang.jayucloud.salon.core.support.privacy.AccountPhoneTypeHandler; import lombok.Getter; import lombok.Setter; import lombok.EqualsAndHashCode; @@ -22,7 +25,7 @@ import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; @Getter @Setter @EqualsAndHashCode(callSuper = true) -@TableName("t_user") +@TableName(value = "t_user", autoResultMap = true) public class UserDO extends BaseEntity { /** @@ -46,21 +49,34 @@ public class UserDO extends BaseEntity { /** * 用户账号(登录用) */ - @TableField("account") + @TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class) private String account; + @TableField(value = "account_hash", fill = FieldFill.INSERT_UPDATE) + private String accountHash; + /** * 手机号 */ - @TableField("phone") + @TableField(value = "phone", typeHandler = PhoneEncryptionTypeHandler.class) private String phone; + @TableField(value = "phone_hash", fill = FieldFill.INSERT_UPDATE) + private String phoneHash; + /** * 联系电话 */ - @TableField("contact_phone") + @TableField(value = "contact_phone", typeHandler = PhoneEncryptionTypeHandler.class) private String contactPhone; + @TableField(value = "contact_phone_hash", fill = FieldFill.INSERT_UPDATE) + private String contactPhoneHash; + + /** 客户姓名、微信号和手机号的组合HMAC,用于原子去重。 */ + @TableField("customer_identity_hash") + private String customerIdentityHash; + /** * 生日 */ @@ -115,6 +131,9 @@ public class UserDO extends BaseEntity { @TableField("signature") private String signature; + @TableField("profile_moderation_status") + private String profileModerationStatus; + /** * 用户等级 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java index 66cf4f64..5b2f95fb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java @@ -2,6 +2,10 @@ package com.xiaowang.jayucloud.salon.core.modules.user.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; /** * 系统用户信息表 Mapper @@ -11,4 +15,19 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; * @date 2026-02-13 */ public interface UserMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_user WHERE is_delete = 0 AND status = 1 AND profile_moderation_status = 'APPROVED' AND (avatar = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}))") + Long countPublicImageReference(@Param("fileId") Long fileId); + + @Select("SELECT id FROM t_user WHERE account = #{account} AND account_hash IS NULL AND is_delete = 0 LIMIT 1") + Long findLegacyIdByAccount(@Param("account") String account); + + @Select("SELECT id FROM t_user WHERE phone = #{phone} AND phone_hash IS NULL AND is_delete = 0 AND type <> 0 LIMIT 1") + Long findLegacyIdByPhone(@Param("phone") String phone); + + @Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0 LIMIT 1") + Long findLegacyIdByContactPhone(@Param("phone") String phone); + + @Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0") + List findLegacyIdsByContactPhone(@Param("phone") String phone); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java index e517db55..2949fa53 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java @@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import java.util.List; @@ -34,6 +35,19 @@ public interface UserService extends IService { */ Long createUser(UserDTO userDTO); + Long createUnlinkedEmployee(UserDTO userDTO, Long shopId); + + Long createManagerCustomer(String nickname, String phone, Long shopId); + + Long createManagerCustomer(String nickname, String wechatId, String phone, Long shopId); + + List findCustomerMatches(String nickname, String phone, Long shopId); + + List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId); + + PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId); + + /** * Update an existing record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -203,6 +217,15 @@ public interface UserService extends IService { */ LoginResponseVO refreshToken(String refreshToken); + /** + * Refresh a token for the platform administrator console. + * + *

This is deliberately separate from the user-facing refresh flow so + * the admin controller cannot accidentally change the rules used by the + * mini-program and front-end sessions.

+ */ + LoginResponseVO adminRefreshToken(String refreshToken); + /** * Run business method `logout`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -236,6 +259,10 @@ public interface UserService extends IService { */ boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); + boolean unbindPhone(Long userId, String verificationCode); + + boolean sendUnbindPhoneCode(Long userId); + /** * Run business method `bindEmail`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 7b65f92f..f0d91a77 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -25,6 +26,7 @@ import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMap import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; @@ -35,13 +37,19 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRe import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport; 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.security.support.PermissionCatalog; import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionPolicy; import com.xiaowang.jayucloud.salon.core.support.RequestShopContext; import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.salon.core.modules.user.support.UserProfileFieldSupport; +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.utils.AccountValidationUtils; import com.xiaowang.jayucloud.salon.core.utils.JwtUtil; import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO; @@ -49,6 +57,7 @@ import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; @@ -61,6 +70,7 @@ import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -69,6 +79,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import com.xiaowang.jayucloud.salon.core.modules.auth.dto.BindEmailRequestDTO; @@ -133,6 +144,9 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserMapper userMapper; + private final PhoneCrypto phoneCrypto; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; private final ShopMapper shopMapper; /** * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. @@ -142,6 +156,7 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ShopService shopService; + private final ShopBusinessExpiryService shopBusinessExpiryService; /** * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -182,6 +197,7 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ObjectStorageFileService objectStorageFileService; /** * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -356,13 +372,45 @@ public class UserServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserDTO userDTO) { + return createUserInternal(userDTO); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createUnlinkedEmployee(UserDTO userDTO, Long shopId) { + if (userDTO == null || !Integer.valueOf(3).equals(userDTO.getType())) throw new IllegalArgumentException("仅支持新增美甲师"); + if (shopId == null || shopId <= 0) throw new IllegalArgumentException("门店不能为空"); + if (!StringUtils.hasText(userDTO.getNickname())) throw new IllegalArgumentException("美甲师姓名不能为空"); + String phone = validateUserPhone(userDTO.getPhone(), null, true); + UserDO userDO = new UserDO(); + userDO.setShopId(shopId); + userDO.setNickname(userDTO.getNickname().trim()); + userDO.setAccount(null); + userDO.setPassword(ENCODED_UNSET_PASSWORD); + userDO.setPhone(phone); + userDO.setContactPhone(StringUtils.hasText(userDTO.getContactPhone()) ? userDTO.getContactPhone().trim() : phone); + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + userDO.setType(3); + userDO.setStatus(1); + userDO.setIsDelete(0); + userDO.setProfileModerationStatus("PENDING"); + userDO.setAvatar(StringUtils.hasText(userDTO.getAvatar()) ? normalizeStoredAvatar(userDTO.getAvatar()) : DEFAULT_AVATAR_URL); + userMapper.insert(userDO); + assignDefaultPermissions(userDO.getId(), 3); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(shopId)); + NailArtistInfoDTO artist = new NailArtistInfoDTO(); + artist.setUserId(userDO.getId()); + artist.setIdentity(""); artist.setExperience(0); artist.setSkills(""); + artist.setRating(DEFAULT_NAIL_ARTIST_RATING); artist.setStatus(1); artist.setPortfolio(""); + artist.setColor(normalizeArtistColor(userDTO.getColor())); + nailArtistInfoService.saveOrUpdateNailArtistInfo(artist); + return userDO.getId(); + } + + private Long createUserInternal(UserDTO userDTO) { String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); // 检查账号是否已存在 - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingUser = findUserByAccount(validatedAccount); if (existingUser != null) { /** * Run business method `RuntimeException`. @@ -374,9 +422,14 @@ public class UserServiceImpl extends ServiceImpl implements List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); Long validatedShopId = pickPrimaryShopId(validatedShopIds); - String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); Integer userType = userDTO.getType(); + String validatedPhone = Integer.valueOf(0).equals(userType) + ? validateCustomerPhone(userDTO.getPhone(), false) + : validateUserPhone(userDTO.getPhone(), null, true); String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); + if (Integer.valueOf(0).equals(userType)) { + ensureCustomerUnique(userDTO.getNickname(), validatedWechatId, validatedPhone); + } UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); /** @@ -391,7 +444,8 @@ public class UserServiceImpl extends ServiceImpl implements // 创建用户实体并设置属性 UserDO userDO = new UserDO(); userDO.setShopId(validatedShopId); - userDO.setNickname(userDTO.getNickname()); + userDO.setNickname(Integer.valueOf(0).equals(userType) && userDTO.getNickname() != null + ? userDTO.getNickname().trim() : userDTO.getNickname()); userDO.setAccount(validatedAccount); String resolvedPassword = AdminDefaultPasswordSupport.resolveCreatePassword( userDTO.getPassword(), @@ -400,6 +454,9 @@ public class UserServiceImpl extends ServiceImpl implements validatePasswordStrength(resolvedPassword); userDO.setPassword(passwordEncoder.encode(resolvedPassword)); userDO.setPhone(validatedPhone); + if (Integer.valueOf(0).equals(userType)) { + userDO.setCustomerIdentityHash(customerIdentityHash(userDO.getNickname(), validatedWechatId, validatedPhone)); + } userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); userDO.setBirthday(userDTO.getBirthday()); userDO.setWechatId(validatedWechatId); @@ -410,6 +467,9 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setVipId(userDTO.getVipId()); userDO.setIsDelete(0); userDO.setStatus(1); + if (!Integer.valueOf(0).equals(userType)) { + userDO.setProfileModerationStatus("PENDING"); + } if (StringUtils.hasText(userDTO.getAvatar())) { userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } else { @@ -441,6 +501,20 @@ public class UserServiceImpl extends ServiceImpl implements throw e; } + if (!Integer.valueOf(0).equals(userType)) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, userDO.getAvatar()); + addImageFileId(profileImages, userDO.getWechatQrCode()); + contentModerationService.assessVersion("USER_PROFILE", userDO.getId(), userDO.getId(), + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + } + // 分配默认权限 assignDefaultPermissions(userDO.getId(), userDO.getType()); userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); @@ -455,12 +529,155 @@ public class UserServiceImpl extends ServiceImpl implements nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5 nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 + nailArtistInfoDTO.setColor(normalizeArtistColor(userDTO.getColor())); nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); } return userDO.getId(); } + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, String phone, Long shopId) { + return createManagerCustomer(nickname, null, phone, shopId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createManagerCustomer(String nickname, String wechatId, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + if (shopId == null || shopId <= 0) { + throw new RuntimeException("请先选择店铺后再新增客户"); + } + String normalizedPhone = phone == null || phone.trim().isEmpty() ? null : phone.trim(); + normalizedPhone = validateCustomerPhone(normalizedPhone, false); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + ensureCustomerUnique(nickname, normalizedWechatId, normalizedPhone); + UserDTO customer = new UserDTO(); + customer.setNickname(nickname.trim()); + customer.setWechatId(normalizedWechatId); + customer.setPhone(normalizedPhone); + customer.setContactPhone(normalizedPhone); + customer.setAccount("customer" + UUID.randomUUID().toString().replace("-", "")); + customer.setType(0); + customer.setShopId(shopId); + customer.setShopIds(List.of(shopId)); + customer.setLevel(VIP_LEVEL_NORMAL); + customer.setVipId(0L); + return createUserInternal(customer); + } + + @Override + public List findCustomerMatches(String nickname, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) { + return List.of(); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + String normalizedName = nickname.trim(); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + if (normalizedPhone != null) { + addPhoneMatch(wrapper, normalizedPhone); + } + if (shopId != null && shopId > 0) { + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) { + wrapper.eq(UserDO::getShopId, shopId); + } else { + wrapper.and(query -> query.eq(UserDO::getShopId, shopId) + .or().in(UserDO::getId, shopUserIds)); + } + } + return userMapper.selectList(wrapper).stream() + .filter(user -> java.util.Objects.equals(normalizedName, user.getNickname())) + .filter(user -> normalizedPhone == null || java.util.Objects.equals(normalizedPhone, decryptPhone(user.getPhone()))) + .map(user -> { + UserVO customer = new UserVO(); + customer.setId(user.getId()); + customer.setNickname(user.getNickname()); + customer.setAccount(phoneCrypto.mask(user.getAccount())); + customer.setPhone(phoneCrypto.mask(user.getPhone())); + customer.setContactPhone(phoneCrypto.mask(user.getContactPhone())); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + return customer; + }).collect(Collectors.toList()); + } + + @Override + public List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) return List.of(); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + applyCustomerShopScope(wrapper, shopId); + String normalizedName = nickname.trim(); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + return userMapper.selectList(wrapper).stream() + .filter(user -> Objects.equals(normalizedName, user.getNickname())) + .filter(user -> Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(user.getWechatId()))) + .filter(user -> Objects.equals(normalizedPhone, resolveCustomerPhone(user))) + .map(user -> { + AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); + customer.setId(user.getId()); + customer.setName(user.getNickname()); + customer.setPhone(resolveCustomerPhone(user)); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + customer.setCreatedAt(user.getCreateTime()); + return customer; + }).collect(Collectors.toList()); + } + + @Override + public PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId) { + int safePage = page == null || page < 1 ? 1 : page; + int safeSize = size == null ? 30 : Math.max(1, Math.min(size, 100)); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0) + .orderByDesc(UserDO::getCreateTime); + applyCustomerShopScope(wrapper, shopId); + if (StringUtils.hasText(keyword)) { + String search = keyword.trim(); + wrapper.and(query -> { + query.like(UserDO::getNickname, search); + if (search.matches(PHONE_REGEX)) query.or(phoneQuery -> addPhoneMatch(phoneQuery, search)); + }); + } + Page users = userMapper.selectPage(new Page<>(safePage, safeSize), wrapper); + PageResultVO result = new PageResultVO<>(); + result.setList(users.getRecords().stream().map(user -> { + AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); + option.setId(user.getId()); + option.setName(user.getNickname()); + option.setPhone(resolveCustomerPhone(user)); + option.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + option.setCreatedAt(user.getCreateTime()); + return option; + }).collect(Collectors.toList())); + result.setTotal(users.getTotal()); + result.setPage(safePage); + result.setSize(safeSize); + return result; + } + + private void applyCustomerShopScope(LambdaQueryWrapper wrapper, Long shopId) { + if (shopId == null || shopId <= 0) return; + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) wrapper.eq(UserDO::getShopId, shopId); + else wrapper.and(query -> query.eq(UserDO::getShopId, shopId).or().in(UserDO::getId, shopUserIds)); + } + + private String resolveCustomerPhone(UserDO customer) { + String contactPhone = decryptPhone(customer.getContactPhone()); + return StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(customer.getPhone()); + } + /** * 分配默认权限 * @param userId 用户ID @@ -519,15 +736,16 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null) { return false; } + String originalNickname = userDO.getNickname(); + String originalAvatar = userDO.getAvatar(); + String originalSignature = userDO.getSignature(); + String originalWechatQrCode = userDO.getWechatQrCode(); // 更新账号(如果提供且变更) String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingUser = findUserByAccount(normalizedAccount); + if (existingUser != null && Objects.equals(existingUser.getId(), id)) existingUser = null; if (existingUser != null) { /** * Run business method `RuntimeException`. @@ -544,14 +762,17 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setShopId(validateAndNormalizeShopId(userDTO.getShopId())); } if (userDTO.getNickname() != null) { - userDO.setNickname(userDTO.getNickname()); + userDO.setNickname(Integer.valueOf(0).equals(userDO.getType()) + ? userDTO.getNickname().trim() : userDTO.getNickname()); } if (userDTO.getPassword() != null) { validatePasswordStrength(userDTO.getPassword()); userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); } if (userDTO.getPhone() != null) { - userDO.setPhone(validateUserPhone(userDTO.getPhone(), id, true)); + userDO.setPhone(Integer.valueOf(0).equals(userDO.getType()) + ? validateCustomerPhone(userDTO.getPhone(), false) + : validateUserPhone(userDTO.getPhone(), id, true)); } if (userDTO.getContactPhone() != null) { userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); @@ -584,8 +805,45 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getVipId() != null) { userDO.setVipId(userDTO.getVipId()); } + boolean publicProfileChanged = !Objects.equals(originalNickname, userDO.getNickname()) + || !Objects.equals(originalAvatar, userDO.getAvatar()) + || !Objects.equals(originalSignature, userDO.getSignature()) + || !Objects.equals(originalWechatQrCode, userDO.getWechatQrCode()); + if (publicProfileChanged) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + if (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) { + addImageFileId(profileImages, userDO.getAvatar()); + } + if (userDTO.getWechatQrCode() != null) { + addImageFileId(profileImages, userDO.getWechatQrCode()); + } + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", id, id, + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + if (!moderationApproved(moderation)) { + userDO.setNickname(originalNickname); + userDO.setAvatar(originalAvatar); + userDO.setSignature(originalSignature); + userDO.setWechatQrCode(originalWechatQrCode); + } + } Integer targetUserType = userDO.getType(); UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); + if (Integer.valueOf(0).equals(targetUserType)) { + String customerPhone = validateCustomerPhone(userDO.getPhone(), false); + ensureCustomerUnique(userDO.getNickname(), userDO.getWechatId(), customerPhone, id); + userDO.setCustomerIdentityHash(customerIdentityHash(userDO.getNickname(), userDO.getWechatId(), customerPhone)); + } else { + userDO.setCustomerIdentityHash(null); + if (StringUtils.hasText(userDO.getPhone()) && !isDeletedPlaceholderPhone(userDO.getPhone())) { + ensurePhoneNotUsed(userDO.getPhone(), id); + } + } List validatedShopIds = null; boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; if (shopBindingChanged) { @@ -650,7 +908,11 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getId, id) .eq(UserDO::getIsDelete, 0) .set(UserDO::getAccount, buildDeletedAccount(userDO)) - .set(UserDO::getPhone, buildDeletedPhone(userDO)) + .set(UserDO::getPhone, null) + .set(UserDO::getContactPhone, null) + .set(UserDO::getPhoneHash, null) + .set(UserDO::getContactPhoneHash, null) + .set(UserDO::getAccountHash, null) .set(UserDO::getStatus, 0) .set(UserDO::getIsDelete, 1) .set(UserDO::getUpdateTime, now) @@ -724,6 +986,7 @@ public class UserServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(UserDO.class) .eq(UserDO::getIsDelete, 0) .eq(UserDO::getType, type) + .eq(UserDO::getProfileModerationStatus, "APPROVED") ); return userDOs.stream() .map(this::convertToVO) @@ -738,11 +1001,7 @@ public class UserServiceImpl extends ServiceImpl implements @Override public UserVO getUserByAccount(String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { return null; } @@ -782,10 +1041,10 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userVO.setNickname(userDO.getNickname()); - userVO.setAccount(userDO.getAccount()); - userVO.setPhone(userDO.getPhone()); + userVO.setAccount(phoneCrypto.mask(userDO.getAccount())); + userVO.setPhone(phoneCrypto.mask(userDO.getPhone())); userVO.setPhoneVerified(userDO.getPhoneVerified()); - userVO.setContactPhone(userDO.getContactPhone()); + userVO.setContactPhone(phoneCrypto.mask(userDO.getContactPhone())); userVO.setBirthday(userDO.getBirthday()); userVO.setWechatId(userDO.getWechatId()); userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); @@ -859,12 +1118,7 @@ public class UserServiceImpl extends ServiceImpl implements } AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null) { return buildLoginShopSelection(List.of(), false, "该账号不存在"); } @@ -909,12 +1163,7 @@ public class UserServiceImpl extends ServiceImpl implements return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺"); } - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByPhone(normalizedPhone); if (userDO == null) { return buildLoginShopSelection( userShopBindingSupport.listAllActiveShopOptions(), @@ -964,12 +1213,7 @@ public class UserServiceImpl extends ServiceImpl implements } AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByAccount(normalizedAccount); if (userDO == null) { return buildLoginShopSelection(List.of(), false, "该账号不存在"); } @@ -1012,10 +1256,7 @@ public class UserServiceImpl extends ServiceImpl implements */ public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); /** * Run business method `assertLoginAccountAvailable`. @@ -1086,15 +1327,12 @@ public class UserServiceImpl extends ServiceImpl implements private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) { String normalizedPhone = normalizeVerifiedPhone(phone); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) - .eq(UserDO::getIsDelete, 0) - ); + UserDO userDO = findUserByPhone(normalizedPhone); if (userDO == null) { return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED"); } + assertWechatLinkedForStaffLogin(userDO); if (userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()).isEmpty()) { return buildRegistrationRequiredResponse(normalizedPhone, userDO, "NO_SHOP_BINDING"); } @@ -1147,12 +1385,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return LoginResponseVO result consumed by the caller or returned to the frontend */ public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO userDO = findUserByPhone(phone); if (userDO == null) { if (shopId == null || shopId == 0) { @@ -1171,6 +1404,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return result consumed by the caller or returned to the frontend */ + assertWechatLinkedForStaffLogin(userDO); assertUserAvailable(userDO); clearLoginFailureCount(userDO.getAccount()); } @@ -1260,10 +1494,7 @@ public class UserServiceImpl extends ServiceImpl implements */ public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); - UserDO userDO = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) - ); + UserDO userDO = findUserByAccount(normalizedAccount); /** * Run business method `assertLoginAccountAvailable`. @@ -1273,6 +1504,10 @@ public class UserServiceImpl extends ServiceImpl implements */ assertLoginAccountAvailable(userDO); + if (!Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以登录后台管理系统"); + } + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { /** * Run business method `handleLoginPasswordFailure`. @@ -1283,17 +1518,6 @@ public class UserServiceImpl extends ServiceImpl implements handleLoginPasswordFailure(userDO); } - Integer userType = userDO.getType(); - if (userType == null || userType < 2) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("该账号不是后台管理账号"); - } - - Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); clearLoginFailureCount(userDO.getAccount()); /** * Run business method `buildLoginResponse`. @@ -1303,7 +1527,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param false parameter `false` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + return buildLoginResponse(userDO, null, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); } @Override @@ -1469,10 +1693,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("验证码错误或已过期"); } - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) - ); + UserDO existingUser = findUserByAccount(validatedAccount); if (existingUser != null) { if (existingUser.getIsDelete() == 0) { @@ -1492,11 +1713,7 @@ public class UserServiceImpl extends ServiceImpl implements } } - UserDO existingPhoneUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, registerRequestDTO.getPhone()) - .eq(UserDO::getIsDelete, 0) - ); + UserDO existingPhoneUser = findUserByPhone(registerRequestDTO.getPhone()); if (existingPhoneUser != null) { /** @@ -1562,12 +1779,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("店铺名称不能为空"); } - UserDO existingUser = userMapper.selectOne( - Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, phone) - .eq(UserDO::getIsDelete, 0) - .last("limit 1") - ); + UserDO existingUser = findUserByAccount(phone); if (existingUser != null) { throw new RuntimeException("该手机号已注册"); } @@ -1580,6 +1792,7 @@ public class UserServiceImpl extends ServiceImpl implements shop.setAuthorizationStartDate(LocalDateTime.now().minusDays(1).toLocalDate()); shop.setAuthorizationDays(0); shop.setAuthorizationExpireTime(LocalDateTime.now().minusSeconds(1)); + shop.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDate.now())); shop.setIsDelete(0); shopMapper.insert(shop); @@ -1613,6 +1826,15 @@ public class UserServiceImpl extends ServiceImpl implements * @return LoginResponseVO result consumed by the caller or returned to the frontend */ public LoginResponseVO refreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, false); + } + + @Override + public LoginResponseVO adminRefreshToken(String refreshToken) { + return refreshTokenInternal(refreshToken, true); + } + + private LoginResponseVO refreshTokenInternal(String refreshToken, boolean adminOnly) { if (!jwtUtil.validateToken(refreshToken)) { /** * Run business method `RuntimeException`. @@ -1635,7 +1857,7 @@ public class UserServiceImpl extends ServiceImpl implements Long userId = jwtUtil.getUserIdFromToken(refreshToken); String account = jwtUtil.getAccountFromToken(refreshToken); - Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + Long currentShopId = adminOnly ? null : normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); String refreshJti = jwtUtil.getJtiFromToken(refreshToken); if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { @@ -1655,7 +1877,10 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ assertUserAvailable(userDO); - boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + if (adminOnly && !Integer.valueOf(4).equals(userDO.getType())) { + throw new RuntimeException("仅平台管理员可以刷新后台登录态"); + } + boolean adminLogin = adminOnly || (userDO.getType() != null && userDO.getType() >= 2); if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { /** * Run business method `RuntimeException`. @@ -1690,7 +1915,18 @@ public class UserServiceImpl extends ServiceImpl implements org.springframework.web.context.request.ServletRequestAttributes attributes = (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); - return userId == null ? null : getUserById(userId); + if (userId == null) return null; + UserVO userInfo = getUserById(userId); + Long currentShopId = RequestShopContext.getCurrentShopId(); + Long expiryShopId = currentShopId == null && userInfo != null ? userInfo.getShopId() : currentShopId; + if (userInfo != null && expiryShopId != null) { + com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO expiry = + shopBusinessExpiryService.getExpiry(expiryShopId); + userInfo.setShopBusinessExpireTime(expiry.getBusinessExpireTime()); + userInfo.setShopBusinessExpired(expiry.getBusinessExpired()); + userInfo.setShopBusinessRemainingDays(expiry.getBusinessRemainingDays()); + } + return userInfo; } @Override @@ -1711,17 +1947,38 @@ public class UserServiceImpl extends ServiceImpl implements */ assertUserAvailable(userDO); - if (userDTO.getNickname() != null) { + boolean profileApproved = true; + if (userDTO.getNickname() != null || userDTO.getSignature() != null + || (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) || userDTO.getWechatQrCode() != null) { + Map content = new java.util.LinkedHashMap<>(); + content.put("nickname", userDTO.getNickname() == null ? userDO.getNickname() : userDTO.getNickname()); + content.put("signature", userDTO.getSignature() == null ? userDO.getSignature() : userDTO.getSignature()); + content.put("avatar", userDTO.getAvatar() == null + ? userDO.getAvatar() + : (userDTO.getAvatar().isEmpty() ? null : normalizeStoredAvatar(userDTO.getAvatar()))); + content.put("wechatQrCode", userDTO.getWechatQrCode() == null + ? userDO.getWechatQrCode() : normalizeStoredProfileImage(userDTO.getWechatQrCode())); + String serialized = serializeModerationPayload(content); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, content.get("avatar")); + addImageFileId(profileImages, content.get("wechatQrCode")); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", userId, userId, + String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized, profileImages); + profileApproved = moderation != null && "APPROVED".equals(moderation.getStatus()); + if (profileApproved) userDO = userMapper.selectById(userId); + } + + if (profileApproved && userDTO.getNickname() != null) { userDO.setNickname(userDTO.getNickname()); } - if (userDTO.getAvatar() != null) { + if (profileApproved && userDTO.getAvatar() != null) { if (userDTO.getAvatar().isEmpty()) { userDO.setAvatar(null); } else { userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } } - if (userDTO.getSignature() != null) { + if (profileApproved && userDTO.getSignature() != null) { userDO.setSignature(userDTO.getSignature()); } if (userDTO.getContactPhone() != null) { @@ -1733,7 +1990,7 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getWechatId() != null) { userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); } - if (userDTO.getWechatQrCode() != null) { + if (profileApproved && userDTO.getWechatQrCode() != null) { userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); } UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); @@ -1919,10 +2176,15 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.eq(UserDO::getIsDelete, 0); // 不再过滤普通用户,由前端根据用户角色进行过滤 if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(UserDO::getAccount, keyword) - .or().like(UserDO::getNickname, keyword) - .or().like(UserDO::getPhone, keyword) - .or().like(UserDO::getContactPhone, keyword)); + wrapper.and(w -> { + w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword); + if (phoneCrypto.isMobilePhone(keyword.trim())) { + String hash = phoneCrypto.index(keyword.trim()); + w.or().eq(UserDO::getAccountHash, hash) + .or().eq(UserDO::getPhoneHash, hash) + .or().eq(UserDO::getContactPhoneHash, hash); + } + }); } if (shopId != null && shopId > 0) { List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); @@ -1964,10 +2226,10 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); } if (Boolean.TRUE.equals(hasPhone)) { - wrapper.isNotNull(UserDO::getPhone); + wrapper.and(w -> w.isNotNull(UserDO::getPhone).or().isNotNull(UserDO::getPhoneHash)); } if (Boolean.FALSE.equals(hasPhone)) { - wrapper.isNull(UserDO::getPhone); + wrapper.isNull(UserDO::getPhone).isNull(UserDO::getPhoneHash); } wrapper.orderByDesc(UserDO::getCreateTime); @@ -2183,9 +2445,41 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ assertUserAvailable(userDO); - userDO.setAvatar(avatarUrl); - userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; + String storedAvatar = normalizeStoredAvatar(avatarUrl); + List imageIds = new ArrayList<>(); + addImageFileId(imageIds, storedAvatar); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_AVATAR", userId, userId, + "", serializeModerationPayload(java.util.Map.of("avatar", storedAvatar)), imageIds); + return moderation != null && ("APPROVED".equals(moderation.getStatus()) || "PENDING".equals(moderation.getStatus()) || "RETRY".equals(moderation.getStatus())); + } + + private void addImageFileId(List imageIds, String reference) { + if (!StringUtils.hasText(reference)) return; + if (DEFAULT_AVATAR_URL.equals(reference)) return; + Long fileId = objectStorageFileService.findFileIdByReference(reference); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("个人资料图片必须引用已上传文件"); + } + if (!imageIds.contains(fileId)) imageIds.add(fileId); + } + + private String serializeModerationPayload(Object payload) { + try { + return objectMapper.writeValueAsString(payload); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("无法保存待复核内容", exception); + } + } + + private void requireApprovedContent(ContentModerationResultVO result) { + if (result == null || !"APPROVED".equals(result.getStatus())) { + String reason = result == null ? null : result.getReason(); + throw new IllegalStateException(StringUtils.hasText(reason) ? reason : "内容正在审核中,暂未更新"); + } + } + + private boolean moderationApproved(ContentModerationResultVO result) { + return result != null && "APPROVED".equals(result.getStatus()); } @Override @@ -2234,8 +2528,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return boolean result consumed by the caller or returned to the frontend */ public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { - String oldPhone = updatePhoneDTO.getOldPhone(); - String newPhone = updatePhoneDTO.getNewPhone(); + String newPhone = validateUserPhone(updatePhoneDTO.getNewPhone(), userId, true); String verificationCode = updatePhoneDTO.getVerificationCode(); UserDO userDO = userMapper.selectById(userId); @@ -2254,15 +2547,6 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("当前账号未绑定手机号"); } - if (!userDO.getPhone().equals(oldPhone)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("原手机号不匹配"); - } - /** * Run business method `validateVerificationCode`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -2271,14 +2555,6 @@ public class UserServiceImpl extends ServiceImpl implements * @return result consumed by the caller or returned to the frontend */ validateVerificationCode(newPhone, verificationCode); - /** - * Run business method `ensurePhoneNotUsed`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param newPhone parameter `newPhone` supplied by the caller - * @param userId parameter `userId` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - ensurePhoneNotUsed(newPhone, userId); userDO.setPhone(newPhone); userDO.setPhoneVerified(1); @@ -2286,6 +2562,37 @@ public class UserServiceImpl extends ServiceImpl implements return userMapper.updateById(userDO) > 0; } + @Override + @Transactional(rollbackFor = Exception.class) + public boolean unbindPhone(Long userId, String verificationCode) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + String phone = userDO.getPhone(); + if (!StringUtils.hasText(phone) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + validateVerificationCode(phone, verificationCode); + userDO.setPhone(null); + userDO.setPhoneHash(null); + userDO.setPhoneVerified(0); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + public boolean sendUnbindPhoneCode(Long userId) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone()) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) { + throw new RuntimeException("当前账号未绑定已验证手机号"); + } + if (!verificationCodeService.canResend(userDO.getPhone())) { + throw new RuntimeException("验证码发送过于频繁,请稍后重试"); + } + verificationCodeService.sendVerificationCode(userDO.getPhone(), "USER_UNBIND_PHONE"); + return true; + } + @Override /** * Run business method `resetPasswordByPhone`. @@ -2308,10 +2615,7 @@ public class UserServiceImpl extends ServiceImpl implements validateVerificationCode(phone, verificationCode); // 根据手机号查找用户 - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getPhone, phone); - wrapper.eq(UserDO::getIsDelete, 0); - UserDO userDO = userMapper.selectOne(wrapper); + UserDO userDO = findUserByPhone(phone); if (userDO == null) { /** @@ -2321,6 +2625,7 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("未绑定手机号,请联系店员"); } + assertWechatLinkedForStaffLogin(userDO); if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { /** * Run business method `RuntimeException`. @@ -2449,6 +2754,13 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return private void result consumed by the caller or returned to the frontend */ + static void assertWechatLinkedForStaffLogin(UserDO userDO) { + if (userDO != null && Integer.valueOf(3).equals(userDO.getType()) + && !StringUtils.hasText(userDO.getAccount())) { + throw new RuntimeException("美甲师档案不能通过手机号登录,请使用关联微信身份或联系店长完成关联"); + } + } + private void handleLoginPasswordFailure(UserDO userDO) { if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { /** @@ -2846,7 +3158,8 @@ public class UserServiceImpl extends ServiceImpl implements LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo(); userInfo.setId(userDO.getId()); - userInfo.setAccount(userDO.getAccount()); + // 登录响应只用于展示账号标识,手机号账号不得以明文返回。 + userInfo.setAccount(phoneCrypto.mask(userDO.getAccount())); userInfo.setNickname(userDO.getNickname()); userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); userInfo.setType(userDO.getType()); @@ -2855,6 +3168,13 @@ public class UserServiceImpl extends ServiceImpl implements ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); + if (currentShop != null) { + com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessExpiryVO businessExpiry = + shopBusinessExpiryService.getExpiry(currentShop.getId()); + userInfo.setShopBusinessExpireTime(businessExpiry.getBusinessExpireTime()); + userInfo.setShopBusinessExpired(businessExpiry.getBusinessExpired()); + userInfo.setShopBusinessRemainingDays(businessExpiry.getBusinessRemainingDays()); + } userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userInfo.setCreateTime(userDO.getCreateTime()); @@ -3033,12 +3353,18 @@ public class UserServiceImpl extends ServiceImpl implements */ private void ensurePhoneNotUsed(String phone, Long currentUserId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) + .ne(UserDO::getType, 0) .eq(UserDO::getIsDelete, 0); if (currentUserId != null) { wrapper.ne(UserDO::getId, currentUserId); } - if (userMapper.selectOne(wrapper) != null) { + UserDO existing = userMapper.selectOne(wrapper); + if (existing == null) { + Long legacyId = userMapper.findLegacyIdByPhone(phone); + existing = legacyId == null || Objects.equals(legacyId, currentUserId) ? null : userMapper.selectById(legacyId); + } + if (existing != null) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -3047,6 +3373,119 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("手机号已被使用"); } } + + private void ensureCustomerUnique(String nickname, String wechatId, String phone) { + ensureCustomerUnique(nickname, wechatId, phone, null); + } + + private void ensureCustomerUnique(String nickname, String wechatId, String phone, Long ignoredCustomerId) { + if (!StringUtils.hasText(nickname)) { + throw new RuntimeException("客户姓名不能为空"); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + boolean duplicate = userMapper.selectList(wrapper).stream().anyMatch(existing -> + !java.util.Objects.equals(ignoredCustomerId, existing.getId()) + && java.util.Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(existing.getWechatId())) + && java.util.Objects.equals(normalizedPhone, decryptPhone(existing.getPhone()))); + if (duplicate) { + throw new RuntimeException("客户已存在,请选择已有客户"); + } + } + + private String decryptPhone(String value) { + return StringUtils.hasText(value) ? phoneCrypto.decrypt(value).trim() : null; + } + + private String validateCustomerPhone(String phone, boolean required) { + String normalizedPhone = phone == null ? null : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + if (required) throw new RuntimeException("手机号不能为空"); + return null; + } + if (!normalizedPhone.matches(PHONE_REGEX)) { + throw new RuntimeException("手机号格式不正确"); + } + return normalizedPhone; + } + + private String customerIdentityHash(String nickname, String wechatId, String phone) { + String normalizedName = StringUtils.hasText(nickname) ? nickname.trim() : ""; + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + return phoneCrypto.index(identityPart(normalizedName) + + identityPart(normalizedWechatId == null ? "" : normalizedWechatId) + + identityPart(normalizedPhone == null ? "" : normalizedPhone)); + } + + private String identityPart(String value) { + return value.length() + ":" + value; + } + + private String normalizeArtistColor(String color) { + if (!StringUtils.hasText(color)) { + return null; + } + String value = color.trim().toUpperCase(java.util.Locale.ROOT); + if (!value.matches("#[0-9A-F]{6}")) { + throw new RuntimeException("美甲师专属颜色格式不正确"); + } + return value; + } + + private void addPhoneMatch(LambdaQueryWrapper wrapper, String phone) { + String hash = phoneCrypto.index(phone.trim()); + List legacyIds = new ArrayList<>(); + QueryWrapper legacyPhoneQuery = new QueryWrapper<>(); + legacyPhoneQuery.select("id") + .eq("phone", phone.trim()) + .isNull("phone_hash") + .eq("type", 0) + .eq("is_delete", 0); + for (UserDO legacyCustomer : userMapper.selectList(legacyPhoneQuery)) { + if (legacyCustomer.getId() != null && !legacyIds.contains(legacyCustomer.getId())) { + legacyIds.add(legacyCustomer.getId()); + } + } + for (Long legacyContactId : userMapper.findLegacyIdsByContactPhone(phone.trim())) { + if (!legacyIds.contains(legacyContactId)) legacyIds.add(legacyContactId); + } + wrapper.and(query -> { + query.eq(UserDO::getPhoneHash, hash).or().eq(UserDO::getContactPhoneHash, hash); + if (!legacyIds.isEmpty()) query.or().in(UserDO::getId, legacyIds); + }); + } + + private UserDO findUserByAccount(String account) { + if (!StringUtils.hasText(account)) return null; + LambdaQueryWrapper query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getIsDelete, 0); + query.eq(UserDO::getAccountHash, phoneCrypto.index(account.trim())); + UserDO user = userMapper.selectOne(query.last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByAccount(account.trim()); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } + + private UserDO findUserByPhone(String phone) { + if (!StringUtils.hasText(phone)) return null; + String normalized = phone.trim(); + UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhoneHash, phoneCrypto.index(normalized)) + .ne(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0) + .last("limit 1")); + if (user == null) { + Long legacyId = userMapper.findLegacyIdByPhone(normalized); + user = legacyId == null ? null : userMapper.selectById(legacyId); + } + return user; + } /** * Run business method `buildRelationVO`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java index 63180c62..394a6909 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupport.java @@ -15,9 +15,8 @@ public final class UserProfileFieldSupport { } public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { - if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) - && !StringUtils.hasText(wechatId)) { - throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); + if (Integer.valueOf(2).equals(userType) && !StringUtils.hasText(wechatId)) { + throw new IllegalArgumentException("店长的微信号不能为空"); } } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java index 0a6628f7..c6b61a6f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/UserVO.java @@ -35,6 +35,10 @@ public class UserVO { */ private String shopName; + private LocalDateTime shopBusinessExpireTime; + private Boolean shopBusinessExpired; + private Integer shopBusinessRemainingDays; + /** * 绑定店铺ID列表 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java new file mode 100644 index 00000000..47978d51 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/AccountPhoneTypeHandler.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class AccountPhoneTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encryptAccount(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(cs.getString(columnIndex)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java new file mode 100644 index 00000000..bc9b731b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneBackfillReport.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import lombok.Data; + +import java.util.List; + +@Data +public class PhoneBackfillReport { + private boolean dryRun; + private int userRowsToUpdate; + private int userRowsUpdated; + private int orderRowsToUpdate; + private int orderRowsUpdated; + private int accountConflictRows; + private int phoneConflictRows; + private List conflictingUserIds; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java new file mode 100644 index 00000000..78150569 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneCrypto.java @@ -0,0 +1,124 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Base64; + +@Component +public class PhoneCrypto { + private static final String CIPHER_PREFIX = "enc:v1:"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static volatile PhoneCrypto current; + + private final PhoneCryptoProperties properties; + private byte[] encryptionKey; + private byte[] indexKey; + + public PhoneCrypto(PhoneCryptoProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void initialize() { + encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key"); + indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key"); + if (encryptionKey.length != 32 || indexKey.length < 32) { + throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥"); + } + if (java.util.Arrays.equals(encryptionKey, indexKey)) { + throw new IllegalStateException("手机号加密密钥与索引密钥必须独立"); + } + current = this; + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + byte[] payload = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, payload, 0, iv.length); + System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length); + return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号加密失败", exception); + } + } + + public String encryptAccount(String value) { + return isMobilePhone(value) ? encrypt(value) : value; + } + + public String decryptAccount(String value) { + return value != null && value.startsWith(CIPHER_PREFIX) ? decrypt(value) : value; + } + + public boolean isMobilePhone(String value) { + return value != null && value.trim().matches("1[3-9]\\d{9}"); + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length())); + if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效"); + byte[] iv = java.util.Arrays.copyOfRange(payload, 0, 12); + byte[] encrypted = java.util.Arrays.copyOfRange(payload, 12, payload.length); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (GeneralSecurityException | IllegalArgumentException exception) { + throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception); + } + } + + public boolean isEncrypted(String value) { + return value != null && value.startsWith(CIPHER_PREFIX); + } + + public String mask(String value) { + if (!StringUtils.hasText(value)) return value; + String plain = isEncrypted(value) ? decrypt(value) : value; + return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain; + } + + public String index(String value) { + if (!StringUtils.hasText(value)) return null; + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(indexKey, "HmacSHA256")); + byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号索引生成失败", exception); + } + } + + public static PhoneCrypto current() { + PhoneCrypto instance = current; + if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化"); + return instance; + } + + private byte[] decodeKey(String value, String name) { + if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-salon.privacy." + name); + try { + return Base64.getDecoder().decode(value.trim()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java new file mode 100644 index 00000000..db0c16e3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneDataBackfillService.java @@ -0,0 +1,112 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +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.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class PhoneDataBackfillService { + private final UserMapper userMapper; + private final OrderMapper orderMapper; + private final PhoneCrypto phoneCrypto; + private final PhoneCryptoProperties properties; + + @Transactional(rollbackFor = Exception.class) + public PhoneBackfillReport backfill(boolean dryRun) { + if (!dryRun && !properties.isBackfillEnabled()) { + throw new IllegalStateException("请先在 Salon Nacos secret.yaml 启用 phone-crypto.backfill-enabled"); + } + + List users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class)); + Map> accountGroups = groupValues(users, UserDO::getAccount); + Map> phoneGroups = groupValues(users, UserDO::getPhone); + Set accountConflicts = duplicateIds(accountGroups); + Set phoneConflicts = duplicateIds(phoneGroups); + Set conflictingIds = new HashSet<>(accountConflicts); + conflictingIds.addAll(phoneConflicts); + + List usersToUpdate = users.stream() + .filter(user -> !conflictingIds.contains(user.getId())) + .filter(this::hasPendingUserFields) + .toList(); + List ordersToUpdate = orderMapper.selectList(Wrappers.lambdaQuery(OrderDO.class) + .isNotNull(OrderDO::getCustomerPhoneSnapshot) + .isNull(OrderDO::getCustomerPhoneSnapshotHash)) + .stream() + .filter(order -> StringUtils.hasText(order.getCustomerPhoneSnapshot())) + .toList(); + + PhoneBackfillReport report = new PhoneBackfillReport(); + report.setDryRun(dryRun); + report.setUserRowsToUpdate(usersToUpdate.size()); + report.setOrderRowsToUpdate(ordersToUpdate.size()); + report.setAccountConflictRows(accountConflicts.size()); + report.setPhoneConflictRows(phoneConflicts.size()); + report.setConflictingUserIds(conflictingIds.stream().sorted().toList()); + if (dryRun) return report; + if (!conflictingIds.isEmpty()) { + throw new IllegalStateException("检测到手机号或登录账号重复,已停止全部回填;请先处理冲突用户 ID:" + + report.getConflictingUserIds()); + } + + int pageSize = Math.max(1, Math.min(properties.getBackfillPageSize(), 2000)); + for (int start = 0; start < usersToUpdate.size(); start += pageSize) { + int end = Math.min(start + pageSize, usersToUpdate.size()); + List batch = usersToUpdate.subList(start, end); + for (UserDO user : batch) { + userMapper.updateById(user); + report.setUserRowsUpdated(report.getUserRowsUpdated() + 1); + } + } + for (int start = 0; start < ordersToUpdate.size(); start += pageSize) { + int end = Math.min(start + pageSize, ordersToUpdate.size()); + List batch = ordersToUpdate.subList(start, end); + for (OrderDO order : batch) { + orderMapper.updateById(order); + report.setOrderRowsUpdated(report.getOrderRowsUpdated() + 1); + } + } + return report; + } + + private Map> groupValues(List users, Function valueGetter) { + Map> groups = new HashMap<>(); + for (UserDO user : users) { + String value = valueGetter.apply(user); + if (StringUtils.hasText(value)) { + groups.computeIfAbsent(phoneCrypto.index(value), ignored -> new ArrayList<>()).add(user.getId()); + } + } + return groups; + } + + private Set duplicateIds(Map> groups) { + return groups.values().stream() + .filter(ids -> ids.size() > 1) + .flatMap(List::stream) + .collect(Collectors.toSet()); + } + + private boolean hasPendingUserFields(UserDO user) { + return (StringUtils.hasText(user.getAccount()) && !StringUtils.hasText(user.getAccountHash())) + || (StringUtils.hasText(user.getPhone()) && !StringUtils.hasText(user.getPhoneHash())) + || (StringUtils.hasText(user.getContactPhone()) && !StringUtils.hasText(user.getContactPhoneHash())); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java new file mode 100644 index 00000000..3f594ffb --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/privacy/PhoneEncryptionTypeHandler.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.salon.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class PhoneEncryptionTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encrypt(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(cs.getString(columnIndex)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java index 360b1961..4805a95b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/OperationGuardService.java @@ -129,8 +129,7 @@ public class OperationGuardService { "public", safeAction, subject, - sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)) + sanitize(resolveClientIp(request)) ); } @@ -304,13 +303,6 @@ public class OperationGuardService { * Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private String resolveDeviceId(HttpServletRequest request) { - if (request == null) { - return "-"; - } - return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); - } - /** * Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java index 47e2900b..59c2c8d1 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java @@ -24,7 +24,6 @@ public class RequestThrottleService { * Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - public static final String DEVICE_ID_HEADER = "X-Device-Id"; /** * Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role. @@ -145,7 +144,6 @@ public class RequestThrottleService { String raw = String.join("|", category, sanitize(resolveClientIp(request)), - sanitize(resolveDeviceId(request)), sanitize(subject) ); String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); @@ -190,7 +188,7 @@ public class RequestThrottleService { * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ private String buildLoginLockRaw(HttpServletRequest request, String account) { - return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); + return String.join("|", sanitize(resolveClientIp(request)), sanitize(account)); } /** @@ -216,10 +214,6 @@ public class RequestThrottleService { * Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ - private String resolveDeviceId(HttpServletRequest request) { - return request == null ? null : request.getHeader(DEVICE_ID_HEADER); - } - /** * Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql new file mode 100644 index 00000000..a6ba4104 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql @@ -0,0 +1,35 @@ +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'appointment_business_hours' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN appointment_business_hours VARCHAR(20) NULL COMMENT ''预约运营营业时间'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'default_appointment_duration_minutes' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN default_appointment_duration_minutes INT NOT NULL DEFAULT 60 COMMENT ''默认预约服务时长(分钟)'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +UPDATE t_shop +SET default_appointment_duration_minutes = 60 +WHERE default_appointment_duration_minutes IS NULL OR default_appointment_duration_minutes <= 0; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql new file mode 100644 index 00000000..c58ddae4 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V11__安全接入配置加密管理_20261030.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS t_secure_integration_config ( + id BIGINT NOT NULL COMMENT '主键ID', + config_group VARCHAR(64) NOT NULL COMMENT '安全配置分组', + config_key VARCHAR(100) NOT NULL COMMENT '安全配置键', + config_value LONGTEXT NULL COMMENT 'AES-GCM 加密后的配置值', + is_secret TINYINT NOT NULL DEFAULT 0 COMMENT '是否为密钥类配置', + enabled TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用', + updated_by BIGINT NULL COMMENT '最后修改管理员ID', + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_secure_integration_config_group_key (config_group, config_key) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Salon安全接入配置'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql b/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql new file mode 100644 index 00000000..3346c041 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V12__微信订阅消息和预约取消原因_20261102.sql @@ -0,0 +1,35 @@ +SET @column_exists = ( + SELECT COUNT(1) FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'cancel_reason' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_order ADD COLUMN cancel_reason VARCHAR(255) NULL COMMENT ''预约取消原因'' AFTER customer_remark', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +CREATE TABLE IF NOT EXISTS t_wechat_subscribe_message_log ( + id BIGINT UNSIGNED NOT NULL COMMENT '订阅消息记录ID', + event_key VARCHAR(200) NOT NULL COMMENT '业务事件幂等键', + template_code VARCHAR(100) NOT NULL COMMENT '固定微信模板ID', + user_id BIGINT UNSIGNED NULL COMMENT '美甲师用户ID', + order_id BIGINT UNSIGNED NULL COMMENT '订单ID', + order_item_id BIGINT UNSIGNED NULL COMMENT '订单项ID', + open_id_hash VARCHAR(128) NULL COMMENT '接收OpenID摘要,不保存明文', + status VARCHAR(20) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/PROCESSING/RETRY/SENT/FAILED', + retry_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '重试次数', + err_code INT NULL COMMENT '微信错误码', + err_msg VARCHAR(500) NULL COMMENT '错误摘要', + next_retry_time DATETIME NULL COMMENT '下次处理时间', + sent_time DATETIME NULL COMMENT '发送成功时间', + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (id), + UNIQUE KEY uk_wechat_subscribe_event (event_key), + KEY idx_wechat_subscribe_due (status, next_retry_time, id), + KEY idx_wechat_subscribe_order (order_id, order_item_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信小程序订阅消息发送记录'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql b/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql new file mode 100644 index 00000000..d21e068e --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V1__Salon空库初始化.sql @@ -0,0 +1,2479 @@ +-- Flyway V1 baseline for JayuCloud Salon. +-- Derived from the frozen empty-database initialization SQL; applied once at Core startup. +-- The jayucloud_salon database must exist before the application starts. +-- 默认平台管理员账号:xiaowang,默认密码沿用当前 bcrypt 值。 +-- Linux MySQL 环境库名大小写敏感,数据源必须指向 jayucloud_salon。 +-- 2026-10-10 已吸收 docs/scripts/sql 下全部 Salon 版本 SQL 的最终状态: +-- 工作台注册审核、短信供应商全局切换、短信模板编码映射调整、短信模板编码统一修复。 + +-- auto-generated definition +create table t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +create table t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +create index idx_change_time + on t_balance_change_detail (change_time) + comment '按时间查询余额变动的索引'; + +create index idx_user_id + on t_balance_change_detail (user_id) + comment '按用户查询余额变动的索引'; + +-- auto-generated definition +create table t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +create index idx_user_id + on t_cart (user_id) + comment '按用户查询购物车的索引'; + +-- auto-generated definition +create table t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + moderation_status varchar(20) default 'APPROVED' not null comment '本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +create index idx_parent_comment_id + on t_comment (parent_comment_id) + comment '按父级评论查询回复的索引'; + +create index idx_product_id + on t_comment (product_id) + comment '按商品查询评论的索引'; + +create index idx_shop_id + on t_comment (shop_id) + comment '按店铺查询评论的索引'; + +create index idx_user_id + on t_comment (user_id) + comment '按用户查询评论的索引'; + +-- auto-generated definition +create table t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +create index idx_status + on t_coupon (status) + comment '按状态查询优惠券的索引'; + +-- auto-generated definition +create table t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +create index idx_coupon_id + on t_coupon_tag (coupon_id) + comment '按优惠券查询标签的索引'; + +create index idx_tag_id + on t_coupon_tag (tag_id) + comment '按标签查询优惠券的索引'; + +-- auto-generated definition +create table t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +create index idx_product_id + on t_effect_diagram (product_id) + comment '按商品查询效果图的索引'; + +-- auto-generated definition +create table t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +create index idx_login_method + on t_login_identity (login_method) + comment '按登录方式查询的索引'; + +create index idx_user_id + on t_login_identity (user_id) + comment '按用户查询登录标识的索引'; + +-- auto-generated definition +create table t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +create index idx_wechat_mini_unionid + on t_wechat_mini_binding (unionid) + comment '按unionid查询的索引'; + +-- auto-generated definition +create table t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +create index idx_status + on t_nail_artist_info (status) + comment '按状态查询美甲师的索引'; + +create index idx_user_id + on t_nail_artist_info (user_id) + comment '按用户查询美甲师信息的索引'; + +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + +-- auto-generated definition +create table t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +create index idx_status + on t_object_storage_file (status) + comment '??????'; + +create index idx_object_storage_file_backup_retry + on t_object_storage_file (backup_upload_status, primary_upload_status, status) + comment '????????'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +create table t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned null comment '关联用户表主键,历史补单可为空', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + customer_remark varchar(500) null comment '用户询价预约备注', + customer_name_snapshot varchar(100) null comment '补单客户名称快照', + customer_phone_snapshot varchar(128) null comment '加密补单客户手机号快照', + customer_phone_snapshot_hash char(64) null comment '补单客户手机号HMAC索引', + order_source varchar(32) default 'NORMAL_APPOINTMENT' not null comment '订单来源:NORMAL_APPOINTMENT/HISTORICAL_BACKFILL', + status tinyint unsigned default 1 not null comment '订单状态:0-价格确认中,1-待服务,2-已完成,3-已取消,4-服务中', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +create index idx_status + on t_order (status) + comment '按状态查询订单的索引'; + +create index idx_user_id + on t_order (user_id) + comment '按用户查询订单的索引'; + +create index idx_order_source_status_delete + on t_order (order_source, status, is_delete) + comment '按订单来源和状态查询的索引'; + +-- auto-generated definition +create table t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + service_date date null comment '业务服务日期,历史补单无具体时间时使用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +create index idx_order_id + on t_order_item (order_id) + comment '按订单查询商品的索引'; + +create index idx_order_item_artist_service_date + on t_order_item (artist_id, service_date, is_delete) + comment '按员工和业务服务日期查询的索引'; + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +create unique index uk_order_artist_review_item + on t_order_artist_review (order_item_id, is_delete); + +create index idx_order_artist_review_customer + on t_order_artist_review (customer_id, status, create_time); + +create index idx_order_artist_review_artist + on t_order_artist_review (artist_id, status); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +create index idx_order_artist_change_customer + on t_order_artist_change_request (customer_id, status, create_time); + +create index idx_order_artist_change_artist + on t_order_artist_change_request (from_artist_id, to_artist_id, status); + +create index idx_order_artist_change_shop + on t_order_artist_change_request (shop_id, status, create_time); + +create unique index uk_order_artist_change_pending_key + on t_order_artist_change_request (pending_key); + +-- auto-generated definition +create table t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +create table t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +create index idx_price + on t_product (price) + comment '按价格筛选商品的索引'; + +create index idx_shop_id + on t_product (shop_id) + comment '按所属店铺查询商品的索引'; + +create index idx_tags + on t_product (tags) + comment '按标签筛选商品的索引'; + +create index idx_title + on t_product (title) + comment '商品标题搜索的索引'; + +create index idx_t_product_front_visible + on t_product (shop_id, front_visible, source_type) + comment '按门店、前台展示和来源筛选商品'; + +-- auto-generated definition +create table t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +create index idx_product_id_like + on t_product_like (product_id) + comment '按商品查询点赞的索引'; + +create index idx_user_id_like + on t_product_like (user_id) + comment '按用户查询点赞的索引'; + +-- auto-generated definition +create table t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +create index idx_shop_name + on t_shop (shop_name) + comment '按店铺名称查询的索引'; + +-- auto-generated definition +create table t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +create table t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(128) null comment '用户账号(手机号账号加密存储)', + account_hash char(64) null comment '账号HMAC索引', + phone varchar(128) null comment '手机号AES-GCM密文', + phone_hash char(64) null comment '手机号HMAC索引', + contact_phone varchar(128) null comment '联系电话AES-GCM密文', + contact_phone_hash char(64) null comment '联系电话HMAC索引', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) null comment '用户密码(加密存储,微信快捷登录用户可为空)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_user_phone_hash + unique (phone_hash) comment '用户手机号HMAC唯一索引(允许多行NULL)', + constraint uk_user_account_hash + unique (account_hash) comment '手机号账号HMAC唯一索引(允许多行NULL)' +) + comment '系统用户信息表'; + +create index idx_email + on t_user (email) + comment '按邮箱查询的索引'; + +create index idx_shop_id + on t_user (shop_id) + comment '按店铺查询用户的索引'; + +create index idx_type + on t_user (type) + comment '按用户类型查询的索引'; + +-- 工作台注册审核申请 +CREATE TABLE IF NOT EXISTS `t_workbench_registration_application` +( + `id` bigint NOT NULL COMMENT '申请ID', + `application_no` varchar(40) NOT NULL COMMENT '申请编号', + `user_id` bigint NOT NULL COMMENT '申请用户ID', + `role_type` varchar(20) NOT NULL COMMENT '申请身份:MANAGER/STAFF', + `shop_id` bigint NULL COMMENT '目标店铺ID', + `shop_name` varchar(120) NULL COMMENT '店铺名称快照', + `shop_address` varchar(255) NULL COMMENT '店铺地址快照', + `status` varchar(30) NOT NULL COMMENT '状态:PENDING_ADMIN/PENDING_MANAGER/APPROVED/REJECTED', + `reviewer_id` bigint NULL COMMENT '审核人ID', + `reviewed_at` datetime NULL COMMENT '审核时间', + `reject_reason` varchar(500) NULL COMMENT '驳回原因', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_workbench_registration_application_no` (`application_no`), + KEY `idx_workbench_registration_user` (`user_id`), + KEY `idx_workbench_registration_shop_status` (`shop_id`, `status`), + KEY `idx_workbench_registration_status` (`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Salon店务工作台注册审核申请'; + +-- auto-generated definition +create table t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +create index idx_status + on t_user_coupon (status) + comment '按状态查询用户优惠券的索引'; + +create index idx_user_id + on t_user_coupon (user_id) + comment '按用户查询优惠券的索引'; + +-- auto-generated definition +create table t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +create index idx_permission_id + on t_user_permission (permission_id) + comment '权限ID索引'; + +create index idx_user_id + on t_user_permission (user_id) + comment '用户ID索引'; + +create table if not exists t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create unique index uk_t_system_message_idempotency + on t_system_message (idempotency_key); + +create table if not exists t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (user_id, read_status, popup_shown); + +create table if not exists t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (sort_order, publish_time); + +create table if not exists t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + +-- auto-generated definition +create table t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +create index idx_required_vip_level + on t_vip_benefit (required_vip_level) + comment '按VIP等级查询权益的索引'; + +-- auto-generated definition +create table t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +create index idx_vip_level + on t_vip_info (vip_level) + comment '按VIP等级查询的索引'; + +-- auto-generated definition +create table t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + +-- auto-generated definition +create table t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +create index idx_product_id + on t_wishlist (product_id) + comment '按商品查询收藏的索引'; + +create index idx_user_id + on t_wishlist (user_id) + comment '按用户查询收藏的索引'; + +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +CREATE TABLE IF NOT EXISTS t_account_closure_request ( + id bigint unsigned NOT NULL COMMENT '账号注销申请ID', + user_id bigint unsigned NOT NULL COMMENT '申请人用户ID', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '申请状态:PENDING/APPROVED/REJECTED/WITHDRAWN', + requested_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间', + processed_at datetime NULL COMMENT '处理时间', + reviewer_id bigint unsigned NULL COMMENT '处理人用户ID', + reviewer_note varchar(500) NULL COMMENT '处理说明', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_account_closure_user_status (user_id, status), + KEY idx_account_closure_status_time (status, requested_at) +) COMMENT='账号注销申请记录'; + +CREATE TABLE IF NOT EXISTS t_content_moderation_record ( + id bigint unsigned NOT NULL COMMENT '内容审核记录ID', + content_type varchar(40) NOT NULL COMMENT '内容类型:USER_PROFILE/USER_AVATAR/PRODUCT/COMMENT', + business_id bigint unsigned NULL COMMENT '业务记录ID', + user_id bigint unsigned NULL COMMENT '内容提交人', + status varchar(20) NOT NULL COMMENT '审核状态:PENDING/APPROVED/REJECTED/RETRY', + provider varchar(30) NOT NULL DEFAULT 'LOCAL_MOCK' COMMENT '审核Provider标识', + result_code varchar(40) NULL COMMENT 'Provider结果代码', + reason varchar(500) NULL COMMENT '审核或复核说明', + payload_json mediumtext NULL COMMENT '隔离内容载荷,仅待审核记录可访问', + reviewed_by bigint unsigned NULL COMMENT '复核人用户ID', + reviewed_at datetime NULL COMMENT '复核时间', + attempt_count int NOT NULL DEFAULT 0 COMMENT '处理尝试次数', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_content_moderation_status_time (status, create_time), + KEY idx_content_moderation_business (content_type, business_id) +) COMMENT='本地内容审核隔离与复核记录'; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); +CALL sp_add_column_if_not_exists('t_user', 'account_hash', 'char(64) NULL COMMENT ''账号HMAC索引'''); +CALL sp_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号HMAC索引'''); +CALL sp_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话HMAC索引'''); +CALL sp_add_column_if_not_exists('t_comment', 'moderation_status', 'varchar(20) NOT NULL DEFAULT ''APPROVED'' COMMENT ''本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY'''); +ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '手机号账号AES-GCM密文'; +ALTER TABLE t_user MODIFY COLUMN phone varchar(128) NULL COMMENT '手机号AES-GCM密文'; +ALTER TABLE t_user MODIFY COLUMN contact_phone varchar(128) NULL COMMENT '联系电话AES-GCM密文'; +SET @drop_legacy_account_index_sql = IF( + EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_account'), + 'ALTER TABLE t_user DROP INDEX uk_account', 'SELECT 1' +); +PREPARE stmt_drop_legacy_account_index FROM @drop_legacy_account_index_sql; +EXECUTE stmt_drop_legacy_account_index; +DEALLOCATE PREPARE stmt_drop_legacy_account_index; +SET @drop_legacy_phone_index_sql = IF( + EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_user_phone'), + 'ALTER TABLE t_user DROP INDEX uk_user_phone', 'SELECT 1' +); +PREPARE stmt_drop_legacy_phone_index FROM @drop_legacy_phone_index_sql; +EXECUTE stmt_drop_legacy_phone_index; +DEALLOCATE PREPARE stmt_drop_legacy_phone_index; +CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(`phone_hash`)'); +CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_account_hash', '(`account_hash`)'); +CALL sp_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(`contact_phone_hash`)'); +CALL sp_add_column_if_not_exists('t_order', 'customer_phone_snapshot_hash', 'char(64) NULL COMMENT ''补单客户手机号HMAC索引'''); +ALTER TABLE t_order MODIFY COLUMN customer_phone_snapshot varchar(128) NULL COMMENT '加密补单客户手机号快照'; +CALL sp_add_index_if_not_exists('t_order', 'idx_order_customer_phone_snapshot_hash', '(`customer_phone_snapshot_hash`)'); +SET @drop_consent_device_id_sql = IF( + EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user_agreement_consent' AND COLUMN_NAME = 'device_id'), + 'ALTER TABLE t_user_agreement_consent DROP COLUMN device_id', 'SELECT 1' +); +PREPARE stmt_drop_consent_device_id FROM @drop_consent_device_id_sql; +EXECUTE stmt_drop_consent_device_id; +DEALLOCATE PREPARE stmt_drop_consent_device_id; +SET @drop_audit_device_id_sql = IF( + EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_security_audit_log' AND COLUMN_NAME = 'device_id'), + 'ALTER TABLE t_security_audit_log DROP COLUMN device_id', 'SELECT 1' +); +PREPARE stmt_drop_audit_device_id FROM @drop_audit_device_id_sql; +EXECUTE stmt_drop_audit_device_id; +DEALLOCATE PREPARE stmt_drop_audit_device_id; +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +SET @sql = (SELECT IF(COUNT(*) = 0, + 'ALTER TABLE t_order MODIFY COLUMN user_id BIGINT UNSIGNED NULL COMMENT ''关联用户表主键,历史补单可为空''', + 'SELECT 1') FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'user_id' AND is_nullable = 'YES'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'customer_name_snapshot', 'varchar(100) NULL COMMENT ''补单客户名称快照'''); +CALL sp_add_column_if_not_exists('t_order', 'customer_phone_snapshot', 'varchar(32) NULL COMMENT ''补单客户手机号快照'''); +CALL sp_add_column_if_not_exists('t_order', 'order_source', 'varchar(32) NOT NULL DEFAULT ''NORMAL_APPOINTMENT'' COMMENT ''订单来源:NORMAL_APPOINTMENT/HISTORICAL_BACKFILL'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_column_if_not_exists('t_order_item', 'service_date', 'date NULL COMMENT ''业务服务日期,历史补单无具体时间时使用'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_order_source_status_delete', '(`order_source`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_order_item_artist_service_date', '(`artist_id`, `service_date`, `is_delete`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-salon' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='JayuCloud Salon 按业务场景投递 MessageHub 的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + ('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$3ZC5HHVK6EYIfkjcU9IHZulGXwNZhy.6LU85HRJC9A.3LHm0IEdMO', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG_SMS_VERIFY_1', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +ALTER TABLE t_user_agreement_consent MODIFY COLUMN user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.10.21', '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息,并确保上传的文字、图片具备合法来源。可在账号设置申请注销;管理员确认门店移交或归档后清理账号资料和登录身份。依法及履行必要业务所需的订单、预约和经营记录可能以匿名化形式保留,目标保留期为五年。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.10.21', '我们处理信息仅用于提供门店工作台:登录时由用户主动同意后调用微信登录并接收 OpenID;昵称、头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要的业务联系,不用于营销。店长和员工可能为预约及订单录入客户姓名、可选手机号和服务信息,这些是门店业务资料,不是客户小程序账号。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息;选择图片只在用户主动操作后调用。账号、客户和订单快照中的手机号使用 AES-GCM 加密保存,并用独立 HMAC 索引完成查重;常规界面、日志和导出对手机号脱敏。服务运行可能使用微信登录、短信服务商、消息通道和按环境配置的对象存储服务。用户可在账号设置申请注销或解绑手机号;注销申请经审核后撤销会话并在目标十五个工作日内删除或匿名化个人资料,订单、预约及经营凭证按产品目标保留五年并解除账号身份关联。头像、作品、评论等内容目前由本地模拟审核流程处理,结果仅用于开发验证,不代表已接入微信内容安全审核,正式上线前将另行完成实际审核平台和隐私指引配置。隐私内容上线前须由运营方核实数据处理方、时限和适用法律要求。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0), + (313931273555139010, 'SMS', 'SMS_PROVIDER', '短信供应商', 'SPUG', 1, '全局切换短信供应商时同步验证码模板和 MessageHub 通道', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +-- 排班规则与例外 +CREATE TABLE IF NOT EXISTS t_artist_schedule_rule ( + id bigint unsigned NOT NULL COMMENT '排班规则ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', preset_type varchar(32) NOT NULL COMMENT '预设类型', work_days varchar(32) NOT NULL COMMENT '工作星期,1-7逗号分隔', start_time time NOT NULL COMMENT '常规开始时间', end_time time NOT NULL COMMENT '常规结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1启用,0停用', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_rule_artist (shop_id, artist_id, is_delete), KEY idx_artist_schedule_rule_shop_status (shop_id, status, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师常规排班规则表'; +CREATE TABLE IF NOT EXISTS t_artist_schedule_exception ( + id bigint unsigned NOT NULL COMMENT '排班例外ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', work_date date NOT NULL COMMENT '例外日期', exception_type varchar(32) NOT NULL COMMENT '例外类型:REST/EXTRA_WORK/CHANGE_SHIFT', start_time time NULL COMMENT '例外开始时间', end_time time NULL COMMENT '例外结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_exception_date (shop_id, artist_id, work_date, is_delete), KEY idx_artist_schedule_exception_artist_date (artist_id, work_date, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师排班例外表'; + +-- 店长员工审核提醒参数。 +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, + create_time, update_time, is_delete +) +VALUES ( + 313931273555139020, 'WORKBENCH', 'MANAGER_REGISTRATION_REVIEW_NOTICE', + '店长员工审核提醒', 'true', 1, + '控制店长登录小程序后是否显式提示当前门店的待审核员工申请', + NOW(), NOW(), 0 +) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +-- 历史命名兼容修正:整合已部署库迁移所需的数据修正,空库执行时无副作用。 +START TRANSACTION; +UPDATE t_messagehub_push_config +SET source_system = 'jayucloud-salon' +WHERE source_system IN ('fingertipdesigner', 'fingertip-designer', 'FingertipDesigner'); +ALTER TABLE t_messagehub_push_config +COMMENT = 'JayuCloud Salon 按业务场景投递 MessageHub 的配置'; +COMMIT; +SET FOREIGN_KEY_CHECKS = 0; +SET FOREIGN_KEY_CHECKS = 1; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql new file mode 100644 index 00000000..ea123a57 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql @@ -0,0 +1,216 @@ +ALTER TABLE t_content_moderation_record + ADD COLUMN version_no int NOT NULL DEFAULT 1 COMMENT '业务内容版本号', + ADD COLUMN image_count int NOT NULL DEFAULT 0 COMMENT '该版本图片总数', + ADD COLUMN text_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '文字审核状态', + ADD COLUMN text_content mediumtext NULL COMMENT '待审文字内容', + ADD COLUMN next_retry_at datetime NULL COMMENT '下次自动重试时间'; + +ALTER TABLE t_product + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公开审核状态'; +ALTER TABLE t_comment + ADD COLUMN moderation_version int NOT NULL DEFAULT 1 COMMENT '评论审核版本号'; +ALTER TABLE t_shop + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '门店展示资料审核状态'; +ALTER TABLE t_announcement + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公告审核状态', + ADD COLUMN image_file_ids text NULL COMMENT '公告图片文件ID集合,多个ID以逗号分隔'; +ALTER TABLE t_system_message + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '人工消息审核状态;自动事务消息默认通过'; +ALTER TABLE t_user + ADD COLUMN profile_moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '公开个人资料审核状态'; +ALTER TABLE t_order_artist_review + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '评价审核状态:PENDING/APPROVED/REJECTED/RETRY'; +ALTER TABLE t_effect_diagram + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '效果图审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_sequence ( + seq int NOT NULL PRIMARY KEY +); +INSERT INTO tmp_content_moderation_sequence (seq) +SELECT ones.n + tens.n * 10 + hundreds.n * 100 + 1 +FROM (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) ones +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) tens +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) hundreds; + +CREATE TABLE t_content_moderation_image_task ( + id bigint unsigned NOT NULL COMMENT '审核图片任务ID', + record_id bigint unsigned NOT NULL COMMENT '内容审核版本ID', + file_id bigint unsigned NOT NULL COMMENT '对象存储文件ID', + provider_task_id varchar(100) NULL COMMENT '微信异步审核任务标识', + status varchar(20) NOT NULL COMMENT '图片审核状态:PENDING/APPROVED/REJECTED/RETRY', + result_code varchar(80) NULL COMMENT '图片审核结果代码', + reason varchar(500) NULL COMMENT '图片审核说明', + attempt_count int NOT NULL DEFAULT 0 COMMENT '提交尝试次数', + next_retry_at datetime NULL COMMENT '下次重试时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_content_moderation_image_provider_task (provider_task_id), + KEY idx_content_moderation_image_record (record_id, status), + KEY idx_content_moderation_image_file (file_id), + KEY idx_content_moderation_image_retry (status, next_retry_at), + CONSTRAINT fk_content_moderation_image_record FOREIGN KEY (record_id) REFERENCES t_content_moderation_record (id) +) COMMENT='内容版本逐图审核与微信异步任务'; + +CREATE INDEX idx_product_moderation_public ON t_product (shop_id, moderation_status, front_visible, is_delete); +CREATE INDEX idx_shop_moderation_public ON t_shop (moderation_status, status, is_delete); +CREATE INDEX idx_announcement_moderation_public ON t_announcement (moderation_status, status, publish_time); +CREATE INDEX idx_system_message_moderation_public ON t_system_message (moderation_status, status, publish_time); +CREATE INDEX idx_order_artist_review_moderation_public ON t_order_artist_review (moderation_status, status, is_delete); +CREATE INDEX idx_effect_diagram_moderation_public ON t_effect_diagram (product_id, moderation_status, is_delete); + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'PRODUCT', p.id, NULL, 1, + (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), p.title, p.description, p.target_audience, p.precautions, p.tags), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开作品等待审核', + JSON_OBJECT('shopId', p.shop_id, 'title', p.title, 'description', p.description, 'targetAudience', p.target_audience, 'precautions', p.precautions, 'imageFileIds', p.image_file_ids, 'price', p.price, 'tags', p.tags, 'approximateDuration', p.approximate_duration, 'bookableArtists', p.bookable_artists, 'availableCoupons', p.available_coupons, 'frontVisible', p.front_visible), 0, NOW(), NOW() +FROM t_product p WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('PRODUCT:', p.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公开作品图片等待审核', 0, NOW(), NOW() +FROM t_product p +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)) +WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT' + AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(p.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_product p JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id SET p.moderation_status = 'PENDING', p.front_visible = 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SHOP', s.id, NULL, 1, + (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), s.shop_name, s.description, s.address, s.business_hours), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量门店展示资料等待审核', + JSON_OBJECT('shopName', s.shop_name, 'description', s.description, 'address', s.address, 'businessHours', s.business_hours, 'coverImageFileId', s.cover_image_file_id, 'imageFileIds', s.image_file_ids, 'themeBackgroundImageFileId', s.theme_background_image_file_id), 0, NOW(), NOW() +FROM t_shop s WHERE s.is_delete = 0 AND s.status = 1; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SHOP:', s.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量门店图片等待审核', 0, NOW(), NOW() +FROM t_shop s +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)) +WHERE s.is_delete = 0 AND s.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_shop s JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id SET s.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'COMMENT', c.id, c.user_id, 1, + (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)), + 'PENDING', c.comment_content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开评论等待审核', + JSON_OBJECT('commentContent', c.comment_content, 'imageFileIds', c.image_file_ids), 0, NOW(), NOW() +FROM t_comment c WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:COMMENT:', c.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量评论图片等待审核', 0, NOW(), NOW() +FROM t_comment c +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)) +WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(c.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_comment c JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id SET c.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ANNOUNCEMENT', a.id, a.publisher_id, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(a.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(a.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), a.title, a.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开公告等待审核', + JSON_OBJECT('title', a.title, 'content', a.content, 'imageFileIds', a.image_file_ids, 'status', a.status), 0, NOW(), NOW() +FROM t_announcement a WHERE a.is_delete = 0 AND a.status = 1; +UPDATE t_announcement a JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id SET a.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ANNOUNCEMENT:', a.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公告图片等待审核', 0, NOW(), NOW() +FROM t_announcement a +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(a.image_file_ids, '') = '', 0, 1)) +WHERE a.is_delete = 0 AND a.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, + IF(m.image_file_id IS NULL, 0, 1), 'PENDING', CONCAT_WS(CHAR(10), m.title, m.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量人工发布消息等待审核', + JSON_OBJECT('title', m.title, 'content', m.content, 'imageFileId', m.image_file_id, 'status', m.status), 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SYSTEM_MESSAGE:', m.id, ':1'), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), m.image_file_id, 'PENDING', 'LEGACY_REVIEW', '存量人工消息图片等待审核', 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL AND m.image_file_id IS NOT NULL; +UPDATE t_system_message m JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id SET m.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'USER_PROFILE', u.id, u.id, 1, + (SELECT COUNT(DISTINCT profile_file.id) FROM t_object_storage_file profile_file + WHERE profile_file.file_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.primary_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.object_name IN (u.avatar, u.wechat_qr_code)), 'PENDING', CONCAT_WS(CHAR(10), u.nickname, u.signature), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量个人资料等待审核', + JSON_OBJECT( + 'nickname', u.nickname, + 'signature', u.signature, + 'avatar', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file avatar_file WHERE avatar_file.file_url = u.avatar OR avatar_file.primary_url = u.avatar OR avatar_file.object_name = u.avatar) THEN u.avatar ELSE NULL END, + 'wechatQrCode', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file qr_file WHERE qr_file.file_url = u.wechat_qr_code OR qr_file.primary_url = u.wechat_qr_code OR qr_file.object_name = u.wechat_qr_code) THEN u.wechat_qr_code ELSE NULL END + ), 0, NOW(), NOW() +FROM t_user u WHERE u.is_delete = 0 AND u.status = 1 + AND (u.nickname IS NOT NULL OR u.signature IS NOT NULL OR u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL); +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:USER_PROFILE:', u.id, ':', f.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), f.id, 'PENDING', 'LEGACY_REVIEW', '存量个人资料图片等待审核', 0, NOW(), NOW() +FROM t_user u JOIN t_object_storage_file f + ON f.file_url IN (u.avatar, u.wechat_qr_code) + OR f.primary_url IN (u.avatar, u.wechat_qr_code) + OR f.object_name IN (u.avatar, u.wechat_qr_code) +WHERE u.is_delete = 0 AND u.status = 1 AND (u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL) +GROUP BY u.id, f.id; +UPDATE t_user u JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id SET u.profile_moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:AUTO_SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, 0, + 'APPROVED', '', 'APPROVED', 'LEGACY_SYSTEM', 'AUTO_TRANSACTION_MESSAGE', '自动事务消息不送审', NULL, 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NOT NULL; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ORDER_ARTIST_REVIEW', r.id, r.customer_id, 1, + (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)), + 'PENDING', r.content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量订单评价等待审核', + JSON_OBJECT('content', r.content, 'imageFileIds', r.image_file_ids), 0, NOW(), NOW() +FROM t_order_artist_review r WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED'; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ORDER_ARTIST_REVIEW:', r.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量订单评价图片等待审核', 0, NOW(), NOW() +FROM t_order_artist_review r +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)) +WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(r.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_order_artist_review r JOIN t_content_moderation_record m ON m.content_type = 'ORDER_ARTIST_REVIEW' AND m.business_id = r.id SET r.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'EFFECT_DIAGRAM', e.id, NULL, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(e.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(e.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), e.category, e.description, e.tag), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量效果图等待审核', + JSON_OBJECT('productId', e.product_id, 'category', e.category, 'imageFileIds', e.image_file_ids, 'description', e.description, 'price', e.price, 'duration', e.duration, 'tag', e.tag), 0, NOW(), NOW() +FROM t_effect_diagram e WHERE e.is_delete = 0; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:EFFECT_DIAGRAM:', e.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量效果图图片等待审核', 0, NOW(), NOW() +FROM t_effect_diagram e +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(e.image_file_ids, '') = '', 0, 1)) +WHERE e.is_delete = 0 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(e.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_effect_diagram e JOIN t_content_moderation_record m ON m.content_type = 'EFFECT_DIAGRAM' AND m.business_id = e.id SET e.moderation_status = 'PENDING'; + +DROP TEMPORARY TABLE tmp_content_moderation_sequence; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql new file mode 100644 index 00000000..b9073f52 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql @@ -0,0 +1,176 @@ +ALTER TABLE t_comment + MODIFY COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' + COMMENT '内容审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record ( + record_id bigint unsigned NOT NULL PRIMARY KEY +); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_product p ON r.content_type = 'PRODUCT' AND r.business_id = p.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_comment c ON r.content_type = 'COMMENT' AND r.business_id = c.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_order_artist_review business_review ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_announcement a ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_effect_diagram e ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_shop s ON r.content_type = 'SHOP' AND r.business_id = s.id +WHERE r.provider = 'LEGACY_REVIEW' + AND ( + (COALESCE(TRIM(s.cover_image_file_id), '') <> '' AND TRIM(s.cover_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(s.theme_background_image_file_id), '') <> '' AND TRIM(s.theme_background_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') <> '' AND ( + TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + )) + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_system_message m ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id +LEFT JOIN t_object_storage_file f ON f.id = m.image_file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND m.image_file_id IS NOT NULL AND f.id IS NULL; + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT DISTINCT r.id +FROM t_content_moderation_record r +JOIN t_content_moderation_image_task task ON task.record_id = r.id +LEFT JOIN t_object_storage_file f ON f.id = task.file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND f.id IS NULL; + +UPDATE t_content_moderation_image_task task +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + task.reason = '历史图片引用无法安全核验,内容保持隐藏', + task.next_retry_at = NULL; + +UPDATE t_content_moderation_record r +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + r.reason = '历史图片引用格式无效、超出迁移范围或文件不可用,内容保持隐藏', + r.payload_json = CASE r.content_type + WHEN 'SHOP' THEN JSON_SET(r.payload_json, '$.coverImageFileId', NULL, '$.imageFileIds', NULL, '$.themeBackgroundImageFileId', NULL) + WHEN 'USER_PROFILE' THEN JSON_SET(r.payload_json, '$.avatar', NULL, '$.wechatQrCode', NULL) + WHEN 'SYSTEM_MESSAGE' THEN JSON_SET(r.payload_json, '$.imageFileId', NULL) + ELSE JSON_SET(r.payload_json, '$.imageFileIds', NULL) + END; + +UPDATE t_product p +JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET p.moderation_status = 'REJECTED', p.front_visible = 0; + +UPDATE t_comment c +JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET c.moderation_status = 'REJECTED'; + +UPDATE t_order_artist_review business_review +JOIN t_content_moderation_record r ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET business_review.moderation_status = 'REJECTED'; + +UPDATE t_announcement a +JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET a.moderation_status = 'REJECTED', a.status = 0; + +UPDATE t_effect_diagram e +JOIN t_content_moderation_record r ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET e.moderation_status = 'REJECTED'; + +UPDATE t_shop s +JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET s.moderation_status = 'REJECTED'; + +UPDATE t_system_message m +JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET m.moderation_status = 'REJECTED', m.status = 0; + +UPDATE t_user u +JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET u.profile_moderation_status = 'REJECTED'; + +UPDATE t_content_moderation_record r +SET r.image_count = (SELECT COUNT(1) FROM t_content_moderation_image_task task WHERE task.record_id = r.id) +WHERE r.provider = 'LEGACY_REVIEW'; + +UPDATE t_legal_agreement SET status = 0, update_time = NOW() +WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY') AND is_delete = 0 AND status = 1; + +INSERT INTO t_legal_agreement + (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555140001, 'USER_TERMS', '用户协议', '2026.10.25', + '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。头像、作品、评论、店铺展示资料、公告和人工发布的消息在公开前进行内容安全审核。DEV 使用本地模拟服务;其他环境未启用审核平台时保持隔离或进入人工复核;只有完成审核资质、回调域名、隐私指引和环境配置后启用微信审核服务时,必要文本、作者 OpenID 与图片短期授权地址才会提交给微信。拒绝、待复核、无法核验作者身份或服务异常的内容不会公开。客户业务资料及自动事务通知不纳入对外内容审核。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息并确保上传内容来源合法。可在账号设置申请注销;门店移交或归档后清理个人账号资料。必要订单、预约和经营记录按产品目标去身份化保留五年。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555140002, 'PRIVACY_POLICY', '隐私政策', '2026.10.25', + '我们处理信息仅用于提供门店工作台:用户主动同意后使用微信 OpenID 识别账号;昵称和头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要业务联系,不用于营销。店长和员工可能录入客户姓名、可选联系电话、预约和订单信息,这些是门店业务资料,不是客户的小程序账号。头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在对外展示前进行内容安全审核;开发环境使用本地模拟服务,其他环境以实际启用的审核 Provider 为准,未配置、待复核、拒绝、缺少作者 OpenID 或服务异常时内容保持隔离。仅在已完成微信资质、回调域名和隐私指引配置并于目标环境启用微信审核服务时,必要的待审文字、作者微信 OpenID 和图片短时授权地址会提交给微信内容安全接口。客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外审核。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息。手机号使用 AES-GCM 加密并以独立 HMAC 索引支持查重,常规页面、日志和导出脱敏。用户可在账号设置申请注销或解绑手机号;注销完成后目标十五个工作日内删除或匿名化个人资料,必要订单、预约和经营记录去除账号身份关联后按产品目标保留五年。隐私内容上线前由运营方核实实际服务商、微信后台指引和适用要求。', + 1, NOW(), NOW(), NOW(), 0); + +DROP TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql new file mode 100644 index 00000000..bb4bd81c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql @@ -0,0 +1,46 @@ +-- Legacy shop media can span three columns. V2 expands at most 1000 files per record; +-- reject snapshots whose source references do not have an exact matching task set. +UPDATE t_content_moderation_record r +JOIN t_shop s + ON r.content_type = 'SHOP' + AND r.business_id = s.id +LEFT JOIN ( + SELECT record_id, COUNT(1) AS task_count + FROM t_content_moderation_image_task + GROUP BY record_id +) image_tasks + ON image_tasks.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + r.reason = '门店存量图片审核任务不完整,内容保持隐藏,请重新提交资料', + r.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.status IN ('PENDING', 'RETRY') + AND ( + CASE WHEN NULLIF(TRIM(s.cover_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE WHEN NULLIF(TRIM(s.theme_background_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE + WHEN NULLIF(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') IS NULL THEN 0 + ELSE LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 + END + ) <> COALESCE(image_tasks.task_count, 0); + +UPDATE t_content_moderation_image_task task +JOIN t_content_moderation_record r ON r.id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + task.reason = '门店存量图片审核任务不完整,内容保持隐藏', + task.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE'; + +UPDATE t_shop s +JOIN t_content_moderation_record r + ON r.content_type = 'SHOP' + AND r.business_id = s.id + AND r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE' +SET s.moderation_status = 'REJECTED'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql new file mode 100644 index 00000000..714d0520 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql @@ -0,0 +1,87 @@ +SET @salon_v5_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_nail_artist_info' + AND COLUMN_NAME = 'moderation_status' + ), + 'SELECT 1', + 'ALTER TABLE t_nail_artist_info ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT ''PENDING'' COMMENT ''美甲师对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY'' AFTER portfolio' +); +PREPARE salon_v5_stmt FROM @salon_v5_ddl; +EXECUTE salon_v5_stmt; +DEALLOCATE PREPARE salon_v5_stmt; + +SET @salon_v5_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_nail_artist_info' + AND INDEX_NAME = 'idx_nail_artist_moderation_public' + ), + 'SELECT 1', + 'CREATE INDEX idx_nail_artist_moderation_public ON t_nail_artist_info (moderation_status, status, is_delete)' +); +PREPARE salon_v5_stmt FROM @salon_v5_ddl; +EXECUTE salon_v5_stmt; +DEALLOCATE PREPARE salon_v5_stmt; + +CREATE TEMPORARY TABLE tmp_legacy_artist_profile_moderation ( + artist_info_id bigint unsigned NOT NULL PRIMARY KEY, + user_id bigint unsigned NOT NULL, + has_public_content tinyint unsigned NOT NULL, + text_content mediumtext NULL, + identity varchar(50) NULL, + experience int NULL, + skills text NULL, + portfolio text NULL +); + +INSERT INTO tmp_legacy_artist_profile_moderation + (artist_info_id, user_id, has_public_content, text_content, identity, experience, skills, portfolio) +SELECT ai.id, + ai.user_id, + CASE WHEN NULLIF(TRIM(ai.identity), '') IS NOT NULL + OR COALESCE(ai.experience, 0) > 0 + OR NULLIF(TRIM(ai.skills), '') IS NOT NULL + OR NULLIF(TRIM(ai.portfolio), '') IS NOT NULL THEN 1 ELSE 0 END, + CONCAT_WS(CHAR(10), NULLIF(TRIM(ai.identity), ''), + CASE WHEN COALESCE(ai.experience, 0) > 0 THEN CONCAT(ai.experience, '年从业经验') END, + (SELECT GROUP_CONCAT(COALESCE(NULLIF(t.display_name, ''), t.tag_name) ORDER BY t.id SEPARATOR ',') + FROM t_tag t + WHERE t.is_delete = 0 AND t.front_visible = 1 + AND FIND_IN_SET( + CONVERT(CAST(t.id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci, + CONVERT(REPLACE(COALESCE(ai.skills, ''), ' ', '') USING utf8mb4) COLLATE utf8mb4_unicode_ci + ) > 0)), + ai.identity, ai.experience, ai.skills, ai.portfolio +FROM t_nail_artist_info ai +JOIN t_user u ON u.id = ai.user_id +WHERE ai.is_delete = 0 AND u.is_delete = 0 AND u.status = 1 AND u.type IN (2, 3); + +UPDATE t_nail_artist_info ai +JOIN tmp_legacy_artist_profile_moderation legacy ON legacy.artist_info_id = ai.id +SET ai.moderation_status = CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, + provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:NAIL_ARTIST_PROFILE:', legacy.artist_info_id), 256), 1, 15), 16, 10) AS UNSIGNED), + 'NAIL_ARTIST_PROFILE', legacy.artist_info_id, NULL, 1, 0, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + legacy.text_content, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_REVIEW' ELSE 'LEGACY_SYSTEM' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_PUBLIC_CONTENT' ELSE 'EMPTY_PROFILE_BASELINE' END, + CASE WHEN legacy.has_public_content = 1 THEN '存量美甲师公开资料等待审核' ELSE '系统默认美甲师资料无需审核' END, + JSON_OBJECT('identity', legacy.identity, 'experience', legacy.experience, + 'skills', legacy.skills, 'portfolio', legacy.portfolio), + 0, NOW(), NOW() +FROM tmp_legacy_artist_profile_moderation legacy +WHERE NOT EXISTS ( + SELECT 1 FROM t_content_moderation_record current_record + WHERE current_record.content_type = 'NAIL_ARTIST_PROFILE' + AND current_record.business_id = legacy.artist_info_id +); + +DROP TEMPORARY TABLE tmp_legacy_artist_profile_moderation; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql b/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql new file mode 100644 index 00000000..5b29771a --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V6__Salon店长审核模式与门店经营有效期_20261026.sql @@ -0,0 +1,58 @@ +-- 店长申请内容审核关联与门店经营有效期。 +-- 当前没有存量门店,不执行任何门店数据回填。 + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_shop' + AND COLUMN_NAME = 'business_expire_time' + ), + 'SELECT 1', + 'ALTER TABLE t_shop ADD COLUMN business_expire_time datetime NULL COMMENT ''门店经营有效期,空表示未设置'' AFTER authorization_expire_time' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_workbench_registration_application' + AND COLUMN_NAME = 'content_moderation_record_id' + ), + 'SELECT 1', + 'ALTER TABLE t_workbench_registration_application ADD COLUMN content_moderation_record_id bigint NULL COMMENT ''店长申请关联的确切内容审核记录ID'' AFTER reject_reason' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +SET @salon_v6_ddl = IF( + EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_workbench_registration_application' + AND INDEX_NAME = 'idx_registration_moderation_record' + ), + 'SELECT 1', + 'CREATE INDEX idx_registration_moderation_record ON t_workbench_registration_application (content_moderation_record_id)' +); +PREPARE salon_v6_stmt FROM @salon_v6_ddl; +EXECUTE salon_v6_stmt; +DEALLOCATE PREPARE salon_v6_stmt; + +INSERT INTO t_system_parameter_config + (id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete) +VALUES + (CAST(CONV(SUBSTR(SHA2('SALON:WORKBENCH:MANAGER_REGISTRATION_AUTO_APPROVE', 256), 1, 15), 16, 10) AS UNSIGNED), + 'WORKBENCH', 'MANAGER_REGISTRATION_AUTO_APPROVE', '店长注册自动审核', 'false', 1, + '开启后仅在申请关联的门店资料内容审核通过时自动批准店长注册;关闭后由平台管理员人工复核', NOW(), NOW(), 0), + (CAST(CONV(SUBSTR(SHA2('SALON:SHOP:SHOP_DEFAULT_VALID_DAYS', 256), 1, 15), 16, 10) AS UNSIGNED), + 'SHOP', 'SHOP_DEFAULT_VALID_DAYS', '新门店默认有效期天数', '30', 1, + '店长注册审核通过后新门店的默认经营有效期天数,范围1-3650', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + update_time = NOW(); diff --git a/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql b/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql new file mode 100644 index 00000000..7159701d --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V7__门店默认有效期缺失修复_20261027.sql @@ -0,0 +1,55 @@ +-- 修复历史门店经营有效期为空的问题,并保证默认天数参数有有效值。 +-- 已有有效期的门店不会被覆盖;已审核通过的店长注册按审核日期起算,其余存量门店从迁移日获得默认期限。 + +INSERT INTO t_system_parameter_config + (id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete) +VALUES + (CAST(CONV(SUBSTR(SHA2('SALON:SHOP:SHOP_DEFAULT_VALID_DAYS', 256), 1, 15), 16, 10) AS UNSIGNED), + 'SHOP', 'SHOP_DEFAULT_VALID_DAYS', '新门店默认有效期天数', '30', 1, + '店长注册审核通过后新门店的默认经营有效期天数,范围1-3650', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + config_value = CASE + WHEN config_value REGEXP '^[0-9]+$' + AND CAST(config_value AS UNSIGNED) BETWEEN 1 AND 3650 THEN config_value + ELSE '30' + END, + enabled = 1, + is_delete = 0, + remark = VALUES(remark), + update_time = NOW(); + +SET @salon_shop_default_valid_days = ( + SELECT CASE + WHEN config_value REGEXP '^[0-9]+$' + AND CAST(config_value AS UNSIGNED) BETWEEN 1 AND 3650 THEN CAST(config_value AS UNSIGNED) + ELSE 30 + END + FROM t_system_parameter_config + WHERE config_group = 'SHOP' + AND config_key = 'SHOP_DEFAULT_VALID_DAYS' + AND enabled = 1 + AND is_delete = 0 + ORDER BY id + LIMIT 1 +); +SET @salon_shop_default_valid_days = COALESCE(@salon_shop_default_valid_days, 30); + +UPDATE t_shop s +LEFT JOIN ( + SELECT shop_id, MAX(reviewed_at) AS approved_at + FROM t_workbench_registration_application + WHERE role_type = 'MANAGER' + AND status = 'APPROVED' + AND is_delete = 0 + GROUP BY shop_id +) approved_application ON approved_application.shop_id = s.id +SET s.business_expire_time = TIMESTAMP( + DATE_ADD( + COALESCE(DATE(approved_application.approved_at), CURDATE()), + INTERVAL (@salon_shop_default_valid_days - 1) DAY + ), + '23:59:59' +) +WHERE s.business_expire_time IS NULL + AND s.is_delete = 0; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql b/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql new file mode 100644 index 00000000..ca0b4603 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V8__客户联系方式去重和美甲师专属颜色_20261029.sql @@ -0,0 +1,117 @@ +-- 客户允许重名及重复手机号;仅姓名、微信号、手机号组合完全相同时拒绝创建。 +-- 美甲师专属颜色持久化到资料表,规划页与员工页面共用同一颜色。 + +DROP PROCEDURE IF EXISTS salon_v8_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_unique_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_drop_index_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE salon_v8_add_column_if_missing( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_add_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_add_unique_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v8_drop_index_if_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v8_sql = CONCAT('ALTER TABLE `', p_table_name, '` DROP INDEX `', p_index_name, '`'); + PREPARE salon_v8_stmt FROM @salon_v8_sql; + EXECUTE salon_v8_stmt; + DEALLOCATE PREPARE salon_v8_stmt; + END IF; +END$$ + +DELIMITER ; + +CALL salon_v8_add_column_if_missing( + 't_user', 'customer_identity_hash', + 'char(64) NULL COMMENT ''客户姓名、微信号和手机号组合HMAC''' +); +CALL salon_v8_add_column_if_missing( + 't_user', 'active_customer_identity_hash', + 'char(64) GENERATED ALWAYS AS (CASE WHEN type = 0 AND COALESCE(is_delete, 0) = 0 THEN customer_identity_hash ELSE NULL END) STORED COMMENT ''有效客户组合身份索引''' +); +CALL salon_v8_add_column_if_missing( + 't_user', 'active_service_phone_hash', + 'char(64) GENERATED ALWAYS AS (CASE WHEN type <> 0 AND COALESCE(is_delete, 0) = 0 THEN phone_hash ELSE NULL END) STORED COMMENT ''有效員工和管理員手机号唯一索引''' +); +CALL salon_v8_add_column_if_missing( + 't_nail_artist_info', 'color', + 'varchar(7) NULL COMMENT ''美甲师规划专属颜色''' +); + +CALL salon_v8_drop_index_if_exists('t_user', 'uk_user_phone_hash'); +CALL salon_v8_add_index_if_missing('t_user', 'idx_user_phone_hash', '(`phone_hash`)'); +CALL salon_v8_add_unique_index_if_missing( + 't_user', 'uk_user_active_customer_identity_hash', '(`active_customer_identity_hash`)' +); +CALL salon_v8_add_unique_index_if_missing( + 't_user', 'uk_user_active_service_phone_hash', '(`active_service_phone_hash`)' +); + +DROP PROCEDURE IF EXISTS salon_v8_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_add_unique_index_if_missing; +DROP PROCEDURE IF EXISTS salon_v8_drop_index_if_exists; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql new file mode 100644 index 00000000..73f6e926 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V9__美甲师注册申请目标员工关联_20261030.sql @@ -0,0 +1,70 @@ +-- 为美甲师申请保存审核资料与目标员工,并保证一个待审核申请最多预关联一个员工。 + +DROP PROCEDURE IF EXISTS salon_v9_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v9_add_unique_index_if_missing; + +DELIMITER $$ + +CREATE PROCEDURE salon_v9_add_column_if_missing( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @salon_v9_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_definition); + PREPARE salon_v9_stmt FROM @salon_v9_sql; + EXECUTE salon_v9_stmt; + DEALLOCATE PREPARE salon_v9_stmt; + END IF; +END$$ + +CREATE PROCEDURE salon_v9_add_unique_index_if_missing( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @salon_v9_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', p_columns); + PREPARE salon_v9_stmt FROM @salon_v9_sql; + EXECUTE salon_v9_stmt; + DEALLOCATE PREPARE salon_v9_stmt; + END IF; +END$$ + +DELIMITER ; + +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'target_artist_user_id', + 'bigint NULL COMMENT ''店长预关联或审核确认的目标美甲师用户ID''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'applicant_nickname', + 'varchar(100) NULL COMMENT ''美甲师申请昵称,审核通过前不展示''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'applicant_avatar_file_id', + 'bigint NULL COMMENT ''美甲师申请头像文件ID,审核通过前不展示''' +); +CALL salon_v9_add_column_if_missing( + 't_workbench_registration_application', 'pending_target_artist_user_id', + 'bigint GENERATED ALWAYS AS (CASE WHEN role_type = ''STAFF'' AND status = ''PENDING_MANAGER'' AND COALESCE(is_delete, 0) = 0 THEN target_artist_user_id ELSE NULL END) STORED COMMENT ''待审核申请预关联员工唯一值''' +); +CALL salon_v9_add_unique_index_if_missing( + 't_workbench_registration_application', 'uk_registration_pending_target_artist', + '(`pending_target_artist_user_id`)' +); + +DROP PROCEDURE IF EXISTS salon_v9_add_column_if_missing; +DROP PROCEDURE IF EXISTS salon_v9_add_unique_index_if_missing; diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java new file mode 100644 index 00000000..cc4ea9d6 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/MetaObjectHandlerRegistrationTest.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.core.type.filter.AssignableTypeFilter; + +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +class MetaObjectHandlerRegistrationTest { + + @Test + void onlyOneMetaObjectHandlerImplementationIsRegistered() { + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); + scanner.addIncludeFilter(new AssignableTypeFilter(MetaObjectHandler.class)); + + Set handlerClasses = scanner + .findCandidateComponents("com.xiaowang.jayucloud.salon.core") + .stream() + .map(beanDefinition -> beanDefinition.getBeanClassName()) + .collect(Collectors.toSet()); + + assertThat(handlerClasses) + .containsExactly(MyMetaObjectHandler.class.getName()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java new file mode 100644 index 00000000..bba8f7f8 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/MiniProgramObjectStorageUploadControllerMappingTest.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.controller.front; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class MiniProgramObjectStorageUploadControllerMappingTest { + + @Test + void miniProgramRouteExposesOnlyDirectUpload() throws Exception { + RequestMapping mapping = MiniProgramObjectStorageUploadController.class.getAnnotation(RequestMapping.class); + assertNotNull(mapping); + assertArrayEquals(new String[]{"/object-storage-file"}, mapping.value()); + + Method uploadMethod = MiniProgramObjectStorageUploadController.class.getMethod( + "uploadFile", javax.servlet.http.HttpServletRequest.class, + org.springframework.web.multipart.MultipartFile.class); + PostMapping uploadMapping = uploadMethod.getAnnotation(PostMapping.class); + assertNotNull(uploadMapping); + assertArrayEquals(new String[]{"/upload"}, uploadMapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java new file mode 100644 index 00000000..b54ed962 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/ObjectStorageFileControllerMappingTest.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.controller.front; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.RequestMapping; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ObjectStorageFileControllerMappingTest { + + @Test + void keepsFileManagementRoutesAdminOnly() { + RequestMapping mapping = ObjectStorageFileController.class.getAnnotation(RequestMapping.class); + + assertNotNull(mapping); + assertArrayEquals(new String[]{"/admin/object-storage-file"}, mapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java new file mode 100644 index 00000000..984fdb9d --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/MinioObjectStorageProviderTest.java @@ -0,0 +1,83 @@ +package com.xiaowang.jayucloud.salon.core.modules.file.service.impl; + +import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties; +import com.xiaowang.jayucloud.salon.core.modules.file.config.MinioStorageConfig; +import io.minio.GetObjectArgs; +import io.minio.GetPresignedObjectUrlArgs; +import io.minio.MinioClient; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; + +import java.io.ByteArrayInputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class MinioObjectStorageProviderTest { + + @Test + void signsClientUrlsWithPublicEndpointWhenConfigured() throws Exception { + ObjectProvider internalClientProvider = mock(ObjectProvider.class); + MinioClient signingClient = mock(MinioClient.class); + when(signingClient.getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class))) + .thenReturn("https://sit.minio.yunail.art/jayucloud-salon-sit/style.jpg?signature=ok"); + + MinioStorageConfig config = new MinioStorageConfig(); + config.setEnabled(true); + config.setEndpoint("http://192.168.10.14:9000"); + config.setPublicEndpoint("https://sit.minio.yunail.art"); + config.setAccessKey("access-key"); + config.setSecretKey("secret-key"); + config.setBucketName("jayucloud-salon-sit"); + config.setPrivateBucket(true); + + MinioObjectStorageProvider provider = new MinioObjectStorageProvider( + internalClientProvider, + config, + new ObjectStorageProperties(), + signingClient + ); + + String signedUrl = provider.getPresignedUrl("style.jpg", 60); + + assertTrue(signedUrl.startsWith("https://sit.minio.yunail.art/jayucloud-salon-sit/style.jpg?")); + verify(internalClientProvider, org.mockito.Mockito.never()).getIfAvailable(); + verify(signingClient).getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class)); + } + + @Test + void usesInternalMinioClientForUploadDownloadAndDelete() throws Exception { + MinioClient internalClient = mock(MinioClient.class); + ObjectProvider internalClientProvider = mock(ObjectProvider.class); + when(internalClientProvider.getIfAvailable()).thenReturn(internalClient); + + MinioStorageConfig config = new MinioStorageConfig(); + config.setEnabled(true); + config.setEndpoint("http://192.168.10.14:9000"); + config.setAccessKey("access-key"); + config.setSecretKey("secret-key"); + config.setBucketName("jayucloud-salon-sit"); + + MinioObjectStorageProvider provider = new MinioObjectStorageProvider( + internalClientProvider, + config, + new ObjectStorageProperties() + ); + + provider.uploadStream(new ByteArrayInputStream(new byte[]{1}), 1, "image/jpeg", "style.jpg"); + provider.downloadFile("style.jpg"); + provider.deleteFile("style.jpg"); + + assertEquals("http://192.168.10.14:9000/jayucloud-salon-sit/style.jpg", provider.getFileUrl("style.jpg")); + verify(internalClient).putObject(org.mockito.ArgumentMatchers.any(PutObjectArgs.class)); + verify(internalClient).getObject(org.mockito.ArgumentMatchers.any(GetObjectArgs.class)); + verify(internalClient).removeObject(org.mockito.ArgumentMatchers.any(RemoveObjectArgs.class)); + verify(internalClient, never()).getPresignedObjectUrl(org.mockito.ArgumentMatchers.any(GetPresignedObjectUrlArgs.class)); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java new file mode 100644 index 00000000..d28d07b5 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/support/ObjectStorageUrlSupportTest.java @@ -0,0 +1,61 @@ +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; +import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ObjectStorageUrlSupportTest { + + private ObjectStorageUrlSupport support; + private ObjectStorageOrchestrationService orchestrationService; + + @BeforeEach + void setUp() { + MinioStorageConfig minio = new MinioStorageConfig(); + minio.setEndpoint("http://192.168.10.14:9000"); + minio.setPublicEndpoint("https://sit.minio.yunail.art"); + minio.setBucketName("jayucloud-salon-sit"); + AliyunOssConfig aliyun = new AliyunOssConfig(); + aliyun.setEndpoint("https://oss-cn-hangzhou.aliyuncs.com"); + aliyun.setBucketName("salon"); + QiniuKodoConfig qiniu = new QiniuKodoConfig(); + qiniu.setDomain("https://sit.qiniu.yunail.art"); + ObjectStorageProperties properties = new ObjectStorageProperties(); + properties.setSignedUrlExpireMinutes(60); + orchestrationService = mock(ObjectStorageOrchestrationService.class); + support = new ObjectStorageUrlSupport(mock(PrimaryObjectStorageService.class), minio, aliyun, + qiniu, mock(AliyunOssService.class), properties, orchestrationService); + } + + @Test + void extractsObjectNameFromMinioInternalAndPublicUrls() { + assertEquals("avatar/7/photo.jpg", support.extractObjectName( + "http://192.168.10.14:9000/jayucloud-salon-sit/avatar/7/photo.jpg")); + assertEquals("avatar/7/photo.jpg", support.extractObjectName( + "https://sit.minio.yunail.art/jayucloud-salon-sit/avatar/7/photo.jpg?X-Amz-Signature=test")); + } + + @Test + void keepsQiniuAndOssReferencesSupported() { + assertEquals("avatar/7/photo.jpg", support.extractObjectName("https://sit.qiniu.yunail.art/avatar/7/photo.jpg")); + assertEquals("avatar/7/photo.jpg", support.extractObjectName("oss://salon/avatar/7/photo.jpg")); + } + + @Test + void doesNotReturnKnownPrivateUrlWhenSigningFails() { + when(orchestrationService.getPresignedUrl("avatar/7/photo.jpg", 60)) + .thenThrow(new IllegalStateException("storage unavailable")); + assertNull(support.toAccessibleUrl("https://sit.minio.yunail.art/jayucloud-salon-sit/avatar/7/photo.jpg")); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java new file mode 100644 index 00000000..6de8fe40 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatSubscribeMessageServiceImplTest.java @@ -0,0 +1,142 @@ +package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +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.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +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.order.support.OrderStatus; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class WechatSubscribeMessageServiceImplTest { + + @Mock private WechatSubscribeMessageLogMapper logMapper; + @Mock private WechatMiniBindingMapper bindingMapper; + @Mock private WechatMiniClientService clientService; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + + private WechatMiniProperties properties; + private WechatSubscribeMessageServiceImpl service; + + @BeforeEach + void setUp() { + properties = new WechatMiniProperties(); + properties.setSubscribeMessageEnabled(true); + properties.setSubscribeMessageProvider("mock"); + properties.setServiceStartReminderLeadMinutes(30); + properties.setSubscribeMessagePage("/pages/appointment-detail/index"); + properties.setSubscribeMessageMiniprogramState("developer"); + properties.setSubscribeMessageMaxRetries(3); + service = new WechatSubscribeMessageServiceImpl(logMapper, bindingMapper, clientService, properties, + orderMapper, orderItemMapper, productMapper, userMapper, phoneCrypto); + } + + @Test + void doesNotEnqueueUnassignedAppointment() { + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + when(orderItemMapper.selectById(101L)).thenReturn(item); + + service.enqueueAppointmentReminder(1L, 101L); + + verify(logMapper, never()).insert(any(WechatSubscribeMessageLogDO.class)); + } + + @Test + void enqueueIncludesCurrentArtistInIdempotencyKey() { + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + item.setArtistId(7L); + when(orderItemMapper.selectById(101L)).thenReturn(item); + + service.enqueueAppointmentReminder(1L, 101L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WechatSubscribeMessageLogDO.class); + verify(logMapper).insert(captor.capture()); + assertEquals("APPOINTMENT:101:7", captor.getValue().getEventKey()); + assertEquals(7L, captor.getValue().getUserId()); + } + + @Test + void sendsOnlyCurrentPendingAppointmentToBoundArtist() { + LocalDateTime appointmentTime = LocalDateTime.now().plusHours(2); + WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO(); + log.setId(1L); + log.setTemplateCode("Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo"); + log.setOrderId(11L); + log.setOrderItemId(101L); + log.setUserId(7L); + log.setStatus("PENDING"); + log.setRetryCount(0); + OrderItemDO item = new OrderItemDO(); + item.setId(101L); + item.setOrderId(11L); + item.setArtistId(7L); + item.setProductId(31L); + item.setAppointmentTime(appointmentTime); + item.setIsDelete(0); + OrderDO order = new OrderDO(); + order.setId(11L); + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setIsDelete(0); + order.setCustomerNameSnapshot("小周"); + UserDO artist = new UserDO(); + artist.setId(7L); + artist.setNickname("小美"); + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setOpenId("openid-value"); + ProductDO product = new ProductDO(); + product.setTitle("纯色美甲"); + when(logMapper.selectDue(any(), any(Integer.class))).thenReturn(List.of(log)); + when(logMapper.claimForProcessing(1L)).thenReturn(1); + when(orderItemMapper.selectById(101L)).thenReturn(item); + when(orderMapper.selectById(11L)).thenReturn(order); + when(userMapper.selectById(7L)).thenReturn(artist); + when(bindingMapper.selectOne(any(Wrapper.class))).thenReturn(binding); + when(productMapper.selectById(31L)).thenReturn(product); + when(phoneCrypto.index("openid-value")).thenReturn("hash"); + when(clientService.sendSubscribeMessage(any(), any(), any(), any(), any())) + .thenReturn(new WechatMiniClientService.SubscribeMessageResult(true, 0, "ok")); + + service.processDueMessages(); + + verify(clientService).sendSubscribeMessage(eq("openid-value"), eq(log.getTemplateCode()), + any(), any(), any()); + assertEquals("hash", log.getOpenIdHash()); + assertEquals("SENT", log.getStatus()); + verify(logMapper, times(2)).updateById(log); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java new file mode 100644 index 00000000..5cd9001e --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerControllerMappingTest.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.manager.controller.admin; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.RequestMapping; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class AdminManagerControllerMappingTest { + + @Test + void exposesAdminCompatibilityAndMiniProgramBusinessRoutes() { + RequestMapping mapping = AdminManagerController.class.getAnnotation(RequestMapping.class); + + assertNotNull(mapping); + assertArrayEquals(new String[]{"/admin/manager", "/manager"}, mapping.value()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java new file mode 100644 index 00000000..806d1098 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,518 @@ +package com.xiaowang.jayucloud.salon.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +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.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +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.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; +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.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +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.shop.service.ShopBusinessExpiryService; +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.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlanningServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserMapper userMapper; + @Mock private UserService userService; + @Mock private NailArtistInfoMapper nailArtistInfoMapper; + @Mock private ArtistScheduleMapper artistScheduleMapper; + @Mock private ArtistScheduleExceptionMapper artistScheduleExceptionMapper; + @Mock private AppointmentReservationMapper appointmentReservationMapper; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private ShopMapper shopMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private WechatSubscribeMessageService wechatSubscribeMessageService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, shopBusinessExpiryService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator, + objectStorageUrlSupport); + } + + @Test + void rejectsCompletingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(11L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(11L)).thenReturn(order); + when(orderItemMapper.selectCount(any(Wrapper.class))).thenReturn(1L); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.updateStatus(operator, 11L, dto)); + + assertEquals("请先分配员工", error.getMessage()); + verify(orderService, never()).processOrder(11L, OrderStatus.COMPLETED.getCode()); + } + + @Test + void rejectsAppointmentCreationWhenShopValidityHasExpired() { + UserDO operator = new UserDO(); + operator.setType(2); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + org.mockito.Mockito.doThrow(new IllegalStateException("门店经营有效期已到期")) + .when(shopBusinessExpiryService).assertShopActive(21L); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("门店经营有效期已到期", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + verify(orderItemMapper, never()).insert(any(OrderItemDO.class)); + } + + @Test + void rejectsCreatingAppointmentForPastDate() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().minusDays(1).toString()); + dto.setAppointmentTime("14:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("历史日期请使用历史补单", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentOutsideBusinessHours() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-20:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("19:30"); + dto.setDurationMinutes(60); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentWhenShopBusinessHoursAreMissing() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("门店营业时间未设置,请先完成设置", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void usesShopDefaultDurationWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(90); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void productDurationTakesPriorityOverShopDefaultWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(60); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setIsDelete(0); + product.setApproximateDuration("120分钟"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(productMapper.selectById(41L)).thenReturn(product); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setProductId(41L); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void backfillOrderDoesNotCheckShopBusinessExpiry() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO artist = new UserDO(); + artist.setId(31L); + artist.setType(3); + artist.setShopId(21L); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setIsDelete(0); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(userMapper.selectById(31L)).thenReturn(artist); + when(productMapper.selectById(41L)).thenReturn(product); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(54L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(64L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 64L); + PlanningBackfillOrderCreateDTO dto = new PlanningBackfillOrderCreateDTO(); + dto.setServiceDate("2025-01-01"); + dto.setProductId(41L); + dto.setArtistId(31L); + dto.setAmount(java.math.BigDecimal.valueOf(80)); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + service.createBackfillOrder(operator, dto); + + verify(shopBusinessExpiryService, never()).assertShopActive(any()); + } + + @Test + void allowsCancellingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(12L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(12L)).thenReturn(order); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.CANCELLED.getCode()); + + service.updateStatus(operator, 12L, dto); + + verify(orderService).processOrder(12L, OrderStatus.CANCELLED.getCode()); + } + + @Test + void createsUnassignedAppointmentWithoutReservation() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(31L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(31L)).thenReturn(customer); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10001"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(51L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(61L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 61L); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(31L); + dto.setProductId(41L); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertNull(itemCaptor.getValue().getArtistId()); + verify(appointmentCapacityService, never()).reserveConfirmedOrThrow( + any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithPhotoOnlyStyleAndSnapshotAmount() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10002"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(42L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(52L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(62L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 62L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小鹿"); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-42"); + dto.setAmount(java.math.BigDecimal.valueOf(168)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("小鹿", productCaptor.getValue().getTitle()); + assertEquals("file-42", productCaptor.getValue().getImageFileIds()); + assertEquals(java.math.BigDecimal.valueOf(168), productCaptor.getValue().getPrice()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertEquals("小鹿", orderCaptor.getValue().getCustomerNameSnapshot()); + assertEquals(java.math.BigDecimal.valueOf(168), orderCaptor.getValue().getActualAmount()); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertEquals(0, itemCaptor.getValue().getPrice().compareTo(java.math.BigDecimal.valueOf(168))); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithoutCustomerUsingWalkInStyleTitle() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10003"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(43L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(53L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(63L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 63L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-43"); + dto.setAmount(java.math.BigDecimal.valueOf(88)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(45); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("散客款式", productCaptor.getValue().getTitle()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + assertNull(orderCaptor.getValue().getCustomerPhoneSnapshot()); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void readsWalkInAppointmentCustomerSnapshotWithoutLookingUpNullUserId() { + UserDO operator = new UserDO(); + operator.setType(2); + OrderDO order = order(54L, OrderStatus.PENDING_SERVICE.getCode()); + order.setCustomerNameSnapshot("散客预约"); + order.setCustomerPhoneSnapshot("13800138000"); + OrderItemDO item = new OrderItemDO(); + item.setId(64L); + item.setOrderId(54L); + item.setQuantity(1); + item.setAppointmentTime(java.time.LocalDateTime.of(2026, 10, 22, 14, 0)); + + when(orderItemMapper.selectById(64L)).thenReturn(item); + when(orderMapper.selectById(54L)).thenReturn(order); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = + service.getAppointment(operator, 64L); + + assertNull(result.getCustomerId()); + assertEquals("散客预约", result.getCustomerName()); + assertEquals("13800138000", result.getCustomerPhone()); + verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); + } + + @Test + void createsCustomerInAppointmentFlowWhenConfirmed() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(71L)).thenReturn(customer); + when(userService.findCustomerIdentityMatches("小周", null, "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", null, "13800138000", 21L)).thenReturn(71L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(55L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(65L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 65L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小周"); + dto.setPhone("13800138000"); + dto.setCreateCustomerRecord(true); + dto.setProductId(41L); + dto.setAmount(java.math.BigDecimal.valueOf(128)); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + verify(userService).createManagerCustomer("小周", null, "13800138000", 21L); + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertEquals(71L, orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + } + + private OrderDO order(Long id, int status) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(21L); + order.setStatus(status); + order.setIsDelete(0); + return order; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java new file mode 100644 index 00000000..616bf0f7 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java @@ -0,0 +1,304 @@ +package com.xiaowang.jayucloud.salon.core.modules.registration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +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.moderation.LocalMockContentModerationProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; +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.privacy.service.ContentModerationService; +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.dto.WorkbenchRegistrationApproveDTO; +import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; +import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; +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.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService; +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.modules.user.service.UserService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; + +import java.util.Collection; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class WorkbenchRegistrationServiceImplTest { + + @Mock private WorkbenchRegistrationApplicationMapper applicationMapper; + @Mock private UserMapper userMapper; + @Mock private ShopMapper shopMapper; + @Mock private UserService userService; + @Mock private UserShopBindingSupport userShopBindingSupport; + @Mock private UserShopBindingMapper userShopBindingMapper; + @Mock private WechatMiniAuthService wechatMiniAuthService; + @Mock private SystemParameterConfigService systemParameterConfigService; + @Mock private ContentModerationService contentModerationService; + @Mock private ContentModerationRecordMapper contentModerationRecordMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private PlatformTransactionManager transactionManager; + @Mock private WechatMiniBindingMapper wechatMiniBindingMapper; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + + private WorkbenchRegistrationServiceImpl service; + + @BeforeEach + void setUp() { + service = new WorkbenchRegistrationServiceImpl(applicationMapper, userMapper, shopMapper, userService, + userShopBindingSupport, userShopBindingMapper, wechatMiniAuthService, systemParameterConfigService, + contentModerationService, contentModerationRecordMapper, shopBusinessExpiryService, transactionManager, + wechatMiniBindingMapper, objectStorageFileService, objectStorageUrlSupport); + } + + @Test + void returnsManagerReviewSummaryFromCurrentShopAndSwitch() { + UserDO manager = manager(7L, 21L); + when(userMapper.selectById(7L)).thenReturn(manager); + when(applicationMapper.selectCount(any(Wrapper.class))).thenReturn(3L); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_REVIEW_NOTICE")) + .thenReturn("true"); + + WorkbenchRegistrationReviewSummaryVO summary = service.getReviewSummary(7L); + + assertEquals(3L, summary.getPendingCount()); + assertEquals(true, summary.isNoticeEnabled()); + } + + @Test + void rejectsSummaryForNonManager() { + UserDO staff = new UserDO(); + staff.setId(8L); + staff.setType(3); + staff.setShopId(21L); + when(userMapper.selectById(8L)).thenReturn(staff); + + assertThrows(IllegalArgumentException.class, () -> service.getReviewSummary(8L)); + } + + @Test + void hidesApplicantProfileUntilItsContentModerationPasses() { + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(31L); + application.setUserId(9L); + application.setApplicationNo("SALON-001"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setShopId(21L); + when(applicationMapper.selectList(any(Wrapper.class))).thenReturn(List.of(application)); + UserDO applicant = new UserDO(); + applicant.setId(9L); + applicant.setNickname("小周"); + applicant.setPhone("13812345678"); + when(userMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(applicant)); + + List result = service.listForReviewer(7L, false); + + assertEquals(1, result.size()); + assertEquals(null, result.get(0).getApplicantNickname()); + assertEquals("138****5678", result.get(0).getApplicantMaskedPhone()); + } + + @Test + void locksApplicationAndRejectsAlreadyProcessedReview() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(31L); + application.setShopId(21L); + application.setStatus(WorkbenchRegistrationStatus.APPROVED); + when(applicationMapper.selectByIdForUpdate(31L)).thenReturn(application); + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + + assertThrows(IllegalArgumentException.class, () -> service.approve(7L, false, 31L)); + verify(applicationMapper).selectByIdForUpdate(31L); + } + + @Test + void approvesStaffApplicationByTransferringWechatIdentityToSelectedEmployee() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(41L); + application.setUserId(99L); + application.setShopId(21L); + application.setRoleType("STAFF"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_MANAGER); + when(applicationMapper.selectByIdForUpdate(41L)).thenReturn(application); + when(userMapper.selectById(7L)).thenReturn(manager(7L, 21L)); + UserDO applicant = new UserDO(); + applicant.setId(99L); + when(userMapper.selectById(99L)).thenReturn(applicant); + UserDO target = new UserDO(); + target.setId(51L); + target.setType(3); + target.setShopId(21L); + target.setStatus(1); + target.setIsDelete(0); + target.setNickname("门店员工"); + when(userMapper.selectOne(any(Wrapper.class))).thenReturn(target); + when(wechatMiniBindingMapper.selectCount(any(Wrapper.class))).thenReturn(0L); + when(applicationMapper.selectOne(any(Wrapper.class))).thenReturn(null); + + WorkbenchRegistrationApproveDTO request = new WorkbenchRegistrationApproveDTO(); + request.setTargetArtistUserId(51L); + assertEquals(true, service.approve(7L, false, 41L, request)); + + assertEquals(WorkbenchRegistrationStatus.APPROVED, application.getStatus()); + assertEquals(51L, application.getTargetArtistUserId()); + assertEquals(0, applicant.getStatus()); + assertEquals(1, target.getStatus()); + verify(wechatMiniAuthService).transferRegistrationBinding(99L, 51L); + verify(userShopBindingSupport).updateBindingStatus(51L, 21L, 1); + verify(userService).syncManagedPermissions(51L); + } + + @Test + void managerApplicationCannotBeApprovedBeforeContentModerationPasses() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(32L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(81L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(81L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectByIdForUpdate(32L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(81L)).thenReturn(moderation); + + assertThrows(IllegalArgumentException.class, () -> service.approve(1L, true, 32L)); + + verify(shopMapper, org.mockito.Mockito.never()).updateById(any()); + verify(userMapper, org.mockito.Mockito.never()).updateById(any()); + } + + @Test + void platformAdminListShowsManagerApplicationsAcrossStatuses() { + WorkbenchRegistrationApplicationDO pending = managerApplication(33L, WorkbenchRegistrationStatus.PENDING_ADMIN); + pending.setContentModerationRecordId(82L); + WorkbenchRegistrationApplicationDO approved = managerApplication(34L, WorkbenchRegistrationStatus.APPROVED); + WorkbenchRegistrationApplicationDO rejected = managerApplication(35L, WorkbenchRegistrationStatus.REJECTED); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(82L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectList(any(Wrapper.class))).thenReturn(List.of(pending, approved, rejected)); + UserDO applicant = new UserDO(); + applicant.setId(9L); + when(userMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(applicant)); + when(contentModerationRecordMapper.selectBatchIds(any(Collection.class))).thenReturn(List.of(moderation)); + + List result = service.listForReviewer(1L, true); + + assertEquals(3, result.size()); + assertEquals(WorkbenchRegistrationStatus.PENDING_ADMIN, result.get(0).getStatus()); + assertEquals("PENDING", result.get(0).getContentModerationStatus()); + assertEquals(WorkbenchRegistrationStatus.APPROVED, result.get(1).getStatus()); + assertEquals(WorkbenchRegistrationStatus.REJECTED, result.get(2).getStatus()); + } + + @Test + void devMockApprovesUnmarkedContentAndKeepsExplicitReviewScenarios() { + LocalMockContentModerationProvider provider = new LocalMockContentModerationProvider(); + + assertEquals(ModerationOutcome.Status.APPROVED, + provider.reviewText("SHOP", "普通门店资料", "openid").status()); + assertEquals(ModerationOutcome.Status.REJECTED, + provider.reviewText("SHOP", "[[MOCK:REJECT]]", "openid").status()); + assertEquals(ModerationOutcome.Status.PENDING, + provider.reviewText("SHOP", "[[MOCK:PENDING]]", "openid").status()); + } + + @Test + void autoApprovesManagerOnlyWhenLinkedShopContentPassed() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(34L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(83L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(83L); + moderation.setContentType("SHOP"); + moderation.setUserId(9L); + moderation.setStatus("APPROVED"); + UserDO applicant = new UserDO(); + applicant.setId(9L); + ShopDO shop = new ShopDO(); + shop.setId(21L); + when(applicationMapper.selectByIdForUpdate(34L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(83L)).thenReturn(moderation); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")) + .thenReturn("true"); + when(userMapper.selectById(9L)).thenReturn(applicant); + when(shopMapper.selectById(21L)).thenReturn(shop); + + service.processManagerModeration(34L); + + assertEquals(WorkbenchRegistrationStatus.APPROVED, application.getStatus()); + verify(shopBusinessExpiryService).startDefaultValidity(org.mockito.ArgumentMatchers.eq(21L), any()); + verify(userShopBindingSupport).updateBindingStatus(9L, 21L, 1); + verify(userService).syncManagedPermissions(9L); + } + + @Test + void automaticApprovalSwitchDoesNotApproveUntilContentReviewPasses() { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(36L); + application.setUserId(9L); + application.setShopId(21L); + application.setRoleType("MANAGER"); + application.setStatus(WorkbenchRegistrationStatus.PENDING_ADMIN); + application.setContentModerationRecordId(84L); + ContentModerationRecordDO moderation = new ContentModerationRecordDO(); + moderation.setId(84L); + moderation.setContentType("SHOP"); + moderation.setUserId(9L); + moderation.setStatus("PENDING"); + when(applicationMapper.selectByIdForUpdate(36L)).thenReturn(application); + when(contentModerationRecordMapper.selectById(84L)).thenReturn(moderation); + when(systemParameterConfigService.getEnabledValue("WORKBENCH", "MANAGER_REGISTRATION_AUTO_APPROVE")) + .thenReturn("true"); + + service.processManagerModeration(36L); + + assertEquals(WorkbenchRegistrationStatus.PENDING_ADMIN, application.getStatus()); + verify(userMapper, org.mockito.Mockito.never()).updateById(any()); + verify(shopMapper, org.mockito.Mockito.never()).updateById(any()); + } + + private UserDO manager(Long id, Long shopId) { + UserDO manager = new UserDO(); + manager.setId(id); + manager.setType(2); + manager.setShopId(shopId); + return manager; + } + + private WorkbenchRegistrationApplicationDO managerApplication(Long id, String status) { + WorkbenchRegistrationApplicationDO application = new WorkbenchRegistrationApplicationDO(); + application.setId(id); + application.setUserId(9L); + application.setRoleType("MANAGER"); + application.setShopId(21L); + application.setStatus(status); + return application; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java new file mode 100644 index 00000000..f1a639a1 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java @@ -0,0 +1,100 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +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.integration.service.MapService; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +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.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +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.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ShopAppointmentSettingsTest { + + @Mock private ShopMapper shopMapper; + @Mock private ContentModerationRecordMapper contentModerationRecordMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private CouponService couponService; + @Mock private CouponMapper couponMapper; + @Mock private ProductMapper productMapper; + @Mock private TagMapper tagMapper; + @Mock private CommentMapper commentMapper; + @Mock private UserCouponMapper userCouponMapper; + @Mock private OrderArtistReviewMapper orderArtistReviewMapper; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private UserShopBindingSupport userShopBindingSupport; + @Mock private NailArtistInfoService nailArtistInfoService; + @Mock private com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService multiLevelCacheService; + @Mock private AppCacheProperties appCacheProperties; + @Mock private MapService mapService; + @Mock private ContentModerationService contentModerationService; + @Mock private ObjectMapper objectMapper; + + @InjectMocks + private ShopServiceImpl shopService; + + @Test + void savesAppointmentSettingsWithoutSubmittingPublicProfileForReview() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(shopMapper.updateById(any(ShopDO.class))).thenReturn(1); + ShopAppointmentSettingsDTO dto = new ShopAppointmentSettingsDTO(); + dto.setBusinessHours("09:30-21:00"); + dto.setDefaultAppointmentDurationMinutes(75); + + assertTrue(shopService.updateAppointmentSettings(21L, dto)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(ShopDO.class); + verify(shopMapper).updateById(saved.capture()); + assertEquals("09:30-21:00", saved.getValue().getAppointmentBusinessHours()); + assertEquals(75, saved.getValue().getDefaultAppointmentDurationMinutes()); + verifyNoInteractions(contentModerationService); + } + + @Test + void returnsDefaultDurationForExistingShopWithoutConfiguredValue() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setShopName("薄荷美甲"); + shop.setBusinessHours("09:00-21:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(contentModerationRecordMapper.selectOne(any(Wrapper.class))).thenReturn(null); + + ShopAppointmentSettingsVO settings = shopService.getAppointmentSettings(21L); + + assertEquals("09:00-21:00", settings.getBusinessHours()); + assertEquals(60, settings.getDefaultAppointmentDurationMinutes()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java new file mode 100644 index 00000000..2c0b7300 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegrationConfigDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.impl.SecureIntegrationConfigServiceImpl; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; + +import java.util.Base64; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SecureIntegrationConfigServiceImplTest { + private static final String MASTER_KEY = Base64.getEncoder().encodeToString(new byte[32]); + private static final String CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + + @Test + void devMockRemainsAvailableWithoutAnEncryptionKeyUntilAProviderWasSaved() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(null); + ContentModerationProperties moderationProperties = new ContentModerationProperties(); + moderationProperties.setAllowMock(true); + SecureIntegrationConfigServiceImpl service = service(mapper, + new SecureConfigEncryptionService(""), moderationProperties, configuredWechat()); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("MOCK", config.getProvider()); + assertTrue(config.isReady()); + } + + @Test + void savedWechatProviderFailsClosedWhenMasterKeyIsMissing() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(config("CONTENT_MODERATION", "PROVIDER", "WECHAT", + new SecureConfigEncryptionService(MASTER_KEY))); + ContentModerationProperties moderationProperties = new ContentModerationProperties(); + moderationProperties.setAllowMock(true); + SecureIntegrationConfigServiceImpl service = service(mapper, + new SecureConfigEncryptionService(""), moderationProperties, configuredWechat()); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("DISABLED", config.getProvider()); + assertFalse(config.isReady()); + } + + @Test + void savedWechatCallbackRequiresPublicExactPathAndBothMiniProgramCredentials() { + SecureConfigEncryptionService encryption = new SecureConfigEncryptionService(MASTER_KEY); + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn( + config("CONTENT_MODERATION", "PROVIDER", "DISABLED", encryption), + config("CONTENT_MODERATION", "CALLBACK_URL", "https://sit.yunail.art" + CALLBACK_PATH, encryption), + config("CONTENT_MODERATION", "CALLBACK_TOKEN", "callback-token", encryption), + config("CONTENT_MODERATION", "ENCODING_AES_KEY", "A".repeat(43), encryption)); + SecureIntegrationConfigServiceImpl service = service(mapper, encryption, + new ContentModerationProperties(), configuredWechat()); + + ModerationRuntimeConfig callback = service.getModerationCallbackConfig(); + + assertEquals("DISABLED", callback.getProvider()); + assertTrue(callback.isReady()); + assertEquals("callback-token", callback.getCallbackToken()); + } + + @Test + void rejectsLocalCallbackAddressAndMissingAppSecret() { + SecureConfigEncryptionService encryption = new SecureConfigEncryptionService(MASTER_KEY); + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn( + config("CONTENT_MODERATION", "PROVIDER", "WECHAT", encryption), + config("CONTENT_MODERATION", "CALLBACK_URL", "https://localhost" + CALLBACK_PATH, encryption), + config("CONTENT_MODERATION", "CALLBACK_TOKEN", "callback-token", encryption), + config("CONTENT_MODERATION", "ENCODING_AES_KEY", "A".repeat(43), encryption)); + WechatMiniProperties incompleteWechat = configuredWechat(); + incompleteWechat.setAppSecret(""); + SecureIntegrationConfigServiceImpl service = service(mapper, encryption, + new ContentModerationProperties(), incompleteWechat); + + ModerationRuntimeConfig config = service.getModerationRuntimeConfig(); + + assertEquals("DISABLED", config.getProvider()); + assertFalse(config.isReady()); + } + + @Test + void rejectsNonAlphanumericCallbackTokenEvenBeforeWechatProviderIsEnabled() { + SecureIntegrationConfigServiceImpl service = service( + mock(SecureIntegrationConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat()); + SecureIntegrationConfigDTO dto = new SecureIntegrationConfigDTO(); + dto.setModerationProvider("DISABLED"); + dto.setModerationCallbackToken("token-with-dash"); + + assertThrows(IllegalArgumentException.class, + () -> service.saveModerationConfig(adminUser(), dto)); + } + + @Test + void mapRuntimeKeyRequiresPlatformAdminBeforeReadingStoredValues() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + UserDO currentUser = new UserDO(); + currentUser.setType(2); + SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( + mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat()); + + assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser)); + verify(mapper, never()).selectOne(any()); + } + + @Test + void platformAdminCanReadMapRuntimeConfig() { + SecureIntegrationConfigMapper mapper = mock(SecureIntegrationConfigMapper.class); + when(mapper.selectOne(any())).thenReturn(null); + when(mapper.selectList(any())).thenReturn(java.util.Collections.emptyList()); + when(mapper.selectCount(any())).thenReturn(0L); + UserDO currentUser = adminUser(); + SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( + mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), + new ContentModerationProperties(), configuredWechat()); + + assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled")); + verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any()); + } + + private SecureIntegrationConfigServiceImpl service(SecureIntegrationConfigMapper mapper, + SecureConfigEncryptionService encryption, + ContentModerationProperties moderationProperties, + WechatMiniProperties wechatProperties) { + return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption, + moderationProperties, wechatProperties); + } + + private UserDO adminUser() { + UserDO user = new UserDO(); + user.setId(1L); + user.setType(4); + return user; + } + + private WechatMiniProperties configuredWechat() { + WechatMiniProperties properties = new WechatMiniProperties(); + properties.setAppId("mini-app-id"); + properties.setAppSecret("mini-app-secret"); + return properties; + } + + private SecureIntegrationConfigDO config(String group, String key, String value, + SecureConfigEncryptionService encryption) { + SecureIntegrationConfigDO record = new SecureIntegrationConfigDO(); + record.setConfigGroup(group); + record.setConfigKey(key); + record.setConfigValue(encryption.encrypt(value)); + record.setEnabled(1); + record.setSecret(1); + return record; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java new file mode 100644 index 00000000..56ec4f1a --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java @@ -0,0 +1,108 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.controller.front; + +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService; +import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService; +import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService; +import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +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.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class UserControllerPhonePrivacyTest { + + @Test + void currentUserInfoUsesServiceEnrichedWithShopExpiry() { + UserService userService = mock(UserService.class); + UserVO profile = new UserVO(); + profile.setShopBusinessExpireTime(java.time.LocalDate.of(2026, 12, 31).atTime(23, 59, 59)); + profile.setShopBusinessExpired(false); + profile.setShopBusinessRemainingDays(66); + when(userService.getCurrentUserInfo()).thenReturn(profile); + UserController controller = new UserController(userService, + mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class), + mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class), + mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class), + mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class), + mock(RequestThrottleService.class), mock(LegalAgreementService.class), + mock(AccountClosureService.class), mock(SecurityAuditLogService.class)); + + Result result = controller.getCurrentUserInfo(mock(HttpServletRequest.class)); + + assertSame(profile, result.getData()); + assertEquals(66, result.getData().getShopBusinessRemainingDays()); + verify(userService).getCurrentUserInfo(); + } + + @Test + void sendsPasswordCodeToVerifiedPhoneFromCurrentAccount() { + UserService userService = mock(UserService.class); + PrimaryObjectStorageService primaryObjectStorageService = mock(PrimaryObjectStorageService.class); + ChunkUploadService chunkUploadService = mock(ChunkUploadService.class); + VerificationCodeService verificationCodeService = mock(VerificationCodeService.class); + UserMapper userMapper = mock(UserMapper.class); + AdminScopeHelper adminScopeHelper = mock(AdminScopeHelper.class); + ShopRoleService shopRoleService = mock(ShopRoleService.class); + TimeOrderedSnowflakeIdGenerator idGenerator = mock(TimeOrderedSnowflakeIdGenerator.class); + WechatMiniAuthService wechatMiniAuthService = mock(WechatMiniAuthService.class); + ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class); + RequestThrottleService requestThrottleService = mock(RequestThrottleService.class); + LegalAgreementService legalAgreementService = mock(LegalAgreementService.class); + AccountClosureService accountClosureService = mock(AccountClosureService.class); + SecurityAuditLogService securityAuditLogService = mock(SecurityAuditLogService.class); + UserController controller = new UserController(userService, primaryObjectStorageService, + chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService, + idGenerator, wechatMiniAuthService, objectStorageUrlSupport, requestThrottleService, + legalAgreementService, accountClosureService, securityAuditLogService); + + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getAttribute("userId")).thenReturn(27L); + UserDO user = new UserDO(); + user.setId(27L); + user.setPhone("13812345678"); + user.setPhoneVerified(1); + user.setStatus(1); + user.setIsDelete(0); + when(userMapper.selectById(27L)).thenReturn(user); + when(verificationCodeService.canResend(user.getPhone())).thenReturn(true); + + Result result = controller.sendCurrentPasswordVerificationCode(request); + + assertEquals(true, result.getData()); + verify(requestThrottleService).checkSendCode(request, user.getPhone()); + verify(verificationCodeService).sendVerificationCode(user.getPhone(), "USER_CHANGE_PASSWORD_SMS_CODE"); + } + + @Test + void rejectsPasswordCodeRequestWithoutAuthenticatedUser() { + UserController controller = new UserController(mock(UserService.class), + mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class), + mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class), + mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class), + mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class), + mock(RequestThrottleService.class), mock(LegalAgreementService.class), + mock(AccountClosureService.class), mock(SecurityAuditLogService.class)); + HttpServletRequest request = mock(HttpServletRequest.class); + + assertThrows(RuntimeException.class, () -> controller.sendCurrentPasswordVerificationCode(request)); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java new file mode 100644 index 00000000..f32bae0f --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java @@ -0,0 +1,117 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserServiceCustomerMatchingTest { + + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + @InjectMocks private UserServiceImpl userService; + + @Test + void findsLegacyCustomerPhoneWithoutUsingServicePhoneLookup() { + UserDO customer = new UserDO(); + customer.setId(91L); + customer.setNickname("周女士"); + customer.setType(0); + customer.setIsDelete(0); + customer.setPhone("13800138000"); + + when(phoneCrypto.index("13800138000")).thenReturn("phone-hash"); + when(phoneCrypto.decrypt("13800138000")).thenReturn("13800138000"); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(customer), List.of(customer)); + when(userMapper.findLegacyIdsByContactPhone("13800138000")).thenReturn(List.of()); + + assertEquals(1, userService.findCustomerMatches("周女士", "13800138000", null).size()); + org.mockito.ArgumentCaptor> queries = org.mockito.ArgumentCaptor.forClass((Class) Wrapper.class); + verify(userMapper, times(2)).selectList(queries.capture()); + QueryWrapper legacyPhoneQuery = (QueryWrapper) queries.getAllValues().get(0); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("phone")); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("phone_hash")); + assertTrue(legacyPhoneQuery.getSqlSegment().contains("type")); + assertTrue(legacyPhoneQuery.getParamNameValuePairs().containsValue("13800138000")); + } + + @Test + void rejectsOnlyAnExactNameWechatAndPhoneDuplicate() throws Exception { + UserDO existing = new UserDO(); + existing.setId(91L); + existing.setNickname("周女士"); + existing.setWechatId("wx-existing"); + existing.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + + Method ensureUnique = UserServiceImpl.class.getDeclaredMethod( + "ensureCustomerUnique", String.class, String.class, String.class, Long.class); + ensureUnique.setAccessible(true); + ensureUnique.invoke(userService, "周女士", "wx-other", "13800138000", null); + + InvocationTargetException duplicate = assertThrows(InvocationTargetException.class, + () -> ensureUnique.invoke(userService, "周女士", "wx-existing", "13800138000", null)); + assertEquals("客户已存在,请选择已有客户", duplicate.getCause().getMessage()); + } + + @Test + void appointmentIdentityLookupReturnsOnlyExactTupleAndFullPhone() { + UserDO existing = new UserDO(); + existing.setId(92L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setPhone("encrypted-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + List wrongWechat = + userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("13800138000", matches.get(0).getPhone()); + assertTrue(wrongWechat.isEmpty()); + } + + @Test + void appointmentIdentityLookupFallsBackToLegacyContactPhone() { + UserDO existing = new UserDO(); + existing.setId(93L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setContactPhone("encrypted-contact-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-contact-phone")).thenReturn("13800138000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("13800138000", matches.get(0).getPhone()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java new file mode 100644 index 00000000..b3adadc8 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServicePhoneUpdateTest.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService; +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserServicePhoneUpdateTest { + + @Mock private UserMapper userMapper; + @Mock private PhoneCrypto phoneCrypto; + @Mock private VerificationCodeService verificationCodeService; + @InjectMocks private UserServiceImpl userService; + + @Test + void updatesPhoneWithoutTrustingMaskedOldPhoneFromClient() { + UserDO currentUser = new UserDO(); + currentUser.setId(27L); + currentUser.setPhone("13812345678"); + currentUser.setPhoneVerified(1); + currentUser.setStatus(1); + currentUser.setIsDelete(0); + when(userMapper.selectById(27L)).thenReturn(currentUser); + when(phoneCrypto.index("13912345678")).thenReturn("new-phone-hash"); + when(userMapper.selectOne(any(Wrapper.class))).thenReturn(null); + when(userMapper.findLegacyIdByPhone("13912345678")).thenReturn(null); + when(verificationCodeService.verifyCode("13912345678", "123456")).thenReturn(true); + when(userMapper.updateById(currentUser)).thenReturn(1); + + UpdatePhoneRequestDTO request = new UpdatePhoneRequestDTO(); + request.setOldPhone("138****5678"); + request.setNewPhone("13912345678"); + request.setVerificationCode("123456"); + + assertTrue(userService.updatePhone(27L, request)); + verify(userMapper).updateById(currentUser); + assertTrue("13912345678".equals(currentUser.getPhone())); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java new file mode 100644 index 00000000..40ed6d5c --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/support/UserProfileFieldSupportTest.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.user.support; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UserProfileFieldSupportTest { + + @Test + void nailArtistWechatIdIsOptional() { + assertDoesNotThrow(() -> UserProfileFieldSupport.requireWechatIdForServiceUser(3, null)); + } + + @Test + void managerWechatIdRemainsRequired() { + assertThrows(IllegalArgumentException.class, + () -> UserProfileFieldSupport.requireWechatIdForServiceUser(2, null)); + } +} diff --git a/JC-Salon-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html new file mode 100644 index 00000000..73b53a31 --- /dev/null +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -0,0 +1,39 @@ + + + + + + + 甲屿手纪 Salon 隐私政策 + + + +

甲屿手纪 Salon 隐私政策

+

版本:2026.10.21 更新日期:2026年10月21日

+

本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储及微信后台隐私指引,并据实更新本政策。

+

一、处理的信息及用途

+
    +
  • 登录:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号。
  • +
  • 可选资料:用户主动选择时处理昵称和头像;未提供时使用系统默认展示。
  • +
  • 手机号:用户主动选择绑定或更换时处理,用于账号找回和必要业务联系,不用于营销;不绑定不影响基础工作台使用。
  • +
  • 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品和订单信息,以履行门店服务管理。客户业务资料不构成客户的小程序登录账号。
  • +
  • 安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取设备标识、IMEI、MAC、麦克风或用户定位。
  • +
+

二、用户主动触发的权限

+

仅在用户主动选择头像、作品图片等操作后调用选图能力;仅在用户主动绑定手机号时调用微信手机号能力或发送短信验证码。短信只用于验证绑定、变更或解绑,不用于营销。手机号绑定和解绑前会显示用途说明。

+

三、存储与保护

+

账号、客户和订单快照中的手机号采用 AES-GCM 加密保存,另以独立 HMAC 索引支持查重。普通页面、日志和导出对手机号脱敏;完整号码仅在业务需要且权限允许时展示。账号密钥由各环境配置管理,运营方需限制配置访问并保留审计。

+

四、第三方服务

+

服务依赖微信小程序登录与用户主动触发的微信能力;验证码由部署环境启用的短信服务商发送;通知由配置的消息通道处理;头像、作品等文件存储于部署环境配置的对象存储服务。运营方上线前应在微信后台列明实际服务商,并确认其处理范围和协议。

+

五、内容审核

+

头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在面向用户或门店成员展示前进行内容安全审核。开发环境使用本地模拟服务;配置启用微信审核服务的环境会将必要的文字、微信 OpenID 和图片的短时授权地址提交给微信内容安全接口,图片审核结果通过加密回调更新。审核未通过、待复核、超时或服务故障时内容保持隔离,不会公开。

+

客户姓名和联系电话、预约及补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外内容审核。审核记录、任务状态和人工复核操作会按安全审计要求保存。

+

六、保留、注销和解绑

+

用户可在小程序“我的-账号设置”申请注销或解绑手机号。解绑通过当前号码验证码核验后立即清除手机号密文和索引。注销申请经管理员完成门店移交或归档后撤销会话,并在目标15个工作日内删除或匿名化 OpenID、昵称、头像、手机号等个人资料。必要订单、预约和经营记录在去除账号身份关联后按产品目标保留五年;该期限及范围由运营方上线前核实。

+

七、政策更新与联系

+

处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。

+

本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。

+ + diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html new file mode 100644 index 00000000..e265071b --- /dev/null +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -0,0 +1,31 @@ + + + + + + + 甲屿手纪 Salon 用户协议 + + + +

甲屿手纪 Salon 用户协议

+

版本:2026.10.21 更新日期:2026年10月21日

+

本服务面向经门店授权的店长和员工,提供门店日程、预约、客户业务资料和经营记录管理。预约金额是业务记录,不表示本平台已收款;当前不提供充值、订阅或平台虚拟权益购买。

+

一、接受协议

+

使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。协议更新后需重新确认。

+

二、账号与使用权限

+

微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整账号权限。

+

三、业务资料与内容

+

使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品和员工资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。

+

头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核。开发环境使用本地模拟服务进行验证;正式环境启用微信内容安全服务后,文字和图片会按审核平台要求处理,未通过、待复核或服务异常的内容不会公开。

+

四、业务记录与金额

+

订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取或虚拟权益交易。

+

五、账号注销

+

用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接;必要的订单、预约和经营记录将去除身份关联后按产品目标保留五年。

+

六、服务调整与联系

+

平台会在合理范围内维护服务,并在功能或数据处理方式发生重要变化时更新说明。隐私相关申请可从账号设置发起;其他问题请联系所属门店管理员。

+

本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。

+ + diff --git a/JC-Salon-Frontend/src/App.vue b/JC-Salon-Frontend/src/App.vue index f444f52c..8632575b 100644 --- a/JC-Salon-Frontend/src/App.vue +++ b/JC-Salon-Frontend/src/App.vue @@ -34,7 +34,7 @@ * App page script. * Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events. */ -import { computed, h, onMounted, onUnmounted, provide, ref, watch } from 'vue' +import { computed, h, onMounted, onUnmounted, ref, watch } from 'vue' import { useRoute, useRouter } from 'vue-router' import { ConfigProvider, Modal } from 'ant-design-vue' import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes' @@ -42,7 +42,6 @@ import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context' import { CheckOutlined } from '@ant-design/icons-vue' import BottomNav from './components/BottomNav.vue' import SystemMessageCard from './components/SystemMessageCard.vue' -import { cartApi } from './api/cart' /** * Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo page or API role. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. @@ -78,7 +77,7 @@ const adminThemeRefreshOptions = { mode: 'admin' as const } const customerThemeRefreshOptions = { mode: 'customer' as const } const isAdminShell = computed(() => route.path.startsWith('/admin') || route.matched.some(r => r.meta.isAdmin)) -const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile']) +const bottomNavRouteNames = new Set(['home', 'products', 'profile']) /** isHiddenNav is a reactive state variable used by the template and event handlers. */ const isHiddenNav = computed(() => { @@ -119,39 +118,9 @@ const antdTheme = computed(() => ({ } })) -// 全局购物车数量状态 -/** cartCount is a reactive state variable used by the template and event handlers. */ -const cartCount = ref(0) /** checkingPopupMessages is a reactive state variable used by the template and event handlers. */ const checkingPopupMessages = ref(false) -// 加载购物车数量 -/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const loadCartCount = async () => { - try { - // 检查用户是否已登录 - const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') - if (!token) { - cartCount.value = 0 - return - } - - const response = await cartApi.getCartList() as any - const data = response || [] - const cartList = Array.isArray(data) ? data : [] - const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0) - cartCount.value = totalQuantity - } catch (error) { - cartCount.value = 0 - } -} - -// 提供更新购物车数量的方法 -/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const updateCartCount = async () => { - await loadCartCount() -} - /** * Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -235,23 +204,14 @@ const checkPopupMessages = async () => { } } -provide('updateCartCount', updateCartCount) -provide('cartCount', cartCount) - -// 监听路由变化,更新购物车数量 watch(() => route.path, async () => { - // 检查当前是否是后台页面,如果是则不加载购物车数据 const isAdminPage = route.matched.some(r => r.meta.isAdmin) await refreshShopTheme(isAdminPage ? adminThemeRefreshOptions : customerThemeRefreshOptions) if (!isAdminPage) { - await loadCartCount() await checkPopupMessages() } }) -// 页面加载时获取购物车数量 -loadCartCount() - onMounted(async () => { stopThemeSync = setupShopThemeSync() await router.isReady() diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 90a90a39..66a48442 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -247,7 +247,6 @@ adminApi.interceptors.response.use( export interface AdminLoginRequest { account: string password: string - shopId?: IdType } /** @@ -260,19 +259,15 @@ export interface AdminLoginResponse { userInfo: any } +export interface AdminPasswordChangeRequest { + currentPassword: string + newPassword: string +} + /** * Purpose: LoginShopSelectionResponse supports admin.ts by holding or executing the login shop selection response page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ -export interface LoginShopSelectionResponse { - allowShoplessLogin: boolean - message: string - shops: Array<{ - id: IdType - shopName: string - }> -} - /** * Purpose: LegalAgreementAdminVO supports admin.ts by holding or executing the legal agreement admin vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -315,14 +310,6 @@ export const adminAuthApi = { login: (data: AdminLoginRequest) => { return adminApi.post('/auth/login', data) }, - /** - * `getLoginShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param account: string caller-supplied value for `account: string` - */ - getLoginShops: (account: string) => { - return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) - }, /** * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -330,14 +317,6 @@ export const adminAuthApi = { logout: () => { return adminApi.post('/auth/logout') }, - /** - * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - switchShop: (shopId?: IdType) => { - return adminApi.post('/auth/switch-shop', { shopId }) - }, /** * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -345,6 +324,9 @@ export const adminAuthApi = { */ refreshToken: (refreshToken: string) => { return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) + }, + changePassword: (data: AdminPasswordChangeRequest) => { + return adminApi.post('/auth/password', data) } } @@ -596,86 +578,6 @@ export const adminArtistApi = { } } -/** - * Purpose: Coupon supports admin.ts by holding or executing the coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Coupon { - id: IdType - couponCode?: string - couponName: string - couponType: number - couponTypeName?: string - discountValue?: string - minAmount?: number - reduceAmount?: string - totalCount?: number - usedCount?: number - remainingCount?: number - startTime: string - endTime: string - status?: number - statusName?: string - shopId?: IdType - shopName?: string - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTags?: Tag[] - unavailableTags?: Tag[] - createTime: string - updateTime: string -} - -/** - * adminCouponApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const adminCouponApi = { - /** - * `listAllCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listAllCoupons: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/coupon/list/all', { params }) as unknown as Promise - }, - /** - * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: any caller-supplied value for `data: any` - */ - createCoupon: (data: any) => { - return adminApi.post('/coupon/create', data) - }, - /** - * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: any caller-supplied value for `data: any` - */ - updateCoupon: (id: IdType, data: any) => { - return adminApi.put(`/coupon/update/${id}`, data) - }, - /** - * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - deleteCoupon: (id: IdType) => { - return adminApi.delete(`/coupon/delete/${id}`) - }, - /** - * `distributeCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: any caller-supplied value for `data: any` - */ - distributeCoupon: (data: any) => { - return adminApi.post('/coupon/distribute', null, { params: data }) - } -} - /** * Purpose: AdminCommentVO supports admin.ts by holding or executing the admin comment vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -737,11 +639,8 @@ export interface Product { imageFileIds?: string imageUrls?: string[] bookableArtists?: string - availableCoupons?: string frontVisible?: number sourceType?: string - likeCount?: number - collectCount?: number createTime: string updateTime: string } @@ -822,6 +721,9 @@ export interface Shop { authorizationExpireTime?: string authorizationExpired?: boolean authorizationStatusText?: string + businessExpireTime?: string + businessExpired?: boolean + businessRemainingDays?: number createTime: string updateTime: string } @@ -837,6 +739,13 @@ export interface ShopListResponse { size: number } +export interface ShopBusinessExpiry { + shopId: IdType + businessExpireTime?: string + businessExpired?: boolean + businessRemainingDays?: number +} + /** * Purpose: CreateShopRequest supports admin.ts by holding or executing the create shop request page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -883,6 +792,12 @@ export const adminShopApi = { listAllShops: () => { return adminApi.get('/shops/list/all') as unknown as Promise }, + listBusinessExpiries: (shopIds: IdType[]) => { + return adminApi.get('/shops/business-expiries', { params: { shopIds: shopIds.join(',') } }) as unknown as Promise + }, + updateBusinessExpiry: (id: IdType, expireDate: string) => { + return adminApi.put(`/shops/${id}/business-expiry`, { expireDate }) + }, /** * `createShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -1016,22 +931,6 @@ export interface ArtistScheduleQuery { endDate?: string } -export interface PaymentOrderVO { - id: IdType - payNo?: string - orderId: IdType - orderNo?: string - userId?: IdType - shopId?: IdType - channel?: string - status?: string - payAmount?: number - paidAmount?: number - payTime?: string - expireTime?: string - remark?: string -} - export interface AfterSaleVO { id: IdType afterSaleNo?: string @@ -1088,43 +987,33 @@ export interface InventoryAdjustRequest { remark?: string } -export interface CampaignVO { - id: IdType - shopId?: IdType - title: string - description?: string - scene?: string - productIds?: string - couponIds?: string - status?: number - startTime?: string - endTime?: string - sortOrder?: number -} - -export interface CampaignRequest { - shopId?: IdType - title?: string - description?: string - scene?: string - productIds?: string - couponIds?: string - status?: number - startTime?: string - endTime?: string - sortOrder?: number -} - -export interface OperationsAnalyticsVO { - viewCount?: number - favoriteCount?: number - cartCount?: number - orderCount?: number - paidOrderCount?: number - completedOrderCount?: number - reviewCount?: number - rebookCount?: number - totalAmount?: number +export interface SalonDashboardOverviewVO { + date: string + degraded?: boolean + degradedMessage?: string + platform: { + activeShopCount: number + activeManagerCount: number + activeStaffCount: number + customerCount: number + styleCount: number + } + today: { + appointmentCount: number + serviceInProgressCount: number + completedServiceCount: number + orderAmount: number + pendingOrderCount: number + } + attention: { + registrationReviewCount: number + contentReviewCount: number + afterSaleCount: number + artistChangeCount: number + lowStockCount: number + } + trend: Array<{ date: string; appointmentCount: number; completedCount: number; amount: number }> + shopRanking: Array<{ shopId: IdType; shopName: string; appointmentCount: number; completedCount: number; amount: number }> } export const adminArtistScheduleApi = { @@ -1136,14 +1025,6 @@ export const adminArtistScheduleApi = { } } -export const adminPaymentApi = { - manualConfirmOrder: (orderId: IdType, remark?: string) => { - return adminApi.post(`/payment/order/${orderId}/manual-confirm`, undefined, { - params: { remark } - }) as unknown as Promise - } -} - export const adminAfterSaleApi = { listAfterSales: (params: AfterSaleQuery) => { return adminApi.get>('/after-sale/list', { params }) as unknown as Promise> @@ -1168,15 +1049,6 @@ export const adminInventoryApi = { } } -export const adminCampaignApi = { - listCampaigns: (params: { status?: number; page: number; size: number }) => { - return adminApi.get>('/campaign/list', { params }) as unknown as Promise> - }, - saveCampaign: (data: CampaignRequest) => { - return adminApi.post('/campaign/save', data) as unknown as Promise - } -} - /** * adminUserApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. @@ -1281,110 +1153,6 @@ export const adminUserApi = { getUserInfo: () => { return adminApi.get('/user/info') as unknown as Promise }, - /** - * `getUserAsset` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getUserAsset: (id: IdType) => { - return adminApi.get(`/user/${id}/asset`) as unknown as Promise - }, - /** - * `getUserBalanceHistory` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getUserBalanceHistory: (id: IdType) => { - return adminApi.get(`/user/${id}/balance/history`) as unknown as Promise - }, - /** - * `changeUserBalance` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: AdminUserBalanceChangeRequest caller-supplied value for `data: AdminUserBalanceChangeRequest` - */ - changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => { - return adminApi.post(`/user/${id}/balance/change`, data) as unknown as Promise - }, - /** - * `overrideUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: AdminUserVipOverrideRequest caller-supplied value for `data: AdminUserVipOverrideRequest` - */ - overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => { - return adminApi.post(`/user/${id}/vip/override`, data) as unknown as Promise - }, - /** - * `recalculateUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - recalculateUserVip: (id: IdType) => { - return adminApi.post(`/user/${id}/vip/recalculate`) as unknown as Promise - } -} - -/** - * Purpose: UserAssetVO supports admin.ts by holding or executing the user asset vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserAssetVO { - userId: IdType - nickname: string - balance: number - totalRechargeAmount: number - lastRechargeTime?: string - vipInfoId?: IdType - vipLevel: string - benefitId?: IdType - benefitInfo?: string - manualOverride: boolean - vipStartTime?: string - vipExpireTime?: string -} - -/** - * Purpose: UserBalanceHistoryItem supports admin.ts by holding or executing the user balance history item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserBalanceHistoryItem { - id: IdType - userId: IdType - userNickname?: string - amount: number - type?: string - currentBalance?: number - beforeBalance?: number - afterBalance?: number - changeScene?: string - relatedOrderId?: IdType - relatedOrderNo?: string - externalOrderNo?: string - operatorId?: IdType - remark?: string - changeTime: string -} - -/** - * Purpose: AdminUserBalanceChangeRequest supports admin.ts by holding or executing the admin user balance change request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface AdminUserBalanceChangeRequest { - amount: number - changeScene: string - relatedOrderId?: IdType - externalOrderNo?: string - remark?: string -} - -/** - * Purpose: AdminUserVipOverrideRequest supports admin.ts by holding or executing the admin user vip override request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface AdminUserVipOverrideRequest { - vipLevel: string - remark?: string } /** @@ -1471,9 +1239,6 @@ export const adminOrderApi = { updateOrderStatus: (id: IdType, status: number) => { return adminApi.put(`/order/update-status/${id}`, {}, { params: { status } }) }, - manualConfirmPayment: (id: IdType, remark?: string) => { - return adminPaymentApi.manualConfirmOrder(id, remark) - }, submitQuote: (id: IdType, data: { remark?: string; items: Array<{ orderItemId: IdType; quotedPrice: number }> }) => { return adminApi.post(`/order/${id}/quote`, data) }, @@ -1482,68 +1247,13 @@ export const adminOrderApi = { } } -/** - * Purpose: HotProductVO supports admin.ts by holding or executing the hot product vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface HotProductVO { - id: IdType - title: string - price: number - likeCount: number - collectCount: number -} - -/** - * Purpose: RecentActivityVO supports admin.ts by holding or executing the recent activity vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface RecentActivityVO { - id: IdType - type: string - title?: string - description: string - time: string - color?: string -} - -/** - * Purpose: DashboardStats supports admin.ts by holding or executing the dashboard stats page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface DashboardStats { - totalUsers: number - totalProducts: number - totalShops: number - todayOrders: number - totalOrderAmount?: number - todayOrderAmount?: number - weekOrderAmount?: number - totalCustomers?: number - totalArtists?: number - newCustomersToday?: number - newCustomers7Days?: number - newOrders7Days?: number - pendingOrders?: number - completedOrders?: number - hotProducts: HotProductVO[] - recentActivities: RecentActivityVO[] -} - /** * adminDashboardApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. */ export const adminDashboardApi = { - /** - * `getStats` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getStats: () => { - return adminApi.get('/dashboard/stats') - }, - getAnalytics: () => { - return adminApi.get('/dashboard/analytics') as unknown as Promise + getOverview: (params?: { date?: string; days?: 7 | 30 }) => { + return adminApi.get('/dashboard/overview', { params }) as unknown as Promise } } @@ -1560,6 +1270,7 @@ export interface NailArtistInfoVO { rating: number status: number portfolio: string + moderationStatus?: string nickname: string shopId: IdType shopName: string @@ -1694,6 +1405,7 @@ export interface AnnouncementVO { id: IdType title: string content: string + imageFileIds?: IdType[] publisherId?: IdType publisherName?: string publisherType?: number @@ -1713,6 +1425,7 @@ export interface AnnouncementVO { export interface AnnouncementCreateRequest { title: string content: string + imageFileIds?: string targetType: string shopIds?: IdType[] userIds?: IdType[] @@ -1757,91 +1470,6 @@ export const adminAnnouncementApi = { } } -/** - * Purpose: VipRechargePlanVO supports admin.ts by holding or executing the vip recharge plan vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanVO { - id: IdType - shopId: IdType - shopName?: string - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status: number - createTime?: string - updateTime?: string -} - -/** - * Purpose: VipRechargePlanRequest supports admin.ts by holding or executing the vip recharge plan request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanRequest { - shopId?: IdType - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status?: number -} - -/** - * adminVipRechargePlanApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const adminVipRechargePlanApi = { - /** - * `listPlans` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listPlans: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/vip-recharge-plan/admin/list', { params }) as unknown as Promise - }, - /** - * `createPlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` - */ - createPlan: (data: VipRechargePlanRequest) => { - return adminApi.post('/vip-recharge-plan/admin/create', data) - }, - /** - * `updatePlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` - */ - updatePlan: (id: IdType, data: VipRechargePlanRequest) => { - return adminApi.put(`/vip-recharge-plan/admin/${id}`, data) - }, - /** - * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param status: number caller-supplied value for `status: number` - */ - updateStatus: (id: IdType, status: number) => { - return adminApi.put(`/vip-recharge-plan/admin/${id}/status`, null, { params: { status } }) - }, - /** - * `listVipLevelOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param shopId?: IdType caller-supplied value for `shopId?: IdType` - */ - listVipLevelOptions: (shopId?: IdType) => { - const params = shopId ? { shopId } : {} - return adminApi.get('/vip-recharge-plan/admin/vip-level-options', { params }) as unknown as Promise - } -} - /** * Purpose: MessageHubPushConfigVO supports admin.ts by holding or executing the message hub push config vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -1950,6 +1578,43 @@ export interface AdminDefaultPasswordResponse { password: string } +export interface SecureIntegrationConfigVO { + mapProvider: 'TENCENT' | 'AMAP' + mapEnabled: boolean + tencentWebKeyConfigured: boolean + amapWebKeyConfigured: boolean + amapMiniKeyConfigured: boolean + mapLegacyMigrationPending: boolean + moderationProvider: 'DISABLED' | 'MOCK' | 'WECHAT' + moderationCallbackUrl: string + moderationCallbackTokenConfigured: boolean + moderationEncodingAesKeyConfigured: boolean + moderationCallbackReady: boolean + moderationReady: boolean + wechatMiniAppConfigured: boolean + wechatMiniAppId: string + mockProviderAllowed: boolean + encryptionKeyConfigured: boolean + updatedAt?: string +} + +export interface SecureIntegrationConfigUpdate { + mapProvider?: 'TENCENT' | 'AMAP' + mapEnabled?: boolean + tencentWebKey?: string + amapWebKey?: string + amapMiniKey?: string + clearTencentWebKey?: boolean + clearAmapWebKey?: boolean + clearAmapMiniKey?: boolean + moderationProvider?: 'DISABLED' | 'MOCK' | 'WECHAT' + moderationCallbackUrl?: string + moderationCallbackToken?: string + moderationEncodingAesKey?: string + clearModerationCallbackToken?: boolean + clearModerationEncodingAesKey?: boolean +} + /** * Purpose: adminSystemParameterConfigApi supports admin.ts by holding or executing the admin system parameter config api page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -1961,17 +1626,18 @@ export const adminSystemParameterConfigApi = { saveConfig: (data: SystemParameterConfigVO) => { return adminApi.post('/system-parameter-config/admin/save', data) }, - getTencentMapKey: () => { - return adminApi.get<{ key: string }>('/system-parameter-config/admin/tencent-map') as unknown as Promise<{ key: string }> - }, - getMapConfig: () => { - return adminApi.get<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }>('/system-parameter-config/admin/map-config') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }> - }, getUserDefaultPassword: () => { return adminApi.get('/system-parameter-config/admin/user-default-password') as unknown as Promise } } +export const adminSecureIntegrationConfigApi = { + getConfig: () => adminApi.get('/system-settings/secure-integration') as unknown as Promise, + getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>, + saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/map', data) as unknown as Promise, + saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation', data) as unknown as Promise +} + export interface WorkbenchRegistrationApplication { id: IdType applicationNo: string @@ -1987,6 +1653,8 @@ export interface WorkbenchRegistrationApplication { applicantNickname?: string applicantAvatar?: string applicantMaskedPhone?: string + contentModerationStatus?: string + contentModerationReason?: string } export const adminWorkbenchRegistrationApi = { @@ -2001,5 +1669,74 @@ export const adminWorkbenchRegistrationApi = { } } +export interface AccountClosureRequestVO { + id: IdType + userId: IdType + nickname: string + userType?: number + shopIds?: IdType[] + shopNames?: string[] + status: string + requestedAt?: string + processingTargetText?: string + processedAt?: string + reviewerNote?: string +} + +export interface ClosureSuccessorManagerVO { + id: IdType + nickname?: string + shopId?: IdType +} + +export interface ContentModerationRecordVO { + id: IdType + contentType: string + businessId?: IdType + authorName?: string + status: string + resultCode?: string + reason?: string + textPreview?: string + images?: Array<{ fileId: IdType; url?: string; status?: string }> + attemptCount?: number + createTime?: string +} + +export interface PhoneBackfillReportVO { + dryRun: boolean + userRowsToUpdate: number + orderRowsToUpdate: number + userRowsUpdated: number + orderRowsUpdated: number + accountConflictRows: number + phoneConflictRows: number + conflictingUserIds: IdType[] +} + +export const adminPrivacyComplianceApi = { + listClosures() { + return adminApi.get('/privacy/account-closure/pending') as unknown as Promise + }, + listSuccessorManagers() { + return adminApi.get('/privacy/account-closure/successor-managers') as unknown as Promise + }, + processClosure(id: IdType, data: { decision: string; successorManagerId?: IdType; archiveShopIds?: IdType[]; note?: string }) { + return adminApi.post(`/privacy/account-closure/${id}/process`, data) + }, + listModeration() { + return adminApi.get('/privacy/content-moderation/pending') as unknown as Promise + }, + reviewContent(id: IdType, data: { approved: boolean; reason: string }) { + return adminApi.post(`/privacy/content-moderation/${id}/review`, data) + }, + phoneBackfillReport() { + return adminApi.get('/privacy/phone-backfill/report') as unknown as Promise + }, + runPhoneBackfill() { + return adminApi.post('/privacy/phone-backfill/run') as unknown as Promise + } +} + export { adminApi } export default adminApi diff --git a/JC-Salon-Frontend/src/api/auth-free-paths.ts b/JC-Salon-Frontend/src/api/auth-free-paths.ts index 6bee7e67..8b45d59c 100644 --- a/JC-Salon-Frontend/src/api/auth-free-paths.ts +++ b/JC-Salon-Frontend/src/api/auth-free-paths.ts @@ -26,7 +26,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ '/tag/list/filter-options', '/file/get-signed-url/', '/admin/auth/login', - '/admin/auth/login-shops/', '/admin/auth/refresh' ] as const @@ -36,7 +35,6 @@ export const WEB_API_AUTH_FREE_PATHS = [ */ export const ADMIN_API_AUTH_FREE_PATHS = [ '/auth/login', - '/auth/login-shops/', '/auth/refresh' ] as const diff --git a/JC-Salon-Frontend/src/api/cart.ts b/JC-Salon-Frontend/src/api/cart.ts deleted file mode 100644 index 5586962e..00000000 --- a/JC-Salon-Frontend/src/api/cart.ts +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -interface CartItem { - productId: IdType - quantity: number -} - -/** - * cartApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const cartApi = { - // 添加作品到购物车 - /** - * `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - addToCart: (item: CartItem) => { - return api.post('/cart/add', item) - }, - - // 从购物车移除作品 - /** - * `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - removeFromCart: (productId: IdType) => { - return api.delete(`/cart/remove/${productId}`) - }, - - // 批量从购物车移除作品 - /** - * `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]` - */ - batchRemoveFromCart: (cartItemIds: IdType[]) => { - return api.post('/cart/batch-remove', cartItemIds) - }, - - // 更新购物车作品数量 - /** - * `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param item: CartItem caller-supplied value for `item: CartItem` - */ - updateCartQuantity: (item: CartItem) => { - return api.put('/cart/update', item) - }, - - // 获取购物车列表 - /** - * `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - getCartList: () => { - return api.get('/cart/list') - }, - - // 清空购物车 - /** - * `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - */ - clearCart: () => { - return api.delete('/cart/clear') - } -} diff --git a/JC-Salon-Frontend/src/api/coupon.ts b/JC-Salon-Frontend/src/api/coupon.ts deleted file mode 100644 index edc87861..00000000 --- a/JC-Salon-Frontend/src/api/coupon.ts +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import request from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Coupon { - id: IdType - couponCode: string - couponName: string - couponType: number - couponTypeName: string - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - usedCount: number - remainingCount: number - startTime: string - endTime: string - status: number - statusName: string - shopId?: IdType - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTags: Tag[] - unavailableTags: Tag[] -} - -/** - * Purpose: Tag supports coupon.ts by holding or executing the tag page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface Tag { - id: IdType - tagName?: string -} - -/** - * Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserCoupon { - id: IdType - couponId: IdType - couponName: string - couponType: number - couponTypeName: string - discountValue: string - minAmount: string - reduceAmount: string - startTime: string - endTime: string - status: number - statusName: string - obtainTime: string - useTime: string - sourceType?: string - requiredVipLevel?: string - autoMatched?: boolean -} - -/** - * Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CreateCouponRequest { - couponCode: string - couponName: string - couponType: number - discountValue?: number - minAmount?: number - reduceAmount?: number - totalCount: number - startTime: string - endTime: string - couponScene?: string - requiredVipLevel?: string - autoMatch?: number - availableTagIds: IdType[] - unavailableTagIds: IdType[] -} - -/** - * Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface CouponListResponse { - list: Coupon[] - total: number - page: number - size: number -} - -/** - * couponApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const couponApi = { - // 创建优惠券 - /** - * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - createCoupon: (data: CreateCouponRequest) => { - return request({ - url: '/coupon/create', - method: 'post', - data - }) - }, - - // 更新优惠券 - /** - * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` - */ - updateCoupon: (id: IdType, data: CreateCouponRequest) => { - return request({ - url: `/coupon/update/${id}`, - method: 'put', - data - }) - }, - - // 删除优惠券 - /** - * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - deleteCoupon: (id: IdType) => { - return request({ - url: `/coupon/delete/${id}`, - method: 'delete' - }) - }, - - // 获取优惠券详情 - /** - * `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param id: IdType caller-supplied value for `id: IdType` - */ - getCouponById: (id: IdType) => { - return request({ - url: `/coupon/detail/${id}`, - method: 'get' - }) - }, - - // 获取优惠券列表 - /** - * `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }` - */ - listCoupons: (params: { page: number; size: number; shopId?: IdType }) => { - return request({ - url: '/coupon/list', - method: 'get', - params - }) - }, - - // 为用户分配优惠券 - /** - * `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userId: IdType caller-supplied value for `userId: IdType` - * @param couponId: IdType caller-supplied value for `couponId: IdType` - */ - assignCouponToUser: (userId: IdType, couponId: IdType) => { - return request({ - url: '/coupon/assign', - method: 'post', - params: { userId, couponId } - }) - }, - - // 获取用户优惠券列表 - listUserCoupons: async (status?: number): Promise => { - return await request({ - url: '/coupon/user/list', - method: 'get', - params: { status } - }) as UserCoupon[] - }, - - // 使用优惠券 - /** - * `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param userCouponId: IdType caller-supplied value for `userCouponId: IdType` - */ - useCoupon: (userCouponId: IdType) => { - return request({ - url: '/coupon/use', - method: 'post', - params: { userCouponId } - }) - }, - - // 获取作品可用的优惠券 - getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise => { - return await request({ - url: '/coupon/available', - method: 'get', - params: { productTags, productPrice, shopId } - }) as UserCoupon[] - } -} diff --git a/JC-Salon-Frontend/src/api/index.ts b/JC-Salon-Frontend/src/api/index.ts index f45d9081..f4f0731a 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -5,7 +5,6 @@ import axios, { AxiosError } from 'axios' import { authApi } from './auth' import { adminAuthApi } from './admin' -import { wishlistApi } from './wishlist' import { message, Modal } from 'ant-design-vue' import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' @@ -393,6 +392,4 @@ export const fileApi = { } } -export { wishlistApi } - export default api diff --git a/JC-Salon-Frontend/src/api/order.ts b/JC-Salon-Frontend/src/api/order.ts index 4a12e9a8..0586b6c6 100644 --- a/JC-Salon-Frontend/src/api/order.ts +++ b/JC-Salon-Frontend/src/api/order.ts @@ -21,74 +21,11 @@ export interface OrderItem { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface CreateOrderRequest { - couponId?: IdType - couponSourceType?: string remark?: string clientRequestId?: string items: OrderItem[] } -export type CheckoutPreviewRequest = CreateOrderRequest - -export interface CheckoutCouponPreview { - id: IdType - couponId?: IdType - userCouponId?: IdType - sourceType?: string - couponName: string - couponType: number - couponTypeName?: string - discountValue?: number - minAmount?: number - reduceAmount?: number - discountAmount?: number - available?: boolean - best?: boolean - vipAuto?: boolean - displayText?: string - savingText?: string - unavailableReason?: string - startTime?: string - endTime?: string -} - -export interface CheckoutIssue { - code: string - message: string - itemId?: IdType - productId?: IdType - productTitle?: string -} - -export interface CheckoutPreview { - subtotalAmount: number - savedAmount: number - payableAmount: number - bestCoupon?: CheckoutCouponPreview - availableCoupons: CheckoutCouponPreview[] - unavailableCoupons: CheckoutCouponPreview[] - bookingAvailable?: boolean - bookingIssues?: CheckoutIssue[] - vipTip?: string - summaryText?: string -} - -export interface PaymentOrderVO { - id: IdType - payNo?: string - orderId: IdType - orderNo?: string - userId?: IdType - shopId?: IdType - channel?: string - status?: string - payAmount?: number - paidAmount?: number - payTime?: string - expireTime?: string - remark?: string -} - export interface OrderQuoteItem { orderItemId: IdType quotedPrice?: number @@ -147,23 +84,6 @@ export interface PageResult { size: number } -export interface GrowthSummaryVO { - userId?: IdType - growthValue?: number - levelName?: string - appointmentCount?: number - reviewCount?: number -} - -export const paymentApi = { - prepareOrderPayment: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO - }, - mockSuccess: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO - } -} - export const afterSaleApi = { apply: async (data: AfterSaleApplyRequest): Promise => { return await api.post('/after-sale/apply', data) as unknown as AfterSaleVO @@ -173,12 +93,6 @@ export const afterSaleApi = { } } -export const growthApi = { - getSummary: async (): Promise => { - return await api.get('/growth/summary') as unknown as GrowthSummaryVO - } -} - /** * Purpose: ArtistCalendarAppointment supports order.ts by holding or executing the artist calendar appointment page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -338,10 +252,6 @@ export const orderApi = { return api.post('/order/create', data) }, - checkoutPreview: async (data: CheckoutPreviewRequest): Promise => { - return await api.post('/order/checkout-preview', data) as unknown as CheckoutPreview - }, - replyQuote: async (orderId: IdType, data?: OrderQuoteReplyRequest): Promise => { return await api.post(`/order/${orderId}/quote/reply`, data || {}) as unknown as any }, @@ -417,8 +327,10 @@ export const orderApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. * @param orderId: IdType caller-supplied value for `orderId: IdType` */ - cancelOrder: (orderId: IdType) => { - return api.put(`/order/cancel/${orderId}`) + cancelOrder: (orderId: IdType, cancelReason?: string) => { + return api.put(`/order/cancel/${orderId}`, undefined, { + params: cancelReason ? { cancelReason } : undefined + }) }, // 后台获取所有订单 diff --git a/JC-Salon-Frontend/src/api/product.ts b/JC-Salon-Frontend/src/api/product.ts index 292db2ac..92e824d8 100644 --- a/JC-Salon-Frontend/src/api/product.ts +++ b/JC-Salon-Frontend/src/api/product.ts @@ -28,14 +28,11 @@ export interface ProductVO { bookableArtists?: string availableBookableArtistCount?: number bookableArtistRestricted?: boolean - availableCoupons?: string category: string tags?: string tagList?: string[] tagInfos?: TagInfo[] status: number - likeCount?: number - collectCount?: number createTime: string updateTime: string } @@ -111,14 +108,6 @@ export const productApi = { return await api.get(`/product/list/tag/${tag}`) as unknown as ProductVO[] }, - likeProduct: async (productId: IdType): Promise => { - return await api.post(`/product-like/like/${productId}`) as unknown as boolean - }, - - unlikeProduct: async (productId: IdType): Promise => { - return await api.post(`/product-like/unlike/${productId}`) as unknown as boolean - }, - searchProducts: async (keyword: string): Promise => { return await api.get('/product/list/search', { params: { diff --git a/JC-Salon-Frontend/src/api/productLike.ts b/JC-Salon-Frontend/src/api/productLike.ts deleted file mode 100644 index 5ce0831d..00000000 --- a/JC-Salon-Frontend/src/api/productLike.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * productLikeApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const productLikeApi = { - /** - * 点赞作品 - * @param productId 作品ID - */ - /** - * `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - likeProduct: (productId: IdType) => { - return api.post(`/product-like/like/${productId}`) - }, - - /** - * 取消点赞作品 - * @param productId 作品ID - */ - /** - * `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - unlikeProduct: (productId: IdType) => { - return api.post(`/product-like/unlike/${productId}`) - }, - - /** - * 检查用户是否已点赞作品 - * @param productId 作品ID - */ - /** - * `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. - * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. - * @param productId: IdType caller-supplied value for `productId: IdType` - */ - checkLikeStatus: (productId: IdType) => { - return api.get(`/product-like/check/${productId}`) - } -} diff --git a/JC-Salon-Frontend/src/api/user.ts b/JC-Salon-Frontend/src/api/user.ts index 4c6fc5df..53072cd9 100644 --- a/JC-Salon-Frontend/src/api/user.ts +++ b/JC-Salon-Frontend/src/api/user.ts @@ -202,51 +202,10 @@ export interface InviteCodeVO { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface UpdatePhoneRequest { - oldPhone: string newPhone: string verificationCode: string } -/** - * Purpose: UserAssetVO supports user.ts by holding or executing the user asset vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface UserAssetVO { - userId: IdType - nickname: string - balance: number - totalRechargeAmount: number - lastRechargeTime?: string - vipInfoId?: IdType - vipLevel: string - benefitId?: IdType - benefitInfo?: string - manualOverride?: boolean - vipStartTime?: string - vipExpireTime?: string -} - -/** - * Purpose: BalanceHistoryItem supports user.ts by holding or executing the balance history item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface BalanceHistoryItem { - id: IdType - userId: IdType - userNickname?: string - amount: number - type?: string - currentBalance?: number - beforeBalance?: number - afterBalance?: number - changeScene?: string - relatedOrderId?: IdType - relatedOrderNo?: string - externalOrderNo?: string - remark?: string - changeTime?: string -} - /** * Purpose: SystemMessageVO supports user.ts by holding or executing the system message vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -285,23 +244,6 @@ export interface AnnouncementVO { publishTime?: string } -/** - * Purpose: VipRechargePlanVO supports user.ts by holding or executing the vip recharge plan vo page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface VipRechargePlanVO { - id: IdType - shopId: IdType - shopName?: string - title: string - rechargeAmount: number - giftAmount: number - vipLevel: string - description?: string - sortOrder?: number - status: number -} - /** * Purpose: ContactInfoVO supports user.ts by holding or executing the contact info vo page or API role. * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. @@ -388,6 +330,9 @@ export const userApi = { sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { return api.post('/user/send-verification-code', data) }, + sendCurrentPasswordVerificationCode: () => { + return api.post('/user/send-current-password-code') + }, /** * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. @@ -396,12 +341,6 @@ export const userApi = { switchShop: (shopId?: string | number) => { return api.post('/user/switch-shop', { shopId }) }, - getMyAsset: async (): Promise => { - return await api.get('/user/asset/me') as unknown as UserAssetVO - }, - getMyBalanceHistory: async (): Promise => { - return await api.get('/user/balance/history/me') as unknown as BalanceHistoryItem[] - }, listMyMessages: async (): Promise => { return await api.get('/system-message/my/list') as unknown as SystemMessageVO[] }, @@ -433,9 +372,6 @@ export const userApi = { listMyAnnouncements: async (): Promise => { return await api.get('/announcement/my/list') as unknown as AnnouncementVO[] }, - listMyVipRechargePlans: async (): Promise => { - return await api.get('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[] - }, getMyRelation: async (): Promise => { return await api.get('/user/relation/me') as unknown as UserRelationVO }, @@ -464,6 +400,14 @@ export const userApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. */ deactivateAccount: () => { - return api.delete('/user/deactivate') - } + return api.post('/user/account-closure', {}) + }, + getAccountClosure: async () => await api.get('/user/account-closure/me') as unknown as Promise<{ + id: IdType + status: string + requestedAt?: string + processingTargetText?: string + reviewerNote?: string + } | null>, + withdrawAccountClosure: () => api.delete('/user/account-closure/me') } diff --git a/JC-Salon-Frontend/src/api/wishlist.ts b/JC-Salon-Frontend/src/api/wishlist.ts deleted file mode 100644 index aacabd9f..00000000 --- a/JC-Salon-Frontend/src/api/wishlist.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Front-end API wrapper for this module. - * Call guide: import the named API object, then call the matching method from a Vue page or composable. - */ -import api from './index' -import type { IdType } from '@/utils/id' - -/** - * Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ -export interface WishlistItem { - id: IdType - userId: IdType - productId: IdType - groupId?: IdType | null - groupName?: string | null - note?: string | null - sortOrder?: number | null - product: { - id: IdType - shopId: IdType | null - shopName?: string - title: string - description: string - imageFileIds?: string - imageUrls?: string[] - price: number - tags?: string - tagList?: string[] - tagInfos?: any[] - likeCount?: number - collectCount?: number - approximateDuration?: string - bookableArtists?: string - availableCoupons?: string - createTime: string - updateTime: string - } -} - -export interface WishlistGroup { - id: IdType - name: string - sortOrder: number - itemCount: number - items?: WishlistItem[] -} - -export interface WishlistInspiration { - total: number - groups: WishlistGroup[] -} - -export interface WishlistGroupPayload { - name: string - sortOrder?: number -} - -export interface WishlistAddWithGroupPayload { - productId: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -export interface WishlistMovePayload { - wishlistId?: IdType - productId?: IdType - groupId?: IdType | null - note?: string - sortOrder?: number -} - -/** - * wishlistApi groups all API calls for this page domain. - * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. - */ -export const wishlistApi = { - addToWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/add', { productId }) as unknown as boolean - }, - - removeFromWishlist: async (productId: IdType): Promise => { - return await api.post('/wishlist/remove', { productId }) as unknown as boolean - }, - - checkWishlist: async (productId: IdType): Promise => { - return await api.get(`/wishlist/check?productId=${productId}`) as unknown as boolean - }, - - getWishlist: async (): Promise => { - return await api.get('/wishlist/list') as unknown as WishlistItem[] - }, - - getGroups: async (): Promise => { - return await api.get('/wishlist/groups') as unknown as WishlistGroup[] - }, - - createGroup: async (payload: WishlistGroupPayload): Promise => { - return await api.post('/wishlist/groups', payload) as unknown as IdType - }, - - updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise => { - return await api.put(`/wishlist/groups/${id}`, payload) as unknown as boolean - }, - - deleteGroup: async (id: IdType): Promise => { - return await api.delete(`/wishlist/groups/${id}`) as unknown as boolean - }, - - addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise => { - return await api.post('/wishlist/add-with-group', payload) as unknown as boolean - }, - - moveWishlist: async (payload: WishlistMovePayload): Promise => { - return await api.post('/wishlist/move', payload) as unknown as boolean - }, - - getInspiration: async (): Promise => { - return await api.get('/wishlist/inspiration') as unknown as WishlistInspiration - } -} diff --git a/JC-Salon-Frontend/src/components/BottomNav.vue b/JC-Salon-Frontend/src/components/BottomNav.vue index af791df6..247cd91e 100644 --- a/JC-Salon-Frontend/src/components/BottomNav.vue +++ b/JC-Salon-Frontend/src/components/BottomNav.vue @@ -19,15 +19,6 @@ 作品集 - - - + + + + + @@ -20,12 +28,13 @@ {{emptyText}} - - - + + + {{item.title}} + {{item.rightText}} {{item.badge}} {{item.subtitle}} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss index d20b4840..bbc14c3c 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss @@ -45,7 +45,7 @@ flex-direction: column; overflow: hidden; border-radius: 34rpx 34rpx 0 0; - background: #fffdf8; + background: #ffffff; box-shadow: 0 -20rpx 48rpx rgba(44, 35, 27, 0.18); animation: selectorSheetUp 220ms ease both; } @@ -59,7 +59,7 @@ } .selector-title { - color: #29241f; + color: #17211f; font-size: 34rpx; font-weight: 900; letter-spacing: 1rpx; @@ -73,9 +73,9 @@ min-height: 52rpx; margin: 0; padding: 0; - border: 1rpx solid #e6dfd6; + border: 1rpx solid #e7ece9; border-radius: 50%; - background: #f8f4ee; + background: #f3f7f4; } .selector-close::before, @@ -87,7 +87,7 @@ width: 22rpx; height: 3rpx; border-radius: 999rpx; - background: #665e56; + background: #71807a; } .selector-close::before { transform: rotate(45deg); } @@ -99,9 +99,9 @@ min-height: 80rpx; margin: 0 28rpx 18rpx; padding: 0 22rpx; - border: 1rpx solid #e7e0d7; + border: 1rpx solid #e7ece9; border-radius: 22rpx; - background: #f7f3ed; + background: #f3f7f4; } .selector-search-icon { @@ -109,7 +109,7 @@ width: 26rpx; height: 26rpx; margin-right: 18rpx; - border: 3rpx solid #8e877f; + border: 3rpx solid #71807a; border-radius: 50%; } @@ -121,14 +121,43 @@ width: 12rpx; height: 3rpx; border-radius: 999rpx; - background: #8e877f; + background: #71807a; transform: rotate(45deg); } +.selector-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + padding: 0 28rpx 16rpx; +} + +.selector-view-switch { + display: flex; + flex: 1; + gap: 8rpx; +} + +.selector-view-switch button, +.selector-sort { + height: 58rpx; + padding: 0 18rpx; + border-radius: 16rpx; + background: #f1f5f3; + color: #687a72; + font-size: 22rpx; + line-height: 58rpx; +} + +.selector-view-switch button { flex: 1; } +.selector-view-switch button.active { background: #dff1e9; color: #247b63; font-weight: 800; } +.selector-sort { flex: 0 0 auto; color: #476259; } + .selector-search { height: 78rpx; flex: 1; - color: #29241f; + color: #17211f; font-size: 27rpx; } @@ -148,21 +177,43 @@ min-height: 112rpx; margin-bottom: 14rpx; padding: 20rpx; - border: 1rpx solid #ece5dc; + border: 1rpx solid #e7ece9; border-radius: 24rpx; background: #fff; transition: transform 140ms ease, border-color 140ms ease, background 140ms ease; } .selector-item:active { transform: scale(0.99); } -.selector-item.selected { border-color: #8eafa3; background: #f0f6f3; } +.selector-item.selected { border-color: #247b63; background: #e5f4ed; } + +.selector-list.card-view { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12rpx; +} + +.selector-item.card-view { + position: relative; + display: block; + min-height: 190rpx; + margin: 0; + padding: 18rpx; +} + +.selector-item.card-view .selector-avatar { width: 66rpx; height: 66rpx; margin-bottom: 12rpx; } +.selector-item.card-view .selector-copy { margin-left: 0; } +.selector-item.card-view .selector-title-row { align-items: flex-start; } +.selector-item.card-view .selector-item-title { white-space: normal; } +.selector-item.card-view .selector-subtitle, +.selector-item.card-view .selector-meta { display: block; margin-top: 8rpx; } +.selector-item.card-view .selector-check { position: absolute; right: 18rpx; bottom: 16rpx; } .selector-avatar { width: 76rpx; height: 76rpx; flex: 0 0 auto; border-radius: 50%; - background: #eee9e2; + background: #e7ece9; } .selector-copy { @@ -180,20 +231,29 @@ } .selector-item-title { + min-width: 0; + flex: 1; overflow: hidden; - color: #2b2621; + color: #17211f; font-size: 28rpx; font-weight: 800; text-overflow: ellipsis; white-space: nowrap; } +.selector-right-text { + flex: 0 0 auto; + color: #756e66; + font-size: 23rpx; + font-weight: 600; +} + .selector-badge { flex: 0 0 auto; padding: 5rpx 12rpx; border-radius: 999rpx; - background: #e7f0ec; - color: #55786d; + background: #e5f4ed; + color: #247b63; font-size: 19rpx; font-weight: 800; } @@ -203,7 +263,7 @@ display: block; margin-top: 7rpx; overflow: hidden; - color: #7f7870; + color: #71807a; font-size: 23rpx; text-overflow: ellipsis; white-space: nowrap; @@ -213,13 +273,13 @@ .selector-check { width: 52rpx; - color: #8c857d; + color: #71807a; font-size: 32rpx; font-weight: 800; text-align: right; } -.selector-item.selected .selector-check { color: #2f6f62; } +.selector-item.selected .selector-check { color: #247b63; } .selector-state { display: flex; @@ -228,7 +288,7 @@ align-items: center; justify-content: center; padding: 40rpx 48rpx; - color: #9a9289; + color: #71807a; font-size: 25rpx; line-height: 1.6; text-align: center; @@ -241,10 +301,10 @@ height: 64rpx; margin-top: 22rpx; padding: 0 28rpx; - border: 1rpx solid #d8d1c8; + border: 1rpx solid #e7ece9; border-radius: 999rpx; background: #fff; - color: #514b44; + color: #71807a; font-size: 23rpx; font-weight: 800; line-height: 64rpx; @@ -255,14 +315,14 @@ height: 20rpx; margin-bottom: 20rpx; border-radius: 50%; - background: #6f8f83; + background: #247b63; box-shadow: -30rpx 0 #c9d8d2, 30rpx 0 #9eb9af; } .selector-footer { padding: 16rpx 28rpx calc(18rpx + env(safe-area-inset-bottom)); - border-top: 1rpx solid #eee7de; - background: #fffdf8; + border-top: 1rpx solid #e7ece9; + background: #ffffff; } .selector-action { @@ -270,8 +330,8 @@ height: 78rpx; border: 1rpx solid #cbdad4; border-radius: 22rpx; - background: #edf4f1; - color: #2f6f62; + background: #e5f4ed; + color: #247b63; font-size: 26rpx; font-weight: 900; line-height: 78rpx; diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.js b/JC-Salon-WeChat/components/product-selector-sheet/index.js index 9983ecd1..d3a2e47c 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.js @@ -13,6 +13,7 @@ Component({ manualForm: { type: Object, value: {} }, manualMoreExpanded: { type: Boolean, value: false }, showManualExtra: { type: Boolean, value: true }, + showManualAction: { type: Boolean, value: true }, manualImageUrl: { type: String, value: '' }, manualImageUploading: { type: Boolean, value: false } }, @@ -24,6 +25,14 @@ Component({ const item = this.data.items[Number(event.currentTarget.dataset.index)] if (item) this.triggerEvent('select', { item }) }, + onCoverImageError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isInteger(index) || !this.data.items[index]) return + this.setData({ [`items[${index}].coverImage`]: '' }) + }, + onManualImageError() { + this.setData({ manualImageUrl: '' }) + }, openManual() { this.triggerEvent('openmanual') }, backToList() { this.triggerEvent('backtolist') }, onManualInput(event) { diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml index d877e401..7c11f39b 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml @@ -12,17 +12,17 @@ {{emptyText}} - 图 - {{item.title}}{{item.priceText || (item.price == null ? '价格待定' : '¥' + item.price)}}{{item.durationText || '时长待定'}} · {{item.artistText || '全部员工'}}{{tag}}{{selectedId == item.id ? '✓' : '›'}} + 图 + {{item.title}}{{item.priceText || (item.price == null ? '价格待定' : '¥' + item.price)}}{{item.durationText || '时长待定'}} · {{item.artistText || '全部美甲师'}}{{tag}}{{selectedId == item.id ? '✓' : '›'}} - + {{manualMoreExpanded ? '⌃ 收起更多信息' : '⌄ 补充更多信息'}} - 图 + 图 diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.wxss b/JC-Salon-WeChat/components/product-selector-sheet/index.wxss index c4442216..b858ca5e 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.wxss +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.wxss @@ -1 +1 @@ -.product-selector-mask{position:fixed;inset:0;z-index:130;display:flex;align-items:flex-end;background:rgba(25,22,18,.5)}.product-selector-sheet{display:flex;width:100%;height:88vh;max-height:88vh;flex-direction:column;overflow:hidden;border-radius:34rpx 34rpx 0 0;background:#fffdf8;box-shadow:0 -20rpx 48rpx rgba(44,35,27,.18)}.product-selector-head{display:flex;align-items:center;justify-content:space-between;min-height:92rpx;padding:0 28rpx}.product-selector-title{display:block;color:#29241f;font-size:34rpx;font-weight:900}.product-selector-subtitle{display:block;margin-top:7rpx;color:#8b8177;font-size:22rpx}.product-selector-close{position:relative;display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:52rpx;height:52rpx;min-width:52rpx;flex:0 0 52rpx;margin:0;padding:0;overflow:hidden;border:1rpx solid #e6dfd6;border-radius:50%;background:#f8f4ee;line-height:1}.product-selector-close::before,.product-selector-close::after{content:"";position:absolute;top:24rpx;left:14rpx;width:22rpx;height:3rpx;border-radius:999rpx;background:#665e56}.product-selector-close::before{transform:rotate(45deg)}.product-selector-close::after{transform:rotate(-45deg)}.product-selector-search{display:flex;align-items:center;height:80rpx;margin:0 28rpx 18rpx;padding:0 22rpx;border-radius:22rpx;background:#f7f3ed}.product-selector-search input{height:78rpx;flex:1;color:#29241f;font-size:27rpx}.product-selector-search-icon{width:24rpx;height:24rpx;margin-right:16rpx;border:3rpx solid #8e877f;border-radius:50%}.product-selector-scroll{height:0;min-height:0;flex:1}.product-selector-scroll.manual{padding:0 28rpx}.product-selector-list{padding:0 28rpx 24rpx}.product-selector-item{display:flex;align-items:center;min-height:132rpx;margin-bottom:14rpx;padding:16rpx;border:1rpx solid #ece5dc;border-radius:20rpx;background:#fff}.product-selector-item.selected{border-color:#8eafa3;background:#f0f6f3}.product-selector-cover{width:92rpx;height:92rpx;flex:0 0 auto;border-radius:14rpx;background:#eee9e2}.product-selector-cover.placeholder,.manual-product-image.placeholder{display:flex;align-items:center;justify-content:center;color:#b79b82;font-size:24rpx}.product-selector-copy{min-width:0;flex:1;margin-left:18rpx}.product-selector-name-row{display:flex;align-items:center;gap:12rpx}.product-selector-name{min-width:0;overflow:hidden;color:#2b2621;font-size:28rpx;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.product-selector-price{flex:0 0 auto;color:#b7683d;font-size:27rpx;font-weight:900}.product-selector-meta{display:block;margin-top:7rpx;overflow:hidden;color:#7f7870;font-size:23rpx;text-overflow:ellipsis;white-space:nowrap}.product-selector-tags{display:flex;gap:8rpx;margin-top:7rpx}.product-selector-tags text{padding:3rpx 10rpx;border-radius:999rpx;background:#f3e9df;color:#826c5b;font-size:19rpx}.product-selector-check{width:42rpx;color:#8c857d;font-size:32rpx;text-align:right}.product-selector-item.selected .product-selector-check{color:#2f6f62}.product-selector-state{display:flex;min-height:360rpx;align-items:center;justify-content:center;padding:40rpx;color:#9a9289;font-size:25rpx;text-align:center}.product-selector-state.error{flex-direction:column;color:#a8554e}.product-selector-retry{margin-top:20rpx;padding:0 24rpx;border:1rpx solid #d8d1c8;border-radius:999rpx;background:#fff;color:#514b44;font-size:23rpx}.product-selector-footer{padding:16rpx 28rpx calc(18rpx + env(safe-area-inset-bottom));border-top:1rpx solid #eee7de;background:#fffdf8}.product-selector-action,.product-selector-confirm,.product-selector-back{width:100%;height:76rpx;margin:0;border-radius:20rpx;font-size:26rpx;line-height:76rpx}.product-selector-action{border:1rpx solid #cbdad4;background:#edf4f1;color:#2f6f62}.manual-product-card{margin:18rpx 0;padding:20rpx;border-radius:18rpx;background:#f8f2eb}.manual-product-grid{display:grid;grid-template-columns:minmax(0,1fr) 180rpx;gap:14rpx}.manual-product-grid input,.manual-product-extra input,.manual-product-extra textarea{box-sizing:border-box;width:100%;padding:0 18rpx;border:0;border-radius:14rpx;background:#fff;color:#302923;font-size:26rpx}.manual-product-grid input{height:72rpx}.manual-product-more{margin-top:16rpx;color:#5f897c;font-size:24rpx}.manual-product-extra{display:grid;gap:14rpx;padding-bottom:20rpx}.manual-product-extra textarea{min-height:120rpx;padding-top:16rpx}.manual-product-extra input{height:68rpx}.manual-product-image-row{display:flex;align-items:center;gap:14rpx}.manual-product-image{width:92rpx;height:92rpx;border-radius:14rpx;background:#efe5da}.manual-product-image-row button{flex:1;min-width:0;padding:0;border-radius:12rpx;background:#edf4f1;color:#2f6f62;font-size:23rpx}.manual-footer{display:grid;gap:10rpx}.product-selector-confirm{background:#4f766d;color:#fff}.product-selector-back{height:58rpx;line-height:58rpx;background:transparent;color:#5f897c;font-size:23rpx} +.product-selector-mask{position:fixed;inset:0;z-index:130;display:flex;align-items:flex-end;background:rgba(25,22,18,.5)}.product-selector-sheet{display:flex;width:100%;height:88vh;max-height:88vh;flex-direction:column;overflow:hidden;border-radius:34rpx 34rpx 0 0;background:#ffffff;box-shadow:0 -20rpx 48rpx rgba(44,35,27,.18)}.product-selector-head{display:flex;align-items:center;justify-content:space-between;min-height:92rpx;padding:0 28rpx}.product-selector-title{display:block;color:#17211f;font-size:34rpx;font-weight:900}.product-selector-subtitle{display:block;margin-top:7rpx;color:#71807a;font-size:22rpx}.product-selector-close{position:relative;display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:52rpx;height:52rpx;min-width:52rpx;flex:0 0 52rpx;margin:0;padding:0;overflow:hidden;border:1rpx solid #e7ece9;border-radius:50%;background:#f3f7f4;line-height:1}.product-selector-close::before,.product-selector-close::after{content:"";position:absolute;top:24rpx;left:14rpx;width:22rpx;height:3rpx;border-radius:999rpx;background:#71807a}.product-selector-close::before{transform:rotate(45deg)}.product-selector-close::after{transform:rotate(-45deg)}.product-selector-search{display:flex;align-items:center;height:80rpx;margin:0 28rpx 18rpx;padding:0 22rpx;border-radius:22rpx;background:#f3f7f4}.product-selector-search input{height:78rpx;flex:1;color:#17211f;font-size:27rpx}.product-selector-search-icon{width:24rpx;height:24rpx;margin-right:16rpx;border:3rpx solid #71807a;border-radius:50%}.product-selector-scroll{height:0;min-height:0;flex:1}.product-selector-scroll.manual{padding:0 28rpx}.product-selector-list{padding:0 28rpx 24rpx}.product-selector-item{display:flex;align-items:center;min-height:132rpx;margin-bottom:14rpx;padding:16rpx;border:1rpx solid #e7ece9;border-radius:20rpx;background:#fff}.product-selector-item.selected{border-color:#247b63;background:#e5f4ed}.product-selector-cover{width:92rpx;height:92rpx;flex:0 0 auto;border-radius:14rpx;background:#e7ece9}.product-selector-cover.placeholder,.manual-product-image.placeholder{display:flex;align-items:center;justify-content:center;color:#71807a;font-size:24rpx}.product-selector-copy{min-width:0;flex:1;margin-left:18rpx}.product-selector-name-row{display:flex;align-items:center;gap:12rpx}.product-selector-name{min-width:0;overflow:hidden;color:#17211f;font-size:28rpx;font-weight:800;text-overflow:ellipsis;white-space:nowrap}.product-selector-price{flex:0 0 auto;color:#247b63;font-size:27rpx;font-weight:900}.product-selector-meta{display:block;margin-top:7rpx;overflow:hidden;color:#71807a;font-size:23rpx;text-overflow:ellipsis;white-space:nowrap}.product-selector-tags{display:flex;gap:8rpx;margin-top:7rpx}.product-selector-tags text{padding:3rpx 10rpx;border-radius:999rpx;background:#e5f4ed;color:#71807a;font-size:19rpx}.product-selector-check{width:42rpx;color:#71807a;font-size:32rpx;text-align:right}.product-selector-item.selected .product-selector-check{color:#247b63}.product-selector-state{display:flex;min-height:360rpx;align-items:center;justify-content:center;padding:40rpx;color:#71807a;font-size:25rpx;text-align:center}.product-selector-state.error{flex-direction:column;color:#a8554e}.product-selector-retry{margin-top:20rpx;padding:0 24rpx;border:1rpx solid #e7ece9;border-radius:999rpx;background:#fff;color:#71807a;font-size:23rpx}.product-selector-footer{padding:16rpx 28rpx calc(18rpx + env(safe-area-inset-bottom));border-top:1rpx solid #e7ece9;background:#ffffff}.product-selector-action,.product-selector-confirm,.product-selector-back{width:100%;height:76rpx;margin:0;border-radius:20rpx;font-size:26rpx;line-height:76rpx}.product-selector-action{border:1rpx solid #cbdad4;background:#e5f4ed;color:#247b63}.manual-product-card{margin:18rpx 0;padding:20rpx;border-radius:18rpx;background:#f3f7f4}.manual-product-grid{display:grid;grid-template-columns:minmax(0,1fr) 180rpx;gap:14rpx}.manual-product-grid input,.manual-product-extra input,.manual-product-extra textarea{box-sizing:border-box;width:100%;padding:0 18rpx;border:0;border-radius:14rpx;background:#fff;color:#17211f;font-size:26rpx}.manual-product-grid input{height:72rpx}.manual-product-more{margin-top:16rpx;color:#71807a;font-size:24rpx}.manual-product-extra{display:grid;gap:14rpx;padding-bottom:20rpx}.manual-product-extra textarea{min-height:120rpx;padding-top:16rpx}.manual-product-extra input{height:68rpx}.manual-product-image-row{display:flex;align-items:center;gap:14rpx}.manual-product-image{width:92rpx;height:92rpx;border-radius:14rpx;background:#f3f7f4}.manual-product-image-row button{flex:1;min-width:0;padding:0;border-radius:12rpx;background:#e5f4ed;color:#247b63;font-size:23rpx}.manual-footer{display:grid;gap:10rpx}.product-selector-confirm{background:#247b63;color:#fff}.product-selector-back{height:58rpx;line-height:58rpx;background:transparent;color:#71807a;font-size:23rpx} diff --git a/JC-Salon-WeChat/employees-review.test.js b/JC-Salon-WeChat/employees-review.test.js index 39852986..7b5dc9aa 100644 --- a/JC-Salon-WeChat/employees-review.test.js +++ b/JC-Salon-WeChat/employees-review.test.js @@ -16,19 +16,46 @@ global.wx = { global.getApp = () => ({ clearSession: () => {}, goLogin: () => {} }) const employeesApi = require('./api/employees') +const authApi = require('./api/auth') +const planningApi = require('./api/planning') +const request = require('./utils/request') async function run() { + await planningApi.calendar({ startDate: '2026-10-27' }) + await authApi.login({ account: 'manager', password: 'secret' }) + await authApi.getLoginShops('manager') + await authApi.switchShop(12) + await authApi.logout() await employeesApi.reviewSummary() await employeesApi.reviewApplications() - await employeesApi.approveApplication(12) + await employeesApi.unboundArtists(12) + await employeesApi.preAssociateApplication(14, 22) + await employeesApi.approveApplication(12, { + targetArtistUserId: 22, + useApplicantNickname: true, + useApplicantAvatar: false + }) await employeesApi.rejectApplication(12, '资料不完整') assert.deepStrictEqual(requests.map(item => [item.method || 'GET', item.url, item.data]), [ - ['GET', 'http://127.0.0.1:80/api/admin/user/workbench/registration/summary', undefined], - ['GET', 'http://127.0.0.1:80/api/admin/user/workbench/registration/list', undefined], - ['POST', 'http://127.0.0.1:80/api/admin/user/workbench/registration/12/approve', undefined], - ['POST', 'http://127.0.0.1:80/api/admin/user/workbench/registration/12/reject', { reason: '资料不完整' }] + ['GET', 'http://127.0.0.1:80/api/manager/planning/calendar?startDate=2026-10-27', undefined], + ['POST', 'http://127.0.0.1:80/api/user/login', { account: 'manager', password: 'secret' }], + ['GET', 'http://127.0.0.1:80/api/user/check/login-shops/account/manager', undefined], + ['POST', 'http://127.0.0.1:80/api/user/switch-shop', { shopId: 12 }], + ['POST', 'http://127.0.0.1:80/api/user/logout', undefined], + ['GET', 'http://127.0.0.1:80/api/user/workbench/registration/summary', undefined], + ['GET', 'http://127.0.0.1:80/api/user/workbench/registration/list', undefined], + ['GET', 'http://127.0.0.1:80/api/user/workbench/registration/12/unbound-artists', undefined], + ['POST', 'http://127.0.0.1:80/api/user/workbench/registration/14/pre-associate', { targetArtistUserId: 22 }], + ['POST', 'http://127.0.0.1:80/api/user/workbench/registration/12/approve', { + targetArtistUserId: 22, + useApplicantNickname: true, + useApplicantAvatar: false + }], + ['POST', 'http://127.0.0.1:80/api/user/workbench/registration/12/reject', { reason: '资料不完整' }] ]) + assert(requests.every(item => !item.url.includes('/api/admin/'))) + assert.strictEqual(request.toBackendRequestPath('http://127.0.0.1:80/api/manager/planning/calendar'), '/manager/planning/calendar') } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/about/index.wxml b/JC-Salon-WeChat/pages/about/index.wxml index a0996ed1..e43a63be 100644 --- a/JC-Salon-WeChat/pages/about/index.wxml +++ b/JC-Salon-WeChat/pages/about/index.wxml @@ -6,6 +6,6 @@ 版本0.0.1 - 定位规划 / 客户 / 员工 / 我的 + 定位日程 / 客户 / 美甲师 / 我的 diff --git a/JC-Salon-WeChat/pages/about/index.wxss b/JC-Salon-WeChat/pages/about/index.wxss index 1fe26daf..62f06174 100644 --- a/JC-Salon-WeChat/pages/about/index.wxss +++ b/JC-Salon-WeChat/pages/about/index.wxss @@ -13,7 +13,7 @@ width: 112rpx; height: 112rpx; border-radius: 30rpx; - background: #e5eee9; + background: #e5f4ed; box-shadow: 0 16rpx 34rpx rgba(111, 143, 131, 0.24); } diff --git a/JC-Salon-WeChat/pages/account-settings/index.js b/JC-Salon-WeChat/pages/account-settings/index.js index 4ac49858..750d7796 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.js +++ b/JC-Salon-WeChat/pages/account-settings/index.js @@ -12,16 +12,62 @@ Page({ codeLoading: false, countdown: 0, timer: null, - smsExpanded: false + smsExpanded: false, + unbindMode: false, + closureRequest: null, + closureLoading: true, + closureError: '' }, - onShow() { this.loadProfile() }, + onShow() { this.loadProfile(); this.loadClosureRequest() }, + + async loadClosureRequest() { + this.setData({ closureLoading: true, closureError: '' }) + try { + const closureRequest = await userApi.getAccountClosure() + this.setData({ closureRequest: closureRequest || null }) + } catch (error) { + this.setData({ closureError: error.message || '注销状态加载失败' }) + } finally { + this.setData({ closureLoading: false }) + } + }, + + async requestClosure() { + const confirmed = await new Promise(resolve => wx.showModal({ + title: '申请注销账号', + content: '申请提交后由管理人员处理。完成后会清理账号身份资料,必要业务记录仍按保存要求保留。你可以在处理前撤回。', + confirmText: '提交申请', + success: result => resolve(result.confirm), + fail: () => resolve(false) + })) + if (!confirmed) return + try { + const closureRequest = await userApi.requestAccountClosure() + this.setData({ closureRequest }) + wx.showToast({ title: '注销申请已提交' }) + } catch (error) { + wx.showToast({ title: error.message || '申请提交失败', icon: 'none' }) + } + }, + + async withdrawClosure() { + const confirmed = await new Promise(resolve => wx.showModal({ title: '撤回注销申请', content: '确定撤回账号注销申请吗?', success: result => resolve(result.confirm), fail: () => resolve(false) })) + if (!confirmed) return + try { + await userApi.withdrawAccountClosure() + await this.loadClosureRequest() + wx.showToast({ title: '申请已撤回' }) + } catch (error) { + wx.showToast({ title: error.message || '撤回失败', icon: 'none' }) + } + }, async loadProfile(options = {}) { this.setData({ loading: true }) try { const profile = await profileCache.getProfile(options) - this.setData({ profile, 'smsForm.phone': profile.phone || '' }) + this.setData({ profile, 'smsForm.phone': '' }) const app = getApp() const session = auth.getSession() app.setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } }) @@ -39,7 +85,11 @@ Page({ }, toggleSms() { - this.setData({ smsExpanded: !this.data.smsExpanded }) + this.setData({ smsExpanded: !this.data.smsExpanded, unbindMode: false }) + }, + + beginUnbind() { + this.setData({ smsExpanded: true, unbindMode: true, 'smsForm.code': '' }) }, async bindWechatPhone(event) { @@ -62,13 +112,14 @@ Page({ async sendCode() { const phone = String(this.data.smsForm.phone || '') - if (!/^1[3-9]\d{9}$/.test(phone)) { + if (!this.data.unbindMode && !/^1[3-9]\d{9}$/.test(phone)) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } if (this.data.codeLoading || this.data.countdown) return this.setData({ codeLoading: true }) try { - await userApi.sendBindPhoneCode(phone) + if (this.data.unbindMode) await userApi.sendUnbindPhoneCode() + else await userApi.sendBindPhoneCode(phone) this.startCountdown() wx.showToast({ title: '验证码已发送' }) } catch (error) { @@ -107,6 +158,33 @@ Page({ } }, + async unbindSmsPhone() { + const code = String(this.data.smsForm.code || '') + if (!/^\d{6}$/.test(code)) { + wx.showToast({ title: '请输入当前手机号收到的6位验证码', icon: 'none' }); return + } + const confirmed = await new Promise(resolve => wx.showModal({ + title: '解绑手机号', + content: '解绑后手机号将从账号资料中删除,短信验证码仅用于验证当前手机号。确定继续吗?', + confirmText: '确认解绑', + success: result => resolve(result.confirm), + fail: () => resolve(false) + })) + if (!confirmed) return + this.setData({ binding: true }) + try { + await userApi.unbindPhone(code) + profileCache.invalidate() + this.setData({ unbindMode: false, smsExpanded: false, 'smsForm.code': '' }) + await this.loadProfile({ force: true }) + wx.showToast({ title: '手机号已解绑' }) + } catch (error) { + wx.showToast({ title: error.message || '解绑失败', icon: 'none' }) + } finally { + this.setData({ binding: false }) + } + }, + async logout() { const confirmed = await new Promise(resolve => wx.showModal({ title: '退出登录', content: '退出后将关闭自动登录,并清除本机提醒设置。', success: result => resolve(result.confirm), fail: () => resolve(false) })) if (!confirmed) return diff --git a/JC-Salon-WeChat/pages/account-settings/index.test.js b/JC-Salon-WeChat/pages/account-settings/index.test.js new file mode 100644 index 00000000..9bfeed6a --- /dev/null +++ b/JC-Salon-WeChat/pages/account-settings/index.test.js @@ -0,0 +1,68 @@ +const assert = require('assert') + +let pageDefinition +let currentProfile + +global.Page = definition => { pageDefinition = definition } +global.wx = { + getStorageSync: () => ({}), + setStorageSync: () => {}, + showToast: () => {} +} +global.getApp = () => ({ setSession: () => {} }) + +const profileCache = require('../../utils/profile-cache') +profileCache.getProfile = async () => currentProfile +const userApi = require('../../api/user') +require('./index') + +async function loadProfile(profile) { + currentProfile = profile + const page = { + data: { ...pageDefinition.data }, + setData(values) { + Object.entries(values).forEach(([key, value]) => { + const parts = key.split('.') + if (parts.length === 1) this.data[key] = value + else this.data[parts[0]] = { ...this.data[parts[0]], [parts[1]]: value } + }) + } + } + await pageDefinition.loadProfile.call(page) + return page.data +} + +async function run() { + const empty = await loadProfile({ + type: 2, + shopBusinessExpireTime: null, + shopBusinessExpired: false, + shopBusinessRemainingDays: null + }) + assert.strictEqual(empty.profile.shopBusinessExpireTime, null) + + const active = await loadProfile({ + type: 2, + shopBusinessExpireTime: '2026-12-31T23:59:59', + shopBusinessExpired: false, + shopBusinessRemainingDays: 66 + }) + assert.strictEqual(active.profile.shopBusinessExpireTime, '2026-12-31T23:59:59') + + userApi.getAccountClosure = async () => { throw new Error('注销状态暂时无法读取') } + const closurePage = { + data: { ...pageDefinition.data }, + setData(values) { Object.assign(this.data, values) } + } + await pageDefinition.loadClosureRequest.call(closurePage) + assert.strictEqual(closurePage.data.closureError, '注销状态暂时无法读取') + assert.strictEqual(closurePage.data.closureLoading, false) + const accountWxml = require('fs').readFileSync(require('path').join(__dirname, 'index.wxml'), 'utf8') + assert(accountWxml.includes('closureError')) + assert(accountWxml.includes('bindtap="loadClosureRequest"')) +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/account-settings/index.wxml b/JC-Salon-WeChat/pages/account-settings/index.wxml index 00554c21..2a17fd95 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.wxml +++ b/JC-Salon-WeChat/pages/account-settings/index.wxml @@ -3,14 +3,32 @@ 手机号 {{profile.phoneVerified == 1 ? (profile.maskedPhone || profile.phone) : '尚未绑定'}}{{profile.phoneVerified == 1 ? '已验证' : '待绑定'}} - + 手机号绑定为可选,不绑定不影响基础使用。仅用于账号找回和必要订单通知;不会用于营销。 + {{profile.phoneVerified == 1 ? '使用短信验证码更换' : '使用短信验证码绑定'}}› - + + 验证码将发送到当前绑定的{{profile.maskedPhone || '手机号'}},仅用于核验解绑操作。 + 发送前再次确认:手机号仅用于账号找回和必要订单通知,不用于营销。 - + + + 解绑当前手机号› + + + + 账号注销 + 正在读取注销申请状态… + {{closureError}} + + 申请处理中,{{closureRequest.processingTargetText || '以管理人员审核和门店交接进度为准'}} + 账号资料已完成清理。 + 上次申请未通过:{{closureRequest.reviewerNote || '请联系管理人员'}} + 可申请注销工作台账号。提交后可在管理人员处理前撤回。 + + + - diff --git a/JC-Salon-WeChat/pages/account-settings/index.wxss b/JC-Salon-WeChat/pages/account-settings/index.wxss index 4eab3ccf..b2830890 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.wxss +++ b/JC-Salon-WeChat/pages/account-settings/index.wxss @@ -1,2 +1,18 @@ -.settings-page { padding-top:24rpx; }.identity-card { display:flex; align-items:center; padding:26rpx; }.identity-mark { display:flex; align-items:center; justify-content:center; width:68rpx; height:68rpx; border-radius:20rpx; background:#dcebe1; color:#35634d; font-size:28rpx; font-weight:800; }.identity-copy { display:flex; flex:1; flex-direction:column; margin-left:18rpx; }.identity-title,.section-title { color:#30483c; font-size:28rpx; font-weight:800; }.identity-status { margin-top:6rpx; color:#8a9a91; font-size:21rpx; }.linked-badge,.status-tag { padding:7rpx 14rpx; border-radius:999rpx; background:#e5f2e8; color:#397055; font-size:20rpx; } -.phone-card { margin-top:20rpx; padding:28rpx; }.phone-status { display:flex; align-items:center; justify-content:space-between; margin-top:20rpx; padding:20rpx; border-radius:14rpx; background:#f4f8f5; color:#425b4e; font-size:26rpx; }.status-tag { background:#fff0db; color:#9a682e; }.status-tag.done { background:#e5f2e8; color:#397055; }.wechat-phone-btn,.sms-bind-btn { height:80rpx; margin-top:22rpx; border-radius:14rpx; background:#35634d; color:#fff; font-size:26rpx; line-height:80rpx; }.sms-entry { display:flex; min-height:82rpx; align-items:center; margin-top:22rpx; border-top:1rpx solid #e5ebe7; color:#627269; font-size:23rpx; }.sms-arrow { margin-left:auto; color:#95a198; font-size:36rpx; transition:transform 180ms ease; }.sms-arrow.expanded { transform:rotate(90deg); }.sms-panel { padding-top:2rpx; }.field input,.code-row input { box-sizing:border-box; height:78rpx; padding:0 20rpx; border:1rpx solid #dde8e0; border-radius:12rpx; background:#f8faf8; }.code-row { display:flex; gap:12rpx; margin-top:14rpx; }.code-row input { min-width:0; flex:1; }.code-row button { width:190rpx; height:78rpx; padding:0; border-radius:12rpx; background:#e7f0ea; color:#426c57; font-size:23rpx; line-height:78rpx; }.sms-bind-btn { background:#eef4f0; color:#35634d; }.account-note { margin:24rpx 18rpx; color:#8e9c94; font-size:21rpx; line-height:1.6; }.logout-btn { margin-top:52rpx; background:transparent; color:#a24f42; font-size:25rpx; } +.settings-page { padding-top:24rpx; }.identity-card { display:flex; align-items:center; padding:26rpx; }.identity-mark { display:flex; align-items:center; justify-content:center; width:68rpx; height:68rpx; border-radius:20rpx; background:#e5f4ed; color:#247b63; font-size:28rpx; font-weight:800; }.identity-copy { display:flex; flex:1; flex-direction:column; margin-left:18rpx; }.identity-title,.section-title { color:#17211f; font-size:28rpx; font-weight:800; }.identity-status { margin-top:6rpx; color:#71807a; font-size:21rpx; }.linked-badge,.status-tag { padding:7rpx 14rpx; border-radius:999rpx; background:#e5f2e8; color:#397055; font-size:20rpx; } +.phone-card { margin-top:20rpx; padding:28rpx; }.phone-status { display:flex; align-items:center; justify-content:space-between; margin-top:20rpx; padding:20rpx; border-radius:14rpx; background:#f3f7f4; color:#71807a; font-size:26rpx; }.status-tag { background:#fff0db; color:#9a682e; }.status-tag.done { background:#e5f2e8; color:#397055; }.wechat-phone-btn,.sms-bind-btn { height:80rpx; margin-top:22rpx; border-radius:14rpx; background:#247b63; color:#fff; font-size:26rpx; line-height:80rpx; }.sms-entry { display:flex; min-height:82rpx; align-items:center; margin-top:22rpx; border-top:1rpx solid #e5ebe7; color:#71807a; font-size:23rpx; }.sms-arrow { margin-left:auto; color:#95a198; font-size:36rpx; transition:transform 180ms ease; }.sms-arrow.expanded { transform:rotate(90deg); }.sms-panel { padding-top:2rpx; }.field input,.code-row input { box-sizing:border-box; height:78rpx; padding:0 20rpx; border:1rpx solid #dde8e0; border-radius:12rpx; background:#f8faf8; }.code-row { display:flex; gap:12rpx; margin-top:14rpx; }.code-row input { min-width:0; flex:1; }.code-row button { width:190rpx; height:78rpx; padding:0; border-radius:12rpx; background:#e7f0ea; color:#426c57; font-size:23rpx; line-height:78rpx; }.sms-bind-btn { background:#eef4f0; color:#247b63; }.account-note { margin:24rpx 18rpx; color:#71807a; font-size:21rpx; line-height:1.6; }.logout-btn { margin-top:52rpx; background:transparent; color:#a24f42; font-size:25rpx; } +.privacy-note { + margin: 12rpx 0; + color: #73817b; + font-size: 24rpx; + line-height: 1.6; +} + +.unbind-entry { + color: #8a5555; +} + +.closure-card { margin-top: 20rpx; padding: 28rpx; } +.closure-btn { height: 76rpx; margin-top: 18rpx; border-radius: 12rpx; background: #fff1ef; color: #9a5147; font-size: 24rpx; line-height: 76rpx; } +.closure-btn.secondary { background: #eef4f0; color: #426c57; } +.closure-error { color: #a24f42; } +.closure-retry { display: inline-block; margin: 0 0 0 12rpx; padding: 0; background: transparent; color: #397055; font-size: 22rpx; line-height: 1.6; } diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index 7b01fd80..775fc609 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -42,11 +42,11 @@ Page({ async updateStatus(status) { if (status !== 3 && this.data.isUnassigned) { - wx.showToast({ title: '请先分配员工', icon: 'none' }) + wx.showToast({ title: '请先分配美甲师', icon: 'none' }) return } try { - await planningApi.updateStatus(this.data.appointment.orderId, status) + await planningApi.updateStatus(this.data.appointment.orderId, status, this._cancelReason || '') markPlanningRefresh() wx.showToast({ title: '已更新' }) this.loadDetail() @@ -65,7 +65,18 @@ Page({ }, cancel() { - this.updateStatus(3) + wx.showModal({ + title: '取消预约', + editable: true, + placeholderText: '可填写取消原因', + content: '', + confirmText: '确认取消', + success: result => { + if (!result.confirm) return + this._cancelReason = result.content || '' + this.updateStatus(3) + } + }) }, goTransfer() { diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index da49d540..dd2fab7a 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -16,7 +16,7 @@ 历史补单 · {{appointment.statusText}} {{appointment.statusText}} - + diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxss b/JC-Salon-WeChat/pages/appointment-detail/index.wxss index 00b7edcd..c8ac9961 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxss @@ -35,7 +35,7 @@ width: 82rpx; height: 82rpx; border-radius: 50%; - background: #e5eee9; + background: #e5f4ed; color: #5d8175; font-size: 32rpx; font-weight: 900; @@ -47,7 +47,7 @@ } .customer { - color: #24211d; + color: #17211f; font-size: 32rpx; font-weight: 800; } @@ -78,20 +78,20 @@ } .label { - color: #9a9288; + color: #71807a; font-size: 22rpx; } .value { margin-top: 8rpx; - color: #2d2924; + color: #17211f; font-size: 28rpx; font-weight: 700; } .note-card { padding: 24rpx; - color: #6d655d; + color: #71807a; line-height: 1.6; } diff --git a/JC-Salon-WeChat/pages/appointment-form/draft-reset.test.js b/JC-Salon-WeChat/pages/appointment-form/draft-reset.test.js new file mode 100644 index 00000000..a0d23f6f --- /dev/null +++ b/JC-Salon-WeChat/pages/appointment-form/draft-reset.test.js @@ -0,0 +1,279 @@ +const assert = require('assert') +const fs = require('fs') +const path = require('path') + +let appointmentDefinition +let backfillDefinition +const storage = new Map() +let modalConfirm = true +let modalCalls = 0 +const app = { globalData: { userInfo: { id: 'manager-1', shopId: 'shop-1', type: 2 } } } + +global.Page = value => { appointmentDefinition = value } +global.getApp = () => app +global.wx = { + getStorageSync(key) { return storage.get(key) }, + setStorageSync(key, value) { storage.set(key, JSON.parse(JSON.stringify(value))) }, + removeStorageSync(key) { storage.delete(key) }, + showModal(options) { modalCalls += 1; options.success({ confirm: modalConfirm }) }, + showToast() {}, + redirectTo() {}, + navigateTo() {} +} + +require('./index') +global.Page = value => { backfillDefinition = value } +require('../backfill-order/index') + +function clone(value) { + return JSON.parse(JSON.stringify(value)) +} + +function createPage(definition) { + const page = { + ...definition, + data: clone(definition.data), + setData(patch, callback) { + Object.entries(patch || {}).forEach(([key, value]) => { + const parts = key.split('.') + let target = this.data + for (let index = 0; index < parts.length - 1; index += 1) { + if (!target[parts[index]]) target[parts[index]] = {} + target = target[parts[index]] + } + target[parts[parts.length - 1]] = value + }) + if (callback) callback() + } + } + return page +} + +function draftKey(userId = 'manager-1', shopId = 'shop-1') { + return `managerAppointmentDraft:${userId}:${shopId}` +} + +async function testDraftRestoreAndEntryOverrides() { + storage.clear() + modalConfirm = true + storage.set(draftKey(), { + form: { + ...appointmentDefinition.data.form, + customerName: '草稿客户', + phone: '13800000000', + productId: 'product-1', + appointmentDate: '2099-10-10', + appointmentTime: '14:00', + artistId: 'artist-1', + durationMinutes: '90' + }, + durationManuallyChanged: true, + savedAt: Date.now() + }) + const page = createPage(appointmentDefinition) + page.loadOptions = () => {} + page.onLoad({ date: '2099-10-11', artistId: 'artist-2', customerName: encodeURIComponent('入口客户') }) + assert.strictEqual(page.data.form.customerName, '入口客户') + assert.strictEqual(page.data.form.phone, '') + assert.strictEqual(page.data.form.productId, 'product-1') + assert.strictEqual(page.data.form.appointmentDate, '2099-10-11') + assert.strictEqual(page.data.form.appointmentTime, '') + assert.strictEqual(page.data.form.artistId, 'artist-2') + assert.strictEqual(page.data.form.durationMinutes, '90') + assert.strictEqual(page.data.durationManuallyChanged, true) + assert.ok(page.data.draftSavedAtText.includes('已恢复草稿')) + + const manualPage = createPage(appointmentDefinition) + manualPage.loadOptions = () => {} + manualPage.onLoad({ dateMode: 'manual', artistId: 'artist-2' }) + assert.strictEqual(manualPage.data.form.appointmentDate, '2099-10-10') + assert.strictEqual(manualPage.data.form.appointmentTime, '14:00') + assert.strictEqual(manualPage.data.form.customerName, '草稿客户') + assert.strictEqual(manualPage.data.form.artistId, 'artist-2') +} + +async function testDraftAutosaveExpiryAndIsolation() { + storage.clear() + modalConfirm = true + const page = createPage(appointmentDefinition) + page.loadOptions = () => {} + page.onLoad({ dateMode: 'manual' }) + page.setData({ 'form.customerName': '自动保存客户' }) + await new Promise(resolve => setTimeout(resolve, 450)) + assert.strictEqual(storage.get(draftKey()).form.customerName, '自动保存客户') + + page.setData({ 'form.phone': '13800000000' }) + page.setData({ 'form.durationMinutes': '90', durationManuallyChanged: true }) + page.saveDraft() + assert.strictEqual(storage.get(draftKey()).form.phone, '13800000000') + assert.strictEqual(storage.get(draftKey()).durationManuallyChanged, true) + + app.globalData.userInfo.id = 'manager-2' + const otherUserPage = createPage(appointmentDefinition) + otherUserPage.loadOptions = () => {} + otherUserPage.onLoad({ dateMode: 'manual' }) + otherUserPage.setData({ 'form.customerName': '另一位店长' }) + await new Promise(resolve => setTimeout(resolve, 450)) + assert.strictEqual(storage.get(draftKey('manager-2')).form.customerName, '另一位店长') + assert.strictEqual(storage.get(draftKey('manager-1')).form.customerName, '自动保存客户') + app.globalData.userInfo.id = 'manager-1' + + app.globalData.userInfo.shopId = 'shop-2' + const otherShopPage = createPage(appointmentDefinition) + otherShopPage.loadOptions = () => {} + otherShopPage.onLoad({ dateMode: 'manual' }) + assert.strictEqual(otherShopPage.data.form.customerName, '') + otherShopPage.setData({ 'form.customerName': '另一家门店' }) + await new Promise(resolve => setTimeout(resolve, 450)) + assert.strictEqual(storage.get(draftKey('manager-1', 'shop-2')).form.customerName, '另一家门店') + app.globalData.userInfo.shopId = 'shop-1' + + storage.set(draftKey(), { + form: { ...appointmentDefinition.data.form, customerName: '过期草稿' }, + savedAt: Date.now() - 8 * 24 * 60 * 60 * 1000 + }) + const expiredPage = createPage(appointmentDefinition) + expiredPage.loadOptions = () => {} + expiredPage.onLoad({ dateMode: 'manual' }) + assert.strictEqual(expiredPage.data.form.customerName, '') + assert.strictEqual(storage.has(draftKey()), false) +} + +async function testResetAndSuccessfulSubmitClearDraft() { + storage.clear() + modalConfirm = true + const page = createPage(appointmentDefinition) + page.data.defaultAppointmentDurationMinutes = 75 + page.loadOptions = () => {} + page.refreshAvailableTimes = async () => {} + page.onLoad({ date: '2099-10-12', artistId: 'artist-3' }) + page.setData({ + 'form.customerName': '需要清空', + 'form.amount': '268', + 'form.appointmentTime': '15:00', + 'form.remark': '备注' + }) + page.saveDraft() + modalConfirm = false + await page.resetForm() + assert.strictEqual(page.data.form.customerName, '需要清空') + assert.strictEqual(storage.has(draftKey()), true) + + const modalCallCount = modalCalls + page.setData({ loading: true }) + await page.resetForm() + assert.strictEqual(modalCalls, modalCallCount) + assert.strictEqual(page.data.form.customerName, '需要清空') + page.setData({ loading: false }) + + page.setData({ manualImageUploading: true }) + await page.resetForm() + assert.strictEqual(modalCalls, modalCallCount) + assert.strictEqual(page.data.form.customerName, '需要清空') + page.setData({ manualImageUploading: false }) + + modalConfirm = true + await page.resetForm() + assert.strictEqual(page.data.form.customerName, '') + assert.strictEqual(page.data.form.amount, '') + assert.strictEqual(page.data.form.appointmentTime, '') + assert.strictEqual(page.data.form.remark, '') + assert.strictEqual(page.data.form.appointmentDate, '2099-10-12') + assert.strictEqual(page.data.form.artistId, 'artist-3') + assert.strictEqual(page.data.form.durationMinutes, '75') + assert.strictEqual(storage.has(draftKey()), false) + assert.strictEqual(page.data.manualProductMoreVisible, false) + assert.strictEqual(page.data.timeSheetVisible, false) + page.setData({ 'form.customerName': '重置后继续填写' }) + await new Promise(resolve => setTimeout(resolve, 450)) + assert.strictEqual(storage.get(draftKey()).form.customerName, '重置后继续填写') + + const planningApi = require('../../api/planning') + const originalCreateAppointment = planningApi.createAppointment + planningApi.createAppointment = async () => ({ orderItemId: 'order-item-1' }) + page.data.form = { + ...page.data.form, + productId: 'product-1', + amount: '120', + appointmentDate: '2099-10-12', + appointmentTime: '15:00', + artistId: 'artist-3', + durationMinutes: '60' + } + page.checkAvailability = async () => ({ ok: true }) + page.ensureCustomerBeforeSubmit = async () => true + storage.set(draftKey(), { form: page.data.form, savedAt: Date.now() }) + await page.submit() + assert.strictEqual(storage.has(draftKey()), false) + planningApi.createAppointment = originalCreateAppointment +} + +async function testBackfillResetAndLibraryGuidance() { + modalConfirm = true + const page = createPage(backfillDefinition) + page.loadArtists = () => {} + page.loadProducts = () => {} + page.loadCustomers = () => {} + page.onLoad({ serviceDate: '2020-01-02', artistId: 'artist-9' }) + page.data.artists = [{ id: 'artist-9', name: '美甲师九' }] + page.setData({ 'form.customerName': '需要清空', 'form.amount': '99', 'form.serviceTime': '12:30' }) + const modalCallCount = modalCalls + page.setData({ manualImageUploading: true }) + await page.resetForm() + assert.strictEqual(modalCalls, modalCallCount) + assert.strictEqual(page.data.form.customerName, '需要清空') + page.setData({ manualImageUploading: false }) + modalConfirm = false + await page.resetForm() + assert.strictEqual(page.data.form.customerName, '需要清空') + modalConfirm = true + await page.resetForm() + assert.strictEqual(page.data.form.serviceDate, '2020-01-02') + assert.strictEqual(page.data.form.artistId, 'artist-9') + assert.strictEqual(page.data.selectedArtistName, '美甲师九') + assert.strictEqual(page.data.form.customerName, '') + assert.strictEqual(page.data.form.amount, '') + assert.strictEqual(page.data.form.serviceTime, '') + assert.strictEqual(page.data.form.status, 4) + + const unassignedPage = createPage(appointmentDefinition) + unassignedPage.loadOptions = () => {} + unassignedPage.refreshAvailableTimes = async () => {} + unassignedPage.onLoad({ date: '2099-10-15', artistId: '__unassigned__' }) + assert.strictEqual(unassignedPage.data.form.artistId, '') + assert.strictEqual(unassignedPage.data.selectedArtist.id, '__unassigned__') + await unassignedPage.resetForm() + assert.strictEqual(unassignedPage.data.form.appointmentDate, '2099-10-15') + assert.strictEqual(unassignedPage.data.form.artistId, '') + assert.strictEqual(unassignedPage.data.selectedArtist.id, '__unassigned__') + unassignedPage.setData({ 'form.appointmentTime': '' }) + await new Promise(resolve => setTimeout(resolve, 450)) + assert.strictEqual(storage.has(draftKey()), false) + + const manualEntryPage = createPage(appointmentDefinition) + manualEntryPage.loadOptions = () => {} + manualEntryPage.onLoad({ dateMode: 'manual' }) + assert.strictEqual(manualEntryPage.data.form.appointmentDate, '') + manualEntryPage.setData({ 'form.appointmentDate': '2099-10-20' }) + await manualEntryPage.resetForm() + assert.strictEqual(manualEntryPage.data.form.appointmentDate, '') + + const appointmentMarkup = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') + const backfillMarkup = fs.readFileSync(path.join(__dirname, '..', 'backfill-order', 'index.wxml'), 'utf8') + const guidance = '仅门店可见,不会公开展示' + assert.ok(appointmentMarkup.includes(guidance)) + assert.ok(backfillMarkup.includes(guidance)) +} + +async function run() { + await testDraftRestoreAndEntryOverrides() + await testDraftAutosaveExpiryAndIsolation() + await testResetAndSuccessfulSubmitClearDraft() + await testBackfillResetAndLibraryGuidance() + console.log('预约草稿与重置测试通过') +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index 128b531b..a09e6503 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -7,13 +7,17 @@ global.wx = { setStorageSync: () => {}, removeStorageSync: () => {}, showToast: () => {}, + showModal: options => options.success({ confirm: modalConfirm }), navigateTo: () => {} } global.getApp = () => ({ globalData: { userInfo: { type: 2, id: 1, shopId: 2 } } }) +let modalConfirm = true + let definition global.Page = value => { definition = value } require('./index') +const customersApi = require('../../api/customers') function createPage() { return { @@ -39,11 +43,28 @@ async function run() { assert.strictEqual(page.data.customerSheetVisible, false) page.data.form.customerUserId = 18 - page.data.manualCustomerForm = { name: '新客户', phone: '13900139000' } - page.useManualCustomer() + page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '13900139000') + assert.strictEqual(page.data.form.phone, '13800138000') + + customersApi.matchIdentityForAppointment = async () => [] + customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '') + assert.strictEqual(page.data.form.createCustomerRecord, true) + + page.data.form.customerUserId = '' + page.data.form.customerName = '小周' + page.data.form.phone = '13800138000' + customersApi.matchIdentityForAppointment = async (name, wechatId, phone) => { + assert.strictEqual(name, '小周') + assert.strictEqual(wechatId, undefined) + assert.strictEqual(phone, '13800138000') + return [{ id: '18', name: '小周', phone: '13800138000' }] + } + assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) + assert.strictEqual(page.data.form.customerUserId, '18') page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] page.onArtistSearch({ detail: { value: '李' } }) diff --git a/JC-Salon-WeChat/pages/appointment-form/history-date.test.js b/JC-Salon-WeChat/pages/appointment-form/history-date.test.js index 0162c849..6ff50240 100644 --- a/JC-Salon-WeChat/pages/appointment-form/history-date.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/history-date.test.js @@ -3,6 +3,7 @@ const assert = require('assert') let definition let modalResult = { confirm: false } let modalOptions +let storedDraft = null const navigations = [] global.Page = value => { definition = value } @@ -13,8 +14,12 @@ global.wx = { }, navigateTo(options) { navigations.push(options.url) - } + }, + getStorageSync() { return storedDraft }, + setStorageSync() {}, + removeStorageSync() {} } +global.getApp = () => ({ globalData: { userInfo: { type: 2 } } }) require('./index') @@ -40,6 +45,38 @@ function createPage() { } async function run() { + const manualDatePage = createPage() + manualDatePage.loadOptions = () => {} + manualDatePage.data.form.appointmentTime = '' + storedDraft = null + manualDatePage.onLoad({ dateMode: 'manual', artistId: '88' }) + assert.strictEqual(manualDatePage.data.form.appointmentDate, '') + assert.strictEqual(manualDatePage.data.form.appointmentTime, '') + assert.strictEqual(manualDatePage.data.form.artistId, '88') + assert.strictEqual(manualDatePage.data.appointmentDateLong, '请选择预约日期') + + const restoredDate = '2099-10-10' + const draftPage = createPage() + draftPage.loadOptions = () => {} + storedDraft = { + form: { + ...definition.data.form, + customerName: '草稿客户', + productId: '41', + appointmentDate: restoredDate, + appointmentTime: '14:00', + artistId: '99' + }, + savedAt: Date.now() + } + draftPage.onLoad({ dateMode: 'manual', artistId: '88' }) + assert.strictEqual(draftPage.data.form.appointmentDate, restoredDate) + assert.strictEqual(draftPage.data.form.appointmentTime, '14:00') + assert.strictEqual(draftPage.data.form.customerName, '草稿客户') + assert.strictEqual(draftPage.data.form.artistId, '88') + assert.ok(draftPage.data.draftSavedAtText.startsWith('已恢复草稿')) + + storedDraft = null const page = createPage() let refreshes = 0 page.loadArtists = async () => { refreshes += 1 } @@ -64,6 +101,8 @@ async function run() { await page.onDateChange({ detail: { value: '2099-10-11' } }) assert.strictEqual(page.data.form.appointmentDate, '2099-10-11') assert.strictEqual(page.data.form.appointmentTime, '') + assert.strictEqual(page.data.appointmentDateBadge.includes('10月11日'), true) + assert.strictEqual(page.data.appointmentDateLong.includes('2099年10月11日'), true) assert.strictEqual(refreshes, 3) } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 2a47ba0f..b778560e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -3,9 +3,11 @@ const productsApi = require('../../api/products') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') -const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload') +const { uploadObjectFile } = require('../../utils/upload') const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' +const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000 +const DRAFT_SAVE_DELAY_MS = 400 const TIME_SLOT_MINUTES = 15 function buildClientRequestId(prefix) { @@ -26,31 +28,58 @@ function canCreateAppointment() { return Number(userInfo.type) !== 3 } +function isShopManager() { + const userInfo = getApp().globalData.userInfo || {} + return Number(userInfo.type) === 2 +} + +function isShopBusinessExpired() { + const userInfo = getApp().globalData.userInfo || {} + return Number(userInfo.type) === 2 && userInfo.shopBusinessExpired === true +} + +function showBusinessExpiryNotice() { + return new Promise(resolve => wx.showModal({ + title: '门店经营有效期已到期', + content: '当前门店暂不能新增普通预约。历史订单、查询和补录不受影响,请联系平台管理员办理续期。', + showCancel: false, + confirmText: '知道了', + success: () => resolve(), + fail: () => resolve() + })) +} + function buildDraftKey() { const app = getApp() const userInfo = app.globalData.userInfo || {} return `${DRAFT_STORAGE_PREFIX}:${userInfo.id || 'guest'}:${userInfo.shopId || 'default'}` } -function hasPresetOptions(options) { - return Boolean(options.customerName || options.phone || options.date || options.artistId) -} - -function readDraftForm() { +function readDraft() { try { const draft = wx.getStorageSync(buildDraftKey()) - return draft && draft.form ? draft.form : null + if (!draft || !draft.form) return null + const savedAt = Number(draft.savedAt) + if (!Number.isFinite(savedAt) || savedAt <= 0 || savedAt > Date.now() || Date.now() - savedAt > DRAFT_TTL_MS) { + wx.removeStorageSync(buildDraftKey()) + return null + } + return draft } catch (error) { throw new Error(`读取预约草稿失败:${error.message || error}`) } } -function writeDraftForm(form) { +function writeDraftForm(form, artistSelectionId, durationManuallyChanged) { try { + const savedAt = Date.now() wx.setStorageSync(buildDraftKey(), { form, - savedAt: Date.now() + artistSelectionId: artistSelectionId === '__unassigned__' ? artistSelectionId : '', + durationManuallyChanged: Boolean(durationManuallyChanged), + savedAt }) + return savedAt } catch (error) { throw new Error(`保存预约草稿失败:${error.message || error}`) } @@ -64,6 +93,94 @@ function removeDraftForm() { } } +function formatDraftStatus(status, savedAt) { + if (!savedAt) return status + const date = new Date(Number(savedAt)) + if (Number.isNaN(date.getTime())) return status + const pad = value => String(value).padStart(2, '0') + return `${status} · ${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}` +} + +function decodeOptionValue(value) { + if (value === undefined || value === null) return '' + try { + return decodeURIComponent(String(value)) + } catch (error) { + return String(value) + } +} + +function hasDraftContent(form, entryDefaults, selectedArtist, defaultDuration) { + if (!form) return false + const changedDate = String(form.appointmentDate || '') !== String(entryDefaults.appointmentDate || '') + const currentArtistSelectionId = selectedArtist && selectedArtist.id === '__unassigned__' + ? '__unassigned__' + : String(form.artistId || '') + const defaultArtistSelectionId = String(entryDefaults.artistSelectionId || entryDefaults.artistId || '') + const changedArtist = currentArtistSelectionId !== defaultArtistSelectionId + return Boolean( + form.customerUserId || form.customerName || form.phone || form.wechatId || + form.productId || form.manualProductTitle || form.manualProductDescription || + form.manualProductTags || form.manualProductTargetAudience || form.manualProductPrecautions || + form.manualProductImageFileIds || (Array.isArray(form.manualProductImages) && form.manualProductImages.length) || + String(form.amount || '').trim() || form.appointmentTime || form.createCustomerRecord || form.remark || + changedDate || changedArtist || + (Number(form.durationMinutes) > 0 && Number(form.durationMinutes) !== Number(defaultDuration || 60)) + ) +} + +function normalizeManualProductImages(form) { + const savedImages = form && Array.isArray(form.manualProductImages) ? form.manualProductImages : null + if (savedImages) { + return savedImages.map(image => { + const fileUrl = image && (image.fileUrl || image.url) ? String(image.fileUrl || image.url) : '' + return { + fileId: image && image.fileId !== undefined ? String(image.fileId) : '', + fileUrl, + previewUrl: image && image.previewUrl ? String(image.previewUrl) : fileUrl + } + }).filter(image => image.fileId).slice(0, 9) + } + const fileIds = String(form && form.manualProductImageFileIds || '').split(',').map(fileId => fileId.trim()).filter(Boolean) + return fileIds.slice(0, 9).map((fileId, index) => ({ + fileId, + fileUrl: index === 0 && form && form.manualProductImageUrl ? String(form.manualProductImageUrl) : '', + previewUrl: index === 0 && form && form.manualProductImageUrl ? String(form.manualProductImageUrl) : '' + })) +} + +function buildManualProductImagePatch(images) { + const normalizedImages = (images || []).slice(0, 9) + return { + 'form.manualProductImages': normalizedImages, + 'form.manualProductImageFileIds': normalizedImages.map(image => image.fileId).filter(Boolean).join(','), + 'form.manualProductImageUrl': normalizedImages[0] ? normalizedImages[0].previewUrl || normalizedImages[0].fileUrl || '' : '' + } +} + +function chooseManualProductImagePaths(count) { + const normalizedCount = Math.min(9, Math.max(1, Math.floor(Number(count) || 1))) + return new Promise((resolve, reject) => { + wx.chooseMedia({ + count: normalizedCount, + mediaType: ['image'], + sourceType: ['album', 'camera'], + sizeType: ['compressed'], + success(result) { + resolve((result.tempFiles || []).map(file => file && file.tempFilePath).filter(Boolean).slice(0, normalizedCount)) + }, + fail(error) { + const message = error && error.errMsg ? error.errMsg : '' + if (message.includes('cancel')) { + resolve([]) + return + } + reject(new Error(`选择图片失败:${message || '未知错误'}`)) + } + }) + }) +} + function normalizeDuration(value) { const duration = Number(value) return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0 @@ -137,12 +254,35 @@ function hasBusyConflict(startMinute, endMinute, ranges) { return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute) } +function resolveBusinessHours(calendar) { + const source = calendar || {} + const parts = String(source.businessHours || '').split('-') + const start = String(source.businessStartTime || parts[0] || '').trim() + const end = String(source.businessEndTime || parts[1] || '').trim() + const valid = value => { + if (!/^\d{1,2}:[0-5]\d$/.test(value)) return false + const hour = Number(value.split(':')[0]) + return hour >= 0 && hour <= 23 + } + if (!valid(start) || !valid(end) || dateUtil.minutesOfDay(end) <= dateUtil.minutesOfDay(start)) { + return { start: '', end: '' } + } + return { start, end } +} + function buildAvailableTimeGroups(calendar, form, durationMinutes) { const schedules = (calendar.schedules || []) .filter(item => String(item.artistId) === String(form.artistId)) .filter(item => item.date === form.appointmentDate) .filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1) const busyRanges = buildBusyRanges(calendar.appointments || [], form) + const today = dateUtil.formatDate(new Date()) + const now = new Date() + const currentMinute = now.getHours() * 60 + now.getMinutes() + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) return [] + const businessStart = dateUtil.minutesOfDay(businessHours.start) + const businessEnd = dateUtil.minutesOfDay(businessHours.end) const groupMap = { morning: { key: 'morning', title: '上午', times: [] }, afternoon: { key: 'afternoon', title: '下午', times: [] }, @@ -152,6 +292,8 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { const scheduleStart = dateUtil.minutesOfDay(extractTimeText(schedule.startTime)) const scheduleEnd = dateUtil.minutesOfDay(extractTimeText(schedule.endTime)) for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) { + if (minute < businessStart || minute + durationMinutes > businessEnd) continue + if (form.appointmentDate < today || (form.appointmentDate === today && minute <= currentMinute)) continue const endMinute = minute + durationMinutes if (!hasBusyConflict(minute, endMinute, busyRanges)) { const period = getTimePeriod(minute) @@ -170,19 +312,27 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { .filter(group => group.times.length > 0) } -function buildUnassignedTimeGroups(durationMinutes) { +function buildUnassignedTimeGroups(durationMinutes, businessStart, businessEnd, appointmentDate) { const groupMap = { morning: { key: 'morning', title: '上午', times: [] }, afternoon: { key: 'afternoon', title: '下午', times: [] }, evening: { key: 'evening', title: '晚上', times: [] } } - const businessStart = dateUtil.minutesOfDay('10:00') - const businessEnd = dateUtil.minutesOfDay('22:00') - for (let minute = businessStart; minute + durationMinutes <= businessEnd; minute += TIME_SLOT_MINUTES) { + if (!businessStart || !businessEnd) return [] + const start = dateUtil.minutesOfDay(businessStart) + const end = dateUtil.minutesOfDay(businessEnd) + if (end <= start) return [] + const now = new Date() + const today = dateUtil.formatDate(now) + const currentMinute = now.getHours() * 60 + now.getMinutes() + for (let minute = start; minute + durationMinutes <= end; minute += TIME_SLOT_MINUTES) { + if (appointmentDate && appointmentDate < today) continue const period = getTimePeriod(minute) groupMap[period.key].times.push({ value: dateUtil.timeFromMinutes(minute), - rangeText: buildTimeRangeLabel(minute, durationMinutes) + rangeText: buildTimeRangeLabel(minute, durationMinutes), + status: appointmentDate === today && minute <= currentMinute ? 'past' : 'available', + statusText: appointmentDate === today && minute <= currentMinute ? '已过时' : '' }) } return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) @@ -192,6 +342,124 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } +function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmentDate) { + const values = [] + if (!businessStart || !businessEnd) return values + const open = dateUtil.minutesOfDay(businessStart) + const close = dateUtil.minutesOfDay(businessEnd) + if (close <= open) return values + const now = new Date() + const today = dateUtil.formatDate(now) + const currentMinute = now.getHours() * 60 + now.getMinutes() + for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) { + if (appointmentDate && appointmentDate < today) continue + values.push({ value: dateUtil.timeFromMinutes(minute), past: appointmentDate === today && minute <= currentMinute }) + } + return values +} + +function buildTimePickerSlots(calendar, form, durationMinutes) { + const schedules = calendar.schedules || [] + const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) return [] + const businessStart = businessHours.start + const businessEnd = businessHours.end + return buildTimeValues(durationMinutes, businessStart, businessEnd, form.appointmentDate).map(time => { + const value = time.value + const startMinute = dateUtil.minutesOfDay(value) + const endMinute = startMinute + durationMinutes + const occupied = hasBusyConflict(startMinute, endMinute, busyRanges) + const scheduled = !form.artistId || schedules.some(schedule => + isScheduleCoveringTime(schedule, form, startMinute, endMinute) + ) + const status = time.past ? 'past' : occupied ? 'occupied' : scheduled ? 'available' : 'off-shift' + return { + value, + hour: Number(value.slice(0, 2)), + minute: Number(value.slice(3, 5)), + rangeText: buildTimeRangeLabel(startMinute, durationMinutes), + status, + statusText: status === 'past' ? '已过时' : status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : '' + } + }) +} + +function buildTimePickerGroups(slots) { + const groupMap = { + morning: { key: 'morning', title: '上午', times: [] }, + afternoon: { key: 'afternoon', title: '下午', times: [] }, + evening: { key: 'evening', title: '晚上', times: [] } + } + ;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot)) + return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) +} + +function buildTimeWheelState(slots, preferredTime) { + if (!slots || slots.length === 0) { + return { + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift' + } + } + const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00') + const firstAvailableSlot = slots.find(slot => slot.status === 'available') + const selectedSlot = preferredSlot && preferredSlot.status === 'available' + ? preferredSlot + : firstAvailableSlot || preferredSlot || slots[0] + const hours = Array.from(new Set(slots.map(slot => slot.hour))) + const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour)) + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute)) + return { + timePickerHours: hours.map(hour => ({ + value: hour, + label: String(hour).padStart(2, '0'), + disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available') + })), + timePickerMinutes: minutes, + timePickerValue: [selectedHourIndex, selectedMinuteIndex], + selectedTimeCandidate: selectedSlot.value, + timePickerCandidateStatus: selectedSlot.status + } +} + +function timeWheelStateForHour(slots, hour, selectedMinute) { + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute)) + return { timePickerMinutes: minutes, selectedMinuteIndex } +} + +function customerCreatedAt(customer) { + return customer.createTime || customer.createdAt || customer.addedAt || '' +} + +function formatCustomerCreatedAt(value) { + if (!value) return '添加时间未知' + return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}` +} + function parseProductTags(product) { if (Array.isArray(product.tagList) && product.tagList.length > 0) { return product.tagList @@ -245,7 +513,8 @@ function normalizeCustomer(customer) { name, phone, displayName: name || phone || '客户', - displayPhone: phone || '未填写手机号' + displayPhone: phone || '未填写手机号', + createdAt: customerCreatedAt(customer) } } @@ -253,21 +522,44 @@ function buildCustomerSelectorItem(customer) { return { ...customer, title: customer.displayName, - subtitle: customer.displayPhone, - badge: '已有客户' + subtitle: formatCustomerCreatedAt(customer.createdAt), + rightText: customer.displayPhone } } function buildArtistSelectorItem(artist) { return { ...artist, - title: artist.name || '未命名员工', + title: artist.name || '未命名美甲师', subtitle: artist.statusText || '可用于指定预约', meta: artist.workStartTime && artist.workEndTime ? `${artist.workStartTime.slice(0, 5)}-${artist.workEndTime.slice(0, 5)}` : '', avatar: artist.avatar || artist.avatarUrl || '/assets/images/default-user-avatar.png' } } +function buildAppointmentDateLabels(value) { + const dateValue = String(value || '') + if (!dateValue) { + return { day: '', badge: '请选择预约日期', long: '请选择预约日期' } + } + const date = new Date(dateValue.replace(/-/g, '/')) + if (Number.isNaN(date.getTime())) { + return { day: '', badge: dateValue, long: dateValue } + } + const today = dateUtil.formatDate(new Date()) + const tomorrow = dateUtil.formatDate(dateUtil.addDays(new Date(), 1)) + const dayLabel = dateValue === today + ? '今天' + : dateValue === tomorrow + ? '明天' + : `周${'日一二三四五六'[date.getDay()]}` + return { + day: dayLabel, + badge: `${dayLabel} · ${dateUtil.formatCnDate(dateValue)}`, + long: `${dayLabel} · ${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日` + } +} + Page({ data: { form: { @@ -276,6 +568,7 @@ Page({ phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '', + amount: '', productId: '', manualProductTitle: '', manualProductPrice: '', @@ -285,18 +578,27 @@ Page({ manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', - durationMinutes: '', + manualProductImages: [], + durationMinutes: '60', + wechatId: '', artistId: '', + createCustomerRecord: false, remark: '' }, - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, + unifiedStyleDescription: '', customerOptions: [], + customerDirectory: [], + businessStartTime: '', + businessEndTime: '', + defaultAppointmentDurationMinutes: 60, + durationManuallyChanged: false, customerSheetVisible: false, customerKeyword: '', + customerViewMode: 'list', + customerNewestFirst: true, + customerSuggestions: [], customerLoading: false, customerError: '', - manualCustomerVisible: false, - manualCustomerForm: { name: '', phone: '' }, products: [], filteredProducts: [], artists: [], @@ -306,59 +608,137 @@ Page({ artistError: '', selectedProduct: {}, selectedProductPriceText: '', + manualProductTitleLength: 0, selectedArtist: {}, productModalVisible: false, - productSelectorMode: 'list', - manualProductMoreExpanded: false, + manualProductSheetVisible: false, + manualProductMoreVisible: false, productKeyword: '', productError: '', loadingProducts: false, conflictTip: '', conflictLevel: 'free', canCreateAppointment: true, + canManageShopSettings: false, draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, + timePickerMode: 'wheel', + timePickerValue: [0, 0], + timePickerHours: [], + timePickerMinutes: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerCandidateStatus: 'off-shift', + selectedTimeCandidate: '', timeLoading: false, timeError: '', + businessHoursMissing: false, timeSelectTip: '请先选择美甲师并填写时长', + appointmentDayLabel: '', + appointmentDateBadge: '', + appointmentDateLong: '', availableTimeGroups: [], loading: false }, - onLoad(options) { + onLoad(options = {}) { + const manualDateMode = options && options.dateMode === 'manual' + const today = dateUtil.formatDate(new Date()) + if (options && options.date && options.date < today) { + this._pendingHistoricalArtistId = options.artistId || '' + this.showBackfillPrompt(options.date, '所选日期已经过去') + return + } const creatable = canCreateAppointment() - const draftForm = creatable && !hasPresetOptions(options) ? readDraftForm() : null - const baseForm = draftForm || {} + let draft = null + if (creatable) { + try { + draft = readDraft() + } catch (error) { + wx.showToast({ title: error.message || '预约草稿读取失败', icon: 'none' }) + } + } + const draftForm = draft && draft.form ? draft.form : {} + const routeDate = options && options.date ? String(options.date) : '' + const routeArtistSelectionId = options && options.artistId ? String(options.artistId) : '' + const routeArtistId = routeArtistSelectionId === '__unassigned__' ? '' : routeArtistSelectionId + const hasRouteCustomer = ['customerUserId', 'customerName', 'wechatId', 'phone'] + .some(key => options && options[key] !== undefined) + const routeDateChanged = Boolean(routeDate && draftForm.appointmentDate && routeDate !== draftForm.appointmentDate) + const draftArtistSelectionId = draft && draft.artistSelectionId === '__unassigned__' + ? '__unassigned__' + : String(draftForm.artistId || '') + const manualProductImages = normalizeManualProductImages(draftForm) + const appointmentDate = routeDate || draftForm.appointmentDate || (manualDateMode ? '' : today) + const appointmentTime = routeDateChanged ? '' : (draftForm.appointmentTime || '') + const dateLabels = buildAppointmentDateLabels(appointmentDate) + this._entryDefaults = { + appointmentDate: routeDate || (manualDateMode ? '' : today), + artistId: routeArtistId, + artistSelectionId: routeArtistSelectionId + } + this._draftReady = false + this._draftPersistenceDisabled = false + this._draftTimer = null this.setData({ canCreateAppointment: creatable, - manualProductDraft: { - title: baseForm.manualProductTitle || '', - price: baseForm.manualProductPrice || '', - description: baseForm.manualProductDescription || '', - tags: baseForm.manualProductTags || '', - targetAudience: baseForm.manualProductTargetAudience || '', - precautions: baseForm.manualProductPrecautions || '', - imageFileIds: baseForm.manualProductImageFileIds || '', - imageUrl: baseForm.manualProductImageUrl || '' - }, + canManageShopSettings: isShopManager(), form: { ...this.data.form, - ...baseForm, - customerName: options.customerName ? decodeURIComponent(options.customerName) : (baseForm.customerName || ''), - phone: options.phone ? decodeURIComponent(options.phone) : (baseForm.phone || ''), - appointmentDate: options.date || baseForm.appointmentDate || dateUtil.formatDate(new Date()), - artistId: options.artistId || baseForm.artistId || '' + ...draftForm, + manualProductImages, + manualProductImageFileIds: manualProductImages.map(image => image.fileId).join(','), + manualProductImageUrl: manualProductImages[0] ? manualProductImages[0].previewUrl || manualProductImages[0].fileUrl : '', + customerUserId: hasRouteCustomer ? String(options.customerUserId || '') : (draftForm.customerUserId || ''), + customerName: hasRouteCustomer ? decodeOptionValue(options.customerName) : (draftForm.customerName || ''), + wechatId: hasRouteCustomer ? decodeOptionValue(options.wechatId) : (draftForm.wechatId || ''), + phone: hasRouteCustomer ? decodeOptionValue(options.phone) : (draftForm.phone || ''), + appointmentDate, + appointmentTime, + artistId: routeArtistId || draftForm.artistId || '' }, - draftSavedAtText: draftForm ? '已恢复本机草稿' : '' + selectedArtist: routeArtistSelectionId === '__unassigned__' || (!routeArtistId && draftArtistSelectionId === '__unassigned__') + ? { id: '__unassigned__', name: '暂不分配美甲师' } + : {}, + durationManuallyChanged: draft && draft.durationManuallyChanged !== undefined + ? Boolean(draft.durationManuallyChanged) + : Boolean(draftForm.durationMinutes && !draftForm.productId && Number(draftForm.durationMinutes) !== 60), + manualProductTitleLength: String(draftForm.manualProductTitle || '').length, + unifiedStyleDescription: String(draftForm.remark || draftForm.manualProductDescription || ''), + draftSavedAtText: draft ? formatDraftStatus('已恢复草稿', draft.savedAt) : '内容变更后自动保存到本机,保留7天', + appointmentDayLabel: dateLabels.day, + appointmentDateBadge: dateLabels.badge, + appointmentDateLong: dateLabels.long }) if (!creatable) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } + this.installDraftAutoSave() + this._draftReady = true this.loadOptions() }, + onHide() { + this.flushDraftSave() + }, + + onShow() { + if (!this._refreshTimesAfterSettings) return + this._refreshTimesAfterSettings = false + this.refreshAvailableTimes() + }, + + openShopSettings() { + if (!this.data.canManageShopSettings) { + wx.showToast({ title: '请联系店长设置门店营业时间', icon: 'none' }) + return + } + this._refreshTimesAfterSettings = true + wx.navigateTo({ url: '/pages/shop-settings/index' }) + }, + async loadOptions() { this.setData({ loadingProducts: true }) try { @@ -377,21 +757,34 @@ Page({ await this.loadArtists() this.refreshProductCards() const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {} - this.setData({ + const selectedProductPatch = { selectedProduct, - selectedProductPriceText: selectedProduct.priceText || '' - }) + selectedProductPriceText: selectedProduct.priceText || '', + unifiedStyleDescription: this.data.unifiedStyleDescription || this.data.form.remark || this.data.form.manualProductDescription || '', + manualProductTitleLength: this.data.form.manualProductTitle + ? String(this.data.form.manualProductTitle).length + : String(selectedProduct.title || '').length + } + if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) { + selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price) + } + this.setData(selectedProductPatch) await this.refreshAvailableTimes() this.checkAvailability() }, async loadArtists(preferredArtistId, fallbackEmployee) { + const unassignedSelection = preferredArtistId === undefined && this.data.selectedArtist.id === '__unassigned__' + ? this.data.selectedArtist + : {} try { const calendar = await planningApi.calendar({ - startDate: this.data.form.appointmentDate, - endDate: this.data.form.appointmentDate + startDate: this.data.form.appointmentDate || dateUtil.formatDate(new Date()), + endDate: this.data.form.appointmentDate || dateUtil.formatDate(new Date()) }) let artists = getCalendarArtists(calendar) + const businessHours = resolveBusinessHours(calendar) + const defaultDuration = Number(calendar.defaultAppointmentDurationMinutes) || 60 const requestedId = preferredArtistId || this.data.form.artistId if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) { artists = artists.concat({ @@ -400,28 +793,79 @@ Page({ avatar: fallbackEmployee.avatar || '' }) } - const selectedArtist = requestedId ? findArtist(artists, requestedId) : {} + const selectedArtist = requestedId + ? findArtist(artists, requestedId) + : unassignedSelection this.setData({ + businessStartTime: businessHours.start, + businessEndTime: businessHours.end, + defaultAppointmentDurationMinutes: defaultDuration, + ...(!this.data.durationManuallyChanged && !this.data.form.productId && !this.data.form.appointmentTime + ? { 'form.durationMinutes': String(defaultDuration) } + : {}), artists, artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword), selectedArtist, artistError: '', - 'form.artistId': selectedArtist.id || '' + 'form.artistId': selectedArtist.id === '__unassigned__' ? '' : selectedArtist.id || '' }) this.refreshProductCards() } catch (error) { this.setData({ artists: [], - artistSelectorItems: [], - selectedArtist: {}, + artistSelectorItems: this.filterArtistItems([], this.data.artistKeyword), + businessStartTime: '', + businessEndTime: '', + selectedArtist: unassignedSelection, 'form.artistId': '', - artistError: error.message || '员工列表加载失败', + artistError: error.message || '美甲师列表加载失败', conflictTip: error.message || '美甲师列表加载失败', conflictLevel: 'danger' }) } }, + async loadCustomerDirectory() { + this.setData({ customerLoading: true }) + try { + const size = 100 + const rows = [] + let page = 1 + let total = Number.POSITIVE_INFINITY + while (rows.length < total) { + const result = await customersApi.listForAppointment({ page, size }) + const currentRows = Array.isArray(result) ? result : (result.list || []) + rows.push(...currentRows) + if (!Array.isArray(result) && Number.isFinite(Number(result.total))) { + total = Number(result.total) + } else if (currentRows.length < size) { + total = rows.length + } + if (currentRows.length === 0) break + page += 1 + } + const directory = rows.map(normalizeCustomer) + this.setData({ + customerDirectory: directory, + customerOptions: this.sortCustomerOptions(directory), + customerError: '' + }) + this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) + } catch (error) { + this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + } finally { + this.setData({ customerLoading: false }) + } + }, + + sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) { + return (customers || []).slice().sort((left, right) => { + const leftDate = String(left.createdAt || '') + const rightDate = String(right.createdAt || '') + return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate) + }).map(buildCustomerSelectorItem) + }, + onInput(event) { const field = event.currentTarget.dataset.field const patch = { @@ -429,11 +873,104 @@ Page({ } this.setData(patch) if (field === 'durationMinutes') { + this.setData({ durationManuallyChanged: true }) this.refreshAvailableTimes() this.checkAvailability() } }, + onStyleTitleInput(event) { + const patch = { + 'form.manualProductTitle': event.detail.value, + manualProductTitleLength: String(event.detail.value || '').length + } + if (this.data.form.productId) { + patch['form.productId'] = '' + patch.selectedProduct = {} + patch.selectedProductPriceText = '' + patch['form.manualProductDescription'] = this.data.unifiedStyleDescription || '' + Object.assign(patch, buildManualProductImagePatch([])) + } + this.setData(patch) + }, + + onUnifiedStyleDescriptionInput(event) { + const description = event.detail.value || '' + const patch = { + unifiedStyleDescription: description, + 'form.remark': description + } + if (!this.data.form.productId) { + patch['form.manualProductDescription'] = description + } + this.setData(patch) + }, + + onCustomerInput(event) { + const field = event.currentTarget.dataset.field + const patch = { + [`form.${field}`]: event.detail.value, + 'form.customerUserId': '', + 'form.createCustomerRecord': false + } + this.setData({ + ...patch + }) + const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName + const phone = field === 'phone' ? event.detail.value : this.data.form.phone + this.refreshCustomerSuggestions(customerName, phone) + }, + + refreshCustomerSuggestions(nameValue, phoneValue) { + const name = String(nameValue || '').trim().toLowerCase() + const phone = String(phoneValue || '').trim().toLowerCase() + if (!name && !phone) { + this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1 + clearTimeout(this._suggestionTimer) + this.setData({ customerSuggestions: [] }) + return + } + const suggestions = this.data.customerDirectory + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: suggestions }) + const requestSeq = (this._customerSuggestionSeq || 0) + 1 + this._customerSuggestionSeq = requestSeq + clearTimeout(this._suggestionTimer) + this._suggestionTimer = setTimeout(async () => { + try { + const result = await customersApi.listForAppointment({ page: 1, size: 50, keyword: name || phone }) + if (requestSeq !== this._customerSuggestionSeq) return + const rows = Array.isArray(result) ? result : (result.list || []) + const remoteSuggestions = rows.map(normalizeCustomer) + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: remoteSuggestions }) + } catch (error) { + if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) { + this.setData({ customerSuggestions: [] }) + } + } + }, 240) + }, + + selectCustomerSuggestion(event) { + const index = Number(event.currentTarget.dataset.index) + const customer = this.data.customerSuggestions[index] + if (!customer) return + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone || '', + 'form.createCustomerRecord': false, + customerSuggestions: [], + customerSheetVisible: false, + customerKeyword: '' + }) + }, + openCustomerSheet() { this.setData({ customerSheetVisible: true }) this.searchCustomers(this.data.customerKeyword) @@ -455,22 +992,24 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() - this.setData({ customerLoading: true }) - try { - const data = await customersApi.list({ keyword, page: 1, size: 20 }) - const list = data.list || data || [] - this.setData({ - customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem), - customerError: '' - }) - } catch (error) { - this.setData({ - customerOptions: [], - customerError: error.message || '客户列表加载失败' - }) - } finally { - this.setData({ customerLoading: false }) - } + if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) + ) + this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + }, + + changeCustomerView(event) { + this.setData({ customerViewMode: event.detail.mode || 'list' }) + }, + + toggleCustomerSort() { + const customerNewestFirst = !this.data.customerNewestFirst + const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) + ) + this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) }, retryCustomerSearch() { @@ -485,55 +1024,170 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone, + 'form.phone': customer.phone || '', + 'form.createCustomerRecord': false, customerSheetVisible: false, - customerKeyword: '' - }) - }, - - openManualCustomer() { - this.setData({ - customerSheetVisible: false, - manualCustomerVisible: true, - manualCustomerForm: { - name: this.data.form.customerName || '', - phone: this.data.form.phone || '' - } - }) - }, - - closeManualCustomer() { - this.setData({ manualCustomerVisible: false }) - }, - - onManualCustomerInput(event) { - this.setData({ [`manualCustomerForm.${event.currentTarget.dataset.field}`]: event.detail.value }) - }, - - useManualCustomer() { - const name = String(this.data.manualCustomerForm.name || '').trim() - const phone = String(this.data.manualCustomerForm.phone || '').trim() - if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) - return - } - if (!/^1[3-9]\d{9}$/.test(phone)) { - wx.showToast({ title: '请输入正确手机号', icon: 'none' }) - return - } - this.setData({ - 'form.customerUserId': '', - 'form.customerName': name, - 'form.phone': phone, - manualCustomerVisible: false, - customerKeyword: '' + customerKeyword: '', + customerSuggestions: [] }) }, onUnload() { + this.flushDraftSave() if (this._customerTimer) { clearTimeout(this._customerTimer) } + if (this._suggestionTimer) { + clearTimeout(this._suggestionTimer) + } + }, + + installDraftAutoSave() { + if (this._draftSetDataInstalled) return + const setData = this.setData.bind(this) + this.setData = (patch, callback) => { + const formChanged = patch && Object.keys(patch).some(key => key === 'form' || key.startsWith('form.')) + const result = setData(patch, callback) + if (formChanged) this.scheduleDraftSave() + return result + } + this._draftSetDataInstalled = true + }, + + scheduleDraftSave() { + if (!this._draftReady || this._draftPersistenceDisabled) return + if (this._draftTimer) clearTimeout(this._draftTimer) + this._draftTimer = setTimeout(() => { + this._draftTimer = null + this.persistDraft(false) + }, DRAFT_SAVE_DELAY_MS) + }, + + cancelDraftSave() { + if (this._draftTimer) clearTimeout(this._draftTimer) + this._draftTimer = null + }, + + flushDraftSave() { + if (!this._draftTimer) return + this.cancelDraftSave() + this.persistDraft(false) + }, + + persistDraft(showToast) { + try { + if (!hasDraftContent( + this.data.form, + this._entryDefaults || {}, + this.data.selectedArtist, + this.data.defaultAppointmentDurationMinutes + )) { + removeDraftForm() + this.setData({ draftSavedAtText: '内容变更后自动保存到本机,保留7天' }) + if (showToast) wx.showToast({ title: '当前没有需要保存的内容', icon: 'none' }) + return false + } + const savedAt = writeDraftForm( + this.data.form, + this.data.selectedArtist && this.data.selectedArtist.id, + this.data.durationManuallyChanged + ) + this.setData({ draftSavedAtText: formatDraftStatus(showToast ? '草稿已手动保存' : '草稿已自动保存', savedAt) }) + if (showToast) wx.showToast({ title: '草稿已保存', icon: 'success' }) + return true + } catch (error) { + this.setData({ draftSavedAtText: '草稿保存失败,请点击保存草稿重试' }) + if (showToast) wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) + return false + } + }, + + async resetForm() { + if (this.data.loading) { + wx.showToast({ title: '预约正在提交,请稍后再恢复默认值', icon: 'none' }) + return + } + if (this.data.manualImageUploading) { + wx.showToast({ title: '图片上传中,请稍后再恢复默认值', icon: 'none' }) + return + } + const result = await new Promise(resolve => wx.showModal({ + title: '恢复默认值', + content: '将清除本表单内容和本机草稿,但不会删除已上传图片文件。保留日历带入的日期和美甲师,确定继续吗?', + cancelText: '继续填写', + confirmText: '恢复默认', + success: resolve, + fail: () => resolve({ confirm: false }) + })) + if (!result.confirm) return + this.cancelDraftSave() + try { + removeDraftForm() + } catch (error) { + wx.showToast({ title: error.message || '草稿清理失败,请稍后重试', icon: 'none' }) + return + } + const defaults = this._entryDefaults || {} + const appointmentDate = defaults.appointmentDate || '' + const artistId = defaults.artistId || '' + const artistSelectionId = defaults.artistSelectionId || artistId + const durationMinutes = String(this.data.defaultAppointmentDurationMinutes || 60) + const selectedArtist = artistSelectionId === '__unassigned__' + ? { id: '__unassigned__', name: '暂不分配美甲师' } + : artistId ? findArtist(this.data.artists, artistId) : {} + const dateLabels = buildAppointmentDateLabels(appointmentDate) + this._draftPersistenceDisabled = true + this.setData({ + form: { + ...this.data.form, + customerUserId: '', + customerName: '', + phone: '', + wechatId: '', + appointmentDate, + appointmentTime: '', + amount: '', + productId: '', + manualProductTitle: '', + manualProductPrice: '', + manualProductDescription: '', + manualProductTags: '', + manualProductTargetAudience: '', + manualProductPrecautions: '', + manualProductImageFileIds: '', + manualProductImageUrl: '', + manualProductImages: [], + durationMinutes, + artistId: artistSelectionId === '__unassigned__' ? '' : artistId, + createCustomerRecord: false, + remark: '' + }, + selectedProduct: {}, + selectedProductPriceText: '', + selectedArtist, + customerSuggestions: [], + customerKeyword: '', + durationManuallyChanged: false, + manualProductTitleLength: 0, + unifiedStyleDescription: '', + draftSavedAtText: '已恢复默认值;后续修改会自动保存到本机', + appointmentDayLabel: dateLabels.day, + appointmentDateBadge: dateLabels.badge, + appointmentDateLong: dateLabels.long, + conflictTip: '', + conflictLevel: 'free', + timeError: '', + selectedTimeCandidate: '', + timeSheetVisible: false, + timePickerMode: 'wheel', + manualProductSheetVisible: false, + manualProductMoreVisible: false, + productModalVisible: false, + customerSheetVisible: false, + artistSheetVisible: false + }) + this._draftPersistenceDisabled = false + await this.refreshAvailableTimes() }, async onDateChange(event) { @@ -543,7 +1197,7 @@ Page({ const result = await new Promise(resolve => { wx.showModal({ title: '历史日期不能新建预约', - content: '之前的日期只能作为历史补单记录,不会校验员工排班,也不会占用预约时段。', + content: '之前的日期只能作为历史补单记录,不会校验美甲师排班,也不会占用预约时段。', cancelText: '取消', confirmText: '去补单', success: resolve, @@ -559,9 +1213,13 @@ Page({ } return } + const dateLabels = buildAppointmentDateLabels(nextDate) this.setData({ 'form.appointmentDate': nextDate, - 'form.appointmentTime': '' + 'form.appointmentTime': '', + appointmentDayLabel: dateLabels.day, + appointmentDateBadge: dateLabels.badge, + appointmentDateLong: dateLabels.long }) await this.loadArtists() await this.refreshAvailableTimes() @@ -582,29 +1240,81 @@ Page({ openProductModal() { this.refreshProductCards() - this.setData({ productModalVisible: true, productSelectorMode: 'list' }) + this.setData({ productModalVisible: true, manualProductSheetVisible: false }) }, closeProductModal() { - this.setData({ productModalVisible: false, productSelectorMode: 'list' }) + this.setData({ productModalVisible: false }) }, openManualProduct() { - this.setData({ productSelectorMode: 'manual', manualProductMoreExpanded: false }) + this.setData({ + productModalVisible: false, + manualProductSheetVisible: true, + manualProductMoreVisible: false, + unifiedStyleDescription: this.data.form.remark || this.data.form.manualProductDescription || this.data.unifiedStyleDescription || '', + manualProductTitleLength: this.data.form.productId + ? String(this.data.selectedProduct.title || '').length + : String(this.data.form.manualProductTitle || '').length + }) }, - backToProductList() { - this.setData({ productSelectorMode: 'list' }) - this.refreshProductCards() + openManualProductFromLibrary() { + const patch = { + 'form.productId': '', + selectedProduct: {}, + selectedProductPriceText: '', + unifiedStyleDescription: this.data.form.remark || this.data.form.manualProductDescription || this.data.unifiedStyleDescription || '', + manualProductTitleLength: String(this.data.form.manualProductTitle || '').length, + productModalVisible: false, + manualProductSheetVisible: true, + manualProductMoreVisible: false + } + if (this.data.form.productId) { + patch['form.manualProductTitle'] = '' + patch['form.manualProductDescription'] = this.data.unifiedStyleDescription || '' + patch.manualProductTitleLength = 0 + } + this.setData(patch) }, - onManualProductInput(event) { - const field = event.detail.field - this.setData({ [`manualProductDraft.${field}`]: event.detail.value }) + closeManualProduct() { + this.setData({ manualProductSheetVisible: false }) }, toggleManualProductMore() { - this.setData({ manualProductMoreExpanded: !this.data.manualProductMoreExpanded }) + this.setData({ manualProductMoreVisible: !this.data.manualProductMoreVisible }) + }, + + confirmManualProduct() { + if (!this.data.form.productId) { + const hasTitle = Boolean(String(this.data.form.manualProductTitle || '').trim()) + const hasImage = (this.data.form.manualProductImages || []).length > 0 || Boolean(String(this.data.form.manualProductImageFileIds || '').trim()) + const hasFallbackName = Boolean(String(this.data.form.customerName || '').trim()) + if (!hasTitle && !hasImage && !hasFallbackName) { + wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }) + return + } + } + const amountText = String(this.data.form.amount === undefined || this.data.form.amount === null ? '' : this.data.form.amount).trim() + const amount = Number(amountText) + if (!amountText || !Number.isFinite(amount) || amount < 0) { + wx.showToast({ title: '请输入不小于0的预约金额', icon: 'none' }) + return + } + if (!normalizeDuration(this.data.form.durationMinutes)) { + wx.showToast({ title: '请输入大于0分钟的预计时长', icon: 'none' }) + return + } + if (this.data.form.productId) { + this.setData({ manualProductSheetVisible: false }) + this.refreshAvailableTimes() + this.checkAvailability() + return + } + this.setData({ 'form.productId': '', selectedProduct: {}, selectedProductPriceText: '', manualProductSheetVisible: false }) + this.refreshAvailableTimes() + this.checkAvailability() }, stopTap() { @@ -624,7 +1334,8 @@ Page({ this.setData({ selectedProduct, selectedProductPriceText: selectedProduct.priceText || '', - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, + unifiedStyleDescription: this.data.form.remark || '', + manualProductTitleLength: String(selectedProduct.title || '').length, 'form.productId': selectedProduct.id, 'form.manualProductTitle': '', 'form.manualProductPrice': '', @@ -634,34 +1345,10 @@ Page({ 'form.manualProductPrecautions': '', 'form.manualProductImageFileIds': '', 'form.manualProductImageUrl': '', - 'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '') - }) - this.closeProductModal() - this.refreshAvailableTimes() - this.checkAvailability() - }, - - useManualProduct() { - const draft = this.data.manualProductDraft - const title = String(draft.title || '').trim() - const priceText = String(draft.price === undefined ? '' : draft.price).trim() - const price = Number(priceText) - if (!title || !priceText || !Number.isFinite(price) || price < 0) { - wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' }) - return - } - this.setData({ - selectedProduct: {}, - selectedProductPriceText: `¥${price}`, - 'form.productId': '', - 'form.manualProductTitle': title, - 'form.manualProductPrice': String(price), - 'form.manualProductDescription': String(draft.description || '').trim(), - 'form.manualProductTags': String(draft.tags || '').trim(), - 'form.manualProductTargetAudience': String(draft.targetAudience || '').trim(), - 'form.manualProductPrecautions': String(draft.precautions || '').trim(), - 'form.manualProductImageFileIds': String(draft.imageFileIds || ''), - 'form.manualProductImageUrl': String(draft.imageUrl || '') + 'form.manualProductImages': [], + 'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price), + 'form.durationMinutes': String(selectedDuration || this.data.defaultAppointmentDurationMinutes || 60), + durationManuallyChanged: false }) this.closeProductModal() this.refreshAvailableTimes() @@ -672,22 +1359,39 @@ Page({ if (this.data.manualImageUploading) { return } + const remainingCount = 9 - (this.data.form.manualProductImages || []).length + if (remainingCount <= 0) { + wx.showToast({ title: '最多添加9张图片', icon: 'none' }) + return + } try { - const filePath = await chooseImageFilePath() - if (!filePath) { + this.setData({ manualImageUploading: true }) + const filePaths = await chooseManualProductImagePaths(remainingCount) + if (!filePaths.length) { return } - this.setData({ manualImageUploading: true }) - const uploadResult = await uploadObjectFile(filePath) - const fileId = uploadResult.id || uploadResult.fileId - const fileUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath - if (!fileId) { - throw new Error('作品图片上传成功但未返回文件ID') + for (const filePath of filePaths) { + const uploadResult = await uploadObjectFile(filePath) + const fileId = uploadResult.id || uploadResult.fileId + const fileUrl = uploadResult.fileUrl || uploadResult.primaryUrl || '' + if (!fileId) { + throw new Error('作品图片上传成功但未返回文件ID') + } + const images = (this.data.form.manualProductImages || []).concat({ + fileId: String(fileId), + fileUrl, + previewUrl: filePath + }).slice(0, 9) + this.setData({ + ...buildManualProductImagePatch(images), + 'form.productId': '', + selectedProduct: {}, + selectedProductPriceText: '' + }) + } + if (filePaths.length > 1) { + wx.showToast({ title: `已添加${filePaths.length}张图片`, icon: 'success' }) } - this.setData({ - 'manualProductDraft.imageFileIds': String(fileId), - 'manualProductDraft.imageUrl': fileUrl - }) } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { @@ -695,11 +1399,28 @@ Page({ } }, - removeManualProductImage() { - this.setData({ - 'manualProductDraft.imageFileIds': '', - 'manualProductDraft.imageUrl': '' - }) + onManualProductImageError(event) { + const index = Number(event && event.currentTarget && event.currentTarget.dataset.index) + const images = this.data.form.manualProductImages || [] + const image = images[index] + if (!Number.isInteger(index) || !image || !image.previewUrl || !image.fileUrl || image.previewUrl === image.fileUrl) { + return + } + const fallbackImages = images.slice() + fallbackImages[index] = { ...image, previewUrl: image.fileUrl } + this.setData(buildManualProductImagePatch(fallbackImages)) + }, + + removeManualProductImage(event) { + if (this.data.manualImageUploading) { + return + } + const index = Number(event && event.currentTarget && event.currentTarget.dataset.index) + const images = this.data.form.manualProductImages || [] + if (!Number.isInteger(index) || index < 0 || index >= images.length) { + return + } + this.setData(buildManualProductImagePatch(images.filter((image, imageIndex) => imageIndex !== index))) }, filterArtistItems(artists, keywordValue) { @@ -708,7 +1429,7 @@ Page({ .filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword)) .map(buildArtistSelectorItem) if (!keyword || '暂不分配'.includes(keyword)) { - items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配员工', badge: '待分配' }) + items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配美甲师', badge: '待分配' }) } return items }, @@ -740,7 +1461,7 @@ Page({ const selectedArtist = event.detail.item || {} if (selectedArtist.id === '__unassigned__') { this.setData({ - selectedArtist: {}, + selectedArtist: { id: '__unassigned__', name: '暂不分配美甲师' }, 'form.artistId': '', artistSheetVisible: false, conflictTip: '', @@ -784,7 +1505,7 @@ Page({ selectedArtist: {}, 'form.artistId': '', 'form.appointmentTime': originalTime, - conflictTip: `${availability.tip || '新员工当前排班无法承接'},预约已保持待分配`, + conflictTip: `${availability.tip || '新美甲师当前排班无法承接'},预约已保持待分配`, conflictLevel: 'danger' }) } @@ -808,7 +1529,15 @@ Page({ if (!form.appointmentDate || !durationMinutes) { const patch = { availableTimeGroups: [], + timePickerGroups: [], + timePickerSlots: [], + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift', timeError: '', + businessHoursMissing: false, timeSelectTip: '请先填写预约日期和时长' } if (form.appointmentTime) { @@ -818,18 +1547,69 @@ Page({ return } if (!form.artistId) { - const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes) - this.setData({ - availableTimeGroups, - timeError: '', - timeLoading: false, - timeSelectTip: '请选择预约时间,员工可稍后分配' - }) + this.setData({ timeLoading: true, timeError: '', timeSelectTip: '正在加载营业时间...' }) + try { + const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate }) + if (requestSeq !== this._availableTimeRequestSeq) return + const businessHours = resolveBusinessHours(calendar) + const businessStartTime = businessHours.start + const businessEndTime = businessHours.end + if (!businessStartTime) { + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: '门店营业时间尚未设置,请先完成设置', + businessHoursMissing: true, + timeLoading: false, + timeSelectTip: '请先设置门店营业时间' + }) + return + } + this.setData({ businessStartTime, businessEndTime }) + const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes, businessStartTime, businessEndTime, form.appointmentDate) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) + this.setData({ + availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), + timeError: '', + businessHoursMissing: false, + timeLoading: false, + timeSelectTip: availableTimeGroups.length ? '请选择预约时间,美甲师可稍后分配' : '当前日期没有可选时段' + }) + } catch (error) { + if (requestSeq === this._availableTimeRequestSeq) { + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: error.message || '营业时间加载失败', + businessHoursMissing: false, + timeLoading: false, + timeSelectTip: '营业时间加载失败' + }) + } + } return } this.setData({ timeLoading: true, timeError: '', + businessHoursMissing: false, timeSelectTip: '正在计算可约时间...' }) try { @@ -841,10 +1621,35 @@ Page({ if (requestSeq !== this._availableTimeRequestSeq) { return } + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) { + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: '门店营业时间尚未设置,请先完成设置', + businessHoursMissing: true, + timeLoading: false, + timeSelectTip: '请先设置门店营业时间' + }) + return + } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) const patch = { availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), + timeError: '', + businessHoursMissing: false, timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { @@ -856,8 +1661,17 @@ Page({ return } this.setData({ + businessStartTime: '', + businessEndTime: '', availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', timeError: error.message || '可约时间加载失败', + businessHoursMissing: false, timeSelectTip: '可约时间加载失败' }) } finally { @@ -872,7 +1686,7 @@ Page({ wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' }) return } - this.setData({ timeSheetVisible: true }) + this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' }) await this.refreshAvailableTimes() }, @@ -882,16 +1696,85 @@ Page({ selectAvailableTime(event) { const value = event.currentTarget.dataset.value - this.setData({ - 'form.appointmentTime': value, - timeSheetVisible: false - }) - this.checkAvailability() + const slot = this.data.timePickerSlots.find(item => item.value === value) + if (!slot || slot.status !== 'available') { + if (slot && slot.status === 'past') { + this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去') + return + } + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status }) }, - async checkAvailability() { + onTimePickerModeChange(event) { + this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' }) + }, + + onTimePickerChange(event) { + const values = event.detail.value || [0, 0] + const hourItem = this.data.timePickerHours[values[0]] + if (!hourItem) return + const hour = Number(hourItem.value) + const minuteIndex = Number(values[1] || 0) + const minuteItem = this.data.timePickerMinutes[minuteIndex] + const minute = minuteItem ? Number(minuteItem.value) : 0 + const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute) + this.setData({ + timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex], + timePickerMinutes: nextMinutes.timePickerMinutes, + selectedTimeCandidate: candidate, + timePickerCandidateStatus: slot ? slot.status : 'off-shift' + }) + }, + + confirmTimeSelection() { + const candidate = this.data.selectedTimeCandidate + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + if (!slot || slot.status !== 'available') { + if (slot && slot.status === 'past') { + this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去') + return + } + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.checkAvailability(candidate).then(availability => { + if (!availability.ok) { + wx.showToast({ + title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约', + icon: 'none' + }) + return + } + this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false }) + this.checkAvailability() + }) + }, + + async showBackfillPrompt(serviceDate, reason = '该日期或时段已过去') { + const result = await new Promise(resolve => wx.showModal({ + title: '转为历史补单', + content: `${reason},普通预约不能使用过去时间。可以前往补录历史订单,或取消继续选择未来时间。`, + cancelText: '取消', + confirmText: '去补录', + success: resolve, + fail: () => resolve({ confirm: false }) + })) + if (!result.confirm) return + const query = [`serviceDate=${encodeURIComponent(serviceDate || dateUtil.formatDate(new Date()))}`] + const artistId = this.data.form.artistId || this._pendingHistoricalArtistId + if (artistId) query.push(`artistId=${encodeURIComponent(artistId)}`) + wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` }) + }, + + async checkAvailability(candidateTime) { const form = this.data.form - if (!form.appointmentDate || !form.appointmentTime) { + const appointmentTime = candidateTime || form.appointmentTime + if (!form.appointmentDate || !appointmentTime) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } @@ -900,15 +1783,29 @@ Page({ this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } - const startMinute = dateUtil.minutesOfDay(form.appointmentTime) + const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes - if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) { - const tip = '该时间超出营业时间 10:00-22:00' + if (!this.data.businessStartTime || !this.data.businessEndTime) { + const tip = this.data.businessHoursMissing + ? '门店营业时间尚未设置,请先完成设置' + : '营业时间暂不可用,请稍后重试' + this.setData({ conflictTip: tip, conflictLevel: 'danger' }) + return { ok: false, tip } + } + if (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime)) { + const tip = `该时间超出营业时间 ${this.data.businessStartTime}-${this.data.businessEndTime}` + this.setData({ conflictTip: tip, conflictLevel: 'danger' }) + return { ok: false, tip } + } + const now = new Date() + const today = dateUtil.formatDate(now) + if (form.appointmentDate < today || (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes())) { + const tip = '该时间已过,请改选未来时段或使用历史补单' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } if (!form.artistId) { - const tip = '预约将保存为待分配,当前不会占用员工时间' + const tip = '预约将保存为待分配,当前不会占用美甲师时间' this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } @@ -939,7 +1836,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { @@ -949,19 +1846,141 @@ Page({ } }, + async ensureCustomerBeforeSubmit() { + const name = String(this.data.form.customerName || '').trim() + const phone = String(this.data.form.phone || '').trim() + const wechatId = String(this.data.form.wechatId || '').trim() + if (!name && (phone || wechatId)) { + this.setData({ 'form.createCustomerRecord': false }) + wx.showToast({ title: '填写联系方式时请同时填写客户姓名', icon: 'none' }) + return false + } + if (!name) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } + if (!name) { + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) + return false + } + if (phone && !/^1[3-9]\d{9}$/.test(phone)) { + wx.showToast({ title: '请输入正确手机号', icon: 'none' }) + return false + } + if (this.data.form.customerUserId) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } + + this.setData({ loading: true }) + try { + const matches = await customersApi.matchIdentityForAppointment(name, wechatId || undefined, phone || undefined) + if (matches.length > 1) { + const choice = await new Promise(resolve => { + wx.showModal({ + title: '找到多个同名客户', + content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。', + cancelText: '不关联提交', + confirmText: '选择客户', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } + this.setData({ + customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), + customerKeyword: name, + customerSheetVisible: true + }) + return false + } + if (matches.length > 0) { + const customer = normalizeCustomer(matches[0]) + const choice = await new Promise(resolve => { + wx.showModal({ + title: '客户已存在', + content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, + cancelText: '不关联提交', + confirmText: '使用已有', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (choice.confirm) { + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false + }) + } else { + this.setData({ 'form.createCustomerRecord': false }) + } + return true + } + + const createChoice = await new Promise(resolve => { + wx.showModal({ + title: '新建客户', + content: '系统中没有匹配客户,是否新建到客户档案?', + cancelText: '不新建', + confirmText: '确认', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) + return true + } catch (error) { + wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) + return false + } finally { + this.setData({ loading: false }) + } + }, + async submit() { + if (this.data.loading) { + return + } if (!this.data.canCreateAppointment) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } - const form = this.data.form - const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() + if (isShopBusinessExpired()) { + await showBusinessExpiryNotice() + return + } + let form = this.data.form + const today = dateUtil.formatDate(new Date()) + const now = new Date() + const selectedMinute = form.appointmentTime ? dateUtil.minutesOfDay(form.appointmentTime) : -1 + if (form.appointmentDate < today || (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes())) { + await this.showBackfillPrompt(form.appointmentDate, form.appointmentDate < today ? '所选日期已经过去' : '所选时段已经过去') + return + } + const manualProductTitle = String(form.manualProductTitle || '').trim() + const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() + const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim()) + const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim() + const amount = Number(amountText) const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } - if (!/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { + if (!Number.isFinite(amount) || amount < 0) { + wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' }) + return + } + if (form.phone && !String(form.customerName || '').trim()) { + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) + return + } + if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return } @@ -978,7 +1997,7 @@ Page({ const result = await new Promise(resolve => { wx.showModal({ title: '保存为待分配预约', - content: '当前未指定员工,预约会正常保存,但不会占用员工时间。可以稍后在预约详情中分配。', + content: '当前未指定美甲师,预约会正常保存,但不会占用美甲师时间。可以稍后在预约详情中分配。', cancelText: '返回选择', confirmText: '继续保存', success: resolve, @@ -987,12 +2006,21 @@ Page({ }) if (!result.confirm) return } + if (!(await this.ensureCustomerBeforeSubmit())) { + return + } + form = this.data.form this.setData({ loading: true }) try { const payload = { ...form, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: form.artistId ? String(form.artistId) : undefined, + customerName: String(form.customerName || '').trim() || undefined, + wechatId: String(form.wechatId || '').trim() || undefined, + phone: String(form.phone || '').trim() || undefined, + amount, + createCustomerRecord: Boolean(form.createCustomerRecord), durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } @@ -1002,8 +2030,8 @@ Page({ payload.manualProductPrice = undefined } else { payload.productId = undefined - payload.manualProductTitle = String(form.manualProductTitle || '').trim() - payload.manualProductPrice = Number(form.manualProductPrice) + payload.manualProductTitle = manualProductTitle || undefined + payload.manualProductPrice = amount payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined @@ -1011,34 +2039,34 @@ Page({ payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined } const result = await planningApi.createAppointment(payload) - removeDraftForm() + this.cancelDraftSave() + this._draftReady = false + this._draftPersistenceDisabled = true + try { + removeDraftForm() + } catch (error) { + console.warn('预约已创建,但草稿清理失败', error) + } markPlanningRefresh() wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` }) } catch (error) { - wx.showToast({ title: error.message || '提交失败', icon: 'none' }) + if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) { + await showBusinessExpiryNotice() + } else { + wx.showToast({ title: error.message || '提交失败', icon: 'none' }) + } } finally { this.setData({ loading: false }) } }, saveDraft() { - try { - writeDraftForm(this.data.form) - this.setData({ draftSavedAtText: '草稿已保存到本机' }) - wx.showToast({ title: '草稿已保存', icon: 'success' }) - } catch (error) { - wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) - } + this.cancelDraftSave() + this.persistDraft(true) }, - clearDraft() { - try { - removeDraftForm() - this.setData({ draftSavedAtText: '' }) - wx.showToast({ title: '草稿已清空', icon: 'success' }) - } catch (error) { - wx.showToast({ title: error.message || '草稿清空失败', icon: 'none' }) - } + onSelectedProductImageError() { + this.setData({ 'selectedProduct.coverImage': '' }) }, back() { diff --git a/JC-Salon-WeChat/pages/appointment-form/index.json b/JC-Salon-WeChat/pages/appointment-form/index.json index 263a301f..28a971f8 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.json +++ b/JC-Salon-WeChat/pages/appointment-form/index.json @@ -1,5 +1,5 @@ { - "navigationBarTitleText": "新建预约", + "navigationBarTitleText": "新增预约", "usingComponents": { "entity-selector-sheet": "/components/entity-selector-sheet/index", "product-selector-sheet": "/components/product-selector-sheet/index" diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index b72a8f68..afedb8a1 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,163 +1,153 @@ - - - - 客户 - - - {{form.customerName || '请选择客户'}} - {{form.phone || '搜索已有客户或手动录入'}} - - 已有 - › + + + + NEW APPOINTMENT + 安排一场美甲 + + ◷{{appointmentDateBadge}} + + + + + 美甲款式* + + - - 预约日期 - - {{form.appointmentDate}} - - - - 预约作品 - - - - 预计时长 - - 分钟 - - - 员工(可稍后分配) - - {{selectedArtist.name || '暂不分配'}} - › + + + + ✦ + {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · 本次 {{form.amount || '待填'}} 元 · {{form.durationMinutes || '60'}} 分钟 + - - 预约时间 - - - {{form.appointmentTime || timeSelectTip}} - {{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 - - › + 名称和图片至少填写一项;名称为空时会使用客户姓名或“散客款式”。 + 手动录入款式在预约提交成功后自动保存到本店款式库,仅门店可见,不会公开展示。 + + + + + 预约信息美甲师可暂不分配,之后再安排 + + + + ▣ + 预约日期{{appointmentDateLong}} + › + + + ◷ + 预约时间{{appointmentDayLabel}} {{form.appointmentTime}} · {{form.durationMinutes}}分钟{{timeSelectTip}}{{selectedArtist.name || '暂不分配美甲师'}} + › - - 备注 -