杂务:整理文档并收口 YumiNail 修复

This commit is contained in:
xiaowang
2026-05-21 18:43:59 +08:00
parent 3797938616
commit 9227ec6175
362 changed files with 8358 additions and 19928 deletions
@@ -0,0 +1,83 @@
---
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
All commands work via `npx` — no global install required.
## Commands
### analyze — Build or refresh the index
```bash
npx gitnexus 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 |
| -------------- | ---------------------------------------------------------------- |
| `--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. |
**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.
### status — Check index freshness
```bash
npx gitnexus 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
npx gitnexus 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
npx gitnexus wiki
```
Generates repository documentation from the knowledge graph using an LLM. Requires an API key (saved to `~/.gitnexus/config.json` on first use).
| Flag | Effect |
| ------------------- | ----------------------------------------- |
| `--force` | Force full regeneration |
| `--model <model>` | LLM model (default: minimax/minimax-m2.5) |
| `--base-url <url>` | LLM API base URL |
| `--api-key <key>` | LLM API key |
| `--concurrency <n>` | Parallel LLM calls (default: 3) |
| `--gist` | Publish wiki as a public GitHub Gist |
### list — Show all indexed repos
```bash
npx gitnexus 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**: Restart Claude Code to reload the MCP server
- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding
@@ -0,0 +1,89 @@
---
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
## Workflow
```
1. gitnexus_query({query: "<error or symptom>"}) → Find related execution flows
2. gitnexus_context({name: "<suspect>"}) → See callers/callees/processes
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow
4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed
```
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] Understand the symptom (error message, unexpected behavior)
- [ ] gitnexus_query for error text or related code
- [ ] Identify the suspect function from returned processes
- [ ] gitnexus_context to see callers and callees
- [ ] Trace execution flow via process resource if applicable
- [ ] gitnexus_cypher for custom call chain traces if needed
- [ ] Read source files to confirm root cause
```
## Debugging Patterns
| Symptom | GitNexus Approach |
| -------------------- | ---------------------------------------------------------- |
| Error message | `gitnexus_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 |
## Tools
**gitnexus_query** — find code related to error:
```
gitnexus_query({query: "payment validation error"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError, PaymentException
```
**gitnexus_context** — full context for a suspect:
```
gitnexus_context({name: "validatePayment"})
→ Incoming calls: processCheckout, webhookHandler
→ Outgoing calls: verifyCard, fetchRates (external API!)
→ Processes: CheckoutFlow (step 3/7)
```
**gitnexus_cypher** — custom call chain traces:
```cypher
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"})
RETURN [n IN nodes(path) | n.name] AS chain
```
## Example: "Payment endpoint returns 500 intermittently"
```
1. gitnexus_query({query: "payment error handling"})
→ Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError
2. gitnexus_context({name: "validatePayment"})
→ 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
```
@@ -0,0 +1,78 @@
---
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
## Workflow
```
1. READ gitnexus://repos → Discover indexed repos
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
3. gitnexus_query({query: "<what you want to understand>"}) → Find related execution flows
4. gitnexus_context({name: "<symbol>"}) → Deep dive on specific symbol
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow
```
> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] READ gitnexus://repo/{name}/context
- [ ] gitnexus_query for the concept you want to understand
- [ ] Review returned processes (execution flows)
- [ ] gitnexus_context on key symbols for callers/callees
- [ ] READ process resource for full execution traces
- [ ] Read source files for implementation details
```
## 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
**gitnexus_query** — find execution flows related to a concept:
```
gitnexus_query({query: "payment processing"})
→ Processes: CheckoutFlow, RefundFlow, WebhookHandler
→ Symbols grouped by flow with file locations
```
**gitnexus_context** — 360-degree view of a symbol:
```
gitnexus_context({name: "validateUser"})
→ Incoming calls: loginHandler, apiMiddleware
→ Outgoing calls: checkToken, getUserById
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3)
```
## Example: "How does payment processing work?"
```
1. READ gitnexus://repo/my-app/context → 918 symbols, 45 processes
2. gitnexus_query({query: "payment processing"})
→ CheckoutFlow: processPayment → validateCard → chargeStripe
→ RefundFlow: initiateRefund → calculateRefund → processRefund
3. gitnexus_context({name: "processPayment"})
→ Incoming: checkoutHandler, webhookHandler
→ Outgoing: validateCard, chargeStripe, saveTransaction
4. Read src/payments/processor.ts for implementation details
```
@@ -0,0 +1,64 @@
---
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 `npx gitnexus 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 |
| `detect_changes` | Git-diff impact — what do your current changes affect |
| `rename` | Multi-file coordinated rename with confidence-tagged edits |
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) |
| `list_repos` | Discover indexed repos |
## 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, Function, Class, Interface, Method, Community, Process
**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS
```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"})
RETURN caller.name, caller.filePath
```
@@ -0,0 +1,97 @@
---
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
## Workflow
```
1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this
2. READ gitnexus://repo/{name}/processes → Check affected execution flows
3. gitnexus_detect_changes() → Map current git changes to affected flows
4. Assess risk and report to user
```
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklist
```
- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents
- [ ] Review d=1 items first (these WILL BREAK)
- [ ] Check high-confidence (>0.8) dependencies
- [ ] READ processes to check affected execution flows
- [ ] gitnexus_detect_changes() for pre-commit check
- [ ] Assess risk level and report to user
```
## 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 |
## Tools
**gitnexus_impact** — the primary tool for symbol blast radius:
```
gitnexus_impact({
target: "validateUser",
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%]
```
**gitnexus_detect_changes** — git-diff based impact analysis:
```
gitnexus_detect_changes({scope: "staged"})
→ Changed: 5 symbols in 3 files
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
→ Risk: MEDIUM
```
## Example: "What breaks if I change validateUser?"
```
1. gitnexus_impact({target: "validateUser", direction: "upstream"})
→ 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
```
@@ -0,0 +1,121 @@
---
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
## Workflow
```
1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents
2. gitnexus_query({query: "X"}) → Find execution flows involving X
3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs
4. Plan update order: interfaces → implementations → callers → tests
```
> If "Index is stale" → run `npx gitnexus analyze` in terminal.
## Checklists
### Rename Symbol
```
- [ ] gitnexus_rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits
- [ ] Review graph edits (high confidence) and ast_search edits (review carefully)
- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits
- [ ] gitnexus_detect_changes() — verify only expected files changed
- [ ] Run tests for affected processes
```
### Extract Module
```
- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs
- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers
- [ ] Define new module interface
- [ ] Extract code, update imports
- [ ] gitnexus_detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
### Split Function/Service
```
- [ ] gitnexus_context({name: target}) — understand all callees
- [ ] Group callees by responsibility
- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update
- [ ] Create new functions/services
- [ ] Update callers
- [ ] gitnexus_detect_changes() — verify affected scope
- [ ] Run tests for affected processes
```
## Tools
**gitnexus_rename** — automated multi-file rename:
```
gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
→ 12 edits across 8 files
→ 10 graph edits (high confidence), 2 ast_search edits (review)
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}]
```
**gitnexus_impact** — map all dependents first:
```
gitnexus_impact({target: "validateUser", direction: "upstream"})
→ d=1: loginHandler, apiMiddleware, testUtils
→ Affected Processes: LoginFlow, TokenRefresh
```
**gitnexus_detect_changes** — verify your changes after refactoring:
```
gitnexus_detect_changes({scope: "all"})
→ Changed: 8 files, 12 symbols
→ Affected processes: LoginFlow, TokenRefresh
→ Risk: MEDIUM
```
**gitnexus_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 gitnexus_rename for automated updates |
| Cross-area refs | Use detect_changes after to verify scope |
| String/dynamic refs | gitnexus_query to find them |
| External/public API | Version and deprecate properly |
## Example: Rename `validateUser` to `authenticateUser`
```
1. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true})
→ 12 edits: 10 graph (safe), 2 ast_search (review)
→ Files: validator.ts, login.ts, middleware.ts, config.json...
2. Review ast_search edits (config.json: dynamic reference!)
3. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false})
→ Applied 12 edits across 8 files
4. gitnexus_detect_changes({scope: "all"})
→ Affected: LoginFlow, TokenRefresh
→ Risk: MEDIUM — run tests for these flows
```
+4
View File
@@ -34,6 +34,8 @@ docs/_book
# TODO: where does this rule come from?
test/
!YumiNail-Core/src/test/
!YumiNail-Core/src/test/**
# ---> Python
# Byte-compiled / optimized / DLL files
@@ -262,6 +264,8 @@ YumiNail-Admin-Program/utils/config.local.js
# Local release/test artifacts
release-packages/
.codex-run/
output/
.codex-temp-*
*.swp
+5 -12
View File
@@ -7,7 +7,6 @@
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="MessageHub" />
<module name="YumiNail-Gateway" />
</profile>
<profile name="Annotation profile for YumiNail-Core" enabled="true">
@@ -15,22 +14,16 @@
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="D:/apache-maven-3.9.9/repository/xiaowang/org/projectlombok/lombok/1.18.30/lombok-1.18.30.jar" />
<entry name="D:/apache-maven-3.9.9/repository/xiaowang/org/projectlombok/lombok/1.18.32/lombok-1.18.32.jar" />
</processorPath>
<module name="YumiNail-Core" />
</profile>
<profile name="Annotation profile for YumiNail-Calendar-Gateway" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="D:/apache-maven-3.9.9/repository/xiaowang/org/projectlombok/lombok/1.18.32/lombok-1.18.32.jar" />
</processorPath>
<module name="YumiNail-Calendar-Gateway" />
<module name="YumiNail-Calendar-Core" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="MessageHub" target="21" />
<module name="YumiNail-Calendar-Core" target="17" />
<module name="YumiNail-Calendar-Gateway" target="17" />
</bytecodeTargetLevel>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
+21
View File
@@ -24,6 +24,7 @@
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.resource.type" value="Deployment" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
@@ -35,6 +36,26 @@
<remarks>$PROJECT_DIR$/YumiNail-Calendar-Core/src/main/resources/application.yaml</remarks>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306/yumi_nail_calendar?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.resource.type" value="Deployment" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="nailart@localhost" uuid="cb963a30-eb87-485a-ae22-aa586856b14a">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<imported>true</imported>
<remarks>$PROJECT_DIR$/YumiNail-Core/src/main/resources/application.yaml</remarks>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306/nailart?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
<property name="com.intellij.clouds.kubernetes.db.container.port" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
-3
View File
@@ -1,9 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/YumiNail-Core/src/main/resources/files/2026-03-20_init_admin_permission_template.sql" dialect="MySQL" />
<file url="file://$PROJECT_DIR$/YumiNail-Core/src/main/resources/files/2026-03-20_user_asset_vip_coupon_permission_patch.sql" dialect="MySQL" />
<file url="file://$PROJECT_DIR$/YumiNail-Core/src/main/resources/files/YumiNail-back.sql" dialect="MySQL" />
<file url="file://$PROJECT_DIR$/YumiNail-Core/src/main/resources/files/YumiNail.sql" dialect="MySQL" />
</component>
</project>
+43
View File
@@ -0,0 +1,43 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **xiaowang** (12294 symbols, 23811 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
+43
View File
@@ -0,0 +1,43 @@
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **xiaowang** (12294 symbols, 23811 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first.
## Always Do
- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user.
- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows.
- **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`.
## Never Do
- NEVER edit a function, class, or method without first running `gitnexus_impact` on it.
- NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope.
## Resources
| Resource | Use for |
|----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace |
## CLI
| Task | Read this skill file |
|------|---------------------|
| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` |
| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` |
| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` |
| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` |
| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` |
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end -->
+219
View File
@@ -0,0 +1,219 @@
# YumiNail 项目记忆文件
这份文件给后续接手本仓库的 AI/开发者快速建立上下文。切换工作区或开启新会话后,优先阅读本文,再看 `README.md`、`YumiNail-Core/src/main/resources/API.md` 和相关源码。
## 1. 项目定位
`E:\code\xiaowang` 是 YumiNail 美甲业务系统主仓库。
当前主链路:
- `YumiNail-Frontend`:Vue 3 Web 前台 + Web 后台管理。
- `WeChatProgram`:微信小程序用户端。
- `YumiNail-Gateway`:Spring Cloud Gateway 主业务网关。
- `YumiNail-Core`:Spring Boot 核心业务服务。
- `YumiNail-Admin-Program`:后台小程序/管理端实验入口,当前不是主要验收面。
已从主仓库移除独立日历实验项目:
- `YumiNail-Calendar-Core`
- `YumiNail-Calendar-Gateway`
- `YumiNail-Calendar-Frontend`
预约日历现在以内置模块存在于 `YumiNail-Core + YumiNail-Frontend`,数据直接来自主系统订单表和订单项表。
## 2. 强约束
- 所有 shell 命令必须带 `rtk` 前缀,例如 `rtk npm run build`、`rtk mvn -q -DskipTests compile`。
- 不新增散落 SQL 文件。结构、补列、索引、权限种子和测试数据都集中到:
- `YumiNail-Core/src/main/resources/files/YumiNail.sql`
- 涉及真实数据库 SQL 时,优先使用 MySQL MCP 执行;如果 MCP 无 DDL 权限,再说明阻塞。
- 不要回滚用户已有改动。这个仓库经常有大量未提交改动,必须按任务范围谨慎编辑。
- 手动改文件优先用 `apply_patch`。
- Web UI 风格偏“柔和浅粉白”,不要再混用大量蓝紫、灰、棕色主题。
- 页面文案必须中文,避免出现英文验收/测试提示。
## 3. 当前重要业务状态
### 店长参与制作
- 店长账号保持 `type=2`。
- 通过 `t_nail_artist_info.participate_production` 控制是否参与美甲制作。
- 参与制作的店长会进入可预约人员体系,用户预约时可选择。
- 美甲师管理列表需要展示普通美甲师和参与制作店长。
### VIP 与余额
- `t_balance` 需要同时有:
- `last_update_time`:业务展示字段。
- `update_time`:MyBatis/BaseEntity 通用更新时间字段。
- 之前用户报错 `Unknown column 'update_time'`,已补到 SQL 和真实库。
- VIP 充值配置只展示档位,不接支付、不写余额流水。
- VIP 等级来源优先取启用的 VIP 充值配置中的等级;没有配置时使用默认等级。
### 消息/公告
- 消息通知和公告是两个独立模块。
- 消息通知:
- 可发布文本和单张图片。
- 可弹窗一次,也可在消息通知模块查看。
- 公告:
- 首页顶部滚动展示。
- 不进入消息历史,不弹窗。
- 消息范围/公告范围都支持管理员平台级、店铺级、指定用户;店长只能管理本店范围。
### 地图与店铺位置
- 店铺地图位置展示给用户时只显示地点名称/地址,不显示经纬度。
- 经纬度只作为隐藏数据,用于距离计算、地图预览和导航。
- 管理员在参数管理中配置地图相关 key。
- 当前需求倾向:位置选择与展示主要使用腾讯位置服务;高德主要用于导航跳转,Web Key 和小程序 Key 分开配置。
### 店铺有效期
- `t_shop.authorization_expire_time` 表示授权有效期。
- 为空代表长期有效。
- 到期不改 `status`,而是动态冻结。
- 前台用户登录过期店铺提示“店铺已被冻结”。
- 后台账号可登录,但非平台管理员业务功能禁用,首页提示授权到期。
### 用户关系与自定义角色
- 店长可创建店铺内自定义角色,分配角色名和权限。
- 用户有“店铺 + 直属上级”关系。
- 自注册可填邀请码绑定上级;不填默认归属当前店铺店长。
- 后台用户管理必须多维筛选并注意脱敏。
### 预约日历
- 日历接口在 `YumiNail-Core` 主系统内。
- 数据来自 `t_order`、`t_order_item.artist_id`、`t_order_item.appointment_time`。
- 美甲师和参与制作店长查看自己的预约。
- Web 页面 `/artist-calendar` 是主入口。
- 预约详情可跳转关联订单、展示订单金额,也可跳转用户选择的作品。
## 4. 最近修过的关键坑
- 后台管理员登录后立刻提示过期:
- 后台请求应只使用 `adminAccessToken/adminRefreshToken`。
- `AdminLoginView` 返回前台时不要误删前台 token。
- 图片上传 JPG 被拒:
- 分片上传的 chunk 不能按最终图片 MIME 校验。
- 初始化阶段校验原文件元数据;chunk 只校验非空、大小和危险扩展名。
- JPG MIME 需兼容 `image/jpeg`、`image/jpg`、`image/pjpeg`。
- 优惠券时间保存失败:
- 后端 Jackson 需兼容 `yyyy-MM-dd HH:mm:ss` 和 ISO `yyyy-MM-ddTHH:mm:ss`。
- 小程序作品详情未登录跳登录:
- 作品详情是匿名可访问。
- 只有收藏、加购、下单、评论等动作需要登录。
- 白名单接口返回 401 时不要触发全局“登录过期”跳转。
- 小程序页面不可滚动:
- 只在弹窗遮罩上 `catchtouchmove`。
- 登录页使用可滚动容器,小屏也要能看到按钮。
## 5. 运行与验证命令
后端:
```powershell
rtk mvn -q -DskipTests compile
```
分别在:
- `E:\code\xiaowang\YumiNail-Core`
- `E:\code\xiaowang\YumiNail-Gateway`
Web 前端:
```powershell
rtk npm run build
```
在:
- `E:\code\xiaowang\YumiNail-Frontend`
小程序 JS 语法检查:
```powershell
rtk powershell -NoProfile -Command '& { Get-ChildItem -LiteralPath "WeChatProgram" -Recurse -Filter "*.js" | ForEach-Object { node --check $_.FullName } }'
```
## 6. 数据库与配置
- 真实 datasource 以 Nacos `YumiNail-Dev / DEFAULT_GROUP / datasource.yaml` 为准。
- 用户曾明确要求:不要把生产/开发配置写到本地文件里,涉及配置修改应走 Nacos。
- MySQL MCP 可用于查询和 DML;DDL 可能因权限受限失败,需要确认 MCP 权限。
- 常用校验:
```sql
SELECT COLUMN_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 't_balance'
AND COLUMN_NAME IN ('update_time', 'last_update_time');
```
## 7. 文档与代码风格
- 新手友好注释是用户明确要求过的方向,但不要机械生成无意义注释。
- 推荐注释重点:
- Controller:接口路径、参数用途、调用链。
- Service/ServiceImpl:业务规则、权限边界、关键校验。
- DTO/VO:字段含义和前端调用注意点。
- 避免英文测试文案、英文占位验收数据出现在用户界面。
- 避免大范围重写乱码文件,除非该文件正好在本轮任务范围内。
## 8. Web 前端体验偏好
- 用户端页面参考小程序布局,顶部栏风格统一。
- 作品列表:
- 不要左侧分类栏。
- 使用顶部横向滑动、吸顶标签栏,类似小红书。
- 作品详情:
- 图片可点击放大。
- 详情信息保持高密度,重点展示所属门店、可约美甲师。
- 分享链接无需登录即可查看详情。
- 我的订单:
- 订单号支持一键复制。
- 提供多维筛选。
- 后台:
- 侧边栏响应式可折叠。
- 左上角 Logo/标题不要挤在一起。
- 仪表盘显示订单金额、客户数、美甲师数、今日/近 7 日增量、快捷跳转。
## 9. 常见文件入口
后端:
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller`
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service`
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl`
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security`
- `YumiNail-Core/src/main/resources/files/YumiNail.sql`
Web:
- `YumiNail-Frontend/src/api`
- `YumiNail-Frontend/src/views`
- `YumiNail-Frontend/src/views/admin`
- `YumiNail-Frontend/src/components`
- `YumiNail-Frontend/src/style.css`
小程序:
- `WeChatProgram/pages`
- `WeChatProgram/api`
- `WeChatProgram/utils/request.js`
- `WeChatProgram/app.wxss`
## 10. 接手建议
1. 先读本文件和 `README.md`。
2. 运行 `git status --short`,确认已有改动,不要回滚无关文件。
3. 根据任务锁定最小文件范围。
4. 后端改动后编译 Core/Gateway。
5. Web 改动后跑 `npm run build`。
6. 小程序改动后跑全量 `node --check`。
7. 涉及 SQL,先改 `YumiNail.sql`,再用 MySQL MCP 对真实库执行或校验。
+7 -42
View File
@@ -2,14 +2,11 @@
## 项目简介
本仓库围绕 `YumiNail` 美甲业务系统展开,当前包含 3 组主要能力:
本仓库围绕 `YumiNail` 美甲业务系统展开,当前主链路包括:
1. `YumiNail` 主业务系统
覆盖网页前台、后台管理、网关、核心业务、数据库初始化脚本。
2. `WeChatProgram`
面向普通用户的小程序端,和主业务系统共用一套核心后端接口。
3. `YumiNail-Calendar-*` 日历子系统
提供独立的预约日历前端、网关和后端服务。
1. `YumiNail` 主业务系统:Web 前台、Web 后台、网关、核心后端和数据库初始化脚本。
2. `WeChatProgram`:面向普通用户的小程序端,复用主业务后端接口。
3. `YumiNail-Core` 内置美甲师预约日历模块:日历数据直接来自主系统订单和订单项,不再维护独立日历服务。
`MessageHub` 已拆分为独立仓库:`http://wcy111.top:3000/xiaowang/messgehub.git`。
@@ -20,50 +17,18 @@
| `YumiNail-Frontend` | Vue 3 前端 | 用户前台 + 后台管理 SPA |
| `WeChatProgram` | 微信小程序 | 用户端小程序入口 |
| `YumiNail-Gateway` | Spring Cloud Gateway | 主业务统一 API 入口 |
| `YumiNail-Core` | Spring Boot | 用户、店铺、商品、订单、优惠券、权限、文件等核心业务 |
| `YumiNail-Calendar-Frontend` | Vue 3 前端 | 美甲师预约日历独立前端 |
| `YumiNail-Calendar-Gateway` | Gateway | 日历系统网关 |
| `YumiNail-Calendar-Core` | Spring Boot | 日历系统后端 |
| `YumiNail-Core` | Spring Boot | 用户、店铺、作品、订单、优惠券、权限、文件、预约日历等核心业务 |
| `docs` | 文档目录 | 架构分析、变更记录、需求跟踪、实施记录 |
## 运行依赖
- `Nacos`:注册中心与配置中心
- `MySQL`:主业务、日历系统数据存储
- `MySQL`:主业务数据存储
- `Redis`:登录态、验证码、缓存、临时 ticket
- `RabbitMQ`:主业务异步消息投递
- `MinIO`:对象存储与图片文件访问
- `JDK 21`、`Maven`、`Node.js / npm`
## 文档入口
- [整体架构总览](docs/architecture/整体架构总览.md)
- [项目架构分析](docs/architecture/项目架构分析.md)
- [功能清单](docs/architecture/功能清单.md)
- [网页前端 README](YumiNail-Frontend/README.md)
- [网页前端项目详细总结](YumiNail-Frontend/项目详细总结.md)
- [待优化建议](docs/features/待优化建议.md)
- [历史变更记录](docs/changes/)
## 初始化说明
### YumiNail 主业务
- 首次部署空库时,优先执行:
- `YumiNail-Core/src/main/resources/files/YumiNail.sql`
- 已部署环境做增量升级时,再按补丁文件逐步执行:
- `YumiNail-Core/src/main/resources/files/*.sql`
## 推荐阅读顺序
1. 先阅读 [README](README.md) 了解模块边界。
2. 再阅读 [整体架构总览](docs/architecture/整体架构总览.md) 把握系统关系。
3. 接着阅读 [项目架构分析](docs/architecture/项目架构分析.md) 了解登录、权限、白名单、消息链路与部署口径。
4. 如需查看业务能力范围,阅读 [功能清单](docs/architecture/功能清单.md)。
5. 如需查看最近改动,阅读 `docs/changes/` 下对应日期文档。
## 维护约定
- 每次任务完成后,在 `docs/changes/` 留存一份变更记录。
- 待确认或待实现建议放在 `docs/features/`。
- 若涉及 SQL 结构或初始化变更,需要同时给出增量 SQL,并同步更新首次部署所需的初始化 SQL。
数据库初始化脚本集中在 `YumiNail-Core/src/main/resources/files/YumiNail.sql`。新增结构、补列、索引、权限种子和验收数据都应继续收口到该文件,不再新增散落 SQL 文件。
+60
View File
@@ -1,8 +1,11 @@
const authApi = require('./api/auth')
const cartApi = require('./api/cart')
const shopApi = require('./api/shop')
const userApi = require('./api/user')
const auth = require('./utils/auth')
const idleSession = require('./utils/idle-session')
const theme = require('./utils/theme')
const file = require('./utils/file')
const { IDLE_TIMEOUT_MS, IDLE_WARNING_MS } = require('./utils/config')
App({
@@ -10,6 +13,7 @@ App({
userInfo: null,
isLoggedIn: false,
cartCount: 0,
shopTheme: theme.DEFAULT_SHOP_THEME,
pendingProductFilter: null,
pendingWechatMiniLogin: null,
wechatMiniAutoLoginState: 'idle'
@@ -41,6 +45,7 @@ App({
const isLoggedIn = auth.isLoggedIn()
this.globalData.userInfo = userInfo
this.globalData.isLoggedIn = isLoggedIn
this.refreshShopTheme(userInfo)
if (userInfo && userInfo.shopId) {
auth.setPreferredMiniLoginShopId(userInfo.shopId)
@@ -161,6 +166,7 @@ App({
auth.setSession(payload)
this.globalData.userInfo = auth.getStoredUserInfo()
this.globalData.isLoggedIn = auth.isLoggedIn()
this.refreshShopTheme(this.globalData.userInfo)
if (this.globalData.userInfo && this.globalData.userInfo.shopId) {
auth.setPreferredMiniLoginShopId(this.globalData.userInfo.shopId)
@@ -173,6 +179,7 @@ App({
auth.updateStoredUserInfo(userInfo)
this.globalData.userInfo = userInfo
this.globalData.isLoggedIn = auth.isLoggedIn()
this.refreshShopTheme(userInfo)
if (userInfo && userInfo.shopId) {
auth.setPreferredMiniLoginShopId(userInfo.shopId)
@@ -183,9 +190,62 @@ App({
auth.clearSession()
this.globalData.userInfo = null
this.globalData.isLoggedIn = false
this.setShopTheme(null)
this.clearCartBadge()
},
setShopTheme(shop) {
const resolvedTheme = theme.resolveShopTheme(shop)
this.globalData.shopTheme = resolvedTheme
this.syncThemeToCurrentPages()
if (resolvedTheme.backgroundImageFileId) {
this.resolveShopThemeBackground(shop, resolvedTheme.backgroundImageFileId)
}
},
async resolveShopThemeBackground(shop, fileId) {
try {
const backgroundImageUrl = await file.getSignedUrl(fileId)
if (
!backgroundImageUrl
|| !this.globalData.shopTheme
|| this.globalData.shopTheme.backgroundImageFileId !== String(fileId)
) {
return
}
this.globalData.shopTheme = theme.resolveShopTheme({
...(shop || {}),
themeBackgroundImageUrl: backgroundImageUrl
})
this.syncThemeToCurrentPages()
} catch (error) {}
},
async refreshShopTheme(userInfo) {
if (!userInfo || !userInfo.shopId) {
this.setShopTheme(null)
return
}
try {
const shop = await shopApi.getShopById(userInfo.shopId)
if (this.globalData.userInfo && String(this.globalData.userInfo.shopId) === String(userInfo.shopId)) {
this.setShopTheme(shop)
}
} catch (error) {
this.setShopTheme(null)
}
},
syncThemeToCurrentPages() {
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const data = theme.pageThemeData(this.globalData.shopTheme)
pages.forEach(page => {
if (page && typeof page.setData === 'function') {
page.setData(data)
}
})
},
async refreshSessionUserInfo() {
if (!auth.isLoggedIn()) {
return
+2 -2
View File
@@ -19,12 +19,12 @@
"navigationBarTextStyle": "black",
"navigationStyle": "custom",
"backgroundTextStyle": "light",
"backgroundColor": "#fff7f8"
"backgroundColor": "#fff7f9"
},
"tabBar": {
"color": "#8f7b83",
"selectedColor": "#c6597d",
"backgroundColor": "#fffaf9",
"backgroundColor": "#fff7f9",
"borderStyle": "black",
"position": "bottom",
"list": [
+36 -28
View File
@@ -1,8 +1,15 @@
page {
min-height: 100%;
background:
radial-gradient(circle at top right, rgba(255, 205, 219, 0.38), transparent 32%),
linear-gradient(180deg, #fff7f8 0%, #fffdfc 100%);
--theme-primary: #c6597d;
--theme-secondary: #e9b7c7;
--theme-accent: #9f4967;
--theme-page-bg: #fff7f9;
--theme-card-bg: #ffffff;
--theme-border: #efd8e0;
--theme-primary-soft: #fbf1f4;
--theme-gradient: linear-gradient(135deg, #c6597d 0%, #e9b7c7 100%);
--theme-gradient-soft: linear-gradient(145deg, #ffffff 0%, #fff1f5 58%, #ffe8ef 100%);
min-height: 100vh;
background: var(--theme-page-bg);
color: #2d2430;
font-size: 28rpx;
}
@@ -39,6 +46,7 @@ button::after {
.page-shell {
min-height: 100vh;
padding-bottom: calc(env(safe-area-inset-bottom) + 48rpx);
background: var(--theme-page-bg);
}
.page-content {
@@ -47,14 +55,14 @@ button::after {
.page-card {
overflow: hidden;
background: #ffffff;
border: 1rpx solid rgba(239, 216, 224, 0.86);
background: var(--theme-card-bg);
border: 1rpx solid var(--theme-border);
border-radius: 32rpx;
box-shadow: 0 22rpx 56rpx rgba(122, 67, 88, 0.1);
}
.glass-card {
background: rgba(255, 255, 255, 0.8);
background: rgba(255, 255, 255, 0.82);
border: 1rpx solid rgba(255, 255, 255, 0.9);
border-radius: 32rpx;
box-shadow: 0 22rpx 56rpx rgba(122, 67, 88, 0.08);
@@ -64,8 +72,8 @@ button::after {
overflow: hidden;
padding: 34rpx 30rpx;
border-radius: 36rpx;
background: linear-gradient(145deg, #fffdfd 0%, #fff1f5 56%, #ffe8ef 100%);
border: 1rpx solid rgba(244, 214, 224, 0.92);
background: var(--theme-gradient-soft);
border: 1rpx solid var(--theme-border);
box-shadow: 0 28rpx 64rpx rgba(122, 67, 88, 0.1);
}
@@ -74,7 +82,7 @@ button::after {
font-size: 22rpx;
font-weight: 700;
letter-spacing: 2rpx;
color: #c6597d;
color: var(--theme-primary);
}
.hero-title {
@@ -114,7 +122,7 @@ button::after {
}
.hero-action.primary {
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
}
@@ -145,7 +153,7 @@ button::after {
font-size: 22rpx;
font-weight: 700;
letter-spacing: 2rpx;
color: #c6597d;
color: var(--theme-primary);
}
.section-title {
@@ -165,7 +173,7 @@ button::after {
.section-link {
font-size: 24rpx;
color: #c6597d;
color: var(--theme-primary);
font-weight: 700;
}
@@ -213,7 +221,7 @@ button::after {
width: 100%;
height: 92rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
font-size: 30rpx;
font-weight: 700;
@@ -226,8 +234,8 @@ button::after {
width: 100%;
height: 84rpx;
border-radius: 999rpx;
border: 2rpx solid #efd7df;
background: #ffffff;
border: 2rpx solid var(--theme-border);
background: var(--theme-card-bg);
color: #7a5262;
font-size: 28rpx;
font-weight: 600;
@@ -241,8 +249,8 @@ button::after {
height: 68rpx;
padding: 0 26rpx;
border-radius: 999rpx;
background: #fdf0f4;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 24rpx;
font-weight: 600;
}
@@ -264,8 +272,8 @@ button::after {
min-height: 92rpx;
padding: 0 28rpx;
border-radius: 24rpx;
background: #fbf5f7;
border: 1rpx solid rgba(239, 216, 224, 0.92);
background: var(--theme-primary-soft);
border: 1rpx solid var(--theme-border);
color: #2d2430;
font-size: 28rpx;
}
@@ -287,18 +295,18 @@ button::after {
}
.status-text.success {
color: #2ea36f;
color: var(--theme-primary);
}
.status-text.error {
color: #d5536f;
color: var(--theme-accent);
}
.hint-card {
padding: 20rpx 22rpx;
border-radius: 22rpx;
background: #fff8ea;
color: #9b6900;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 24rpx;
line-height: 1.7;
}
@@ -336,17 +344,17 @@ button::after {
}
.chip {
background: #fce8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.soft-chip {
background: #fbf5f7;
background: var(--theme-primary-soft);
color: #8d7a84;
}
.divider-line {
width: 100%;
height: 2rpx;
background: #f3e7eb;
background: var(--theme-border);
}
@@ -4,8 +4,8 @@
min-width: 0;
overflow: hidden;
border-radius: 28rpx;
background: #ffffff;
border: 1rpx solid rgba(239, 216, 224, 0.84);
background: var(--theme-card-bg);
border: 1rpx solid var(--theme-border);
box-shadow: 0 18rpx 42rpx rgba(122, 67, 88, 0.08);
}
@@ -16,7 +16,7 @@
.product-cover {
width: 100%;
height: 288rpx;
background: #f7ecf0;
background: var(--theme-primary-soft);
}
.product-cover-shadow {
@@ -82,8 +82,8 @@
max-width: 100%;
padding: 6rpx 14rpx;
border-radius: 999rpx;
background: #fbecf1;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 18rpx;
line-height: 1;
overflow: hidden;
@@ -114,7 +114,7 @@
font-size: 34rpx;
line-height: 1.12;
font-weight: 800;
color: #d5536f;
color: var(--theme-accent);
}
.product-stats {
@@ -132,7 +132,7 @@
width: 64rpx;
height: 64rpx;
border-radius: 22rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
box-shadow: 0 14rpx 30rpx rgba(198, 89, 125, 0.22);
}
@@ -209,8 +209,8 @@
height: 56rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #f8eef1;
color: #8f6e7a;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 20rpx;
font-weight: 700;
white-space: nowrap;
+2 -1
View File
@@ -4,6 +4,7 @@ const userApi = require('../../api/user')
const authStore = require('../../utils/auth')
const actionGuard = require('../../utils/action-guard')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { runWithLoading } = require('../../utils/loading')
const {
createKeyboardSafeData,
@@ -23,7 +24,7 @@ const phoneRegex = /^1[3-9]\d{9}$/
Page({
data: Object.assign(createKeyboardSafeData({
cursorSpacing: 108
}), {
}), theme.pageThemeData(getApp().globalData.shopTheme), {
redirect: '',
activeTab: 'login',
loginType: 'password',
+6 -6
View File
@@ -1,7 +1,7 @@
<view class="auth-page-root">
<navigation-bar title="账号中心" showBack="{{true}}" fallbackPath="/pages/home/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="auth-page-root" style="{{themeVars}}">
<navigation-bar title="账号中心" showBack="{{true}}" fallbackPath="/pages/home/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="auth-scroll">
<scroll-view class="auth-scroll" scroll-y="true" enhanced="true" show-scrollbar="false">
<view class="page-shell auth-page-shell auth-page">
<view class="page-content auth-content {{keyboardVisible ? 'keyboard-active' : ''}}">
<view class="page-card auth-panel">
@@ -11,7 +11,7 @@
</view>
<block wx:if="{{activeTab === 'login'}}">
<view class="wechat-login-panel">
<view wx:if="{{!traditionalLoginExpanded}}" class="wechat-login-panel">
<view class="wechat-login-copy">
<text class="wechat-login-title">微信手机号一键登录</text>
<text class="wechat-login-desc">更快登录</text>
@@ -213,7 +213,7 @@
</picker>
</view>
<view wx:if="{{activeTab === 'login' && traditionalLoginExpanded && !allowLoginShopless && loginShops.length}}" class="field-block">
<view wx:if="{{activeTab === 'login' && traditionalLoginExpanded && loginShops.length}}" class="field-block">
<text class="field-label">选择登录门店</text>
<picker mode="selector" range="{{loginShops}}" range-key="shopName" value="{{loginShopIndex}}" bindchange="handleLoginShopChange">
<view class="field-picker">{{loginShopDisplayName || '请选择登录门店'}}</view>
@@ -306,7 +306,7 @@
<view wx:if="{{keyboardVisible}}" class="keyboard-spacer" style="height: {{keyboardInsetRpx}}rpx;"></view>
</view>
</view>
</scroll-view>
<view wx:if="{{showMiniShopSelector}}" class="mini-shop-mask" catchtouchmove="noop">
<view class="page-card mini-shop-modal">
+26 -26
View File
@@ -1,9 +1,11 @@
.auth-page-root {
min-height: 100vh;
overflow: visible;
}
.auth-scroll {
min-height: 100%;
height: 100vh;
box-sizing: border-box;
}
.auth-page-shell {
@@ -11,18 +13,16 @@
}
.auth-page {
background:
radial-gradient(circle at top right, rgba(255, 204, 219, 0.32), transparent 30%),
linear-gradient(180deg, #fff8fa 0%, #fffdfc 100%);
background: var(--theme-page-bg);
}
.auth-content {
min-height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
justify-content: flex-start;
align-items: center;
padding: 24rpx 24rpx 40rpx;
padding: 24rpx 24rpx calc(80rpx + env(safe-area-inset-bottom));
}
.auth-content.keyboard-active {
@@ -38,7 +38,7 @@
}
.auth-panel {
margin-top: 0;
margin-top: 24rpx;
}
.reset-card {
@@ -62,7 +62,7 @@
margin-bottom: 14rpx;
padding: 10rpx;
border-radius: 999rpx;
background: #faf4f6;
background: var(--theme-primary-soft);
}
.tab-item,
@@ -80,16 +80,16 @@
.tab-item.active,
.toggle-item.active {
background: #fde8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.wechat-login-panel {
padding: 24rpx 22rpx;
border-radius: 28rpx;
background: linear-gradient(145deg, #f3fff8 0%, #e4fff0 52%, #d5fae6 100%);
border: 1rpx solid rgba(121, 214, 152, 0.46);
box-shadow: 0 18rpx 38rpx rgba(45, 175, 93, 0.12);
background: var(--theme-gradient-soft);
border: 1rpx solid var(--theme-border);
box-shadow: 0 18rpx 38rpx rgba(122, 67, 88, 0.1);
}
.wechat-login-copy {
@@ -117,13 +117,13 @@
}
.wechat-login-btn.primary-btn {
background: linear-gradient(135deg, #32d16d 0%, #13a847 100%);
box-shadow: 0 16rpx 36rpx rgba(19, 168, 71, 0.24);
background: var(--theme-gradient);
box-shadow: 0 16rpx 36rpx rgba(122, 67, 88, 0.16);
}
.wechat-login-btn-disabled {
color: #5d8f69;
border-color: rgba(121, 214, 152, 0.42);
color: var(--theme-accent);
border-color: var(--theme-border);
background: rgba(255, 255, 255, 0.82);
}
@@ -132,7 +132,7 @@
margin-top: 14rpx;
font-size: 22rpx;
line-height: 1.6;
color: #58806a;
color: var(--theme-accent);
}
.mini-login-resume {
@@ -207,8 +207,8 @@
height: 92rpx;
padding: 0 18rpx;
border-radius: 24rpx;
background: #fde8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 24rpx;
font-weight: 700;
}
@@ -226,7 +226,7 @@
.aux-link {
font-size: 24rpx;
color: #c6597d;
color: var(--theme-primary);
font-weight: 600;
}
@@ -268,8 +268,8 @@
}
.agreement-check.checked {
border-color: #c6597d;
background: #c6597d;
border-color: var(--theme-primary);
background: var(--theme-primary);
}
.agreement-copy {
@@ -278,7 +278,7 @@
}
.agreement-link {
color: #c6597d;
color: var(--theme-primary);
font-weight: 700;
}
@@ -331,7 +331,7 @@
margin-top: 22rpx;
padding: 20rpx;
border-radius: 22rpx;
background: #fff7f8;
background: var(--theme-primary-soft);
color: #5a4a52;
font-size: 24rpx;
line-height: 1.85;
@@ -366,7 +366,7 @@
font-size: 22rpx;
font-weight: 700;
letter-spacing: 2rpx;
color: #c6597d;
color: var(--theme-primary);
}
.mini-shop-title {
+3 -2
View File
@@ -3,6 +3,7 @@ const couponApi = require('../../api/coupon')
const orderApi = require('../../api/order')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { resolveLegacyImage } = require('../../utils/file')
const { NO_COUPON_KEY } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
@@ -113,7 +114,7 @@ function buildCheckoutIssues(items) {
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
isLoggedIn: false,
loading: false,
minDate: getMinDateText(),
@@ -128,7 +129,7 @@ Page({
totalAmountText: '¥0.00',
checkoutIssues: [],
submittingOrder: false
},
}),
/**
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
+4 -4
View File
@@ -1,6 +1,6 @@
<navigation-bar title="购物车" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="购物车" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell cart-page">
<view class="page-shell cart-page" style="{{themeVars}}">
<view class="page-content cart-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看购物车</text>
@@ -97,14 +97,14 @@
<radio-group bindchange="handleCouponChange">
<label class="coupon-option">
<radio value="NONE" checked="{{selectedCouponKey === 'NONE'}}" color="#c6597d"></radio>
<radio value="NONE" checked="{{selectedCouponKey === 'NONE'}}" color="{{navThemeColor || '#C6597D'}}"></radio>
<view class="coupon-texts">
<view class="coupon-name">不使用优惠</view>
</view>
</label>
<label wx:for="{{availableCoupons}}" wx:key="key" wx:for-item="coupon" class="coupon-option {{selectedCouponKey === coupon.key ? 'active' : ''}}">
<radio value="{{coupon.key}}" checked="{{selectedCouponKey === coupon.key}}" color="#c6597d"></radio>
<radio value="{{coupon.key}}" checked="{{selectedCouponKey === coupon.key}}" color="{{navThemeColor || '#C6597D'}}"></radio>
<view class="coupon-texts">
<view class="coupon-name">{{coupon.displayText}}</view>
<view class="coupon-desc">{{coupon.sourceType === 'SYSTEM_VIP' ? 'VIP 自动折扣' : '用户优惠券'}}</view>
+20 -21
View File
@@ -1,5 +1,6 @@
.cart-page {
padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);
background: var(--theme-page-bg);
}
.cart-content {
@@ -7,9 +8,7 @@
}
.cart-hero {
background:
radial-gradient(circle at top right, rgba(255, 192, 210, 0.42), transparent 34%),
linear-gradient(145deg, #fffdfd 0%, #fff2f6 56%, #ffe7ef 100%);
background: var(--theme-gradient-soft);
}
.issue-card {
@@ -17,8 +16,8 @@
margin-bottom: 20rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: #fff7e8;
color: #9b6900;
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
.issue-title {
@@ -57,15 +56,15 @@
}
.select-dot.active {
border-color: #c6597d;
background: #c6597d;
border-color: var(--theme-primary);
background: var(--theme-primary);
}
.cart-thumb {
width: 140rpx;
height: 140rpx;
border-radius: 22rpx;
background: #f6edf1;
background: var(--theme-primary-soft);
}
.cart-main {
@@ -91,7 +90,7 @@
.cart-price {
font-size: 30rpx;
font-weight: 700;
color: #d5536f;
color: var(--theme-accent);
}
.cart-meta-row {
@@ -109,8 +108,8 @@
height: 42rpx;
padding: 0 16rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 20rpx;
font-weight: 700;
}
@@ -131,7 +130,7 @@
min-height: 76rpx;
padding: 0 22rpx;
border-radius: 20rpx;
background: #fbf5f7;
background: var(--theme-primary-soft);
}
.selector-row.compact {
@@ -139,7 +138,7 @@
}
.selector-row.issue {
background: #fff7e8;
background: var(--theme-primary-soft);
}
.selector-label {
@@ -189,8 +188,8 @@
width: 56rpx;
height: 56rpx;
border-radius: 50%;
background: #fbf5f7;
color: #7a5262;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 34rpx;
}
@@ -204,7 +203,7 @@
.remove-btn {
font-size: 24rpx;
color: #d5536f;
color: var(--theme-accent);
font-weight: 700;
}
@@ -228,7 +227,7 @@
}
.coupon-option.active {
color: #c6597d;
color: var(--theme-primary);
}
.coupon-texts {
@@ -255,8 +254,8 @@
height: 44rpx;
padding: 0 14rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 20rpx;
font-weight: 700;
}
@@ -302,7 +301,7 @@
.checkout-total {
font-size: 36rpx;
font-weight: 800;
color: #d5536f;
color: var(--theme-accent);
}
.checkout-meta {
@@ -319,7 +318,7 @@
height: 84rpx;
padding: 0 26rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
font-size: 28rpx;
font-weight: 700;
+3 -2
View File
@@ -1,6 +1,7 @@
const couponApi = require('../../api/coupon')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
function getBenefitText(coupon) {
if (Number(coupon.couponType) === 1) {
@@ -14,7 +15,7 @@ function getBenefitText(coupon) {
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
loading: false,
isLoggedIn: false,
coupons: [],
@@ -26,7 +27,7 @@ Page({
{ value: 'used', label: '已使用' },
{ value: 'expired', label: '已过期' }
]
},
}),
/**
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
+2 -2
View File
@@ -1,6 +1,6 @@
<navigation-bar title="我的优惠券" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="我的优惠券" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell coupons-page">
<view class="page-shell coupons-page" style="{{themeVars}}">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看优惠券</text>
+7 -5
View File
@@ -17,14 +17,16 @@
height: 60rpx;
padding: 0 24rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.78);
background: var(--theme-card-bg);
border: 1rpx solid var(--theme-border);
color: #8d7a84;
font-size: 24rpx;
font-weight: 600;
}
.coupon-filter-chip.active {
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
border-color: transparent;
color: #ffffff;
}
@@ -34,7 +36,7 @@
.coupon-card {
padding: 26rpx 28rpx;
background: linear-gradient(135deg, #fff8fa 0%, #fff1f5 100%);
background: var(--theme-gradient-soft);
}
.coupon-top {
@@ -65,7 +67,7 @@
padding: 0 18rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.8);
color: #c6597d;
color: var(--theme-primary);
font-size: 22rpx;
font-weight: 700;
}
@@ -74,7 +76,7 @@
margin-top: 26rpx;
font-size: 42rpx;
font-weight: 800;
color: #d5536f;
color: var(--theme-primary);
}
.coupon-period {
+6 -3
View File
@@ -15,6 +15,7 @@ const {
const productApi = require('../../api/product')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const theme = require('../../utils/theme')
/**
* home page logic.
@@ -23,7 +24,7 @@ const userApi = require('../../api/user')
Page({
data: Object.assign(createKeyboardSafeData({
cursorSpacing: 96
}), {
}), theme.pageThemeData(getApp().globalData.shopTheme), {
initialized: false,
loading: false,
loadingMore: false,
@@ -146,7 +147,8 @@ Page({
greeting: isLoggedIn ? '欢迎回来' : '游客模式',
displayName: isLoggedIn
? ((userInfo && userInfo.nickname) || 'Yumi 用户')
: '先逛逛喜欢的款式和门店'
: '先逛逛喜欢的款式和门店',
bannerImages: isLoggedIn ? [] : this.data.bannerImages
})
},
@@ -187,10 +189,11 @@ Page({
this.syncUserState()
try {
const loggedIn = auth.isLoggedIn()
await Promise.all([
this.loadUserProfile(),
this.loadAnnouncements(),
this.loadBannerImages(requestId),
loggedIn ? Promise.resolve() : this.loadBannerImages(requestId),
this.loadFeaturedProducts(requestId),
this.loadPopularProducts(true, requestId)
])
+4 -4
View File
@@ -1,5 +1,5 @@
<view class="home-page-root">
<navigation-bar title="{{navTitle}}" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="home-page-root" style="{{themeVars}}">
<navigation-bar title="{{navTitle}}" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="home-scroll">
<view class="page-shell home-page {{keyboardVisible ? 'keyboard-active' : ''}}">
@@ -39,7 +39,7 @@
</swiper>
<view class="summary-strip">
<view class="summary-metric">
<view wx:if="{{!isLoggedIn}}" class="summary-metric">
<text class="summary-label">门店橱窗</text>
<text class="summary-value">{{bannerImages.length ? bannerImages.length : 0}} 家</text>
<text class="summary-note">看环境</text>
@@ -61,7 +61,7 @@
</view>
</view>
<view class="section-block">
<view wx:if="{{!isLoggedIn}}" class="section-block">
<view class="section-head">
<view class="section-copy">
<text class="section-kicker">门店氛围</text>
+8 -12
View File
@@ -8,9 +8,7 @@
.home-page {
min-height: 100%;
background:
radial-gradient(circle at top right, rgba(255, 196, 214, 0.4), transparent 36%),
linear-gradient(180deg, #fff7f8 0%, #fffdfb 100%);
background: var(--theme-page-bg);
}
.home-page.keyboard-active {
@@ -18,9 +16,7 @@
}
.home-hero {
background:
radial-gradient(circle at top right, rgba(255, 186, 207, 0.5), transparent 36%),
linear-gradient(145deg, #fffdfd 0%, #fff2f6 52%, #ffe8ef 100%);
background: var(--theme-gradient-soft);
}
.search-box {
@@ -48,7 +44,7 @@
min-width: 150rpx;
height: 72rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
font-size: 26rpx;
font-weight: 700;
@@ -98,8 +94,8 @@
height: 58rpx;
margin-top: 18rpx;
border-radius: 16rpx;
background: #fff7ed;
border: 1rpx solid #fed7aa;
background: var(--theme-primary-soft);
border: 1rpx solid var(--theme-border);
overflow: hidden;
}
@@ -108,7 +104,7 @@
line-height: 58rpx;
padding: 0 22rpx;
font-size: 24rpx;
color: #7c2d12;
color: var(--theme-accent);
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
@@ -120,8 +116,8 @@
justify-content: center;
padding: 8rpx 18rpx;
border-radius: 999rpx;
background: #fce8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 22rpx;
font-weight: 700;
}
+3 -2
View File
@@ -2,6 +2,7 @@ const orderApi = require('../../api/order')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const actionGuard = require('../../utils/action-guard')
const theme = require('../../utils/theme')
const { resolveLegacyImage } = require('../../utils/file')
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
const { runWithLoading } = require('../../utils/loading')
@@ -11,11 +12,11 @@ const { runWithLoading } = require('../../utils/loading')
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
loading: false,
isLoggedIn: false,
orders: []
},
}),
/**
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
+2 -2
View File
@@ -1,6 +1,6 @@
<navigation-bar title="我的订单" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="我的订单" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell orders-page">
<view class="page-shell orders-page" style="{{themeVars}}">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看订单</text>
+11 -11
View File
@@ -20,12 +20,12 @@
.order-head {
padding-bottom: 18rpx;
border-bottom: 2rpx solid #f3e7eb;
border-bottom: 2rpx solid var(--theme-border);
}
.order-shop {
margin: 14rpx 0 0;
color: #8f6e7a;
color: #8d7a84;
font-size: 24rpx;
line-height: 1.5;
}
@@ -62,18 +62,18 @@
}
.order-status.pending {
background: #fff6e8;
color: #cb7b00;
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
.order-status.completed {
background: #ecfbf3;
color: #2ea36f;
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.order-status.cancelled {
background: #fff1f5;
color: #d5536f;
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
.order-item {
@@ -86,7 +86,7 @@
width: 132rpx;
height: 132rpx;
border-radius: 20rpx;
background: #f6edf1;
background: var(--theme-primary-soft);
}
.order-main {
@@ -126,8 +126,8 @@
height: 60rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #d5536f;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 24rpx;
font-weight: 700;
}
+16 -3
View File
@@ -7,7 +7,8 @@ const wishlistApi = require('../../api/wishlist')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { resolveImageList } = require('../../utils/file')
const theme = require('../../utils/theme')
const { getSignedUrl, resolveImageList } = require('../../utils/file')
const { DEFAULT_PRODUCT_IMAGE } = require('../../utils/config')
const { formatPrice, getProductTitle, splitCsv } = require('../../utils/format')
const { runWithLoading } = require('../../utils/loading')
@@ -83,7 +84,7 @@ function estimateEarliestBookable(businessHours) {
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
loading: true,
loadError: '',
productId: '',
@@ -97,7 +98,7 @@ Page({
isLiked: false,
artistCountText: '门店安排',
earliestBookableText: '以门店安排为准'
},
}),
/**
* `onLoad` page method. Use this from WXML event bindings or lifecycle hooks.
@@ -139,6 +140,18 @@ Page({
const product = await productApi.getProductById(productId)
const productImages = await resolveImageList(product.imageFileIds, DEFAULT_PRODUCT_IMAGE)
const shopInfo = product.shopId ? await shopApi.getShopById(product.shopId) : null
if (shopInfo) {
const shopTheme = theme.resolveShopTheme(shopInfo)
this.setData(theme.pageThemeData(shopTheme))
if (shopTheme.backgroundImageFileId) {
try {
const backgroundImageUrl = await getSignedUrl(shopTheme.backgroundImageFileId)
if (backgroundImageUrl) {
this.setData(theme.pageThemeData(shopTheme, backgroundImageUrl))
}
} catch (error) {}
}
}
const artistCount = typeof product.availableBookableArtistCount === 'number'
? product.availableBookableArtistCount
: splitCsv(product.bookableArtists).length
@@ -1,6 +1,6 @@
<navigation-bar title="{{product ? product.displayTitle : '作品详情'}}" showBack="{{true}}" fallbackPath="/pages/products/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="{{product ? product.displayTitle : '作品详情'}}" showBack="{{true}}" fallbackPath="/pages/products/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell detail-page">
<view class="page-shell detail-page" style="{{themeVars}}">
<view wx:if="{{loadError}}" class="page-content">
<view class="page-card empty-card">
<text class="empty-title">暂时无法查看作品详情</text>
+18 -16
View File
@@ -1,11 +1,13 @@
.detail-page {
padding-bottom: calc(env(safe-area-inset-bottom) + 160rpx);
background: var(--theme-page-bg);
}
.media-box {
position: relative;
overflow: hidden;
border-radius: 0 0 40rpx 40rpx;
background: var(--theme-primary-soft);
}
.media-swiper,
@@ -51,7 +53,7 @@
margin-top: 12rpx;
font-size: 38rpx;
font-weight: 700;
color: #d5536f;
color: var(--theme-accent);
}
.product-brief {
@@ -74,7 +76,7 @@
margin-top: 28rpx;
padding: 24rpx;
border-radius: 24rpx;
background: linear-gradient(135deg, #fff8fa 0%, #fff1f5 100%);
background: var(--theme-gradient-soft);
}
.shop-box-head {
@@ -92,7 +94,7 @@
.shop-link {
font-size: 24rpx;
color: #c6597d;
color: var(--theme-primary);
font-weight: 700;
}
@@ -117,15 +119,15 @@
height: 68rpx;
padding: 0 24rpx;
border-radius: 999rpx;
background: #fbf5f7;
color: #7a5262;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 24rpx;
font-weight: 600;
}
.action-pill.active {
background: #fde8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.tags-wrap {
@@ -141,8 +143,8 @@
justify-content: center;
padding: 10rpx 18rpx;
border-radius: 999rpx;
background: #fbecf1;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 22rpx;
}
@@ -181,7 +183,7 @@
margin-top: 20rpx;
padding: 20rpx;
border-radius: 20rpx;
background: #fff8fa;
background: var(--theme-primary-soft);
}
.comment-input {
@@ -201,7 +203,7 @@
.comment-submit,
.comment-reply-btn {
font-size: 24rpx;
color: #c6597d;
color: var(--theme-primary);
font-weight: 700;
}
@@ -212,7 +214,7 @@
text-align: center;
border-radius: 999rpx;
color: #ffffff;
background: #c6597d;
background: var(--theme-primary);
}
.comment-empty {
@@ -252,7 +254,7 @@
margin-top: 14rpx;
padding: 16rpx;
border-radius: 18rpx;
background: #faf4f6;
background: var(--theme-primary-soft);
}
.reply-item {
@@ -293,11 +295,11 @@
}
.footer-btn.secondary {
background: #fbf5f7;
color: #7a5262;
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
.footer-btn.primary {
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
}
+2 -1
View File
@@ -6,6 +6,7 @@ const cartApi = require('../../api/cart')
const actionGuard = require('../../utils/action-guard')
const { buildProductCards } = require('../../utils/product')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { runWithLoading } = require('../../utils/loading')
const { CACHE_TTL } = require('../../utils/config')
const {
@@ -28,7 +29,7 @@ const CART_BUSY_MESSAGE = '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52f
Page({
data: Object.assign(createKeyboardSafeData({
cursorSpacing: 96
}), {
}), theme.pageThemeData(getApp().globalData.shopTheme), {
initialized: false,
loading: false,
loadingMore: false,
+2 -2
View File
@@ -1,6 +1,6 @@
<navigation-bar title="作品库" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="作品库" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell product-page {{keyboardVisible ? 'keyboard-active' : ''}}">
<view class="page-shell product-page {{keyboardVisible ? 'keyboard-active' : ''}}" style="{{themeVars}}">
<view class="page-content product-page-content" style="{{keyboardVisible ? 'padding-bottom: ' + keyboardInsetRpx + 'rpx;' : ''}}">
<view class="sticky-filter-bar">
<view class="filter-surface">
+11 -14
View File
@@ -1,7 +1,5 @@
.product-page {
background:
radial-gradient(circle at top left, rgba(255, 207, 220, 0.35), transparent 34%),
linear-gradient(180deg, #fff8fa 0%, #fffdfc 100%);
background: var(--theme-page-bg);
}
.product-page-content {
@@ -13,15 +11,14 @@
top: 0;
z-index: 12;
padding: 6rpx 0 16rpx;
background:
linear-gradient(180deg, rgba(255, 248, 250, 0.98) 0%, rgba(255, 252, 251, 0.94) 76%, rgba(255, 252, 251, 0) 100%);
background: var(--theme-page-bg);
}
.filter-surface {
padding: 16rpx 16rpx 14rpx;
border-radius: 24rpx;
border: 1rpx solid rgba(239, 216, 224, 0.86);
background: rgba(255, 255, 255, 0.92);
border: 1rpx solid var(--theme-border);
background: var(--theme-card-bg);
box-shadow: 0 18rpx 40rpx rgba(122, 67, 88, 0.08);
}
@@ -36,7 +33,7 @@
height: 68rpx;
padding: 0 22rpx;
border-radius: 999rpx;
background: #fbf5f7;
background: var(--theme-primary-soft);
color: #2d2430;
font-size: 26rpx;
}
@@ -49,7 +46,7 @@
height: 68rpx;
padding: 0 28rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
background: var(--theme-gradient);
color: #ffffff;
font-size: 24rpx;
font-weight: 700;
@@ -80,15 +77,15 @@
height: 50rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: #f7edf1;
background: var(--theme-primary-soft);
color: #8d7a84;
font-size: 22rpx;
font-weight: 600;
}
.category-item.active {
background: #fde8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.results-head {
@@ -121,8 +118,8 @@
height: 46rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #fdeff4;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 22rpx;
font-weight: 600;
overflow: hidden;
+3 -2
View File
@@ -6,6 +6,7 @@ const wishlistApi = require('../../api/wishlist')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
@@ -14,7 +15,7 @@ const { runWithLoading } = require('../../utils/loading')
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
isLoggedIn: false,
loading: false,
needSetPassword: false,
@@ -24,7 +25,7 @@ Page({
wishlistCount: 0,
unreadMessageCount: 0,
defaultAvatar: DEFAULT_AVATAR
},
}),
/**
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
+1 -1
View File
@@ -1,4 +1,4 @@
<view class="profile-page-root">
<view class="profile-page-root" style="{{themeVars}}">
<navigation-bar title="个人中心" showBack="{{false}}" isTabPage="{{true}}" color="#ffffff" background="transparent" safeAreaMode="overlay"></navigation-bar>
<view class="profile-bg"></view>
+11 -9
View File
@@ -1,14 +1,16 @@
.profile-page-root {
min-height: 100vh;
background: var(--theme-page-bg);
}
.profile-scroll {
min-height: 100%;
background: var(--theme-page-bg);
}
.profile-page {
min-height: 100%;
background: linear-gradient(180deg, #d66c90 0%, #fff8fa 220rpx, #fffdfc 100%);
background: var(--theme-page-bg);
}
.profile-bg {
@@ -17,7 +19,7 @@
left: 0;
right: 0;
height: 228rpx;
background: linear-gradient(135deg, #d66c90 0%, #9a4f6d 100%);
background: var(--theme-gradient);
}
.profile-content {
@@ -67,7 +69,7 @@
width: 120rpx;
height: 120rpx;
border-radius: 50%;
background: #f7edf1;
background: var(--theme-primary-soft);
}
.profile-copy {
@@ -100,7 +102,7 @@
margin-top: 26rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: #fff1f5;
background: var(--theme-primary-soft);
}
.shop-label {
@@ -117,7 +119,7 @@
.shop-link {
font-size: 24rpx;
color: #c6597d;
color: var(--theme-primary);
font-weight: 700;
}
@@ -125,8 +127,8 @@
margin-top: 22rpx;
padding: 20rpx 24rpx;
border-radius: 20rpx;
background: #fff7e8;
color: #9b6900;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 24rpx;
line-height: 1.7;
}
@@ -167,7 +169,7 @@
height: 36rpx;
padding: 0 10rpx;
border-radius: 18rpx;
background: #ff5c8a;
background: var(--theme-primary);
color: #ffffff;
font-size: 22rpx;
line-height: 36rpx;
@@ -179,7 +181,7 @@
}
.logout-item {
color: #d5536f;
color: var(--theme-accent);
font-weight: 700;
}
+2 -1
View File
@@ -2,6 +2,7 @@ const authApi = require('../../api/auth')
const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft')
const { runWithLoading } = require('../../utils/loading')
@@ -23,7 +24,7 @@ const SETTINGS_DRAFT_KEY = 'user-settings'
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: Object.assign(createKeyboardSafeData({
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), createKeyboardSafeData({
cursorSpacing: 108
}), {
isLoggedIn: false,
+2 -2
View File
@@ -1,5 +1,5 @@
<view class="settings-page-root">
<navigation-bar title="设置中心" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="settings-page-root" style="{{themeVars}}">
<navigation-bar title="设置中心" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="settings-scroll">
<view class="page-shell settings-page-shell {{keyboardVisible ? 'keyboard-active' : ''}}">
+15 -12
View File
@@ -1,5 +1,6 @@
.settings-page-root {
min-height: 100vh;
background: var(--theme-page-bg);
}
.settings-scroll {
@@ -8,6 +9,7 @@
.settings-page-shell {
min-height: 100%;
background: var(--theme-page-bg);
}
.settings-page-shell.keyboard-active {
@@ -37,7 +39,7 @@
width: 110rpx;
height: 110rpx;
border-radius: 50%;
background: #f7edf1;
background: var(--theme-primary-soft);
}
.profile-preview-copy {
@@ -75,7 +77,7 @@
.text-action {
font-size: 24rpx;
font-weight: 600;
color: #c6597d;
color: var(--theme-primary);
}
.field-block {
@@ -100,7 +102,7 @@
justify-content: space-between;
gap: 18rpx;
padding: 24rpx 0;
border-bottom: 1rpx solid rgba(239, 216, 224, 0.92);
border-bottom: 1rpx solid var(--theme-border);
}
.setting-row:first-of-type {
@@ -134,14 +136,14 @@
flex-shrink: 0;
font-size: 24rpx;
font-weight: 700;
color: #c6597d;
color: var(--theme-primary);
}
.security-panel {
margin-top: 6rpx;
padding: 26rpx 24rpx;
border-radius: 28rpx;
background: #fff7f8;
background: var(--theme-primary-soft);
}
.field-static {
@@ -150,7 +152,8 @@
min-height: 92rpx;
padding: 0 28rpx;
border-radius: 24rpx;
background: #f5edf0;
background: var(--theme-card-bg);
border: 1rpx solid var(--theme-border);
color: #5d4b55;
font-size: 28rpx;
}
@@ -173,14 +176,14 @@
height: 92rpx;
padding: 0 18rpx;
border-radius: 24rpx;
background: #fde8ef;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 24rpx;
font-weight: 700;
}
.code-btn.disabled {
background: #f3e7eb;
background: var(--theme-card-bg);
color: #a998a0;
}
@@ -199,7 +202,7 @@
}
.danger-text {
color: #d5536f;
color: var(--theme-accent);
}
.logout-btn {
@@ -209,8 +212,8 @@
height: 92rpx;
margin-top: 24rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #d5536f;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 28rpx;
font-weight: 700;
}
+14 -3
View File
@@ -1,6 +1,7 @@
const shopApi = require('../../api/shop')
const navigation = require('../../utils/navigation')
const { resolveImageList } = require('../../utils/file')
const theme = require('../../utils/theme')
const { getSignedUrl, resolveImageList } = require('../../utils/file')
const { DEFAULT_SHOP_IMAGE } = require('../../utils/config')
/**
@@ -8,7 +9,7 @@ const { DEFAULT_SHOP_IMAGE } = require('../../utils/config')
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
loading: true,
loadError: '',
shopId: '',
@@ -16,7 +17,7 @@ Page({
shopInfo: null,
distanceText: '',
shopImages: []
},
}),
/**
* `onLoad` page method. Use this from WXML event bindings or lifecycle hooks.
@@ -56,6 +57,16 @@ Page({
try {
const shopInfo = await shopApi.getShopById(this.data.shopId)
const shopImages = await resolveImageList(shopInfo.imageFileIds || shopInfo.coverImageFileId, DEFAULT_SHOP_IMAGE)
const shopTheme = theme.resolveShopTheme(shopInfo)
this.setData(theme.pageThemeData(shopTheme))
if (shopTheme.backgroundImageFileId) {
try {
const backgroundImageUrl = await getSignedUrl(shopTheme.backgroundImageFileId)
if (backgroundImageUrl) {
this.setData(theme.pageThemeData(shopTheme, backgroundImageUrl))
}
} catch (error) {}
}
this.setData({
shopInfo,
shopImages,
+1 -1
View File
@@ -1,6 +1,6 @@
<navigation-bar title="{{shopInfo ? shopInfo.shopName : '门店详情'}}" showBack="{{true}}" fallbackPath="{{returnTo || '/pages/home/index'}}" color="#ffffff" background="transparent" safeAreaMode="overlay"></navigation-bar>
<view class="page-shell shop-page">
<view class="page-shell shop-page" style="{{themeVars}}">
<view class="shop-hero">
<image wx:if="{{shopImages.length}}" class="shop-hero-image" src="{{shopImages[0]}}" mode="aspectFill" lazy-load="{{true}}"></image>
<view class="shop-hero-mask"></view>
+8 -5
View File
@@ -1,5 +1,5 @@
.shop-page {
background: linear-gradient(180deg, #f4dbe3 0%, #fff8fa 220rpx, #fffdfc 100%);
background: var(--theme-page-bg);
}
.shop-hero {
@@ -8,7 +8,7 @@
left: 0;
right: 0;
height: 320rpx;
background: linear-gradient(135deg, #c6597d 0%, #8d4763 100%);
background: var(--theme-gradient);
}
.shop-hero-image {
@@ -79,19 +79,22 @@
}
.copy-row {
display: flex;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16rpx;
margin-top: 26rpx;
}
.map-row {
display: grid;
grid-template-columns: 1fr;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16rpx;
margin-top: 18rpx;
}
.copy-row .ghost-btn,
.map-btn {
min-width: 0;
width: 100%;
}
@@ -105,5 +108,5 @@
width: calc(50% - 9rpx);
height: 240rpx;
border-radius: 24rpx;
background: #f6edf1;
background: var(--theme-primary-soft);
}
+3 -2
View File
@@ -3,6 +3,7 @@ const cartApi = require('../../api/cart')
const actionGuard = require('../../utils/action-guard')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const theme = require('../../utils/theme')
const { buildProductCard } = require('../../utils/product')
const { runWithLoading } = require('../../utils/loading')
@@ -11,11 +12,11 @@ const { runWithLoading } = require('../../utils/loading')
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: {
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
loading: false,
isLoggedIn: false,
wishlist: []
},
}),
/**
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
+2 -2
View File
@@ -1,6 +1,6 @@
<navigation-bar title="我的收藏" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
<navigation-bar title="我的收藏" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="{{navThemeBackground || '#FFF7F9'}}"></navigation-bar>
<view class="page-shell wishlist-page">
<view class="page-shell wishlist-page" style="{{themeVars}}">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看收藏</text>
+4 -4
View File
@@ -19,13 +19,13 @@
height: 74rpx;
flex: 1;
border-radius: 20rpx;
background: #fff1f5;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 26rpx;
font-weight: 600;
}
.wishlist-action--secondary {
background: #fff1f5;
color: #c6597d;
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
+5 -1
View File
@@ -192,7 +192,11 @@ async function refreshToken() {
}
async function handleUnauthorized(options) {
if (options._retry || isWhitelistedPath(options.url)) {
if (isWhitelistedPath(options.url)) {
throw normalizeError('\u8bf7\u6c42\u9700\u8981\u767b\u5f55\uff0c\u4f46\u5f53\u524d\u9875\u9762\u5141\u8bb8\u533f\u540d\u67e5\u770b', 401)
}
if (options._retry) {
auth.clearSession()
const app = getApp()
if (app && typeof app.clearUserSession === 'function') {
+137
View File
@@ -0,0 +1,137 @@
const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/
function normalizeHexColor(value) {
if (!value || typeof value !== 'string') {
return ''
}
const normalized = value.trim()
return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : ''
}
function hexToRgb(color) {
const value = color.replace('#', '')
return {
r: parseInt(value.slice(0, 2), 16),
g: parseInt(value.slice(2, 4), 16),
b: parseInt(value.slice(4, 6), 16)
}
}
function toHex(value) {
return Math.min(255, Math.max(0, value)).toString(16).padStart(2, '0').toUpperCase()
}
function rgbToHex(rgb) {
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
}
function mixColor(foreground, background, backgroundWeight) {
const fg = hexToRgb(foreground)
const bg = hexToRgb(background)
const weight = Math.min(1, Math.max(0, backgroundWeight))
return rgbToHex({
r: Math.round(fg.r * (1 - weight) + bg.r * weight),
g: Math.round(fg.g * (1 - weight) + bg.g * weight),
b: Math.round(fg.b * (1 - weight) + bg.b * weight)
})
}
function buildStyleVars(theme) {
const styleVars = [
`--theme-primary: ${theme.primaryColor};`,
`--theme-secondary: ${theme.secondaryColor};`,
`--theme-accent: ${theme.accentColor};`,
`--theme-page-bg: ${theme.pageBgColor};`,
`--theme-card-bg: ${theme.cardBgColor};`,
`--theme-border: ${theme.borderColor};`,
`--theme-primary-soft: ${theme.primarySoftColor};`,
`--theme-gradient: ${theme.gradient};`,
`--theme-gradient-soft: ${theme.softGradient};`
]
if (theme.backgroundImageUrl) {
styleVars.push(
`background-image: url("${theme.backgroundImageUrl}");`,
'background-size: cover;',
'background-position: center top;'
)
}
return styleVars.join(' ')
}
function resolveShopTheme(source) {
const themeSource = source || {}
const normalizedPrimaryColor = normalizeHexColor(themeSource.themePrimaryColor)
const primaryColor = normalizedPrimaryColor || DEFAULT_SHOP_THEME.primaryColor
const secondaryColor = normalizeHexColor(themeSource.themeSecondaryColor)
|| (normalizedPrimaryColor ? mixColor(primaryColor, '#FFFFFF', 0.68) : DEFAULT_SHOP_THEME.secondaryColor)
const accentColor = normalizeHexColor(themeSource.themeAccentColor)
|| (normalizedPrimaryColor ? mixColor(primaryColor, '#7A3F56', 0.38) : DEFAULT_SHOP_THEME.accentColor)
const pageBgColor = normalizeHexColor(themeSource.themePageBgColor) || DEFAULT_SHOP_THEME.pageBgColor
const cardBgColor = normalizeHexColor(themeSource.themeCardBgColor) || DEFAULT_SHOP_THEME.cardBgColor
const borderColor = mixColor(primaryColor, cardBgColor, 0.82)
const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.88)
const gradient = `linear-gradient(135deg, ${primaryColor} 0%, ${secondaryColor} 100%)`
const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${mixColor(secondaryColor, pageBgColor, 0.55)} 58%, ${mixColor(primaryColor, pageBgColor, 0.82)} 100%)`
const backgroundImageFileId = themeSource.themeBackgroundImageFileId
? String(themeSource.themeBackgroundImageFileId).trim()
: ''
const backgroundImageUrl = themeSource.themeBackgroundImageUrl
? String(themeSource.themeBackgroundImageUrl).trim()
: ''
const theme = {
primaryColor,
secondaryColor,
accentColor,
pageBgColor,
cardBgColor,
borderColor,
primarySoftColor,
gradient,
softGradient,
backgroundImageFileId,
backgroundImageUrl
}
theme.styleVars = buildStyleVars(theme)
return theme
}
const DEFAULT_SHOP_THEME = {
primaryColor: '#C6597D',
secondaryColor: '#E9B7C7',
accentColor: '#9F4967',
pageBgColor: '#FFF7F9',
cardBgColor: '#FFFFFF',
borderColor: '#EFD8E0',
primarySoftColor: '#FBF1F4',
gradient: 'linear-gradient(135deg, #C6597D 0%, #E9B7C7 100%)',
softGradient: 'linear-gradient(145deg, #FFFFFF 0%, #FFF1F5 58%, #FFE8EF 100%)',
backgroundImageFileId: '',
backgroundImageUrl: ''
}
DEFAULT_SHOP_THEME.styleVars = buildStyleVars(DEFAULT_SHOP_THEME)
function pageThemeData(theme, backgroundImageUrl) {
const resolved = theme || DEFAULT_SHOP_THEME
const themeData = backgroundImageUrl
? {
...resolved,
backgroundImageUrl: String(backgroundImageUrl).trim()
}
: resolved
if (backgroundImageUrl) {
themeData.styleVars = buildStyleVars(themeData)
}
return {
theme: themeData,
themeVars: themeData.styleVars,
navThemeColor: themeData.primaryColor,
navThemeBackground: themeData.pageBgColor
}
}
module.exports = {
DEFAULT_SHOP_THEME,
resolveShopTheme,
pageThemeData
}
+33
View File
@@ -0,0 +1,33 @@
const assert = require('assert')
const theme = require('./theme')
const customized = theme.resolveShopTheme({
themePrimaryColor: '#8b4f65',
themeSecondaryColor: '#f2c9d4',
themeAccentColor: '#b86f84',
themePageBgColor: '#fff8fa',
themeCardBgColor: '#ffffff',
themeBackgroundImageFileId: 'bg-file'
})
assert.strictEqual(customized.primaryColor, '#8B4F65')
assert.strictEqual(customized.secondaryColor, '#F2C9D4')
assert.strictEqual(customized.accentColor, '#B86F84')
assert.strictEqual(customized.pageBgColor, '#FFF8FA')
assert.strictEqual(customized.cardBgColor, '#FFFFFF')
assert.strictEqual(customized.backgroundImageFileId, 'bg-file')
assert.ok(customized.styleVars.includes('--theme-primary: #8B4F65;'))
assert.ok(customized.styleVars.includes('--theme-gradient: linear-gradient(135deg, #8B4F65 0%, #F2C9D4 100%);'))
const themedPageData = theme.pageThemeData(customized, 'https://static.example.test/bg.jpg')
assert.ok(themedPageData.themeVars.includes('background-image: url("https://static.example.test/bg.jpg");'))
assert.strictEqual(themedPageData.theme.backgroundImageUrl, 'https://static.example.test/bg.jpg')
const fallback = theme.resolveShopTheme({
themePrimaryColor: '#fff',
themeSecondaryColor: 'blue'
})
assert.strictEqual(fallback.primaryColor, theme.DEFAULT_SHOP_THEME.primaryColor)
assert.strictEqual(fallback.secondaryColor, theme.DEFAULT_SHOP_THEME.secondaryColor)
assert.ok(fallback.styleVars.includes('--theme-page-bg:'))
@@ -15,7 +15,7 @@
<view class="surface-card">
<text class="section-title">账号密码登录</text>
<text class="section-desc">输入后台账号后,会自动预加载可登录店铺。管理员在系统尚无店铺时,也可无店铺登录并先进入店铺管理。</text>
<text class="section-desc">输入后台账号后,会自动识别登录范围。平台管理员可直接进入总览,也可选择本次登录店铺。</text>
<view class="field-group">
<text class="field-label">后台账号</text>
@@ -35,7 +35,7 @@
</picker>
</view>
<view wx:if="{{allowShoplessLogin || loginShopMessage}}" class="hint-card">{{loginShopMessage || '当前账号允许无店铺登录,可先进入店铺管理完成初始化。'}}</view>
<view wx:if="{{allowShoplessLogin || loginShopMessage}}" class="hint-card">{{loginShopMessage || '平台管理员可直接进入总览,也可选择本次登录店铺。'}}</view>
<view class="action-row">
<button class="primary-btn" loading="{{loading}}" disabled="{{loading}}" bindtap="handleSubmit">进入管理台</button>
@@ -8,7 +8,7 @@
<text class="hero-desc">这里不复刻网页后台的大表格首页,而是把可用模块拆成移动端更好点到的入口卡片。</text>
</view>
<view wx:if="{{!currentShop && userInfo && userInfo.type === 4}}" class="hint-card">当前是无店铺管理员登录状态。用户、作品、优惠券、标签、美甲师等强店铺模块会先置灰,避免误操作。</view>
<view wx:if="{{!currentShop && userInfo && userInfo.type === 4}}" class="hint-card">当前是平台总览模式。用户、作品、订单、优惠券、标签、美甲师等店铺业务可以查看,编辑操作由服务端关闭。</view>
<block wx:for="{{modules}}" wx:key="key">
<view class="list-card" data-module="{{item}}" bindtap="handleOpenModule">
@@ -17,7 +17,7 @@
<text class="list-title">{{item.title}}</text>
<text class="list-subtitle">{{item.description}}</text>
</view>
<text class="{{item.allowed ? 'badge' : 'soft-badge'}}">{{item.allowed ? '可进入' : '待解锁'}}</text>
<text class="{{item.allowed ? 'badge' : 'soft-badge'}}">{{item.readonly ? '仅查看' : (item.allowed ? '可进入' : '待解锁')}}</text>
</view>
<view wx:if="{{!item.allowed}}" class="hint-card">{{item.disabledReason}}</view>
</view>
@@ -32,7 +32,7 @@ Page({
permissionCodes: app.globalData.permissionCodes || [],
roleLabel: userInfo ? permission.getRoleLabel(userInfo.type) : '--',
shopScopeText,
currentShopText: currentShop ? `当前店铺:${currentShop.shopName}` : '当前为无店铺登录'
currentShopText: currentShop ? `当前店铺:${currentShop.shopName}` : '当前为平台总览模式'
})
},
@@ -54,18 +54,18 @@ Page({
const result = await authApi.getLoginShops(userInfo.account)
const shops = Array.isArray(result && result.shops) ? result.shops : []
const allowShoplessLogin = Boolean(result && result.allowShoplessLogin)
if (allowShoplessLogin && permission.isPlatformAdmin(userInfo)) {
wx.showToast({
title: '平台管理员固定为总览模式',
icon: 'none'
})
return
}
const items = shops.map(shop => ({
label: shop.shopName,
value: shop.id
}))
if (allowShoplessLogin && permission.isPlatformAdmin(userInfo)) {
items.unshift({
label: '无店铺登录',
value: ''
})
}
if (!items.length) {
wx.showToast({
title: '当前账号没有可切换的店铺',
@@ -21,14 +21,14 @@
</view>
<view class="meta-item">
<text class="meta-label">店铺状态</text>
<text class="meta-value">{{currentShop ? currentShop.shopName : '无店铺登录'}}</text>
<text class="meta-value">{{currentShop ? currentShop.shopName : '平台总览模式'}}</text>
</view>
<view class="meta-item">
<text class="meta-label">可登录店铺</text>
<text class="meta-value">{{shopScopeText}}</text>
</view>
</view>
<view class="action-row">
<view wx:if="{{currentShop}}" class="action-row">
<button class="secondary-btn" bindtap="handleSwitchShop">切换店铺</button>
</view>
</view>
@@ -4,17 +4,17 @@
<view class="page-stack">
<view class="hero-panel">
<text class="hero-kicker">{{userInfo.nickname || userInfo.account || '后台账号'}}</text>
<text class="hero-title">{{currentShop ? currentShop.shopName : '无店铺登录工作台'}}</text>
<text class="hero-title">{{currentShop ? currentShop.shopName : '平台总览模式'}}</text>
<text class="hero-desc">当前身份:{{userInfo ? userInfo.type === 4 ? '平台管理员' : userInfo.type === 2 ? '店长' : '美甲师' : '--'}}。已同步 {{permissionCount}} 项后台权限。</text>
<view class="badge-row">
<text class="badge">{{currentShop ? '当前店铺已锁定' : '当前无店铺上下文'}}</text>
<text class="soft-badge">{{shoplessAdmin ? '先完成门店初始化' : '移动端工作流已就绪'}}</text>
<text class="badge">{{currentShop ? '当前店铺已锁定' : '平台总览'}}</text>
<text class="soft-badge">{{shoplessAdmin ? '店铺业务仅查看' : '移动端工作流已就绪'}}</text>
</view>
</view>
<view wx:if="{{shoplessAdmin}}" class="surface-card">
<text class="section-title">先创建第一家店铺</text>
<text class="section-desc">当前是无店铺管理员登录状态。为避免误进入强店铺范围页面,首版仅建议先完成店铺初始化,再继续订单、商品和用户管理。</text>
<text class="section-title">平台总览模式</text>
<text class="section-desc">当前管理员不绑定具体店铺,可查看全局数据和店铺业务列表;涉及新增、编辑、删除、发放等操作会被服务端拦截。</text>
<view class="action-row">
<button class="primary-btn" bindtap="handleOpenShops">进入店铺管理</button>
</view>
+5 -3
View File
@@ -5,7 +5,7 @@ const MANAGE_MODULES = [
description: '用户资料、停用删除、解绑、余额与 VIP',
path: '/pages/users/index',
permissionCodes: ['user:view'],
requiresShopContext: true
requiresShopContext: false
},
{
key: 'products',
@@ -153,8 +153,9 @@ function checkModuleAccess(module, userInfo, permissionCodes, currentShop) {
if (module.requiresShopContext && !currentShop) {
if (isPlatformAdmin(userInfo)) {
return {
allowed: false,
reason: '当前为无店铺登录,请先创建或切换店铺'
allowed: true,
reason: '平台总览模式下该模块仅可查看,编辑操作已关闭',
readonly: true
}
}
@@ -176,6 +177,7 @@ function getManageModules(userInfo, permissionCodes, currentShop) {
return {
...module,
allowed: access.allowed,
readonly: Boolean(access.readonly),
disabledReason: access.reason
}
})
-137
View File
@@ -1,137 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.xiaowang</groupId>
<artifactId>YumiNail-Calendar-Core</artifactId>
<version>1.0.0</version>
<name>YumiNail-Calendar-Core</name>
<description>Independent appointment calendar backend for nail artists.</description>
<properties>
<java.version>17</java.version>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
<druid.version>1.2.23</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>YumiNail-Calendar-Core</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -1,12 +0,0 @@
package com.xiaowang.yuminailcalendarcore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YumiNailCalendarCoreApplication {
public static void main(String[] args) {
SpringApplication.run(YumiNailCalendarCoreApplication.class, args);
}
}
@@ -1,8 +0,0 @@
package com.xiaowang.yuminailcalendarcore.common;
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
}
@@ -1,64 +0,0 @@
package com.xiaowang.yuminailcalendarcore.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ConflictException.class)
public Result<Void> handleConflictException(ConflictException e) {
return Result.error(409, e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(BindException.class)
public Result<Void> handleBindException(BindException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(ConstraintViolationException.class)
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream()
.map(violation -> violation.getMessage())
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(IllegalArgumentException.class)
public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
return Result.error(e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public Result<Void> handleRuntimeException(RuntimeException e) {
log.error("业务异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
log.error("系统异常", e);
return Result.error("系统繁忙,请稍后重试");
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.yuminailcalendarcore.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
private Integer code;
private String message;
private T data;
public static <T> Result<T> success() {
return new Result<>(200, "操作成功", null);
}
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
public static <T> Result<T> error(String message) {
return new Result<>(500, message, null);
}
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
}
@@ -1,18 +0,0 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
return builder -> {
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
};
}
}
@@ -1,22 +0,0 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.xiaowang.yuminailcalendarcore.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
@@ -1,22 +0,0 @@
package com.xiaowang.yuminailcalendarcore.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
@@ -1,123 +0,0 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/appointment")
public class AppointmentController {
private final AppointmentService appointmentService;
@GetMapping("/day")
public Result<List<AppointmentVO>> getAppointmentsByDay(@RequestParam("date")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate date,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "sortBy", required = false) String sortBy) {
return Result.success(appointmentService.getAppointmentsByDay(date, keyword, sortBy));
}
@GetMapping("/list")
public Result<List<AppointmentVO>> searchAppointments(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate,
@RequestParam(value = "customerId", required = false) Long customerId,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "serviceName", required = false) String serviceName,
@RequestParam(value = "status", required = false) String status,
@RequestParam(value = "sortBy", required = false) String sortBy) {
return Result.success(appointmentService.searchAppointments(startDate, endDate, customerId, keyword, serviceName, status, sortBy));
}
@GetMapping("/month-overview")
public Result<List<CalendarDaySummaryVO>> getMonthOverview(@RequestParam("month") String month) {
return Result.success(appointmentService.getMonthSummary(YearMonth.parse(month)));
}
@GetMapping("/dashboard")
public Result<AppointmentDashboardVO> getDashboard(@RequestParam(value = "date", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate date) {
return Result.success(appointmentService.getDashboard(date));
}
@GetMapping("/{id}")
public Result<AppointmentVO> getAppointment(@PathVariable("id") Long id) {
return Result.success(appointmentService.getAppointment(id));
}
@PostMapping
public Result<List<AppointmentVO>> createAppointment(@Valid @RequestBody AppointmentSaveRequest request) {
return Result.success(appointmentService.createAppointment(request));
}
@PutMapping("/{id}")
public Result<List<AppointmentVO>> updateAppointment(@PathVariable("id") Long id,
@Valid @RequestBody AppointmentSaveRequest request) {
return Result.success(appointmentService.updateAppointment(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteAppointment(@PathVariable("id") Long id,
@RequestParam(value = "deleteSeries", defaultValue = "false") boolean deleteSeries) {
appointmentService.deleteAppointment(id, deleteSeries);
return Result.success();
}
@PostMapping("/batch-delete")
public Result<Void> batchDelete(@Valid @RequestBody AppointmentBatchDeleteRequest request) {
appointmentService.batchDelete(request);
return Result.success();
}
@PatchMapping("/{id}/status")
public Result<AppointmentVO> updateStatus(@PathVariable("id") Long id,
@Valid @RequestBody AppointmentStatusUpdateRequest request) {
return Result.success(appointmentService.updateStatus(id, request));
}
@GetMapping("/export")
public Result<AppointmentExportVO> exportAppointments(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate) {
return Result.success(appointmentService.exportAppointments(startDate, endDate));
}
@PostMapping("/import")
public Result<List<AppointmentVO>> importAppointments(@Valid @RequestBody AppointmentImportRequest request) {
return Result.success(appointmentService.importAppointments(request));
}
}
@@ -1,59 +0,0 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.BackupImportRequest;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.BackupExportVO;
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.validation.Valid;
import java.time.LocalDateTime;
import java.util.Collections;
@RestController
@RequiredArgsConstructor
@RequestMapping("/backup")
public class BackupController {
private final AppointmentService appointmentService;
private final CustomerService customerService;
private final ServiceOrderService serviceOrderService;
@GetMapping("/export")
public Result<BackupExportVO> exportAll() {
BackupExportVO exportVO = new BackupExportVO();
exportVO.setExportedAt(LocalDateTime.now());
exportVO.setCustomers(customerService.searchCustomers(null, null));
exportVO.setAppointments(appointmentService.searchAppointments(null, null, null, null, null, null, "time"));
exportVO.setOrders(serviceOrderService.searchOrders(null, null, null, null, null, null));
exportVO.setCustomerCount(exportVO.getCustomers().size());
exportVO.setAppointmentCount(exportVO.getAppointments().size());
exportVO.setOrderCount(exportVO.getOrders().size());
exportVO.setSettings(Collections.emptyMap());
return Result.success(exportVO);
}
@PostMapping("/import")
public Result<Void> importAll(@Valid @RequestBody BackupImportRequest request) {
if (request.getCustomers() != null && !request.getCustomers().isEmpty()) {
customerService.importCustomers(request.getCustomers());
}
if (request.getAppointments() != null && !request.getAppointments().isEmpty()) {
AppointmentImportRequest appointmentImportRequest = new AppointmentImportRequest();
appointmentImportRequest.setAppointments(request.getAppointments());
appointmentService.importAppointments(appointmentImportRequest);
}
if (request.getOrders() != null && !request.getOrders().isEmpty()) {
serviceOrderService.importOrders(request.getOrders());
}
return Result.success();
}
}
@@ -1,55 +0,0 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
@GetMapping("/list")
public Result<List<CustomerVO>> searchCustomers(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "tag", required = false) String tag) {
return Result.success(customerService.searchCustomers(keyword, tag));
}
@GetMapping("/{id}")
public Result<CustomerVO> getCustomer(@PathVariable("id") Long id) {
return Result.success(customerService.getCustomer(id));
}
@PostMapping
public Result<CustomerVO> createCustomer(@Valid @RequestBody CustomerSaveRequest request) {
return Result.success(customerService.createCustomer(request));
}
@PutMapping("/{id}")
public Result<CustomerVO> updateCustomer(@PathVariable("id") Long id,
@Valid @RequestBody CustomerSaveRequest request) {
return Result.success(customerService.updateCustomer(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteCustomer(@PathVariable("id") Long id) {
customerService.deleteCustomer(id);
return Result.success();
}
}
@@ -1,16 +0,0 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/health")
public class HealthController {
@GetMapping("/check")
public Result<String> check() {
return Result.success("YumiNail-Calendar-Core is running");
}
}
@@ -1,65 +0,0 @@
package com.xiaowang.yuminailcalendarcore.controller;
import com.xiaowang.yuminailcalendarcore.common.Result;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/order")
public class OrderController {
private final ServiceOrderService serviceOrderService;
@GetMapping("/list")
public Result<List<ServiceOrderVO>> searchOrders(@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate,
@RequestParam(value = "customerId", required = false) Long customerId,
@RequestParam(value = "appointmentId", required = false) Long appointmentId,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "paymentStatus", required = false) String paymentStatus) {
return Result.success(serviceOrderService.searchOrders(startDate, endDate, customerId, appointmentId, keyword, paymentStatus));
}
@GetMapping("/{id}")
public Result<ServiceOrderVO> getOrder(@PathVariable("id") Long id) {
return Result.success(serviceOrderService.getOrder(id));
}
@PostMapping
public Result<ServiceOrderVO> createOrder(@Valid @RequestBody OrderSaveRequest request) {
return Result.success(serviceOrderService.createOrder(request));
}
@PutMapping("/{id}")
public Result<ServiceOrderVO> updateOrder(@PathVariable("id") Long id,
@Valid @RequestBody OrderSaveRequest request) {
return Result.success(serviceOrderService.updateOrder(id, request));
}
@DeleteMapping("/{id}")
public Result<Void> deleteOrder(@PathVariable("id") Long id) {
serviceOrderService.deleteOrder(id);
return Result.success();
}
}
@@ -1,15 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Data
public class AppointmentBatchDeleteRequest {
@NotEmpty(message = "请选择要删除的预约")
private List<Long> ids;
private Boolean deleteSeries;
}
@@ -1,15 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;
@Data
public class AppointmentImportRequest {
@Valid
@NotEmpty(message = "导入内容不能为空")
private List<AppointmentSaveRequest> appointments;
}
@@ -1,69 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class AppointmentSaveRequest {
private Long id;
private Long seriesId;
private Long customerId;
private Long orderId;
@NotBlank(message = "客户姓名不能为空")
@Size(max = 50, message = "客户姓名长度不能超过50个字符")
private String customerName;
@Pattern(regexp = "^$|^[0-9+\\-() ]{6,20}$", message = "联系电话格式不正确")
private String customerPhone;
@NotNull(message = "预约开始时间不能为空")
private LocalDateTime appointmentStartTime;
@NotNull(message = "预约结束时间不能为空")
private LocalDateTime appointmentEndTime;
@NotBlank(message = "服务项目不能为空")
@Size(max = 100, message = "服务项目长度不能超过100个字符")
private String serviceName;
@NotBlank(message = "预约类型不能为空")
@Size(max = 32, message = "预约类型长度不能超过32个字符")
private String appointmentType;
@Size(max = 64, message = "订单号长度不能超过64个字符")
private String orderReference;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
@Min(value = 0, message = "提醒时间不能小于0分钟")
@Max(value = 10080, message = "提醒时间不能超过7天")
private Integer reminderMinutes;
@Size(max = 32, message = "重复类型长度不能超过32个字符")
private String repeatType;
private LocalDate repeatUntil;
@Size(max = 32, message = "预约状态长度不能超过32个字符")
private String status;
private Boolean notificationEnabled;
private Boolean applyToSeries;
private LocalDateTime expectedUpdateTime;
}
@@ -1,17 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
@Data
public class AppointmentStatusUpdateRequest {
@NotBlank(message = "预约状态不能为空")
@Size(max = 32, message = "预约状态长度不能超过32个字符")
private String status;
private LocalDateTime expectedUpdateTime;
}
@@ -1,22 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
@Data
public class BackupImportRequest {
@Valid
private List<CustomerSaveRequest> customers;
@Valid
private List<OrderSaveRequest> orders;
@Valid
private List<AppointmentSaveRequest> appointments;
private Map<String, Object> settings;
}
@@ -1,33 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
@Data
public class CustomerSaveRequest {
private Long id;
@Size(max = 50, message = "客户姓名长度不能超过50个字符")
private String name;
@Pattern(regexp = "^$|^[0-9+\\-() ]{6,20}$", message = "联系电话格式不正确")
private String phone;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
@Size(max = 500, message = "偏好长度不能超过500个字符")
private String preferences;
@Size(max = 500, message = "禁忌说明长度不能超过500个字符")
private String cautions;
@Size(max = 255, message = "标签长度不能超过255个字符")
private String tags;
private LocalDateTime expectedUpdateTime;
}
@@ -1,42 +0,0 @@
package com.xiaowang.yuminailcalendarcore.dto;
import lombok.Data;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
public class OrderSaveRequest {
private Long id;
private Long customerId;
private Long appointmentId;
@Size(max = 100, message = "服务项目长度不能超过100个字符")
private String serviceName;
private LocalDateTime appointmentTime;
@DecimalMin(value = "0.00", inclusive = true, message = "成交金额不能小于0")
private BigDecimal amount;
@DecimalMin(value = "0.00", inclusive = true, message = "定金不能小于0")
private BigDecimal depositAmount;
@DecimalMin(value = "0.00", inclusive = true, message = "实收金额不能小于0")
private BigDecimal receivedAmount;
@Size(max = 32, message = "支付状态长度不能超过32个字符")
private String paymentStatus;
private LocalDateTime completedAt;
@Size(max = 500, message = "备注长度不能超过500个字符")
private String notes;
private LocalDateTime expectedUpdateTime;
}
@@ -1,50 +0,0 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_appointment")
public class AppointmentDO extends BaseEntity {
private Long seriesId;
private Long customerId;
private Long orderId;
private String customerName;
private String customerPhone;
private LocalDate appointmentDate;
private LocalDateTime appointmentStartTime;
private LocalDateTime appointmentEndTime;
private String serviceName;
private String appointmentType;
private String orderReference;
private String notes;
private Integer reminderMinutes;
private String repeatType;
private LocalDate repeatUntil;
private String status;
private Boolean notificationEnabled;
private String syncStatus;
}
@@ -1,22 +0,0 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public abstract class BaseEntity {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -1,23 +0,0 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_customer")
public class CustomerDO extends BaseEntity {
private String name;
private String phone;
private String notes;
private String preferences;
private String cautions;
private String tags;
}
@@ -1,38 +0,0 @@
package com.xiaowang.yuminailcalendarcore.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_calendar_order")
public class ServiceOrderDO extends BaseEntity {
private Long customerId;
private Long appointmentId;
private String customerName;
private String customerPhone;
private String serviceName;
private LocalDateTime appointmentTime;
private BigDecimal amount;
private BigDecimal depositAmount;
private BigDecimal receivedAmount;
private String paymentStatus;
private LocalDateTime completedAt;
private String notes;
}
@@ -1,7 +0,0 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
public interface AppointmentMapper extends BaseMapper<AppointmentDO> {
}
@@ -1,7 +0,0 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
public interface CustomerMapper extends BaseMapper<CustomerDO> {
}
@@ -1,7 +0,0 @@
package com.xiaowang.yuminailcalendarcore.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
public interface ServiceOrderMapper extends BaseMapper<ServiceOrderDO> {
}
@@ -1,42 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
public interface AppointmentService {
List<AppointmentVO> getAppointmentsByDay(LocalDate date, String keyword, String sortBy);
List<AppointmentVO> searchAppointments(LocalDate startDate, LocalDate endDate, Long customerId, String keyword,
String serviceName, String status, String sortBy);
List<CalendarDaySummaryVO> getMonthSummary(YearMonth month);
AppointmentDashboardVO getDashboard(LocalDate date);
AppointmentVO getAppointment(Long id);
List<AppointmentVO> createAppointment(AppointmentSaveRequest request);
List<AppointmentVO> updateAppointment(Long id, AppointmentSaveRequest request);
void deleteAppointment(Long id, boolean deleteSeries);
void batchDelete(AppointmentBatchDeleteRequest request);
AppointmentVO updateStatus(Long id, AppointmentStatusUpdateRequest request);
AppointmentExportVO exportAppointments(LocalDate startDate, LocalDate endDate);
List<AppointmentVO> importAppointments(AppointmentImportRequest request);
}
@@ -1,21 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import java.util.List;
public interface CustomerService {
List<CustomerVO> searchCustomers(String keyword, String tag);
CustomerVO getCustomer(Long id);
CustomerVO createCustomer(CustomerSaveRequest request);
CustomerVO updateCustomer(Long id, CustomerSaveRequest request);
void deleteCustomer(Long id);
List<CustomerVO> importCustomers(List<CustomerSaveRequest> requests);
}
@@ -1,23 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import java.time.LocalDate;
import java.util.List;
public interface ServiceOrderService {
List<ServiceOrderVO> searchOrders(LocalDate startDate, LocalDate endDate, Long customerId, Long appointmentId,
String keyword, String paymentStatus);
ServiceOrderVO getOrder(Long id);
ServiceOrderVO createOrder(OrderSaveRequest request);
ServiceOrderVO updateOrder(Long id, OrderSaveRequest request);
void deleteOrder(Long id);
List<ServiceOrderVO> importOrders(List<OrderSaveRequest> requests);
}
@@ -1,574 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
import com.xiaowang.yuminailcalendarcore.vo.IncomeTrendPointVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, AppointmentDO> implements AppointmentService {
private static final String STATUS_SCHEDULED = "SCHEDULED";
private static final String STATUS_IN_SERVICE = "IN_SERVICE";
private static final String STATUS_COMPLETED = "COMPLETED";
private static final String STATUS_CANCELLED = "CANCELLED";
private static final String STATUS_NO_SHOW = "NO_SHOW";
private static final String STATUS_MISSED = "MISSED";
private static final String REPEAT_NONE = "NONE";
private static final String REPEAT_WEEKLY = "WEEKLY";
private static final String REPEAT_MONTHLY = "MONTHLY";
private static final String SYNC_STATUS_SYNCED = "SYNCED";
private final CustomerMapper customerMapper;
private final ServiceOrderMapper serviceOrderMapper;
@Override
public List<AppointmentVO> getAppointmentsByDay(LocalDate date, String keyword, String sortBy) {
if (date == null) {
throw new IllegalArgumentException("请选择查询日期");
}
LambdaQueryWrapper<AppointmentDO> queryWrapper = new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getAppointmentDate, date);
applyKeywordFilter(queryWrapper, keyword);
applySort(queryWrapper, sortBy);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public List<AppointmentVO> searchAppointments(LocalDate startDate, LocalDate endDate, Long customerId, String keyword,
String serviceName, String status, String sortBy) {
LambdaQueryWrapper<AppointmentDO> queryWrapper = new LambdaQueryWrapper<>();
if (startDate != null) {
queryWrapper.ge(AppointmentDO::getAppointmentDate, startDate);
}
if (endDate != null) {
queryWrapper.le(AppointmentDO::getAppointmentDate, endDate);
}
if (customerId != null) {
queryWrapper.eq(AppointmentDO::getCustomerId, customerId);
}
if (StringUtils.hasText(serviceName)) {
queryWrapper.like(AppointmentDO::getServiceName, serviceName.trim());
}
if (StringUtils.hasText(status)) {
queryWrapper.eq(AppointmentDO::getStatus, normalizeStatus(status));
}
applyKeywordFilter(queryWrapper, keyword);
applySort(queryWrapper, sortBy);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public List<CalendarDaySummaryVO> getMonthSummary(YearMonth month) {
if (month == null) {
throw new IllegalArgumentException("请选择查询月份");
}
LocalDate startDate = month.atDay(1);
LocalDate endDate = month.atEndOfMonth();
List<AppointmentDO> appointments = list(new LambdaQueryWrapper<AppointmentDO>()
.between(AppointmentDO::getAppointmentDate, startDate, endDate)
.orderByAsc(AppointmentDO::getAppointmentDate)
.orderByAsc(AppointmentDO::getAppointmentStartTime));
Map<LocalDate, CalendarDaySummaryVO> daySummaryMap = new LinkedHashMap<>();
for (AppointmentDO appointment : appointments) {
CalendarDaySummaryVO summary = daySummaryMap.computeIfAbsent(appointment.getAppointmentDate(), key -> {
CalendarDaySummaryVO item = new CalendarDaySummaryVO();
item.setDate(key);
item.setTotalCount(0);
item.setScheduledCount(0);
item.setCompletedCount(0);
item.setCancelledCount(0);
return item;
});
summary.setTotalCount(summary.getTotalCount() + 1);
String normalizedStatus = normalizeStatus(appointment.getStatus());
if (STATUS_COMPLETED.equals(normalizedStatus)) {
summary.setCompletedCount(summary.getCompletedCount() + 1);
} else if (STATUS_CANCELLED.equals(normalizedStatus) || STATUS_NO_SHOW.equals(normalizedStatus)) {
summary.setCancelledCount(summary.getCancelledCount() + 1);
} else {
summary.setScheduledCount(summary.getScheduledCount() + 1);
}
}
return new ArrayList<>(daySummaryMap.values());
}
@Override
public AppointmentDashboardVO getDashboard(LocalDate date) {
LocalDate targetDate = date == null ? LocalDate.now() : date;
List<AppointmentDO> appointments = list();
List<ServiceOrderDO> orders = serviceOrderMapper.selectList(null);
LocalDateTime now = LocalDateTime.now();
LocalDateTime reminderWindowEnd = now.plusHours(24);
int total = appointments.size();
int today = 0;
int scheduled = 0;
int completed = 0;
int cancelled = 0;
int upcomingReminderCount = 0;
for (AppointmentDO appointment : appointments) {
String normalizedStatus = normalizeStatus(appointment.getStatus());
if (targetDate.equals(appointment.getAppointmentDate())) {
today++;
if (STATUS_SCHEDULED.equals(normalizedStatus) || STATUS_IN_SERVICE.equals(normalizedStatus)) {
scheduled++;
}
if (STATUS_COMPLETED.equals(normalizedStatus)) {
completed++;
}
if (STATUS_CANCELLED.equals(normalizedStatus) || STATUS_NO_SHOW.equals(normalizedStatus)) {
cancelled++;
}
}
if ((STATUS_SCHEDULED.equals(normalizedStatus) || STATUS_IN_SERVICE.equals(normalizedStatus))
&& Boolean.TRUE.equals(appointment.getNotificationEnabled())
&& !appointment.getAppointmentStartTime().isBefore(now)
&& !appointment.getAppointmentStartTime().isAfter(reminderWindowEnd)) {
upcomingReminderCount++;
}
}
BigDecimal todayIncome = BigDecimal.ZERO;
BigDecimal pendingReceivables = BigDecimal.ZERO;
Map<LocalDate, BigDecimal> trendMap = new LinkedHashMap<>();
for (int index = 6; index >= 0; index--) {
trendMap.put(targetDate.minusDays(index), BigDecimal.ZERO);
}
for (ServiceOrderDO order : orders) {
BigDecimal outstanding = normalizeAmount(order.getAmount()).subtract(normalizeAmount(order.getReceivedAmount()));
if (outstanding.compareTo(BigDecimal.ZERO) > 0 && !"REFUNDED".equals(normalizePaymentStatus(order.getPaymentStatus()))) {
pendingReceivables = pendingReceivables.add(outstanding);
}
if (order.getCompletedAt() != null) {
LocalDate completedDate = order.getCompletedAt().toLocalDate();
if (targetDate.equals(completedDate)) {
todayIncome = todayIncome.add(normalizeAmount(order.getReceivedAmount()));
}
if (trendMap.containsKey(completedDate)) {
trendMap.put(completedDate, trendMap.get(completedDate).add(normalizeAmount(order.getReceivedAmount())));
}
}
}
AppointmentDashboardVO dashboardVO = new AppointmentDashboardVO();
dashboardVO.setTotalAppointments(total);
dashboardVO.setTodayAppointments(today);
dashboardVO.setScheduledAppointments(scheduled);
dashboardVO.setCompletedAppointments(completed);
dashboardVO.setCancelledAppointments(cancelled);
dashboardVO.setUpcomingReminderCount(upcomingReminderCount);
dashboardVO.setPendingReminders(upcomingReminderCount);
dashboardVO.setTodayIncome(todayIncome);
dashboardVO.setPendingReceivables(pendingReceivables);
dashboardVO.setIncomeTrend(trendMap.entrySet().stream().map(entry -> {
IncomeTrendPointVO pointVO = new IncomeTrendPointVO();
pointVO.setDate(entry.getKey());
pointVO.setAmount(entry.getValue());
return pointVO;
}).collect(Collectors.toList()));
return dashboardVO;
}
@Override
public AppointmentVO getAppointment(Long id) {
return toVO(getByIdOrThrow(id));
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> createAppointment(AppointmentSaveRequest request) {
String repeatType = normalizeRepeatType(request.getRepeatType());
Long seriesId = REPEAT_NONE.equals(repeatType)
? request.getSeriesId()
: (request.getSeriesId() == null ? IdWorker.getId() : request.getSeriesId());
List<AppointmentDO> appointments = buildSeriesAppointments(request, seriesId);
saveBatch(appointments);
return appointments.stream()
.sorted(Comparator.comparing(AppointmentDO::getAppointmentStartTime))
.map(this::toVO)
.collect(Collectors.toList());
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> updateAppointment(Long id, AppointmentSaveRequest request) {
AppointmentDO existing = getByIdOrThrow(id);
assertExpectedUpdateTime(existing, request.getExpectedUpdateTime());
boolean applyToSeries = Boolean.TRUE.equals(request.getApplyToSeries());
String repeatType = normalizeRepeatType(request.getRepeatType());
if (applyToSeries) {
Long seriesId = existing.getSeriesId() == null ? IdWorker.getId() : existing.getSeriesId();
if (existing.getSeriesId() == null) {
removeById(existing.getId());
} else {
remove(new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getSeriesId, seriesId)
.ge(AppointmentDO::getAppointmentStartTime, existing.getAppointmentStartTime()));
}
request.setSeriesId(REPEAT_NONE.equals(repeatType) ? seriesId : (request.getSeriesId() == null ? seriesId : request.getSeriesId()));
List<AppointmentDO> appointments = buildSeriesAppointments(request, request.getSeriesId());
saveBatch(appointments);
return appointments.stream()
.sorted(Comparator.comparing(AppointmentDO::getAppointmentStartTime))
.map(this::toVO)
.collect(Collectors.toList());
}
validateRequest(request);
copyEditableFields(existing, request, existing.getSeriesId());
existing.setAppointmentStartTime(request.getAppointmentStartTime());
existing.setAppointmentEndTime(request.getAppointmentEndTime());
existing.setAppointmentDate(request.getAppointmentStartTime().toLocalDate());
existing.setRepeatType(repeatType);
existing.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
if (StringUtils.hasText(request.getStatus())) {
existing.setStatus(normalizeStatus(request.getStatus()));
}
updateById(existing);
return List.of(toVO(existing));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAppointment(Long id, boolean deleteSeries) {
AppointmentDO existing = getByIdOrThrow(id);
if (deleteSeries && existing.getSeriesId() != null) {
remove(new LambdaQueryWrapper<AppointmentDO>().eq(AppointmentDO::getSeriesId, existing.getSeriesId()));
return;
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void batchDelete(AppointmentBatchDeleteRequest request) {
if (CollectionUtils.isEmpty(request.getIds())) {
throw new IllegalArgumentException("请选择要删除的预约");
}
if (!Boolean.TRUE.equals(request.getDeleteSeries())) {
removeByIds(request.getIds());
return;
}
List<AppointmentDO> appointments = listByIds(request.getIds());
Set<Long> seriesIds = appointments.stream()
.map(AppointmentDO::getSeriesId)
.filter(seriesId -> seriesId != null)
.collect(Collectors.toCollection(LinkedHashSet::new));
Set<Long> singleIds = appointments.stream()
.filter(appointment -> appointment.getSeriesId() == null)
.map(AppointmentDO::getId)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (!seriesIds.isEmpty()) {
remove(new LambdaQueryWrapper<AppointmentDO>().in(AppointmentDO::getSeriesId, seriesIds));
}
if (!singleIds.isEmpty()) {
removeByIds(singleIds);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public AppointmentVO updateStatus(Long id, AppointmentStatusUpdateRequest request) {
AppointmentDO existing = getByIdOrThrow(id);
assertExpectedUpdateTime(existing, request.getExpectedUpdateTime());
existing.setStatus(normalizeStatus(request.getStatus()));
updateById(existing);
return toVO(existing);
}
@Override
public AppointmentExportVO exportAppointments(LocalDate startDate, LocalDate endDate) {
List<AppointmentVO> appointments = searchAppointments(startDate, endDate, null, null, null, null, "time");
AppointmentExportVO exportVO = new AppointmentExportVO();
exportVO.setExportedAt(LocalDateTime.now());
exportVO.setStartDate(startDate);
exportVO.setEndDate(endDate);
exportVO.setTotal(appointments.size());
exportVO.setAppointments(appointments);
return exportVO;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<AppointmentVO> importAppointments(AppointmentImportRequest request) {
List<AppointmentVO> imported = new ArrayList<>();
for (AppointmentSaveRequest item : request.getAppointments()) {
imported.add(toVO(saveImportedAppointment(item)));
}
return imported;
}
private List<AppointmentDO> buildSeriesAppointments(AppointmentSaveRequest request, Long seriesId) {
validateRequest(request);
List<AppointmentDO> appointments = new ArrayList<>();
String repeatType = normalizeRepeatType(request.getRepeatType());
LocalDateTime cursorStart = request.getAppointmentStartTime();
LocalDateTime cursorEnd = request.getAppointmentEndTime();
if (REPEAT_NONE.equals(repeatType)) {
appointments.add(buildAppointment(request, seriesId, cursorStart, cursorEnd, repeatType));
return appointments;
}
while (!cursorStart.toLocalDate().isAfter(request.getRepeatUntil())) {
appointments.add(buildAppointment(request, seriesId, cursorStart, cursorEnd, repeatType));
if (REPEAT_WEEKLY.equals(repeatType)) {
cursorStart = cursorStart.plusWeeks(1);
cursorEnd = cursorEnd.plusWeeks(1);
} else {
cursorStart = cursorStart.plusMonths(1);
cursorEnd = cursorEnd.plusMonths(1);
}
}
return appointments;
}
private AppointmentDO buildAppointment(AppointmentSaveRequest request, Long seriesId, LocalDateTime startTime,
LocalDateTime endTime, String repeatType) {
AppointmentDO appointment = new AppointmentDO();
copyEditableFields(appointment, request, seriesId);
appointment.setAppointmentStartTime(startTime);
appointment.setAppointmentEndTime(endTime);
appointment.setAppointmentDate(startTime.toLocalDate());
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
if (!StringUtils.hasText(appointment.getStatus())) {
appointment.setStatus(STATUS_SCHEDULED);
}
return appointment;
}
private AppointmentDO saveImportedAppointment(AppointmentSaveRequest request) {
validateRequest(request);
String repeatType = normalizeRepeatType(request.getRepeatType());
AppointmentDO appointment = request.getId() == null ? new AppointmentDO() : getById(request.getId());
if (appointment == null) {
appointment = new AppointmentDO();
}
if (request.getId() != null) {
appointment.setId(request.getId());
}
copyEditableFields(appointment, request, request.getSeriesId());
appointment.setAppointmentStartTime(request.getAppointmentStartTime());
appointment.setAppointmentEndTime(request.getAppointmentEndTime());
appointment.setAppointmentDate(request.getAppointmentStartTime().toLocalDate());
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
appointment.setStatus(normalizeStatus(request.getStatus()));
appointment.setSyncStatus(SYNC_STATUS_SYNCED);
if (appointment.getCreateTime() == null) {
save(appointment);
} else {
updateById(appointment);
}
return appointment;
}
private void copyEditableFields(AppointmentDO appointment, AppointmentSaveRequest request, Long seriesId) {
String repeatType = normalizeRepeatType(request.getRepeatType());
CustomerDO customer = request.getCustomerId() == null ? null : customerMapper.selectById(request.getCustomerId());
if (request.getCustomerId() != null && customer == null) {
throw new IllegalArgumentException("关联客户不存在");
}
appointment.setSeriesId(seriesId);
appointment.setCustomerId(customer == null ? request.getCustomerId() : customer.getId());
appointment.setOrderId(request.getOrderId());
appointment.setCustomerName(resolveCustomerName(customer, request));
appointment.setCustomerPhone(resolveCustomerPhone(customer, request));
appointment.setServiceName(requireText(request.getServiceName(), "服务项目不能为空"));
appointment.setAppointmentType(normalizeAppointmentType(request.getAppointmentType()));
appointment.setOrderReference(resolveOrderReference(request.getOrderId(), request.getOrderReference()));
appointment.setNotes(trimToNull(request.getNotes()));
appointment.setReminderMinutes(request.getReminderMinutes() == null ? 60 : request.getReminderMinutes());
appointment.setNotificationEnabled(request.getNotificationEnabled() == null || request.getNotificationEnabled());
appointment.setSyncStatus(SYNC_STATUS_SYNCED);
if (!StringUtils.hasText(appointment.getStatus())) {
appointment.setStatus(StringUtils.hasText(request.getStatus()) ? normalizeStatus(request.getStatus()) : STATUS_SCHEDULED);
}
appointment.setRepeatType(repeatType);
appointment.setRepeatUntil(REPEAT_NONE.equals(repeatType) ? null : request.getRepeatUntil());
}
private void validateRequest(AppointmentSaveRequest request) {
if (!request.getAppointmentEndTime().isAfter(request.getAppointmentStartTime())) {
throw new IllegalArgumentException("预约结束时间必须晚于开始时间");
}
requireText(request.getCustomerName(), "客户姓名不能为空");
requireText(request.getServiceName(), "服务项目不能为空");
String repeatType = normalizeRepeatType(request.getRepeatType());
if (!REPEAT_NONE.equals(repeatType)) {
if (request.getRepeatUntil() == null) {
throw new IllegalArgumentException("重复预约请填写截止日期");
}
if (request.getRepeatUntil().isBefore(request.getAppointmentStartTime().toLocalDate())) {
throw new IllegalArgumentException("重复预约截止日期不能早于开始日期");
}
}
}
private void applyKeywordFilter(LambdaQueryWrapper<AppointmentDO> queryWrapper, String keyword) {
if (!StringUtils.hasText(keyword)) {
return;
}
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(AppointmentDO::getCustomerName, trimmed)
.or()
.like(AppointmentDO::getCustomerPhone, trimmed)
.or()
.like(AppointmentDO::getServiceName, trimmed)
.or()
.like(AppointmentDO::getOrderReference, trimmed));
}
private void applySort(LambdaQueryWrapper<AppointmentDO> queryWrapper, String sortBy) {
if ("customerName".equalsIgnoreCase(sortBy)) {
queryWrapper.orderByAsc(AppointmentDO::getCustomerName)
.orderByAsc(AppointmentDO::getAppointmentStartTime);
return;
}
if ("date".equalsIgnoreCase(sortBy)) {
queryWrapper.orderByAsc(AppointmentDO::getAppointmentDate)
.orderByAsc(AppointmentDO::getAppointmentStartTime);
return;
}
queryWrapper.orderByAsc(AppointmentDO::getAppointmentStartTime)
.orderByAsc(AppointmentDO::getCustomerName);
}
private AppointmentDO getByIdOrThrow(Long id) {
AppointmentDO appointment = getById(id);
if (appointment == null) {
throw new IllegalArgumentException("预约不存在或已删除");
}
return appointment;
}
private AppointmentVO toVO(AppointmentDO appointment) {
AppointmentVO vo = new AppointmentVO();
BeanUtils.copyProperties(appointment, vo);
return vo;
}
private String normalizeRepeatType(String repeatType) {
if (!StringUtils.hasText(repeatType)) {
return REPEAT_NONE;
}
String normalized = repeatType.trim().toUpperCase(Locale.ROOT);
if (REPEAT_WEEKLY.equals(normalized) || REPEAT_MONTHLY.equals(normalized)) {
return normalized;
}
return REPEAT_NONE;
}
private String normalizeStatus(String status) {
if (!StringUtils.hasText(status)) {
return STATUS_SCHEDULED;
}
String normalized = status.trim().toUpperCase(Locale.ROOT);
if (STATUS_COMPLETED.equals(normalized) || STATUS_CANCELLED.equals(normalized)
|| STATUS_IN_SERVICE.equals(normalized) || STATUS_NO_SHOW.equals(normalized)) {
return normalized;
}
if (STATUS_MISSED.equals(normalized)) {
return STATUS_NO_SHOW;
}
return STATUS_SCHEDULED;
}
private String normalizeAppointmentType(String appointmentType) {
if (!StringUtils.hasText(appointmentType)) {
return "NORMAL";
}
return appointmentType.trim().toUpperCase(Locale.ROOT);
}
private String normalizePaymentStatus(String paymentStatus) {
return StringUtils.hasText(paymentStatus) ? paymentStatus.trim().toUpperCase(Locale.ROOT) : "UNPAID";
}
private BigDecimal normalizeAmount(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
private void assertExpectedUpdateTime(AppointmentDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("预约记录已在其他设备变更,请刷新后再决定保留哪一份");
}
}
private String resolveCustomerName(CustomerDO customer, AppointmentSaveRequest request) {
String value = customer != null && StringUtils.hasText(customer.getName()) ? customer.getName() : request.getCustomerName();
return requireText(value, "客户姓名不能为空");
}
private String resolveCustomerPhone(CustomerDO customer, AppointmentSaveRequest request) {
String value = customer != null && StringUtils.hasText(customer.getPhone()) ? customer.getPhone() : request.getCustomerPhone();
return trimToNull(value);
}
private String resolveOrderReference(Long orderId, String orderReference) {
if (orderId != null) {
return "ORD-" + orderId;
}
return trimToNull(orderReference);
}
private String requireText(String value, String message) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(message);
}
return value.trim();
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -1,193 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.CustomerSaveRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.CustomerService;
import com.xiaowang.yuminailcalendarcore.vo.CustomerVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
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 CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerDO> implements CustomerService {
private static final String STATUS_COMPLETED = "COMPLETED";
private static final String PAYMENT_REFUNDED = "REFUNDED";
private final AppointmentMapper appointmentMapper;
private final ServiceOrderMapper serviceOrderMapper;
@Override
public List<CustomerVO> searchCustomers(String keyword, String tag) {
LambdaQueryWrapper<CustomerDO> queryWrapper = new LambdaQueryWrapper<>();
if (StringUtils.hasText(keyword)) {
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(CustomerDO::getName, trimmed)
.or()
.like(CustomerDO::getPhone, trimmed));
}
if (StringUtils.hasText(tag)) {
queryWrapper.like(CustomerDO::getTags, tag.trim());
}
queryWrapper.orderByDesc(CustomerDO::getUpdateTime);
List<CustomerDO> customers = list(queryWrapper);
return enrich(customers);
}
@Override
public CustomerVO getCustomer(Long id) {
CustomerDO customer = getById(id);
if (customer == null) {
throw new IllegalArgumentException("客户不存在或已删除");
}
return enrich(List.of(customer)).get(0);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CustomerVO createCustomer(CustomerSaveRequest request) {
CustomerDO customer = new CustomerDO();
if (request.getId() != null) {
customer.setId(request.getId());
}
copyEditableFields(customer, request);
save(customer);
return getCustomer(customer.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public CustomerVO updateCustomer(Long id, CustomerSaveRequest request) {
CustomerDO customer = getById(id);
if (customer == null) {
throw new IllegalArgumentException("客户不存在或已删除");
}
assertExpectedUpdateTime(customer, request.getExpectedUpdateTime());
copyEditableFields(customer, request);
updateById(customer);
return getCustomer(customer.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCustomer(Long id) {
long appointmentCount = appointmentMapper.selectCount(new LambdaQueryWrapper<AppointmentDO>()
.eq(AppointmentDO::getCustomerId, id));
long orderCount = serviceOrderMapper.selectCount(new LambdaQueryWrapper<ServiceOrderDO>()
.eq(ServiceOrderDO::getCustomerId, id));
if (appointmentCount > 0 || orderCount > 0) {
throw new IllegalArgumentException("该客户已有预约或订单历史,暂不支持直接删除");
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<CustomerVO> importCustomers(List<CustomerSaveRequest> requests) {
for (CustomerSaveRequest request : requests) {
if (request.getId() != null && getById(request.getId()) != null) {
CustomerDO existing = getById(request.getId());
copyEditableFields(existing, request);
updateById(existing);
continue;
}
CustomerDO customer = new CustomerDO();
if (request.getId() != null) {
customer.setId(request.getId());
}
copyEditableFields(customer, request);
save(customer);
}
return searchCustomers(null, null);
}
private List<CustomerVO> enrich(List<CustomerDO> customers) {
if (customers.isEmpty()) {
return Collections.emptyList();
}
Set<Long> customerIds = customers.stream().map(CustomerDO::getId).collect(Collectors.toSet());
List<AppointmentDO> appointments = appointmentMapper.selectList(new LambdaQueryWrapper<AppointmentDO>()
.in(AppointmentDO::getCustomerId, customerIds));
List<ServiceOrderDO> orders = serviceOrderMapper.selectList(new LambdaQueryWrapper<ServiceOrderDO>()
.in(ServiceOrderDO::getCustomerId, customerIds));
Map<Long, List<AppointmentDO>> appointmentMap = appointments.stream()
.collect(Collectors.groupingBy(AppointmentDO::getCustomerId));
Map<Long, List<ServiceOrderDO>> orderMap = orders.stream()
.collect(Collectors.groupingBy(ServiceOrderDO::getCustomerId));
return customers.stream()
.map(customer -> toVO(customer, appointmentMap.get(customer.getId()), orderMap.get(customer.getId())))
.sorted(Comparator.comparing(CustomerVO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
}
private CustomerVO toVO(CustomerDO customer, List<AppointmentDO> appointments, List<ServiceOrderDO> orders) {
List<AppointmentDO> safeAppointments = appointments == null ? Collections.emptyList() : appointments;
List<ServiceOrderDO> safeOrders = orders == null ? Collections.emptyList() : orders;
CustomerVO vo = new CustomerVO();
BeanUtils.copyProperties(customer, vo);
vo.setTotalVisitCount((int) safeAppointments.stream()
.filter(item -> STATUS_COMPLETED.equalsIgnoreCase(item.getStatus()))
.count());
vo.setLastVisitTime(safeAppointments.stream()
.map(AppointmentDO::getAppointmentStartTime)
.max(LocalDateTime::compareTo)
.orElse(null));
vo.setTotalSpentAmount(safeOrders.stream()
.filter(item -> !PAYMENT_REFUNDED.equalsIgnoreCase(item.getPaymentStatus()))
.map(ServiceOrderDO::getReceivedAmount)
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
private void copyEditableFields(CustomerDO customer, CustomerSaveRequest request) {
customer.setName(requireText(request.getName(), "客户姓名不能为空"));
customer.setPhone(trimToNull(request.getPhone()));
customer.setNotes(trimToNull(request.getNotes()));
customer.setPreferences(trimToNull(request.getPreferences()));
customer.setCautions(trimToNull(request.getCautions()));
customer.setTags(trimToNull(request.getTags()));
}
private void assertExpectedUpdateTime(CustomerDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("客户资料已在其他设备变更,请先处理冲突");
}
}
private String requireText(String value, String message) {
if (!StringUtils.hasText(value)) {
throw new IllegalArgumentException(message);
}
return value.trim();
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -1,283 +0,0 @@
package com.xiaowang.yuminailcalendarcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcalendarcore.common.ConflictException;
import com.xiaowang.yuminailcalendarcore.dto.OrderSaveRequest;
import com.xiaowang.yuminailcalendarcore.entity.AppointmentDO;
import com.xiaowang.yuminailcalendarcore.entity.CustomerDO;
import com.xiaowang.yuminailcalendarcore.entity.ServiceOrderDO;
import com.xiaowang.yuminailcalendarcore.mapper.AppointmentMapper;
import com.xiaowang.yuminailcalendarcore.mapper.CustomerMapper;
import com.xiaowang.yuminailcalendarcore.mapper.ServiceOrderMapper;
import com.xiaowang.yuminailcalendarcore.service.ServiceOrderService;
import com.xiaowang.yuminailcalendarcore.vo.ServiceOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ServiceOrderServiceImpl extends ServiceImpl<ServiceOrderMapper, ServiceOrderDO> implements ServiceOrderService {
private static final String PAYMENT_UNPAID = "UNPAID";
private static final String PAYMENT_PARTIALLY_PAID = "PARTIALLY_PAID";
private static final String PAYMENT_PAID = "PAID";
private static final String PAYMENT_REFUNDED = "REFUNDED";
private final CustomerMapper customerMapper;
private final AppointmentMapper appointmentMapper;
@Override
public List<ServiceOrderVO> searchOrders(LocalDate startDate, LocalDate endDate, Long customerId, Long appointmentId,
String keyword, String paymentStatus) {
LambdaQueryWrapper<ServiceOrderDO> queryWrapper = new LambdaQueryWrapper<>();
if (startDate != null) {
queryWrapper.ge(ServiceOrderDO::getAppointmentTime, startDate.atStartOfDay());
}
if (endDate != null) {
queryWrapper.le(ServiceOrderDO::getAppointmentTime, LocalDateTime.of(endDate, LocalTime.MAX));
}
if (customerId != null) {
queryWrapper.eq(ServiceOrderDO::getCustomerId, customerId);
}
if (appointmentId != null) {
queryWrapper.eq(ServiceOrderDO::getAppointmentId, appointmentId);
}
if (StringUtils.hasText(paymentStatus)) {
queryWrapper.eq(ServiceOrderDO::getPaymentStatus, normalizePaymentStatus(paymentStatus, BigDecimal.ZERO, BigDecimal.ZERO));
}
if (StringUtils.hasText(keyword)) {
String trimmed = keyword.trim();
queryWrapper.and(wrapper -> wrapper.like(ServiceOrderDO::getCustomerName, trimmed)
.or()
.like(ServiceOrderDO::getServiceName, trimmed)
.or()
.like(ServiceOrderDO::getNotes, trimmed));
}
queryWrapper.orderByDesc(ServiceOrderDO::getAppointmentTime).orderByDesc(ServiceOrderDO::getUpdateTime);
return list(queryWrapper).stream().map(this::toVO).collect(Collectors.toList());
}
@Override
public ServiceOrderVO getOrder(Long id) {
ServiceOrderDO order = getById(id);
if (order == null) {
throw new IllegalArgumentException("订单不存在或已删除");
}
return toVO(order);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ServiceOrderVO createOrder(OrderSaveRequest request) {
ServiceOrderDO order = new ServiceOrderDO();
if (request.getId() != null) {
order.setId(request.getId());
}
copyEditableFields(order, request);
save(order);
linkAppointment(order);
return getOrder(order.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public ServiceOrderVO updateOrder(Long id, OrderSaveRequest request) {
ServiceOrderDO order = getById(id);
if (order == null) {
throw new IllegalArgumentException("订单不存在或已删除");
}
assertExpectedUpdateTime(order, request.getExpectedUpdateTime());
copyEditableFields(order, request);
updateById(order);
linkAppointment(order);
return getOrder(order.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteOrder(Long id) {
ServiceOrderDO order = getById(id);
if (order == null) {
return;
}
if (order.getAppointmentId() != null) {
AppointmentDO appointment = appointmentMapper.selectById(order.getAppointmentId());
if (appointment != null && id.equals(appointment.getOrderId())) {
appointment.setOrderId(null);
appointment.setOrderReference(null);
appointmentMapper.updateById(appointment);
}
}
removeById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<ServiceOrderVO> importOrders(List<OrderSaveRequest> requests) {
for (OrderSaveRequest request : requests) {
if (request.getId() != null && getById(request.getId()) != null) {
ServiceOrderDO existing = getById(request.getId());
copyEditableFields(existing, request);
updateById(existing);
linkAppointment(existing);
continue;
}
ServiceOrderDO order = new ServiceOrderDO();
if (request.getId() != null) {
order.setId(request.getId());
}
copyEditableFields(order, request);
save(order);
linkAppointment(order);
}
return searchOrders(null, null, null, null, null, null);
}
private void copyEditableFields(ServiceOrderDO order, OrderSaveRequest request) {
AppointmentDO appointment = request.getAppointmentId() == null ? null : appointmentMapper.selectById(request.getAppointmentId());
if (request.getAppointmentId() != null && appointment == null) {
throw new IllegalArgumentException("关联预约不存在");
}
Long customerId = request.getCustomerId() != null ? request.getCustomerId()
: (appointment == null ? null : appointment.getCustomerId());
CustomerDO customer = customerId == null ? null : customerMapper.selectById(customerId);
if (customerId != null && customer == null) {
throw new IllegalArgumentException("关联客户不存在");
}
BigDecimal amount = normalizeAmount(request.getAmount());
BigDecimal receivedAmount = normalizeAmount(request.getReceivedAmount());
BigDecimal depositAmount = normalizeAmount(request.getDepositAmount());
if (request.getAmount() == null && appointment == null) {
throw new IllegalArgumentException("成交金额不能为空");
}
order.setCustomerId(customer == null ? customerId : customer.getId());
order.setAppointmentId(appointment == null ? request.getAppointmentId() : appointment.getId());
order.setCustomerName(resolveCustomerName(customer, appointment));
order.setCustomerPhone(resolveCustomerPhone(customer, appointment));
order.setServiceName(resolveServiceName(request.getServiceName(), appointment));
order.setAppointmentTime(resolveAppointmentTime(request.getAppointmentTime(), appointment));
order.setAmount(amount);
order.setDepositAmount(depositAmount);
order.setReceivedAmount(receivedAmount);
order.setPaymentStatus(normalizePaymentStatus(request.getPaymentStatus(), amount, receivedAmount));
order.setCompletedAt(resolveCompletedAt(request.getCompletedAt(), order.getPaymentStatus()));
order.setNotes(trimToNull(request.getNotes()));
}
private void linkAppointment(ServiceOrderDO order) {
if (order.getAppointmentId() == null) {
return;
}
AppointmentDO appointment = appointmentMapper.selectById(order.getAppointmentId());
if (appointment == null) {
return;
}
appointment.setOrderId(order.getId());
appointment.setOrderReference("ORD-" + order.getId());
appointmentMapper.updateById(appointment);
}
private ServiceOrderVO toVO(ServiceOrderDO order) {
ServiceOrderVO vo = new ServiceOrderVO();
BeanUtils.copyProperties(order, vo);
vo.setOutstandingAmount(normalizeAmount(order.getAmount()).subtract(normalizeAmount(order.getReceivedAmount())).max(BigDecimal.ZERO));
return vo;
}
private void assertExpectedUpdateTime(ServiceOrderDO existing, LocalDateTime expectedUpdateTime) {
if (expectedUpdateTime != null && existing.getUpdateTime() != null && !existing.getUpdateTime().equals(expectedUpdateTime)) {
throw new ConflictException("订单已在其他设备变更,请先处理冲突");
}
}
private String resolveCustomerName(CustomerDO customer, AppointmentDO appointment) {
if (customer != null && StringUtils.hasText(customer.getName())) {
return customer.getName().trim();
}
if (appointment != null && StringUtils.hasText(appointment.getCustomerName())) {
return appointment.getCustomerName().trim();
}
return "未命名客户";
}
private String resolveCustomerPhone(CustomerDO customer, AppointmentDO appointment) {
if (customer != null && StringUtils.hasText(customer.getPhone())) {
return customer.getPhone().trim();
}
if (appointment != null && StringUtils.hasText(appointment.getCustomerPhone())) {
return appointment.getCustomerPhone().trim();
}
return null;
}
private String resolveServiceName(String serviceName, AppointmentDO appointment) {
if (StringUtils.hasText(serviceName)) {
return serviceName.trim();
}
if (appointment != null && StringUtils.hasText(appointment.getServiceName())) {
return appointment.getServiceName().trim();
}
throw new IllegalArgumentException("服务项目不能为空");
}
private LocalDateTime resolveAppointmentTime(LocalDateTime appointmentTime, AppointmentDO appointment) {
if (appointmentTime != null) {
return appointmentTime;
}
if (appointment != null) {
return appointment.getAppointmentStartTime();
}
return null;
}
private LocalDateTime resolveCompletedAt(LocalDateTime completedAt, String paymentStatus) {
if (completedAt != null) {
return completedAt;
}
if (PAYMENT_PAID.equals(paymentStatus) || PAYMENT_PARTIALLY_PAID.equals(paymentStatus)) {
return LocalDateTime.now();
}
return null;
}
private String normalizePaymentStatus(String paymentStatus, BigDecimal amount, BigDecimal receivedAmount) {
if (StringUtils.hasText(paymentStatus)) {
String normalized = paymentStatus.trim().toUpperCase(Locale.ROOT);
if (PAYMENT_UNPAID.equals(normalized) || PAYMENT_PARTIALLY_PAID.equals(normalized)
|| PAYMENT_PAID.equals(normalized) || PAYMENT_REFUNDED.equals(normalized)) {
return normalized;
}
}
if (receivedAmount.compareTo(BigDecimal.ZERO) <= 0) {
return PAYMENT_UNPAID;
}
if (receivedAmount.compareTo(amount) < 0) {
return PAYMENT_PARTIALLY_PAID;
}
return PAYMENT_PAID;
}
private BigDecimal normalizeAmount(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
private String trimToNull(String value) {
return StringUtils.hasText(value) ? value.trim() : null;
}
}
@@ -1,30 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class AppointmentDashboardVO {
private Integer totalAppointments;
private Integer todayAppointments;
private Integer scheduledAppointments;
private Integer completedAppointments;
private Integer cancelledAppointments;
private Integer upcomingReminderCount;
private Integer pendingReminders;
private BigDecimal todayIncome;
private BigDecimal pendingReceivables;
private List<IncomeTrendPointVO> incomeTrend;
}
@@ -1,21 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class AppointmentExportVO {
private LocalDateTime exportedAt;
private LocalDate startDate;
private LocalDate endDate;
private Integer total;
private List<AppointmentVO> appointments;
}
@@ -1,52 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
public class AppointmentVO {
private Long id;
private Long seriesId;
private Long customerId;
private Long orderId;
private String customerName;
private String customerPhone;
private LocalDate appointmentDate;
private LocalDateTime appointmentStartTime;
private LocalDateTime appointmentEndTime;
private String serviceName;
private String appointmentType;
private String orderReference;
private String notes;
private Integer reminderMinutes;
private String repeatType;
private LocalDate repeatUntil;
private String status;
private Boolean notificationEnabled;
private String syncStatus;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -1,27 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Data
public class BackupExportVO {
private LocalDateTime exportedAt;
private Integer customerCount;
private Integer appointmentCount;
private Integer orderCount;
private List<CustomerVO> customers;
private List<AppointmentVO> appointments;
private List<ServiceOrderVO> orders;
private Map<String, Object> settings;
}
@@ -1,19 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.time.LocalDate;
@Data
public class CalendarDaySummaryVO {
private LocalDate date;
private Integer totalCount;
private Integer scheduledCount;
private Integer completedCount;
private Integer cancelledCount;
}
@@ -1,34 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
public class CustomerVO {
private Long id;
private String name;
private String phone;
private String notes;
private String preferences;
private String cautions;
private String tags;
private LocalDateTime lastVisitTime;
private Integer totalVisitCount;
private BigDecimal totalSpentAmount;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -1,14 +0,0 @@
package com.xiaowang.yuminailcalendarcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
@Data
public class IncomeTrendPointVO {
private LocalDate date;
private BigDecimal amount;
}

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