Compare commits
87 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 20ba514117 | |||
| e3f46c3614 | |||
| fd522b6c71 | |||
| a1184ef5ed | |||
| 7c6efe9dfe | |||
| c0ece054a0 | |||
| 0d57450283 | |||
| f2033fd4b9 | |||
| 3284cb45f0 | |||
| 6041bc3419 | |||
| 4581a6fc17 | |||
| 2bdce44e12 | |||
| 4fa9fcd232 | |||
| f6911965dc | |||
| c4b2ebf7e1 | |||
| f946504cb8 | |||
| 7d2f98b7c9 | |||
| 8bc8e81e95 | |||
| 54daa923da | |||
| 463d3e2315 | |||
| 559d59b4f8 | |||
| d4f0d559cf | |||
| cbb451d18c | |||
| 595e4c62f9 | |||
| 9dd5dcb9d2 | |||
| 110c97ada4 | |||
| d748a7e75d | |||
| cf70838142 | |||
| 280437be91 | |||
| 59b7056a20 | |||
| 769622f087 | |||
| 91935e3109 | |||
| 3b3ed7b3c1 | |||
| b52e01eaa2 | |||
| 32e3dc3c73 | |||
| 6b64e8c461 | |||
| 47696b9e68 | |||
| 79427c9f4c | |||
| bcefb274ab | |||
| 3ae85f68ea | |||
| ac57272018 | |||
| 68c7b0a8ec | |||
| 0ec0e2b9d2 | |||
| ab38cd4943 | |||
| 5b49aa8242 | |||
| 9db4762904 | |||
| ae62ecc6b3 | |||
| 4b73cd4d3c | |||
| 2c9833df58 | |||
| 23a7a292ef | |||
| f1bfc78d66 | |||
| 9912df9ac6 | |||
| bafb13cf06 | |||
| 9a8ae8b6fd | |||
| c8258dc93b | |||
| c0d839deb9 | |||
| 800f9c8460 | |||
| 954b19c332 | |||
| 62cf68b49b | |||
| e818ac8764 | |||
| 98d8525fa9 | |||
| 19777df2ed | |||
| d586bbeabb | |||
| 92f278d38b | |||
| 3417da2a9e | |||
| 2362b67634 | |||
| 06e4698888 | |||
| e51dbea7c7 | |||
| c8f172dc0e | |||
| 52aaaf4de5 | |||
| 877a471e24 | |||
| 40cfe46ba8 | |||
| 5733ebe40d | |||
| 0b1e6ce3c3 | |||
| 3167465865 | |||
| 8838fc51f8 | |||
| ea34718a0b | |||
| 98972401c2 | |||
| abc9864d46 | |||
| fd48afd0ab | |||
| e3cd0643e1 | |||
| 6724e341b8 | |||
| 202c1c18d7 | |||
| e0b2be2058 | |||
| d351d9e436 | |||
| d072217e85 | |||
| c431393266 |
@@ -1,38 +0,0 @@
|
|||||||
# .agents Directory
|
|
||||||
|
|
||||||
This directory contains agent configuration and skills for OpenAI Codex CLI.
|
|
||||||
|
|
||||||
## Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
.agents/
|
|
||||||
config.toml # Main configuration file
|
|
||||||
skills/ # Skill definitions
|
|
||||||
skill-name/
|
|
||||||
SKILL.md # Skill instructions
|
|
||||||
scripts/ # Optional scripts
|
|
||||||
docs/ # Optional documentation
|
|
||||||
README.md # This file
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
The `config.toml` file controls:
|
|
||||||
- Model selection
|
|
||||||
- Approval policies
|
|
||||||
- Sandbox modes
|
|
||||||
- MCP server connections
|
|
||||||
- Skills configuration
|
|
||||||
|
|
||||||
## Skills
|
|
||||||
|
|
||||||
Skills are invoked using `$skill-name` syntax. Each skill has:
|
|
||||||
- YAML frontmatter with metadata
|
|
||||||
- Trigger and skip conditions
|
|
||||||
- Commands and examples
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
- Main instructions: `AGENTS.md` (project root)
|
|
||||||
- Local overrides: `.codex/AGENTS.override.md` (gitignored)
|
|
||||||
- Claude Flow: https://github.com/ruvnet/claude-flow
|
|
||||||
@@ -1,298 +0,0 @@
|
|||||||
# =============================================================================
|
|
||||||
# Claude Flow V3 - Codex Configuration
|
|
||||||
# =============================================================================
|
|
||||||
# Generated by: @claude-flow/codex
|
|
||||||
# Documentation: https://github.com/ruvnet/claude-flow
|
|
||||||
#
|
|
||||||
# This file configures the Codex CLI for Claude Flow integration.
|
|
||||||
# Place in .agents/config.toml (project) or .codex/config.toml (user).
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Core Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
# Model selection - the AI model to use for code generation
|
|
||||||
# Options: gpt-5.3-codex, gpt-4o, claude-sonnet, claude-opus
|
|
||||||
model = "gpt-5.3-codex"
|
|
||||||
|
|
||||||
# Approval policy determines when human approval is required
|
|
||||||
# - untrusted: Always require approval
|
|
||||||
# - on-failure: Require approval only after failures
|
|
||||||
# - on-request: Require approval for significant changes
|
|
||||||
# - never: Auto-approve all actions (use with caution)
|
|
||||||
approval_policy = "on-request"
|
|
||||||
|
|
||||||
# Sandbox mode controls file system access
|
|
||||||
# - read-only: Can only read files, no modifications
|
|
||||||
# - workspace-write: Can write within workspace directory
|
|
||||||
# - danger-full-access: Full file system access (dangerous)
|
|
||||||
sandbox_mode = "workspace-write"
|
|
||||||
|
|
||||||
# Web search enables internet access for research
|
|
||||||
# - disabled: No web access
|
|
||||||
# - cached: Use cached results when available
|
|
||||||
# - live: Always fetch fresh results
|
|
||||||
web_search = "cached"
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Project Documentation
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
# Maximum bytes to read from AGENTS.md files
|
|
||||||
project_doc_max_bytes = 65536
|
|
||||||
|
|
||||||
# Fallback filenames if AGENTS.md not found
|
|
||||||
project_doc_fallback_filenames = [
|
|
||||||
"AGENTS.md",
|
|
||||||
"TEAM_GUIDE.md",
|
|
||||||
".agents.md"
|
|
||||||
]
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Features
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[features]
|
|
||||||
# Enable child AGENTS.md guidance
|
|
||||||
child_agents_md = true
|
|
||||||
|
|
||||||
# Cache shell environment for faster repeated commands
|
|
||||||
shell_snapshot = true
|
|
||||||
|
|
||||||
# Smart approvals based on request context
|
|
||||||
request_rule = true
|
|
||||||
|
|
||||||
# Enable remote compaction for large histories
|
|
||||||
remote_compaction = true
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# MCP Servers
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[mcp_servers.claude-flow]
|
|
||||||
command = "npx"
|
|
||||||
args = ["-y", "@claude-flow/cli@latest"]
|
|
||||||
enabled = true
|
|
||||||
tool_timeout_sec = 120
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Skills Configuration
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[[skills.config]]
|
|
||||||
path = ".agents/skills/swarm-orchestration"
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
[[skills.config]]
|
|
||||||
path = ".agents/skills/memory-management"
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
[[skills.config]]
|
|
||||||
path = ".agents/skills/sparc-methodology"
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
[[skills.config]]
|
|
||||||
path = ".agents/skills/security-audit"
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Profiles
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
# Development profile - more permissive for local work
|
|
||||||
[profiles.dev]
|
|
||||||
approval_policy = "never"
|
|
||||||
sandbox_mode = "danger-full-access"
|
|
||||||
web_search = "live"
|
|
||||||
|
|
||||||
# Safe profile - maximum restrictions
|
|
||||||
[profiles.safe]
|
|
||||||
approval_policy = "untrusted"
|
|
||||||
sandbox_mode = "read-only"
|
|
||||||
web_search = "disabled"
|
|
||||||
|
|
||||||
# CI profile - for automated pipelines
|
|
||||||
[profiles.ci]
|
|
||||||
approval_policy = "never"
|
|
||||||
sandbox_mode = "workspace-write"
|
|
||||||
web_search = "cached"
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# History
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[history]
|
|
||||||
# Save all session transcripts
|
|
||||||
persistence = "save-all"
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Shell Environment
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[shell_environment_policy]
|
|
||||||
# Inherit environment variables
|
|
||||||
inherit = "core"
|
|
||||||
|
|
||||||
# Exclude sensitive variables
|
|
||||||
exclude = ["*_KEY", "*_SECRET", "*_TOKEN", "*_PASSWORD"]
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Sandbox Workspace Write Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[sandbox_workspace_write]
|
|
||||||
# Additional writable paths beyond workspace
|
|
||||||
writable_roots = []
|
|
||||||
|
|
||||||
# Allow network access
|
|
||||||
network_access = true
|
|
||||||
|
|
||||||
# Exclude temp directories
|
|
||||||
exclude_slash_tmp = false
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Security Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[security]
|
|
||||||
# Enable input validation for all user inputs
|
|
||||||
input_validation = true
|
|
||||||
|
|
||||||
# Prevent directory traversal attacks
|
|
||||||
path_traversal_prevention = true
|
|
||||||
|
|
||||||
# Scan for hardcoded secrets
|
|
||||||
secret_scanning = true
|
|
||||||
|
|
||||||
# Scan dependencies for known CVEs
|
|
||||||
cve_scanning = true
|
|
||||||
|
|
||||||
# Maximum file size for operations (bytes)
|
|
||||||
max_file_size = 10485760
|
|
||||||
|
|
||||||
# Allowed file extensions (empty = allow all)
|
|
||||||
allowed_extensions = []
|
|
||||||
|
|
||||||
# Blocked file patterns (regex)
|
|
||||||
blocked_patterns = ["\\.env$", "credentials\\.json$", "\\.pem$", "\\.key$"]
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Performance Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[performance]
|
|
||||||
# Maximum concurrent agents
|
|
||||||
max_agents = 8
|
|
||||||
|
|
||||||
# Task timeout in seconds
|
|
||||||
task_timeout = 300
|
|
||||||
|
|
||||||
# Memory limit per agent
|
|
||||||
memory_limit = "512MB"
|
|
||||||
|
|
||||||
# Enable response caching
|
|
||||||
cache_enabled = true
|
|
||||||
|
|
||||||
# Cache TTL in seconds
|
|
||||||
cache_ttl = 3600
|
|
||||||
|
|
||||||
# Enable parallel task execution
|
|
||||||
parallel_execution = true
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Logging Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[logging]
|
|
||||||
# Log level: debug, info, warn, error
|
|
||||||
level = "info"
|
|
||||||
|
|
||||||
# Log format: json, text, pretty
|
|
||||||
format = "pretty"
|
|
||||||
|
|
||||||
# Log destination: stdout, file, both
|
|
||||||
destination = "stdout"
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Neural Intelligence Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[neural]
|
|
||||||
# Enable SONA (Self-Optimizing Neural Architecture)
|
|
||||||
sona_enabled = true
|
|
||||||
|
|
||||||
# Enable HNSW vector search
|
|
||||||
hnsw_enabled = true
|
|
||||||
|
|
||||||
# HNSW index parameters
|
|
||||||
hnsw_m = 16
|
|
||||||
hnsw_ef_construction = 200
|
|
||||||
hnsw_ef_search = 100
|
|
||||||
|
|
||||||
# Enable pattern learning
|
|
||||||
pattern_learning = true
|
|
||||||
|
|
||||||
# Learning rate for neural adaptation
|
|
||||||
learning_rate = 0.01
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Swarm Orchestration Settings
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[swarm]
|
|
||||||
# Default topology: hierarchical, mesh, ring, star
|
|
||||||
default_topology = "hierarchical"
|
|
||||||
|
|
||||||
# Default strategy: balanced, specialized, adaptive
|
|
||||||
default_strategy = "specialized"
|
|
||||||
|
|
||||||
# Consensus algorithm: raft, byzantine, gossip
|
|
||||||
consensus = "raft"
|
|
||||||
|
|
||||||
# Enable anti-drift measures
|
|
||||||
anti_drift = true
|
|
||||||
|
|
||||||
# Checkpoint interval (tasks)
|
|
||||||
checkpoint_interval = 10
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Hooks Configuration
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[hooks]
|
|
||||||
# Enable lifecycle hooks
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
# Pre-task hook
|
|
||||||
pre_task = true
|
|
||||||
|
|
||||||
# Post-task hook (for learning)
|
|
||||||
post_task = true
|
|
||||||
|
|
||||||
# Enable neural training on post-edit
|
|
||||||
train_on_edit = true
|
|
||||||
|
|
||||||
# =============================================================================
|
|
||||||
# Background Workers
|
|
||||||
# =============================================================================
|
|
||||||
|
|
||||||
[workers]
|
|
||||||
# Enable background workers
|
|
||||||
enabled = true
|
|
||||||
|
|
||||||
# Worker configuration
|
|
||||||
[workers.audit]
|
|
||||||
enabled = true
|
|
||||||
priority = "critical"
|
|
||||||
interval = 300
|
|
||||||
|
|
||||||
[workers.optimize]
|
|
||||||
enabled = true
|
|
||||||
priority = "high"
|
|
||||||
interval = 600
|
|
||||||
|
|
||||||
[workers.consolidate]
|
|
||||||
enabled = true
|
|
||||||
priority = "low"
|
|
||||||
interval = 1800
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
---
|
|
||||||
name: memory-management
|
|
||||||
description: >
|
|
||||||
AgentDB memory system with HNSW vector search. Provides 150x-12,500x faster pattern retrieval, persistent storage, and semantic search capabilities for learning and knowledge management.
|
|
||||||
Use when: need to store successful patterns, searching for similar solutions, semantic lookup of past work, learning from previous tasks, sharing knowledge between agents, building knowledge base.
|
|
||||||
Skip when: no learning needed, ephemeral one-off tasks, external data sources available, read-only exploration.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Memory Management Skill
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
AgentDB memory system with HNSW vector search. Provides 150x-12,500x faster pattern retrieval, persistent storage, and semantic search capabilities for learning and knowledge management.
|
|
||||||
|
|
||||||
## When to Trigger
|
|
||||||
- need to store successful patterns
|
|
||||||
- searching for similar solutions
|
|
||||||
- semantic lookup of past work
|
|
||||||
- learning from previous tasks
|
|
||||||
- sharing knowledge between agents
|
|
||||||
- building knowledge base
|
|
||||||
|
|
||||||
## When to Skip
|
|
||||||
- no learning needed
|
|
||||||
- ephemeral one-off tasks
|
|
||||||
- external data sources available
|
|
||||||
- read-only exploration
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
### Store Pattern
|
|
||||||
Store a pattern or knowledge item in memory
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory store --key "[key]" --value "[value]" --namespace patterns
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory store --key "auth-jwt-pattern" --value "JWT validation with refresh tokens" --namespace patterns
|
|
||||||
```
|
|
||||||
|
|
||||||
### Semantic Search
|
|
||||||
Search memory using semantic similarity
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory search --query "[search terms]" --limit 10
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory search --query "authentication best practices" --limit 5
|
|
||||||
```
|
|
||||||
|
|
||||||
### Retrieve Entry
|
|
||||||
Retrieve a specific memory entry by key
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory get --key "[key]" --namespace [namespace]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory get --key "auth-jwt-pattern" --namespace patterns
|
|
||||||
```
|
|
||||||
|
|
||||||
### List Entries
|
|
||||||
List all entries in a namespace
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory list --namespace [namespace]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory list --namespace patterns --limit 20
|
|
||||||
```
|
|
||||||
|
|
||||||
### Delete Entry
|
|
||||||
Delete a memory entry
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory delete --key "[key]" --namespace [namespace]
|
|
||||||
```
|
|
||||||
|
|
||||||
### Initialize HNSW Index
|
|
||||||
Initialize HNSW vector search index
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory init --enable-hnsw
|
|
||||||
```
|
|
||||||
|
|
||||||
### Memory Stats
|
|
||||||
Show memory usage statistics
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory stats
|
|
||||||
```
|
|
||||||
|
|
||||||
### Export Memory
|
|
||||||
Export memory to JSON
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory export --output memory-backup.json
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
| Script | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| `memory-backup` | `.agents/scripts/memory-backup.sh` | Backup memory to external storage |
|
|
||||||
| `memory-consolidate` | `.agents/scripts/memory-consolidate.sh` | Consolidate and optimize memory |
|
|
||||||
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
| Document | Path | Description |
|
|
||||||
|----------|------|-------------|
|
|
||||||
| `HNSW Guide` | `docs/hnsw.md` | HNSW vector search configuration |
|
|
||||||
| `Memory Schema` | `docs/memory-schema.md` | Memory namespace and schema reference |
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
1. Check memory for existing patterns before starting
|
|
||||||
2. Use hierarchical topology for coordination
|
|
||||||
3. Store successful patterns after completion
|
|
||||||
4. Document any new learnings
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
---
|
|
||||||
name: security-audit
|
|
||||||
description: >
|
|
||||||
Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement.
|
|
||||||
Use when: authentication implementation, authorization logic, payment processing, user data handling, API endpoint creation, file upload handling, database queries, external API integration.
|
|
||||||
Skip when: read-only operations on public data, internal development tooling, static documentation, styling changes.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Security Audit Skill
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
Comprehensive security scanning and vulnerability detection. Includes input validation, path traversal prevention, CVE detection, and secure coding pattern enforcement.
|
|
||||||
|
|
||||||
## When to Trigger
|
|
||||||
- authentication implementation
|
|
||||||
- authorization logic
|
|
||||||
- payment processing
|
|
||||||
- user data handling
|
|
||||||
- API endpoint creation
|
|
||||||
- file upload handling
|
|
||||||
- database queries
|
|
||||||
- external API integration
|
|
||||||
|
|
||||||
## When to Skip
|
|
||||||
- read-only operations on public data
|
|
||||||
- internal development tooling
|
|
||||||
- static documentation
|
|
||||||
- styling changes
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
### Full Security Scan
|
|
||||||
Run comprehensive security analysis on the codebase
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --depth full
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --depth full --output security-report.json
|
|
||||||
```
|
|
||||||
|
|
||||||
### Input Validation Check
|
|
||||||
Check for input validation issues
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --check input-validation
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --check input-validation --path ./src/api
|
|
||||||
```
|
|
||||||
|
|
||||||
### Path Traversal Check
|
|
||||||
Check for path traversal vulnerabilities
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --check path-traversal
|
|
||||||
```
|
|
||||||
|
|
||||||
### SQL Injection Check
|
|
||||||
Check for SQL injection vulnerabilities
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --check sql-injection
|
|
||||||
```
|
|
||||||
|
|
||||||
### XSS Check
|
|
||||||
Check for cross-site scripting vulnerabilities
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security scan --check xss
|
|
||||||
```
|
|
||||||
|
|
||||||
### CVE Scan
|
|
||||||
Scan dependencies for known CVEs
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security cve --scan
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security cve --scan --severity high
|
|
||||||
```
|
|
||||||
|
|
||||||
### Security Audit Report
|
|
||||||
Generate full security audit report
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security audit --report
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security audit --report --format markdown --output SECURITY.md
|
|
||||||
```
|
|
||||||
|
|
||||||
### Threat Modeling
|
|
||||||
Run threat modeling analysis
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security threats --analyze
|
|
||||||
```
|
|
||||||
|
|
||||||
### Validate Secrets
|
|
||||||
Check for hardcoded secrets
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli security validate --check secrets
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
| Script | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| `security-scan` | `.agents/scripts/security-scan.sh` | Run full security scan pipeline |
|
|
||||||
| `cve-remediate` | `.agents/scripts/cve-remediate.sh` | Auto-remediate known CVEs |
|
|
||||||
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
| Document | Path | Description |
|
|
||||||
|----------|------|-------------|
|
|
||||||
| `Security Checklist` | `docs/security-checklist.md` | Security review checklist |
|
|
||||||
| `OWASP Guide` | `docs/owasp-top10.md` | OWASP Top 10 mitigation guide |
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
1. Check memory for existing patterns before starting
|
|
||||||
2. Use hierarchical topology for coordination
|
|
||||||
3. Store successful patterns after completion
|
|
||||||
4. Document any new learnings
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
---
|
|
||||||
name: sparc-methodology
|
|
||||||
description: >
|
|
||||||
SPARC development workflow: Specification, Pseudocode, Architecture, Refinement, Completion. A structured approach for complex implementations that ensures thorough planning before coding.
|
|
||||||
Use when: new feature implementation, complex implementations, architectural changes, system redesign, integration work, unclear requirements.
|
|
||||||
Skip when: simple bug fixes, documentation updates, configuration changes, well-defined small tasks, routine maintenance.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Sparc Methodology Skill
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
SPARC development workflow: Specification, Pseudocode, Architecture, Refinement, Completion. A structured approach for complex implementations that ensures thorough planning before coding.
|
|
||||||
|
|
||||||
## When to Trigger
|
|
||||||
- new feature implementation
|
|
||||||
- complex implementations
|
|
||||||
- architectural changes
|
|
||||||
- system redesign
|
|
||||||
- integration work
|
|
||||||
- unclear requirements
|
|
||||||
|
|
||||||
## When to Skip
|
|
||||||
- simple bug fixes
|
|
||||||
- documentation updates
|
|
||||||
- configuration changes
|
|
||||||
- well-defined small tasks
|
|
||||||
- routine maintenance
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
### Specification Phase
|
|
||||||
Define requirements, acceptance criteria, and constraints
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "specification: [requirements]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "specification: user authentication with OAuth2, MFA, and session management"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Pseudocode Phase
|
|
||||||
Write high-level pseudocode for the implementation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "pseudocode: [feature]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "pseudocode: OAuth2 login flow with token refresh"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Architecture Phase
|
|
||||||
Design system structure, interfaces, and dependencies
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "architecture: [design]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "architecture: auth module with service layer, repository, and API endpoints"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Refinement Phase
|
|
||||||
Iterate on the design based on feedback
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "refinement: [feedback]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "refinement: add rate limiting and brute force protection"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Completion Phase
|
|
||||||
Finalize implementation with tests and documentation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "completion: [final checks]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "completion: verify all tests pass, update API docs, security review"
|
|
||||||
```
|
|
||||||
|
|
||||||
### SPARC Coordinator
|
|
||||||
Spawn SPARC coordinator agent
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli agent spawn --type sparc-coord --name sparc-lead
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
| Script | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| `sparc-init` | `.agents/scripts/sparc-init.sh` | Initialize SPARC workflow for a new feature |
|
|
||||||
| `sparc-review` | `.agents/scripts/sparc-review.sh` | Run SPARC phase review checklist |
|
|
||||||
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
| Document | Path | Description |
|
|
||||||
|----------|------|-------------|
|
|
||||||
| `SPARC Overview` | `docs/sparc.md` | Complete SPARC methodology guide |
|
|
||||||
| `Phase Templates` | `docs/sparc-templates.md` | Templates for each SPARC phase |
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
1. Check memory for existing patterns before starting
|
|
||||||
2. Use hierarchical topology for coordination
|
|
||||||
3. Store successful patterns after completion
|
|
||||||
4. Document any new learnings
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
---
|
|
||||||
name: swarm-orchestration
|
|
||||||
description: >
|
|
||||||
Multi-agent swarm coordination for complex tasks. Uses hierarchical topology with specialized agents to break down and execute complex work across multiple files and modules.
|
|
||||||
Use when: 3+ files need changes, new feature implementation, cross-module refactoring, API changes with tests, security-related changes, performance optimization across codebase, database schema changes.
|
|
||||||
Skip when: single file edits, simple bug fixes (1-2 lines), documentation updates, configuration changes, quick exploration.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Swarm Orchestration Skill
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
Multi-agent swarm coordination for complex tasks. Uses hierarchical topology with specialized agents to break down and execute complex work across multiple files and modules.
|
|
||||||
|
|
||||||
## When to Trigger
|
|
||||||
- 3+ files need changes
|
|
||||||
- new feature implementation
|
|
||||||
- cross-module refactoring
|
|
||||||
- API changes with tests
|
|
||||||
- security-related changes
|
|
||||||
- performance optimization across codebase
|
|
||||||
- database schema changes
|
|
||||||
|
|
||||||
## When to Skip
|
|
||||||
- single file edits
|
|
||||||
- simple bug fixes (1-2 lines)
|
|
||||||
- documentation updates
|
|
||||||
- configuration changes
|
|
||||||
- quick exploration
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
### Initialize Swarm
|
|
||||||
Start a new swarm with hierarchical topology (anti-drift)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli swarm init --topology hierarchical --max-agents 8 --strategy specialized
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli swarm init --topology hierarchical --max-agents 6 --strategy specialized
|
|
||||||
```
|
|
||||||
|
|
||||||
### Route Task
|
|
||||||
Route a task to the appropriate agents based on task type
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "[task description]"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli hooks route --task "implement OAuth2 authentication flow"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Spawn Agent
|
|
||||||
Spawn a specific agent type
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli agent spawn --type [type] --name [name]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli agent spawn --type coder --name impl-auth
|
|
||||||
```
|
|
||||||
|
|
||||||
### Monitor Status
|
|
||||||
Check the current swarm status
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli swarm status --verbose
|
|
||||||
```
|
|
||||||
|
|
||||||
### Orchestrate Task
|
|
||||||
Orchestrate a task across multiple agents
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli task orchestrate --task "[task]" --strategy adaptive
|
|
||||||
```
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli task orchestrate --task "refactor auth module" --strategy parallel --max-agents 4
|
|
||||||
```
|
|
||||||
|
|
||||||
### List Agents
|
|
||||||
List all active agents
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli agent list --filter active
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
| Script | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| `swarm-start` | `.agents/scripts/swarm-start.sh` | Initialize swarm with default settings |
|
|
||||||
| `swarm-monitor` | `.agents/scripts/swarm-monitor.sh` | Real-time swarm monitoring dashboard |
|
|
||||||
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
| Document | Path | Description |
|
|
||||||
|----------|------|-------------|
|
|
||||||
| `Agent Types` | `docs/agents.md` | Complete list of agent types and capabilities |
|
|
||||||
| `Topology Guide` | `docs/topology.md` | Swarm topology configuration guide |
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
1. Check memory for existing patterns before starting
|
|
||||||
2. Use hierarchical topology for coordination
|
|
||||||
3. Store successful patterns after completion
|
|
||||||
4. Document any new learnings
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var c config.Config
|
||||||
|
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||||
|
ctx := svc.NewServiceContext(c)
|
||||||
|
const key = "cache:auth:method:device"
|
||||||
|
before, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
|
||||||
|
fmt.Printf("cache before=%q\n", before)
|
||||||
|
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||||
|
fmt.Printf("model err=%v enabled_nil=%v", err, m == nil || m.Enabled == nil)
|
||||||
|
if m != nil && m.Enabled != nil { fmt.Printf(" enabled=%v", *m.Enabled) }
|
||||||
|
if m != nil { fmt.Printf(" config=%s", m.Config) }
|
||||||
|
fmt.Println()
|
||||||
|
after, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
|
||||||
|
fmt.Printf("cache after=%q\n", after)
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
initpkg "github.com/perfect-panel/server/initialize"
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var c config.Config
|
||||||
|
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||||
|
ctx := svc.NewServiceContext(c)
|
||||||
|
method, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("db auth_method.enabled=%v config=%s\n", *method.Enabled, method.Config)
|
||||||
|
initpkg.Device(ctx)
|
||||||
|
fmt.Printf("ctx.Config.Device.Enable=%v SecuritySecret=%q EnableSecurity=%v\n", ctx.Config.Device.Enable, ctx.Config.Device.SecuritySecret, ctx.Config.Device.EnableSecurity)
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
type row struct {
|
||||||
|
ID int64
|
||||||
|
Method string
|
||||||
|
Enabled int
|
||||||
|
Config string
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var c config.Config
|
||||||
|
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||||
|
ctx := svc.NewServiceContext(c)
|
||||||
|
|
||||||
|
var rows []row
|
||||||
|
if err := ctx.DB.Raw("SELECT id, method, enabled, config FROM auth_method WHERE method = ?", "device").Scan(&rows).Error; err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("raw rows: %+v\n", rows)
|
||||||
|
|
||||||
|
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
|
||||||
|
fmt.Printf("model err=%v\n", err)
|
||||||
|
if err == nil && m != nil && m.Enabled != nil {
|
||||||
|
fmt.Printf("model row: id=%d method=%s enabled=%v config=%s\n", m.Id, m.Method, *m.Enabled, m.Config)
|
||||||
|
} else {
|
||||||
|
fmt.Printf("model row nil or no enabled ptr: %#v\n", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
authmodel "github.com/perfect-panel/server/internal/model/auth"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var c config.Config
|
||||||
|
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
|
||||||
|
ctx := svc.NewServiceContext(c)
|
||||||
|
|
||||||
|
var a1 authmodel.Auth
|
||||||
|
err1 := ctx.DB.Model(&authmodel.Auth{}).Where("method = ?", "device").First(&a1).Error
|
||||||
|
fmt.Printf("gorm direct err=%v enabled_nil=%v", err1, a1.Enabled == nil)
|
||||||
|
if a1.Enabled != nil { fmt.Printf(" enabled=%v", *a1.Enabled) }
|
||||||
|
fmt.Printf(" config=%s\n", a1.Config)
|
||||||
|
|
||||||
|
var a2 authmodel.Auth
|
||||||
|
err2 := ctx.DB.Table("auth_method").Where("method = ?", "device").First(&a2).Error
|
||||||
|
fmt.Printf("gorm table err=%v enabled_nil=%v", err2, a2.Enabled == nil)
|
||||||
|
if a2.Enabled != nil { fmt.Printf(" enabled=%v", *a2.Enabled) }
|
||||||
|
fmt.Printf(" config=%s\n", a2.Config)
|
||||||
|
}
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": ["@commitlint/config-conventional"]
|
|
||||||
}
|
|
||||||
@@ -9,3 +9,10 @@ GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
|||||||
|
|
||||||
# PPanel Server 镜像标签(留空使用 latest)
|
# PPanel Server 镜像标签(留空使用 latest)
|
||||||
PPANEL_SERVER_TAG=latest
|
PPANEL_SERVER_TAG=latest
|
||||||
|
|
||||||
|
# AWS 区域(香港)
|
||||||
|
AWS_REGION=ap-east-1
|
||||||
|
|
||||||
|
# Grafana 公开域名(如需反代)
|
||||||
|
GRAFANA_DOMAIN=logs-new.hifast.biz
|
||||||
|
GRAFANA_ROOT_URL=https://logs-new.hifast.biz
|
||||||
|
|||||||
+32
-29
@@ -14,11 +14,12 @@ on:
|
|||||||
env:
|
env:
|
||||||
# Docker镜像仓库
|
# Docker镜像仓库
|
||||||
REPO: ${{ vars.REPO || 'registry.kxsw.us/vpn-server' }}
|
REPO: ${{ vars.REPO || 'registry.kxsw.us/vpn-server' }}
|
||||||
# SSH连接信息 (根据分支自动选择)
|
# SSH连接信息 (根据分支自动选择服务器和用户)
|
||||||
SSH_HOST: ${{ github.ref_name == 'main' && vars.SSH_HOST || vars.DEV_SSH_HOST }}
|
SSH_HOST: ${{ github.ref_name == 'main' && vars.SSH_HOST || vars.DEV_SSH_HOST }}
|
||||||
SSH_PORT: ${{ vars.SSH_PORT }}
|
SSH_PORT: ${{ vars.SSH_PORT }}
|
||||||
SSH_USER: ${{ vars.SSH_USER }}
|
SSH_USER: ${{ github.ref_name == 'main' && 'ubuntu' || 'root' }}
|
||||||
SSH_PASSWORD: ${{ github.ref_name == 'main' && vars.SSH_PASSWORD || vars.DEV_SSH_PASSWORD }}
|
# SSH私钥(Gitea Secret 名称:AWS)
|
||||||
|
SSH_KEY: ${{ secrets.AWS }}
|
||||||
# TG通知
|
# TG通知
|
||||||
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
|
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
|
||||||
TG_CHAT_ID: "-4940243803"
|
TG_CHAT_ID: "-4940243803"
|
||||||
@@ -49,7 +50,7 @@ jobs:
|
|||||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||||
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
||||||
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
|
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
|
||||||
echo "为 main 分支设置生产环境变量"
|
echo "为 main 分支设置生产环境变量"
|
||||||
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
||||||
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
||||||
@@ -137,17 +138,15 @@ jobs:
|
|||||||
|
|
||||||
echo "镜像推送完成"
|
echo "镜像推送完成"
|
||||||
|
|
||||||
# 调试: 打印 SSH 连接信息
|
# 调试: 打印部署目标(不输出敏感信息)
|
||||||
- name: 🔍 调试 - 打印 SSH 连接信息
|
- name: 🔍 调试 - 打印部署目标
|
||||||
run: |
|
run: |
|
||||||
echo "========== SSH 连接信息调试 =========="
|
echo "========== 部署目标调试 =========="
|
||||||
echo "当前分支: ${{ github.ref_name }}"
|
echo "当前分支: ${{ github.ref_name }}"
|
||||||
echo "SSH_HOST: ${{ env.SSH_HOST }}"
|
echo "SSH_HOST: ${{ env.SSH_HOST }}"
|
||||||
echo "SSH_PORT: ${{ env.SSH_PORT }}"
|
echo "SSH_PORT: ${{ env.SSH_PORT }}"
|
||||||
echo "SSH_USER: ${{ env.SSH_USER }}"
|
echo "SSH_USER: ${{ env.SSH_USER }}"
|
||||||
echo "SSH_PASSWORD 长度: ${#SSH_PASSWORD}"
|
echo "SSH认证方式: 私钥 (AWS)"
|
||||||
echo "SSH_PASSWORD 前3位: $(echo "$SSH_PASSWORD" | cut -c1-3)***"
|
|
||||||
echo "SSH_PASSWORD 完整值: ${{ env.SSH_PASSWORD }}"
|
|
||||||
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
||||||
echo "====================================="
|
echo "====================================="
|
||||||
|
|
||||||
@@ -157,10 +156,10 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
host: ${{ env.SSH_HOST }}
|
host: ${{ env.SSH_HOST }}
|
||||||
username: ${{ env.SSH_USER }}
|
username: ${{ env.SSH_USER }}
|
||||||
password: ${{ env.SSH_PASSWORD }}
|
key: ${{ env.SSH_KEY }}
|
||||||
port: ${{ env.SSH_PORT }}
|
port: ${{ env.SSH_PORT }}
|
||||||
source: "docker-compose.cloud.yml"
|
source: "docker-compose.cloud.yml"
|
||||||
target: "${{ env.DEPLOY_PATH }}/"
|
target: "/tmp/ppanel-deploy/"
|
||||||
|
|
||||||
# 步骤6: 连接服务器更新并启动
|
# 步骤6: 连接服务器更新并启动
|
||||||
- name: 🚀 连接服务器更新并启动
|
- name: 🚀 连接服务器更新并启动
|
||||||
@@ -168,7 +167,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
host: ${{ env.SSH_HOST }}
|
host: ${{ env.SSH_HOST }}
|
||||||
username: ${{ env.SSH_USER }}
|
username: ${{ env.SSH_USER }}
|
||||||
password: ${{ env.SSH_PASSWORD }}
|
key: ${{ env.SSH_KEY }}
|
||||||
port: ${{ env.SSH_PORT }}
|
port: ${{ env.SSH_PORT }}
|
||||||
timeout: 300s
|
timeout: 300s
|
||||||
command_timeout: 600s
|
command_timeout: 600s
|
||||||
@@ -176,23 +175,27 @@ jobs:
|
|||||||
echo "连接服务器成功,开始部署..."
|
echo "连接服务器成功,开始部署..."
|
||||||
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
||||||
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||||
|
echo "登录用户: ${{ env.SSH_USER }}"
|
||||||
|
|
||||||
# 进入部署目录
|
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||||
cd ${{ env.DEPLOY_PATH }}
|
sudo mkdir -p ${{ env.DEPLOY_PATH }}
|
||||||
|
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||||
# 创建/更新环境变量文件
|
cd ${{ env.DEPLOY_PATH }}
|
||||||
# echo "PPANEL_SERVER_TAG=${{ env.DOCKER_TAG_SUFFIX }}" > .env
|
echo "📥 拉取镜像..."
|
||||||
|
sudo docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||||
# 拉取最新镜像
|
echo "🚀 启动服务..."
|
||||||
echo "📥 拉取镜像..."
|
sudo docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||||
docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
sudo docker image prune -f || true
|
||||||
|
else
|
||||||
# 启动服务
|
mkdir -p ${{ env.DEPLOY_PATH }}
|
||||||
echo "🚀 启动服务..."
|
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||||
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
cd ${{ env.DEPLOY_PATH }}
|
||||||
|
echo "📥 拉取镜像..."
|
||||||
# 清理未使用的镜像
|
docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||||
docker image prune -f || true
|
echo "🚀 启动服务..."
|
||||||
|
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||||
|
docker image prune -f || true
|
||||||
|
fi
|
||||||
|
|
||||||
echo "✅ 部署命令执行完成"
|
echo "✅ 部署命令执行完成"
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
<component name="ProjectRunConfigurationManager">
|
|
||||||
<configuration default="false" name="go build github.com/perfect-panel/server" type="GoApplicationRunConfiguration" factoryName="Go Application" nameIsGenerated="true">
|
|
||||||
<module name="server" />
|
|
||||||
<working_directory value="$PROJECT_DIR$" />
|
|
||||||
<parameters value="run --config etc/ppanel-dev.yaml" />
|
|
||||||
<kind value="PACKAGE" />
|
|
||||||
<package value="github.com/perfect-panel/server" />
|
|
||||||
<directory value="$PROJECT_DIR$" />
|
|
||||||
<filePath value="$PROJECT_DIR$/ppanel.go" />
|
|
||||||
<method v="2" />
|
|
||||||
</configuration>
|
|
||||||
</component>
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
# ppanel-server
|
|
||||||
|
|
||||||
> Multi-agent orchestration framework for agentic coding
|
|
||||||
|
|
||||||
## Project Overview
|
|
||||||
|
|
||||||
A Claude Flow powered project
|
|
||||||
|
|
||||||
**Tech Stack**: TypeScript, Node.js
|
|
||||||
**Architecture**: Domain-Driven Design with bounded contexts
|
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
### Installation
|
|
||||||
```bash
|
|
||||||
npm install
|
|
||||||
```
|
|
||||||
|
|
||||||
### Build
|
|
||||||
```bash
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
### Test
|
|
||||||
```bash
|
|
||||||
npm test
|
|
||||||
```
|
|
||||||
|
|
||||||
### Development
|
|
||||||
```bash
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Agent Coordination
|
|
||||||
|
|
||||||
### Swarm Configuration
|
|
||||||
|
|
||||||
This project uses hierarchical swarm coordination for complex tasks:
|
|
||||||
|
|
||||||
| Setting | Value | Purpose |
|
|
||||||
|---------|-------|---------|
|
|
||||||
| Topology | `hierarchical` | Queen-led coordination (anti-drift) |
|
|
||||||
| Max Agents | 8 | Optimal team size |
|
|
||||||
| Strategy | `specialized` | Clear role boundaries |
|
|
||||||
| Consensus | `raft` | Leader-based consistency |
|
|
||||||
|
|
||||||
### When to Use Swarms
|
|
||||||
|
|
||||||
**Invoke swarm for:**
|
|
||||||
- Multi-file changes (3+ files)
|
|
||||||
- New feature implementation
|
|
||||||
- Cross-module refactoring
|
|
||||||
- API changes with tests
|
|
||||||
- Security-related changes
|
|
||||||
- Performance optimization
|
|
||||||
|
|
||||||
**Skip swarm for:**
|
|
||||||
- Single file edits
|
|
||||||
- Simple bug fixes (1-2 lines)
|
|
||||||
- Documentation updates
|
|
||||||
- Configuration changes
|
|
||||||
|
|
||||||
### Available Skills
|
|
||||||
|
|
||||||
Use `$skill-name` syntax to invoke:
|
|
||||||
|
|
||||||
| Skill | Use Case |
|
|
||||||
|-------|----------|
|
|
||||||
| `$swarm-orchestration` | Multi-agent task coordination |
|
|
||||||
| `$memory-management` | Pattern storage and retrieval |
|
|
||||||
| `$sparc-methodology` | Structured development workflow |
|
|
||||||
| `$security-audit` | Security scanning and CVE detection |
|
|
||||||
|
|
||||||
### Agent Types
|
|
||||||
|
|
||||||
| Type | Role | Use Case |
|
|
||||||
|------|------|----------|
|
|
||||||
| `researcher` | Requirements analysis | Understanding scope |
|
|
||||||
| `architect` | System design | Planning structure |
|
|
||||||
| `coder` | Implementation | Writing code |
|
|
||||||
| `tester` | Test creation | Quality assurance |
|
|
||||||
| `reviewer` | Code review | Security and quality |
|
|
||||||
|
|
||||||
## Code Standards
|
|
||||||
|
|
||||||
### File Organization
|
|
||||||
- **NEVER** save to root folder
|
|
||||||
- `/src` - Source code files
|
|
||||||
- `/tests` - Test files
|
|
||||||
- `/docs` - Documentation
|
|
||||||
- `/config` - Configuration files
|
|
||||||
|
|
||||||
### Quality Rules
|
|
||||||
- Files under 500 lines
|
|
||||||
- No hardcoded secrets
|
|
||||||
- Input validation at boundaries
|
|
||||||
- Typed interfaces for public APIs
|
|
||||||
- TDD London School (mock-first) preferred
|
|
||||||
|
|
||||||
### Commit Messages
|
|
||||||
```
|
|
||||||
<type>(<scope>): <description>
|
|
||||||
|
|
||||||
[optional body]
|
|
||||||
|
|
||||||
Co-Authored-By: claude-flow <ruv@ruv.net>
|
|
||||||
```
|
|
||||||
|
|
||||||
Types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `chore`
|
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
### Critical Rules
|
|
||||||
- NEVER commit secrets, credentials, or .env files
|
|
||||||
- NEVER hardcode API keys
|
|
||||||
- Always validate user input
|
|
||||||
- Use parameterized queries for SQL
|
|
||||||
- Sanitize output to prevent XSS
|
|
||||||
|
|
||||||
### Path Security
|
|
||||||
- Validate all file paths
|
|
||||||
- Prevent directory traversal (../)
|
|
||||||
- Use absolute paths internally
|
|
||||||
|
|
||||||
## Memory System
|
|
||||||
|
|
||||||
### Storing Patterns
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory store \
|
|
||||||
--key "pattern-name" \
|
|
||||||
--value "pattern description" \
|
|
||||||
--namespace patterns
|
|
||||||
```
|
|
||||||
|
|
||||||
### Searching Memory
|
|
||||||
```bash
|
|
||||||
npx @claude-flow/cli memory search \
|
|
||||||
--query "search terms" \
|
|
||||||
--namespace patterns
|
|
||||||
```
|
|
||||||
|
|
||||||
## Links
|
|
||||||
|
|
||||||
- Documentation: https://github.com/ruvnet/claude-flow
|
|
||||||
- Issues: https://github.com/ruvnet/claude-flow/issues
|
|
||||||
+1
-1
@@ -28,7 +28,7 @@ FROM scratch
|
|||||||
|
|
||||||
# Copy CA certificates and timezone data
|
# Copy CA certificates and timezone data
|
||||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
|
||||||
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai
|
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
|
||||||
|
|
||||||
ENV TZ=Asia/Shanghai
|
ENV TZ=Asia/Shanghai
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
upstream api_backend {
|
||||||
|
server 127.0.0.1:8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
|
||||||
|
listen 80;
|
||||||
|
server_name api.hifast.biz 4d3vsw888xgaen.hifast.biz;
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/html;
|
||||||
|
allow all;
|
||||||
|
}
|
||||||
|
location / {
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name api.hifast.biz;
|
||||||
|
client_max_body_size 150M;
|
||||||
|
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "DENY";
|
||||||
|
|
||||||
|
add_header X-Content-Type-Options nosniff;
|
||||||
|
if ($http_user_agent ~* '(9999|91\.78)') {
|
||||||
|
return 444;
|
||||||
|
}
|
||||||
|
location ~ ^/v1/common/client/download/file/(?<download_name>Hi快VPN-(?<os>windows|mac|android)-1.0.0-ic-.*\.(?<ext>exe|dmg|apk))$ {
|
||||||
|
alias /var/www/download/Hi快VPN-$os-1.0.0.$ext;
|
||||||
|
charset utf-8;
|
||||||
|
add_header Content-Disposition 'attachment; filename="$download_name"';
|
||||||
|
add_header Content-Type application/octet-stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /v1/common/client/download/file/ {
|
||||||
|
alias /var/www/download/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name 4d3vsw888xgaen.hifast.biz;
|
||||||
|
client_max_body_size 150M;
|
||||||
|
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options DENY;
|
||||||
|
add_header X-Content-Type-Options nosniff;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json image/svg+xml;
|
||||||
|
root /var/www/admin;
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -149,6 +149,35 @@ type (
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
List []CommissionLog `json:"list"`
|
List []CommissionLog `json:"list"`
|
||||||
}
|
}
|
||||||
|
OrderRefundLog {
|
||||||
|
OrderId int64 `json:"order_id"`
|
||||||
|
OrderNo string `json:"order_no"`
|
||||||
|
OperatorUserId int64 `json:"operator_user_id"`
|
||||||
|
OperatorAuthIdentifier string `json:"operator_auth_identifier,omitempty"`
|
||||||
|
TargetUserId int64 `json:"target_user_id"`
|
||||||
|
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||||
|
RefererUserId int64 `json:"referer_user_id,omitempty"`
|
||||||
|
CommissionAmount int64 `json:"commission_amount"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
OrderStatusBefore uint8 `json:"order_status_before"`
|
||||||
|
OrderStatusAfter uint8 `json:"order_status_after"`
|
||||||
|
SubscribeStatusBefore uint8 `json:"subscribe_status_before"`
|
||||||
|
SubscribeStatusAfter uint8 `json:"subscribe_status_after"`
|
||||||
|
SubscribeExpireBefore int64 `json:"subscribe_expire_before"`
|
||||||
|
SubscribeExpireAfter int64 `json:"subscribe_expire_after"`
|
||||||
|
CommissionBefore int64 `json:"commission_before"`
|
||||||
|
CommissionAfter int64 `json:"commission_after"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
}
|
||||||
|
FilterOrderRefundLogRequest {
|
||||||
|
FilterLogParams
|
||||||
|
OrderId int64 `form:"order_id,optional"`
|
||||||
|
UserId int64 `form:"user_id,optional"`
|
||||||
|
}
|
||||||
|
FilterOrderRefundLogResponse {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
List []OrderRefundLog `json:"list"`
|
||||||
|
}
|
||||||
GiftLog {
|
GiftLog {
|
||||||
Type uint16 `json:"type"`
|
Type uint16 `json:"type"`
|
||||||
userId int64 `json:"user_id"`
|
userId int64 `json:"user_id"`
|
||||||
@@ -291,6 +320,10 @@ service ppanel {
|
|||||||
@handler FilterCommissionLog
|
@handler FilterCommissionLog
|
||||||
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
|
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
|
||||||
|
|
||||||
|
@doc "Filter order refund log"
|
||||||
|
@handler FilterOrderRefundLog
|
||||||
|
get /order/refund/list (FilterOrderRefundLogRequest) returns (FilterOrderRefundLogResponse)
|
||||||
|
|
||||||
@doc "Filter gift log"
|
@doc "Filter gift log"
|
||||||
@handler FilterGiftLog
|
@handler FilterGiftLog
|
||||||
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
|
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ type (
|
|||||||
PaymentId int64 `json:"payment_id,omitempty"`
|
PaymentId int64 `json:"payment_id,omitempty"`
|
||||||
TradeNo string `json:"trade_no,omitempty"`
|
TradeNo string `json:"trade_no,omitempty"`
|
||||||
}
|
}
|
||||||
|
RefundOrderRequest {
|
||||||
|
Id int64 `json:"id" validate:"required"`
|
||||||
|
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
|
||||||
|
}
|
||||||
ActivateOrderRequest {
|
ActivateOrderRequest {
|
||||||
OrderNo string `json:"order_no" validate:"required"`
|
OrderNo string `json:"order_no" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -68,6 +72,10 @@ service ppanel {
|
|||||||
@handler UpdateOrderStatus
|
@handler UpdateOrderStatus
|
||||||
put /status (UpdateOrderStatusRequest)
|
put /status (UpdateOrderStatusRequest)
|
||||||
|
|
||||||
|
@doc "Refund order"
|
||||||
|
@handler RefundOrder
|
||||||
|
post /refund (RefundOrderRequest)
|
||||||
|
|
||||||
@doc "Manually activate order"
|
@doc "Manually activate order"
|
||||||
@handler ActivateOrder
|
@handler ActivateOrder
|
||||||
post /activate (ActivateOrderRequest)
|
post /activate (ActivateOrderRequest)
|
||||||
|
|||||||
+32
-4
@@ -44,13 +44,13 @@ type (
|
|||||||
Balance int64 `json:"balance"`
|
Balance int64 `json:"balance"`
|
||||||
Commission int64 `json:"commission"`
|
Commission int64 `json:"commission"`
|
||||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||||
OnlyFirstPurchase bool `json:"only_first_purchase"`
|
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Telegram int64 `json:"telegram"`
|
Telegram int64 `json:"telegram"`
|
||||||
ReferCode string `json:"refer_code"`
|
ReferCode string `json:"refer_code"`
|
||||||
RefererId int64 `json:"referer_id"`
|
RefererId int64 `json:"referer_id"`
|
||||||
Enable bool `json:"enable"`
|
Enable *bool `json:"enable"`
|
||||||
IsAdmin bool `json:"is_admin"`
|
IsAdmin *bool `json:"is_admin"`
|
||||||
Remark string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
}
|
}
|
||||||
UpdateUserNotifySettingRequest {
|
UpdateUserNotifySettingRequest {
|
||||||
@@ -230,6 +230,23 @@ type (
|
|||||||
FamilyId int64 `json:"family_id" validate:"required,gt=0"`
|
FamilyId int64 `json:"family_id" validate:"required,gt=0"`
|
||||||
Reason string `json:"reason,omitempty"`
|
Reason string `json:"reason,omitempty"`
|
||||||
}
|
}
|
||||||
|
GetWithdrawalListRequest {
|
||||||
|
Page int `form:"page"`
|
||||||
|
Size int `form:"size"`
|
||||||
|
UserId *int64 `form:"user_id,omitempty"`
|
||||||
|
Status *uint8 `form:"status,omitempty"`
|
||||||
|
}
|
||||||
|
GetWithdrawalListResponse {
|
||||||
|
List []WithdrawalLog `json:"list"`
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
}
|
||||||
|
ApproveWithdrawalRequest {
|
||||||
|
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||||
|
}
|
||||||
|
RejectWithdrawalRequest {
|
||||||
|
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||||
|
Reason string `json:"reason" validate:"required,max=500"`
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@server (
|
@server (
|
||||||
@@ -370,5 +387,16 @@ service ppanel {
|
|||||||
@doc "Dissolve family"
|
@doc "Dissolve family"
|
||||||
@handler DissolveFamily
|
@handler DissolveFamily
|
||||||
put /family/dissolve (DissolveFamilyRequest)
|
put /family/dissolve (DissolveFamilyRequest)
|
||||||
}
|
|
||||||
|
|
||||||
|
@doc "Get withdrawal list"
|
||||||
|
@handler GetWithdrawalList
|
||||||
|
get /withdrawal/list (GetWithdrawalListRequest) returns (GetWithdrawalListResponse)
|
||||||
|
|
||||||
|
@doc "Approve withdrawal"
|
||||||
|
@handler ApproveWithdrawal
|
||||||
|
post /withdrawal/approve (ApproveWithdrawalRequest)
|
||||||
|
|
||||||
|
@doc "Reject withdrawal"
|
||||||
|
@handler RejectWithdrawal
|
||||||
|
post /withdrawal/reject (RejectWithdrawalRequest)
|
||||||
|
}
|
||||||
|
|||||||
+6
-5
@@ -149,11 +149,12 @@ type (
|
|||||||
State string `form:"state"`
|
State string `form:"state"`
|
||||||
}
|
}
|
||||||
DeviceLoginRequest {
|
DeviceLoginRequest {
|
||||||
Identifier string `json:"identifier" validate:"required"`
|
Identifier string `json:"identifier" validate:"required"`
|
||||||
IP string `header:"X-Original-Forwarded-For"`
|
IP string `header:"X-Original-Forwarded-For"`
|
||||||
UserAgent string `json:"user_agent" validate:"required"`
|
UserAgent string `json:"user_agent" validate:"required"`
|
||||||
CfToken string `json:"cf_token,optional"`
|
CfToken string `json:"cf_token,optional"`
|
||||||
ShortCode string `json:"short_code,optional"`
|
ShortCode string `json:"short_code,optional"`
|
||||||
|
BasePayload string `json:"base_payload,optional"`
|
||||||
}
|
}
|
||||||
GenerateCaptchaResponse {
|
GenerateCaptchaResponse {
|
||||||
Id string `json:"id"`
|
Id string `json:"id"`
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
syntax = "v1"
|
||||||
|
|
||||||
|
info (
|
||||||
|
title: "File API"
|
||||||
|
desc: "API for ppanel file upload"
|
||||||
|
author: "Codex"
|
||||||
|
email: "codex@openai.com"
|
||||||
|
version: "0.0.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
import "../types.api"
|
||||||
|
|
||||||
|
type (
|
||||||
|
FileUploadRequest {
|
||||||
|
BizType string `form:"biz_type" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUploadResponse {
|
||||||
|
FileId string `json:"file_id"`
|
||||||
|
FileName string `json:"file_name"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUploadInitRequest {
|
||||||
|
BizType string `json:"biz_type" validate:"required"`
|
||||||
|
FileName string `json:"file_name" validate:"required"`
|
||||||
|
ContentType string `json:"content_type" validate:"required"`
|
||||||
|
Size int64 `json:"size" validate:"required"`
|
||||||
|
Sha256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUploadInitResponse {
|
||||||
|
FileId string `json:"file_id"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
UploadURL string `json:"upload_url"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
Headers map[string]string `json:"headers"`
|
||||||
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUploadCompleteRequest {
|
||||||
|
FileId string `json:"file_id" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
FileUploadCompleteResponse {
|
||||||
|
FileId string `json:"file_id"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Etag string `json:"etag"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@server (
|
||||||
|
prefix: v1/public/file
|
||||||
|
group: public/file
|
||||||
|
middleware: AuthMiddleware,DeviceMiddleware
|
||||||
|
)
|
||||||
|
service ppanel {
|
||||||
|
@doc "Upload file to RustFS"
|
||||||
|
@handler FileUpload
|
||||||
|
post /upload (FileUploadRequest) returns (FileUploadResponse)
|
||||||
|
|
||||||
|
@doc "Init file upload"
|
||||||
|
@handler FileUploadInit
|
||||||
|
post /upload/init (FileUploadInitRequest) returns (FileUploadInitResponse)
|
||||||
|
|
||||||
|
@doc "Complete file upload"
|
||||||
|
@handler FileUploadComplete
|
||||||
|
post /upload/complete (FileUploadCompleteRequest) returns (FileUploadCompleteResponse)
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
syntax = "v1"
|
||||||
|
|
||||||
|
info (
|
||||||
|
title: "recovery API"
|
||||||
|
desc: "API for order recovery"
|
||||||
|
author: "Tension"
|
||||||
|
email: "tension@ppanel.com"
|
||||||
|
version: "0.0.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
import "../types.api"
|
||||||
|
|
||||||
|
type (
|
||||||
|
RecoverySendCodeRequest {
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
}
|
||||||
|
RecoverOrderRequest {
|
||||||
|
OrderNo string `json:"order_no" validate:"required"`
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
Code string `json:"code" validate:"required"`
|
||||||
|
}
|
||||||
|
RecoverOrderResponse {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@server (
|
||||||
|
prefix: v1/public/recovery
|
||||||
|
group: public/recovery
|
||||||
|
middleware: DeviceMiddleware
|
||||||
|
)
|
||||||
|
service ppanel {
|
||||||
|
@doc "Send recovery verification code"
|
||||||
|
@handler SendCode
|
||||||
|
post /send_code (RecoverySendCodeRequest) returns (SendCodeResponse)
|
||||||
|
|
||||||
|
@doc "Recover order subscription"
|
||||||
|
@handler RecoverOrder
|
||||||
|
post /order (RecoverOrderRequest) returns (RecoverOrderResponse)
|
||||||
|
}
|
||||||
+4
-1
@@ -27,6 +27,7 @@ type (
|
|||||||
EnableLoginNotify bool `json:"enable_login_notify"`
|
EnableLoginNotify bool `json:"enable_login_notify"`
|
||||||
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
|
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
|
||||||
EnableTradeNotify bool `json:"enable_trade_notify"`
|
EnableTradeNotify bool `json:"enable_trade_notify"`
|
||||||
|
UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
|
||||||
AuthMethods []UserAuthMethod `json:"auth_methods"`
|
AuthMethods []UserAuthMethod `json:"auth_methods"`
|
||||||
UserDevices []UserDevice `json:"user_devices"`
|
UserDevices []UserDevice `json:"user_devices"`
|
||||||
Rules []string `json:"rules"`
|
Rules []string `json:"rules"`
|
||||||
@@ -227,6 +228,7 @@ type (
|
|||||||
SubscribeDiscount {
|
SubscribeDiscount {
|
||||||
Quantity int64 `json:"quantity"`
|
Quantity int64 `json:"quantity"`
|
||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
|
MapApple string `json:"map_apple"`
|
||||||
}
|
}
|
||||||
TrafficLimit {
|
TrafficLimit {
|
||||||
StatType string `json:"stat_type"`
|
StatType string `json:"stat_type"`
|
||||||
@@ -425,6 +427,7 @@ type (
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
|
StatusName string `json:"status_name,omitempty"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
@@ -447,6 +450,7 @@ type (
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
|
StatusName string `json:"status_name,omitempty"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
@@ -1003,4 +1007,3 @@ type (
|
|||||||
ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"`
|
ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"`
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,796 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
logmodel "github.com/perfect-panel/server/internal/model/log"
|
||||||
|
ordermodel "github.com/perfect-panel/server/internal/model/order"
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/pkg/conf"
|
||||||
|
"github.com/perfect-panel/server/pkg/orm"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroAgentIdStr, "agent-id", "", "目标代理用户 ID,或 * 表示所有 referral_percentage>0 的代理(必填)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroPoolStart, "pool-start", "2025-05-04", "自然流量订单起始时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认 2025-05-04)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroPoolEnd, "pool-end", "", "自然流量订单截止时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认今天)")
|
||||||
|
retroactiveReferralCmd.Flags().IntVar(&retroPercentage, "percentage", 120, "补偿百分比,例如 120 表示 120%(默认 120)")
|
||||||
|
retroactiveReferralCmd.Flags().IntVar(&retroForceCommissionPct, "force-commission-pct", 50, "强制指定发佣比例(0=使用数据库/配置,非0时覆盖代理设置,默认 50%)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroOutput, "output", "retro_result.txt", "结果输出到指定 txt 文件(默认 retro_result.txt)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroConfigPath, "config", "etc/ppanel.yaml", "配置文件路径")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroAgentCreatedAfter, "agent-created-after", "", "仅处理在此日期之后注册的代理,格式 YYYY-MM-DD(留空=不限)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroLossStart, "loss-start", "2026-05-06", "数据丢失起始时间,丢失时长=现在-此时间(默认 2026-05-06)")
|
||||||
|
retroactiveReferralCmd.Flags().StringVar(&retroOrderStart, "order-start", "2026-05-01", "池内用户至少有一笔 updated_at >= 此时间的订单才入池(默认 2026-05-01)")
|
||||||
|
retroactiveReferralCmd.Flags().BoolVar(&retroDryRun, "dry-run", false, "仅预览,不执行写入")
|
||||||
|
rootCmd.AddCommand(retroactiveReferralCmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
retroAgentIdStr string
|
||||||
|
retroAgentCreatedAfter string
|
||||||
|
retroLossStart string
|
||||||
|
retroOrderStart string
|
||||||
|
retroPoolStart string
|
||||||
|
retroPoolEnd string
|
||||||
|
retroPercentage int
|
||||||
|
retroForceCommissionPct int
|
||||||
|
retroConfigPath string
|
||||||
|
retroDryRun bool
|
||||||
|
retroOutput string
|
||||||
|
)
|
||||||
|
|
||||||
|
var retroactiveReferralCmd = &cobra.Command{
|
||||||
|
Use: "retro-referral",
|
||||||
|
Short: "补单:按代理历史日均佣金补偿指定比例的用户",
|
||||||
|
Long: `统计代理从首次邀请到 pool-end 的日均佣金,
|
||||||
|
按指定百分比计算目标补偿金额,
|
||||||
|
从 pool-start 到 pool-end 的自然流量用户中随机抽取匹配的用户数量挂载到该代理。
|
||||||
|
--agent-id 支持单个 ID 或 *(处理所有 referral_percentage>0 的代理)。`,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
if retroAgentIdStr == "" {
|
||||||
|
return fmt.Errorf("--agent-id 必填(单个 ID 或 *)")
|
||||||
|
}
|
||||||
|
return runRetroactiveReferral()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// commissionRule holds resolved commission settings for an agent.
|
||||||
|
type commissionRule struct {
|
||||||
|
Percentage uint8
|
||||||
|
OnlyFirstPurchase bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// candidateUser holds a pool user plus their pre-calculated qualifying orders.
|
||||||
|
type candidateUser struct {
|
||||||
|
Id int64
|
||||||
|
CreatedAt time.Time
|
||||||
|
Identifier string
|
||||||
|
Orders []ordermodel.Order
|
||||||
|
CommissionTotal int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// agentPlan holds one agent's computed allocation plan (preview phase output).
|
||||||
|
type agentPlan struct {
|
||||||
|
Agent *usermodel.User
|
||||||
|
Rule commissionRule
|
||||||
|
Selected []candidateUser
|
||||||
|
TargetAmt float64 // in cents
|
||||||
|
PreviewCommission int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func runRetroactiveReferral() error {
|
||||||
|
// ── 0. 初始化输出(终端 + 可选文件)─────────────────────────
|
||||||
|
var w io.Writer = os.Stdout
|
||||||
|
if retroOutput != "" {
|
||||||
|
f, err := os.Create(retroOutput)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("创建输出文件失败: %w", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
w = io.MultiWriter(os.Stdout, f)
|
||||||
|
fmt.Printf("结果将同步写入: %s\n\n", retroOutput)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 1. 加载配置 ──────────────────────────────────────────────
|
||||||
|
var c config.Config
|
||||||
|
conf.MustLoad(retroConfigPath, &c)
|
||||||
|
|
||||||
|
// ── 2. 初始化 DB + Redis ──────────────────────────────────────
|
||||||
|
db, err := orm.ConnectMysql(orm.Mysql{Config: c.MySQL})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("连接数据库失败: %w", err)
|
||||||
|
}
|
||||||
|
rds := redis.NewClient(&redis.Options{
|
||||||
|
Addr: c.Redis.Host,
|
||||||
|
Password: c.Redis.Pass,
|
||||||
|
DB: c.Redis.DB,
|
||||||
|
})
|
||||||
|
ctx := context.Background()
|
||||||
|
if err = rds.Ping(ctx).Err(); err != nil {
|
||||||
|
return fmt.Errorf("连接 Redis 失败: %w", err)
|
||||||
|
}
|
||||||
|
um := usermodel.NewModel(db, rds)
|
||||||
|
|
||||||
|
// ── 3. 解析时间参数 ───────────────────────────────────────────
|
||||||
|
poolStart, err := parseFlexibleTime(retroPoolStart)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("--pool-start 格式错误: %w", err)
|
||||||
|
}
|
||||||
|
poolEnd := time.Now()
|
||||||
|
if retroPoolEnd != "" {
|
||||||
|
poolEnd, err = parseFlexibleTime(retroPoolEnd)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("--pool-end 格式错误: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !poolEnd.After(poolStart) {
|
||||||
|
return fmt.Errorf("--pool-end 必须晚于 --pool-start")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 4. 确定代理列表 ───────────────────────────────────────────
|
||||||
|
var agents []*usermodel.User
|
||||||
|
if retroAgentIdStr == "*" {
|
||||||
|
agents, err = queryAllActiveAgents(ctx, db, retroAgentCreatedAfter)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("查询代理列表失败: %w", err)
|
||||||
|
}
|
||||||
|
if len(agents) == 0 {
|
||||||
|
return fmt.Errorf("没有找到任何 referral_percentage>0 的代理用户")
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "模式:全量代理,共找到 %d 个代理(referral_percentage>0)\n\n", len(agents))
|
||||||
|
} else {
|
||||||
|
agentID, parseErr := strconv.ParseInt(retroAgentIdStr, 10, 64)
|
||||||
|
if parseErr != nil || agentID <= 0 {
|
||||||
|
return fmt.Errorf("--agent-id 必须是正整数或 *")
|
||||||
|
}
|
||||||
|
agent, findErr := um.FindOne(ctx, agentID)
|
||||||
|
if findErr != nil {
|
||||||
|
return fmt.Errorf("查询代理用户失败: %w", findErr)
|
||||||
|
}
|
||||||
|
if agent.DeletedAt.Valid {
|
||||||
|
return fmt.Errorf("代理用户 %d 已被删除", agentID)
|
||||||
|
}
|
||||||
|
agents = []*usermodel.User{agent}
|
||||||
|
}
|
||||||
|
|
||||||
|
if retroForceCommissionPct > 0 {
|
||||||
|
fmt.Fprintf(w, "⚠️ 强制覆盖所有代理佣金比例为 %d%%\n\n", retroForceCommissionPct)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 5. 查询自然流量用户池(所有代理共用同一个池)────────────
|
||||||
|
// 先用 50% 规则(或强制值)预加载池,以便预览;执行时每个代理用自身规则
|
||||||
|
var orderStart time.Time
|
||||||
|
if retroOrderStart != "" {
|
||||||
|
orderStart, err = parseFlexibleTime(retroOrderStart)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("--order-start 格式错误: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
previewRule := commissionRule{Percentage: uint8(retroForceCommissionPct), OnlyFirstPurchase: false}
|
||||||
|
pool, err := queryNaturalTrafficPool(ctx, db, poolStart, poolEnd, orderStart, previewRule)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("查询自然流量用户池失败: %w", err)
|
||||||
|
}
|
||||||
|
orderStartDesc := ""
|
||||||
|
if !orderStart.IsZero() {
|
||||||
|
orderStartDesc = fmt.Sprintf(",订单 updated_at >= %s", orderStart.Format("2006-01-02"))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "自然流量用户池(%s ~ %s,referer_id=0,有已支付订单%s):共 %d 人\n\n",
|
||||||
|
poolStart.Format("2006-01-02 15:04"), poolEnd.Format("2006-01-02 15:04"), orderStartDesc, len(pool))
|
||||||
|
if len(pool) == 0 {
|
||||||
|
return fmt.Errorf("自然流量用户池为空,无法补充")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 6. 逐代理生成分配计划(预览阶段)────────────────────────
|
||||||
|
// 池按顺序分配:每个代理从剩余池中取用户,避免重复分配
|
||||||
|
remainingPool := make([]candidateUser, len(pool))
|
||||||
|
copy(remainingPool, pool)
|
||||||
|
|
||||||
|
plans := make([]agentPlan, 0, len(agents))
|
||||||
|
for _, agent := range agents {
|
||||||
|
plan, planErr := buildAgentPlan(w, ctx, db, c, agent, remainingPool, poolEnd)
|
||||||
|
if planErr != nil {
|
||||||
|
fmt.Fprintf(w, "⚠️ 代理 %d 跳过: %v\n\n", agent.Id, planErr)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 从剩余池中移除已分配给该代理的用户
|
||||||
|
assignedSet := make(map[int64]struct{}, len(plan.Selected))
|
||||||
|
for _, u := range plan.Selected {
|
||||||
|
assignedSet[u.Id] = struct{}{}
|
||||||
|
}
|
||||||
|
newRemaining := remainingPool[:0]
|
||||||
|
for _, u := range remainingPool {
|
||||||
|
if _, used := assignedSet[u.Id]; !used {
|
||||||
|
newRemaining = append(newRemaining, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
remainingPool = newRemaining
|
||||||
|
plans = append(plans, plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(plans) == 0 {
|
||||||
|
return fmt.Errorf("所有代理均无法生成分配计划")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 7. 汇总预览 ───────────────────────────────────────────────
|
||||||
|
var grandTotalUsers int
|
||||||
|
var grandTotalCommission int64
|
||||||
|
var grandTargetAmt float64
|
||||||
|
for _, p := range plans {
|
||||||
|
grandTotalUsers += len(p.Selected)
|
||||||
|
grandTotalCommission += p.PreviewCommission
|
||||||
|
grandTargetAmt += p.TargetAmt
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||||
|
fmt.Fprintf(w, "汇总:共 %d 个代理,补充 %d 个用户\n", len(plans), grandTotalUsers)
|
||||||
|
fmt.Fprintf(w, " 预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f)\n",
|
||||||
|
float64(grandTotalCommission)/100, grandTargetAmt/100)
|
||||||
|
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
|
||||||
|
if retroDryRun {
|
||||||
|
fmt.Fprintln(w, "[dry-run] 预览完成,未执行任何写入。")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 8. 执行前汇总打印 ─────────────────────────────────────────
|
||||||
|
fmt.Fprintf(w, "\n┌─────────────────────────────────────────────┐\n")
|
||||||
|
fmt.Fprintf(w, "│ 即将写入数据库 │\n")
|
||||||
|
fmt.Fprintf(w, "│ 代理数量 : %-4d 个 │\n", len(plans))
|
||||||
|
fmt.Fprintf(w, "│ 补充用户 : %-4d 人 │\n", grandTotalUsers)
|
||||||
|
fmt.Fprintf(w, "│ 赠送金额 : $%-10.2f │\n", float64(grandTotalCommission)/100)
|
||||||
|
fmt.Fprintf(w, "└─────────────────────────────────────────────┘\n\n")
|
||||||
|
fmt.Printf("确认执行?(yes/no): ")
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
answer, _ := reader.ReadString('\n')
|
||||||
|
answer = strings.TrimSpace(strings.ToLower(answer))
|
||||||
|
if answer != "yes" && answer != "y" {
|
||||||
|
fmt.Fprintln(w, "已取消。")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 9. 逐代理执行 ─────────────────────────────────────────────
|
||||||
|
var totalSuccess, totalFailed int
|
||||||
|
var totalCreditedOrder, totalCreditedAmt int64
|
||||||
|
|
||||||
|
for _, plan := range plans {
|
||||||
|
fmt.Fprintf(w, "\n── 执行代理 %d ──────────────────────────────────────────────\n", plan.Agent.Id)
|
||||||
|
var sc, fc int
|
||||||
|
var co, ca int64
|
||||||
|
for _, eu := range plan.Selected {
|
||||||
|
if eu.Id == plan.Agent.Id {
|
||||||
|
fmt.Fprintf(w, "[SKIP] 用户 %d 与代理相同,跳过\n", eu.Id)
|
||||||
|
fc++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
credited, amount, execErr := processOneUser(ctx, db, um, plan.Agent.Id, eu.Id, plan.Rule, orderStart)
|
||||||
|
if execErr != nil {
|
||||||
|
fmt.Fprintf(w, "[FAIL] 用户 %d: %v\n", eu.Id, execErr)
|
||||||
|
fc++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "[OK] 用户 %d → 代理 %d,发佣 %d 单,金额 $%.2f\n",
|
||||||
|
eu.Id, plan.Agent.Id, credited, float64(amount)/100)
|
||||||
|
sc++
|
||||||
|
co += credited
|
||||||
|
ca += amount
|
||||||
|
}
|
||||||
|
// 直接删除代理的缓存 key,下次请求时从 DB 重新加载(避免 FindOne 读到旧缓存再写回)
|
||||||
|
if sc > 0 {
|
||||||
|
cacheKey := fmt.Sprintf("cache:user:id:%d", plan.Agent.Id)
|
||||||
|
_ = rds.Del(ctx, cacheKey).Err()
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " 代理 %d 小计:成功 %d 人,失败 %d 人,佣金 $%.2f\n", plan.Agent.Id, sc, fc, float64(ca)/100)
|
||||||
|
totalSuccess += sc
|
||||||
|
totalFailed += fc
|
||||||
|
totalCreditedOrder += co
|
||||||
|
totalCreditedAmt += ca
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 10. 全局汇总 ──────────────────────────────────────────────
|
||||||
|
fmt.Fprintf(w, "\n══════════════════════════════════════════════\n")
|
||||||
|
fmt.Fprintf(w, " 成功挂载 : %d 人\n", totalSuccess)
|
||||||
|
fmt.Fprintf(w, " 失败/跳过 : %d 人\n", totalFailed)
|
||||||
|
fmt.Fprintf(w, " 追溯佣金 : %d 单,总额 $%.2f\n", totalCreditedOrder, float64(totalCreditedAmt)/100)
|
||||||
|
fmt.Fprintf(w, "══════════════════════════════════════════════\n")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildAgentPlan 计算一个代理的补单预览,同时打印预览内容,返回分配计划。
|
||||||
|
func buildAgentPlan(w io.Writer, ctx context.Context, db *gorm.DB, c config.Config,
|
||||||
|
agent *usermodel.User, pool []candidateUser, poolEnd time.Time) (agentPlan, error) {
|
||||||
|
|
||||||
|
rule := resolveCommissionRule(agent, c)
|
||||||
|
if retroForceCommissionPct > 0 {
|
||||||
|
rule.Percentage = uint8(retroForceCommissionPct)
|
||||||
|
}
|
||||||
|
// 补单场景:不区分新购/续费,所有已支付订单均参与佣金计算
|
||||||
|
rule.OnlyFirstPurchase = false
|
||||||
|
|
||||||
|
firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, err :=
|
||||||
|
queryAgentStats(ctx, db, agent.Id, poolEnd)
|
||||||
|
if err != nil {
|
||||||
|
return agentPlan{}, fmt.Errorf("查询历史数据失败: %w", err)
|
||||||
|
}
|
||||||
|
if totalReferred == 0 {
|
||||||
|
return agentPlan{}, fmt.Errorf("在 %s 之前没有任何邀请记录", poolEnd.Format("2006-01-02"))
|
||||||
|
}
|
||||||
|
|
||||||
|
lossStartTime, err := parseFlexibleTime(retroLossStart)
|
||||||
|
if err != nil {
|
||||||
|
return agentPlan{}, fmt.Errorf("--loss-start 格式错误: %w", err)
|
||||||
|
}
|
||||||
|
lossHours := time.Now().Sub(lossStartTime).Hours()
|
||||||
|
|
||||||
|
statsDays := lastReferralTime.Sub(firstReferralTime).Hours() / 24
|
||||||
|
if statsDays < 1 {
|
||||||
|
statsDays = 1
|
||||||
|
}
|
||||||
|
dailyAvgOrders := float64(totalOrders) / statsDays
|
||||||
|
avgOrdersPerUser := float64(totalOrders) / float64(totalReferred)
|
||||||
|
if avgOrdersPerUser < 1 {
|
||||||
|
avgOrdersPerUser = 1
|
||||||
|
}
|
||||||
|
dailyAvgCommission := float64(totalCommission) / statsDays
|
||||||
|
|
||||||
|
// 用用户池自身的平均佣金估算人数(避免历史费率与当前50%费率不匹配导致超发)
|
||||||
|
var poolAvgCommissionPerUser float64
|
||||||
|
if len(pool) > 0 {
|
||||||
|
var poolCommTotal int64
|
||||||
|
for _, u := range pool {
|
||||||
|
poolCommTotal += u.CommissionTotal
|
||||||
|
}
|
||||||
|
poolAvgCommissionPerUser = float64(poolCommTotal) / float64(len(pool))
|
||||||
|
}
|
||||||
|
if poolAvgCommissionPerUser < 1 {
|
||||||
|
poolAvgCommissionPerUser = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
estimatedLostCommission := dailyAvgCommission * (lossHours / 24)
|
||||||
|
targetCommission := estimatedLostCommission * (float64(retroPercentage) / 100)
|
||||||
|
extraCount := int(targetCommission/poolAvgCommissionPerUser + 0.5)
|
||||||
|
if extraCount < 1 {
|
||||||
|
extraCount = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(w, "\n═══════════════════════════════════════════════════════════\n")
|
||||||
|
fmt.Fprintf(w, " 代理 ID : %d(注册于 %s)\n", agent.Id, agentCreatedAt.Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Fprintf(w, " 统计起点 : %s(首次邀请时间)\n", firstReferralTime.Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Fprintf(w, " 统计截止 : %s(最后邀请时间)\n", lastReferralTime.Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Fprintf(w, " 统计天数 : %.2f 天\n", statsDays)
|
||||||
|
fmt.Fprintf(w, " 历史邀请总人数 : %d 人\n", totalReferred)
|
||||||
|
fmt.Fprintf(w, " 下线总订单数 : %d 单(所有下线,不限时间)\n", totalOrders)
|
||||||
|
fmt.Fprintf(w, " 日均订单 : %.4f 单/天\n", dailyAvgOrders)
|
||||||
|
fmt.Fprintf(w, " 每用户平均订单 : %.4f 单\n", avgOrdersPerUser)
|
||||||
|
fmt.Fprintf(w, " 历史佣金总额 : $%.2f\n", float64(totalCommission)/100)
|
||||||
|
fmt.Fprintf(w, " 日均佣金 : $%.4f\n", dailyAvgCommission/100)
|
||||||
|
fmt.Fprintf(w, " 池内用户均佣金 : $%.4f\n", poolAvgCommissionPerUser/100)
|
||||||
|
fmt.Fprintf(w, " 佣金规则 : %d%% 仅首单=%v\n", rule.Percentage, rule.OnlyFirstPurchase)
|
||||||
|
fmt.Fprintf(w, "───────────────────────────────────────────────────────────\n")
|
||||||
|
fmt.Fprintf(w, " 丢失时长 : %.2f 小时(%s → 现在)\n",
|
||||||
|
lossHours, lossStartTime.Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Fprintf(w, " 预估丢失佣金 : $%.4f($%.4f × %.2f/24)\n",
|
||||||
|
estimatedLostCommission/100, dailyAvgCommission/100, lossHours)
|
||||||
|
fmt.Fprintf(w, " 目标补偿金额 : $%.4f(× %d%%)\n",
|
||||||
|
targetCommission/100, retroPercentage)
|
||||||
|
fmt.Fprintf(w, " 需补充人数 : %d 人($%.4f ÷ $%.4f)\n",
|
||||||
|
extraCount, targetCommission/100, poolAvgCommissionPerUser/100)
|
||||||
|
fmt.Fprintf(w, "═══════════════════════════════════════════════════════════\n\n")
|
||||||
|
|
||||||
|
// 重新按当前代理规则计算池内用户佣金(pool 由调用方传入,已是当前规则计算好的)
|
||||||
|
if len(pool) == 0 {
|
||||||
|
return agentPlan{}, fmt.Errorf("剩余用户池为空")
|
||||||
|
}
|
||||||
|
if len(pool) < extraCount {
|
||||||
|
fmt.Fprintf(w, "⚠️ 剩余用户池只有 %d 人,少于需要的 %d 人,将全部分配\n\n", len(pool), extraCount)
|
||||||
|
extraCount = len(pool)
|
||||||
|
}
|
||||||
|
|
||||||
|
selected := randomSampleCandidates(pool, extraCount)
|
||||||
|
|
||||||
|
// 兜底追加:确保佣金合计 >= 目标
|
||||||
|
{
|
||||||
|
selectedSet := make(map[int64]struct{}, len(selected))
|
||||||
|
var selectedCommTotal int64
|
||||||
|
for _, u := range selected {
|
||||||
|
selectedSet[u.Id] = struct{}{}
|
||||||
|
selectedCommTotal += u.CommissionTotal
|
||||||
|
}
|
||||||
|
if selectedCommTotal < int64(targetCommission) {
|
||||||
|
remaining := make([]candidateUser, 0, len(pool)-len(selected))
|
||||||
|
for _, u := range pool {
|
||||||
|
if _, used := selectedSet[u.Id]; !used {
|
||||||
|
remaining = append(remaining, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 按佣金从小到大排序,追加时精准补足,减少超发
|
||||||
|
sort.Slice(remaining, func(i, j int) bool {
|
||||||
|
return remaining[i].CommissionTotal < remaining[j].CommissionTotal
|
||||||
|
})
|
||||||
|
for _, u := range remaining {
|
||||||
|
if selectedCommTotal >= int64(targetCommission) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
selected = append(selected, u)
|
||||||
|
selectedCommTotal += u.CommissionTotal
|
||||||
|
}
|
||||||
|
if selectedCommTotal < int64(targetCommission) {
|
||||||
|
fmt.Fprintf(w, "⚠️ 用户池佣金不足,已抽取全部可用用户(实际 $%.2f < 目标 $%.2f)\n\n",
|
||||||
|
float64(selectedCommTotal)/100, targetCommission/100)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打印选中用户明细
|
||||||
|
var previewTotalCommission int64
|
||||||
|
fmt.Fprintf(w, "随机抽取 %d 个用户(含待追溯佣金订单):\n", len(selected))
|
||||||
|
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||||
|
for i, u := range selected {
|
||||||
|
fmt.Fprintf(w, "[%d] 用户 %-10d 注册: %s %s\n",
|
||||||
|
i+1, u.Id, u.CreatedAt.Format("2006-01-02 15:04:05"), u.Identifier)
|
||||||
|
if len(u.Orders) == 0 {
|
||||||
|
fmt.Fprintln(w, " (无符合条件的订单)")
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(w, " %-38s %10s %8s %10s %s\n", "订单号", "金额", "手续费", "佣金", "类型")
|
||||||
|
fmt.Fprintf(w, " %s\n", strings.Repeat("-", 72))
|
||||||
|
for _, od := range u.Orders {
|
||||||
|
commAmt := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
|
||||||
|
orderType := "首购"
|
||||||
|
if od.Type == 2 {
|
||||||
|
orderType = "续费"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " %-38s $%8.2f $%6.2f $%8.2f %s\n",
|
||||||
|
od.OrderNo,
|
||||||
|
float64(od.Amount)/100,
|
||||||
|
float64(od.FeeAmount)/100,
|
||||||
|
float64(commAmt)/100,
|
||||||
|
orderType)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " 本用户追溯佣金合计: $%.2f\n", float64(u.CommissionTotal)/100)
|
||||||
|
}
|
||||||
|
previewTotalCommission += u.CommissionTotal
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, strings.Repeat("═", 75))
|
||||||
|
fmt.Fprintf(w, "预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f)\n\n",
|
||||||
|
float64(previewTotalCommission)/100, targetCommission/100)
|
||||||
|
|
||||||
|
return agentPlan{
|
||||||
|
Agent: agent,
|
||||||
|
Rule: rule,
|
||||||
|
Selected: selected,
|
||||||
|
TargetAmt: targetCommission,
|
||||||
|
PreviewCommission: previewTotalCommission,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryAllActiveAgents returns all agents with referral_percentage > 0, optionally filtered by created_after.
|
||||||
|
func queryAllActiveAgents(ctx context.Context, db *gorm.DB, createdAfter string) ([]*usermodel.User, error) {
|
||||||
|
q := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||||
|
Where("referral_percentage > 0 AND deleted_at IS NULL")
|
||||||
|
if createdAfter != "" {
|
||||||
|
t, err := parseFlexibleTime(createdAfter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("--agent-created-after 格式错误: %w", err)
|
||||||
|
}
|
||||||
|
q = q.Where("created_at >= ?", t)
|
||||||
|
}
|
||||||
|
var agents []*usermodel.User
|
||||||
|
if err := q.Order("id ASC").Find(&agents).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return agents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseFlexibleTime parses "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD".
|
||||||
|
func parseFlexibleTime(s string) (time.Time, error) {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if t, err := time.ParseInLocation("2006-01-02 15:04:05", s, time.Local); err == nil {
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
return time.ParseInLocation("2006-01-02", s, time.Local)
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryAgentStats returns (firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, error).
|
||||||
|
func queryAgentStats(ctx context.Context, db *gorm.DB, agentID int64, endTime time.Time) (time.Time, time.Time, time.Time, int64, int64, int64, error) {
|
||||||
|
var agent usermodel.User
|
||||||
|
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||||
|
Where("id = ?", agentID).
|
||||||
|
First(&agent).Error; err != nil {
|
||||||
|
return time.Time{}, time.Time{}, time.Time{}, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
agentCreatedAt := agent.CreatedAt
|
||||||
|
|
||||||
|
var firstUser usermodel.User
|
||||||
|
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||||
|
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||||
|
agentID, agentCreatedAt, endTime).
|
||||||
|
Order("created_at ASC").
|
||||||
|
First(&firstUser).Error; err != nil {
|
||||||
|
if err == gorm.ErrRecordNotFound {
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, nil
|
||||||
|
}
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var lastUser usermodel.User
|
||||||
|
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||||
|
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||||
|
agentID, agentCreatedAt, endTime).
|
||||||
|
Order("created_at DESC").
|
||||||
|
First(&lastUser).Error; err != nil {
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var totalReferred int64
|
||||||
|
if err := db.WithContext(ctx).Model(&usermodel.User{}).
|
||||||
|
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
|
||||||
|
agentID, agentCreatedAt, endTime).
|
||||||
|
Count(&totalReferred).Error; err != nil {
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var totalOrders int64
|
||||||
|
if err := db.WithContext(ctx).Model(&ordermodel.Order{}).
|
||||||
|
Joins("JOIN user u ON u.id = `order`.user_id").
|
||||||
|
Where("u.referer_id = ?", agentID).
|
||||||
|
Where("`order`.status IN (2, 5)").
|
||||||
|
Count(&totalOrders).Error; err != nil {
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type commResult struct{ Total int64 }
|
||||||
|
var result commResult
|
||||||
|
err := db.WithContext(ctx).Raw(`
|
||||||
|
SELECT COALESCE(SUM(
|
||||||
|
CAST(JSON_UNQUOTE(JSON_EXTRACT(content, '$.amount')) AS SIGNED)
|
||||||
|
), 0) AS total
|
||||||
|
FROM system_logs
|
||||||
|
WHERE type = 33
|
||||||
|
AND object_id = ?
|
||||||
|
AND created_at <= ?
|
||||||
|
AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.type')) IN ('331', '332')
|
||||||
|
`, agentID, endTime).Scan(&result).Error
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return firstUser.CreatedAt, lastUser.CreatedAt, agentCreatedAt, totalReferred, totalOrders, result.Total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryNaturalTrafficPool returns pool candidates with pre-loaded qualifying orders.
|
||||||
|
// orderStart (可为零值):若非零,则只收录至少有一笔 updated_at >= orderStart 订单的用户,
|
||||||
|
// 且只加载/统计 updated_at >= orderStart 的订单(确保分配后代理能在对应月份的销售报表中看到记录)。
|
||||||
|
func queryNaturalTrafficPool(ctx context.Context, db *gorm.DB, start, end time.Time, orderStart time.Time, rule commissionRule) ([]candidateUser, error) {
|
||||||
|
type userRow struct {
|
||||||
|
Id int64
|
||||||
|
CreatedAt time.Time
|
||||||
|
AuthIdentifier string
|
||||||
|
}
|
||||||
|
var userRows []userRow
|
||||||
|
q := db.WithContext(ctx).
|
||||||
|
Table("user u").
|
||||||
|
Select("u.id, u.created_at, COALESCE(am.auth_identifier, '') AS auth_identifier").
|
||||||
|
Joins("JOIN `order` o ON o.user_id = u.id AND o.status IN (2, 5)").
|
||||||
|
Joins("LEFT JOIN user_auth_methods am ON am.user_id = u.id AND am.auth_type = 'email'").
|
||||||
|
Where("u.created_at >= ? AND u.created_at <= ?", start, end).
|
||||||
|
Where("u.referer_id = 0").
|
||||||
|
Where("u.deleted_at IS NULL")
|
||||||
|
if !orderStart.IsZero() {
|
||||||
|
// 只入池那些在 orderStart 之后有过订单的用户(保证代理销售报表里能看到)
|
||||||
|
q = q.Where("o.updated_at >= ?", orderStart)
|
||||||
|
}
|
||||||
|
if err := q.Group("u.id, u.created_at, am.auth_identifier").
|
||||||
|
Order("u.id ASC").
|
||||||
|
Scan(&userRows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(userRows) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
userIDs := make([]int64, len(userRows))
|
||||||
|
for i, r := range userRows {
|
||||||
|
userIDs[i] = r.Id
|
||||||
|
}
|
||||||
|
orderQuery := db.WithContext(ctx).Model(&ordermodel.Order{}).
|
||||||
|
Where("user_id IN ? AND status IN (2, 5)", userIDs)
|
||||||
|
if !orderStart.IsZero() {
|
||||||
|
// 只加载 orderStart 之后的订单:保证佣金统计和销售记录对齐
|
||||||
|
orderQuery = orderQuery.Where("updated_at >= ?", orderStart)
|
||||||
|
}
|
||||||
|
var allOrders []ordermodel.Order
|
||||||
|
if err := orderQuery.Order("user_id ASC, created_at ASC").Find(&allOrders).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ordersByUser := make(map[int64][]ordermodel.Order, len(userRows))
|
||||||
|
for _, od := range allOrders {
|
||||||
|
ordersByUser[od.UserId] = append(ordersByUser[od.UserId], od)
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates := make([]candidateUser, 0, len(userRows))
|
||||||
|
for _, r := range userRows {
|
||||||
|
orders := ordersByUser[r.Id]
|
||||||
|
var commTotal int64
|
||||||
|
for i := range orders {
|
||||||
|
if canCreditOrder(rule, &orders[i]) {
|
||||||
|
commTotal += calcCommissionAmount(orders[i].Amount, orders[i].FeeAmount, rule.Percentage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates = append(candidates, candidateUser{
|
||||||
|
Id: r.Id,
|
||||||
|
CreatedAt: r.CreatedAt,
|
||||||
|
Identifier: r.AuthIdentifier,
|
||||||
|
Orders: orders,
|
||||||
|
CommissionTotal: commTotal,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return candidates, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// randomSampleCandidates picks n random elements from pool without replacement.
|
||||||
|
func randomSampleCandidates(pool []candidateUser, n int) []candidateUser {
|
||||||
|
if n >= len(pool) {
|
||||||
|
return append([]candidateUser{}, pool...)
|
||||||
|
}
|
||||||
|
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
indices := rng.Perm(len(pool))[:n]
|
||||||
|
result := make([]candidateUser, n)
|
||||||
|
for i, idx := range indices {
|
||||||
|
result[i] = pool[idx]
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// processOneUser assigns agentId as referer and retroactively credits commission for qualifying orders.
|
||||||
|
func processOneUser(
|
||||||
|
ctx context.Context,
|
||||||
|
db *gorm.DB,
|
||||||
|
um usermodel.Model,
|
||||||
|
agentID, userID int64,
|
||||||
|
rule commissionRule,
|
||||||
|
orderStart time.Time,
|
||||||
|
) (int64, int64, error) {
|
||||||
|
var creditedOrders, creditedAmount int64
|
||||||
|
|
||||||
|
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
var target usermodel.User
|
||||||
|
if e := tx.Model(&usermodel.User{}).
|
||||||
|
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
|
||||||
|
First(&target).Error; e != nil {
|
||||||
|
if e == gorm.ErrRecordNotFound {
|
||||||
|
return fmt.Errorf("用户不存在或已有代理或已删除")
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
var orders []ordermodel.Order
|
||||||
|
oq := tx.Model(&ordermodel.Order{}).
|
||||||
|
Where("user_id = ? AND status IN (2, 5)", userID)
|
||||||
|
if !orderStart.IsZero() {
|
||||||
|
oq = oq.Where("updated_at >= ?", orderStart)
|
||||||
|
}
|
||||||
|
if e := oq.Order("created_at ASC, id ASC").Find(&orders).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if len(orders) == 0 {
|
||||||
|
return fmt.Errorf("无合格订单")
|
||||||
|
}
|
||||||
|
|
||||||
|
if e := tx.Model(&usermodel.User{}).
|
||||||
|
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"referer_id": agentID,
|
||||||
|
"updated_at": time.Now(),
|
||||||
|
}).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range orders {
|
||||||
|
od := &orders[i]
|
||||||
|
if !canCreditOrder(rule, od) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
amount := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
|
||||||
|
if amount <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var existCount int64
|
||||||
|
if e := tx.Model(&logmodel.SystemLog{}).
|
||||||
|
Where("type = ? AND object_id = ? AND content LIKE ?",
|
||||||
|
logmodel.TypeCommission.Uint8(), agentID,
|
||||||
|
fmt.Sprintf("%%\"%s\"%%", od.OrderNo),
|
||||||
|
).Count(&existCount).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if existCount > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if e := tx.Model(&usermodel.User{}).
|
||||||
|
Where("id = ? AND deleted_at IS NULL", agentID).
|
||||||
|
UpdateColumn("commission", gorm.Expr("commission + ?", amount)).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
commType := logmodel.CommissionTypePurchase
|
||||||
|
if od.Type == 2 {
|
||||||
|
commType = logmodel.CommissionTypeRenewal
|
||||||
|
}
|
||||||
|
payload := &logmodel.Commission{
|
||||||
|
Type: commType,
|
||||||
|
Amount: amount,
|
||||||
|
OrderNo: od.OrderNo,
|
||||||
|
Timestamp: od.CreatedAt.UnixMilli(),
|
||||||
|
}
|
||||||
|
content, _ := payload.Marshal()
|
||||||
|
if e := tx.Create(&logmodel.SystemLog{
|
||||||
|
Type: logmodel.TypeCommission.Uint8(),
|
||||||
|
Date: od.CreatedAt.Format("2006-01-02"),
|
||||||
|
ObjectID: agentID,
|
||||||
|
Content: string(content),
|
||||||
|
CreatedAt: od.CreatedAt,
|
||||||
|
}).Error; e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
creditedOrders++
|
||||||
|
creditedAmount += amount
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if updated, e := um.FindOne(ctx, userID); e == nil {
|
||||||
|
_ = um.UpdateUserCache(ctx, updated)
|
||||||
|
}
|
||||||
|
return creditedOrders, creditedAmount, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveCommissionRule(agent *usermodel.User, c config.Config) commissionRule {
|
||||||
|
if agent.ReferralPercentage > 0 {
|
||||||
|
onlyFirst := true
|
||||||
|
if agent.OnlyFirstPurchase != nil {
|
||||||
|
onlyFirst = *agent.OnlyFirstPurchase
|
||||||
|
}
|
||||||
|
return commissionRule{Percentage: agent.ReferralPercentage, OnlyFirstPurchase: onlyFirst}
|
||||||
|
}
|
||||||
|
return commissionRule{
|
||||||
|
Percentage: uint8(c.Invite.ReferralPercentage),
|
||||||
|
OnlyFirstPurchase: c.Invite.OnlyFirstPurchase,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func canCreditOrder(rule commissionRule, od *ordermodel.Order) bool {
|
||||||
|
if rule.Percentage == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if rule.OnlyFirstPurchase && !od.IsNew {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return od.Status == 2 || od.Status == 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func calcCommissionAmount(amount, feeAmount int64, percentage uint8) int64 {
|
||||||
|
base := amount - feeAmount
|
||||||
|
if base <= 0 || percentage == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return int64(float64(base) * float64(percentage) / 100)
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# MySQL 8.0 master/replica compose for two separate servers.
|
||||||
|
#
|
||||||
|
# Master server:
|
||||||
|
# COMPOSE_PROFILES=master docker compose -f config/docker-compose.mysql-replication.yml up -d
|
||||||
|
#
|
||||||
|
# Replica server:
|
||||||
|
# MASTER_HOST=<master_public_or_private_ip> COMPOSE_PROFILES=replica docker compose -f config/docker-compose.mysql-replication.yml up -d
|
||||||
|
#
|
||||||
|
# Required env on both servers:
|
||||||
|
# MYSQL_ROOT_PASSWORD=<strong-root-password>
|
||||||
|
# MYSQL_REPLICATION_PASSWORD=<strong-replication-password>
|
||||||
|
#
|
||||||
|
# Optional env:
|
||||||
|
# MYSQL_DATABASE=ppanel
|
||||||
|
# MYSQL_REPLICATION_USER=repl
|
||||||
|
# MYSQL_MASTER_PORT=3306
|
||||||
|
# MYSQL_REPLICA_PORT=3306
|
||||||
|
# MYSQL_SERVER_ID=1 # master default
|
||||||
|
# MYSQL_REPLICA_ID=2 # replica default
|
||||||
|
#
|
||||||
|
# If the master already has data, import a GTID-aware dump into the replica
|
||||||
|
# before starting replication. Fresh empty deployments can start master first,
|
||||||
|
# then replica, then point the application at the master.
|
||||||
|
|
||||||
|
services:
|
||||||
|
mysql-master:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: ppanel-mysql-master
|
||||||
|
profiles:
|
||||||
|
- master
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "${MYSQL_MASTER_PORT:-3306}:3306"
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||||
|
MYSQL_DATABASE: "${MYSQL_DATABASE:-ppanel}"
|
||||||
|
MYSQL_REPLICATION_USER: "${MYSQL_REPLICATION_USER:-repl}"
|
||||||
|
MYSQL_REPLICATION_PASSWORD: "${MYSQL_REPLICATION_PASSWORD:?please set MYSQL_REPLICATION_PASSWORD}"
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
command:
|
||||||
|
- --default-authentication-plugin=mysql_native_password
|
||||||
|
- --server-id=${MYSQL_SERVER_ID:-1}
|
||||||
|
- --log-bin=mysql-bin
|
||||||
|
- --binlog-format=ROW
|
||||||
|
- --gtid-mode=ON
|
||||||
|
- --enforce-gtid-consistency=ON
|
||||||
|
- --log-replica-updates=ON
|
||||||
|
- --binlog-expire-logs-seconds=604800
|
||||||
|
- --max_connections=1000
|
||||||
|
- --character-set-server=utf8mb4
|
||||||
|
- --collation-server=utf8mb4_unicode_ci
|
||||||
|
volumes:
|
||||||
|
- mysql_master_data:/var/lib/mysql
|
||||||
|
configs:
|
||||||
|
- source: mysql_master_init
|
||||||
|
target: /docker-entrypoint-initdb.d/01-create-replication-user.sh
|
||||||
|
mode: 0755
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$${MYSQL_ROOT_PASSWORD}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
mysql-replica:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: ppanel-mysql-replica
|
||||||
|
profiles:
|
||||||
|
- replica
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "${MYSQL_REPLICA_PORT:-3306}:3306"
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||||
|
MYSQL_DATABASE: "${MYSQL_DATABASE:-ppanel}"
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
command:
|
||||||
|
- --default-authentication-plugin=mysql_native_password
|
||||||
|
- --server-id=${MYSQL_REPLICA_ID:-2}
|
||||||
|
- --relay-log=mysql-relay-bin
|
||||||
|
- --read-only=ON
|
||||||
|
- --super-read-only=ON
|
||||||
|
- --gtid-mode=ON
|
||||||
|
- --enforce-gtid-consistency=ON
|
||||||
|
- --log-replica-updates=ON
|
||||||
|
- --binlog-format=ROW
|
||||||
|
- --max_connections=1000
|
||||||
|
- --character-set-server=utf8mb4
|
||||||
|
- --collation-server=utf8mb4_unicode_ci
|
||||||
|
volumes:
|
||||||
|
- mysql_replica_data:/var/lib/mysql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$${MYSQL_ROOT_PASSWORD}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
mysql-replica-init:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: ppanel-mysql-replica-init
|
||||||
|
profiles:
|
||||||
|
- replica
|
||||||
|
restart: "no"
|
||||||
|
depends_on:
|
||||||
|
mysql-replica:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?please set MYSQL_ROOT_PASSWORD}"
|
||||||
|
MYSQL_REPLICATION_USER: "${MYSQL_REPLICATION_USER:-repl}"
|
||||||
|
MYSQL_REPLICATION_PASSWORD: "${MYSQL_REPLICATION_PASSWORD:?please set MYSQL_REPLICATION_PASSWORD}"
|
||||||
|
MASTER_HOST: "${MASTER_HOST:?please set MASTER_HOST to the master server ip or hostname}"
|
||||||
|
MASTER_PORT: "${MASTER_PORT:-3306}"
|
||||||
|
entrypoint:
|
||||||
|
- /bin/sh
|
||||||
|
- -ec
|
||||||
|
- |
|
||||||
|
mysql -hmysql-replica -uroot -p"$${MYSQL_ROOT_PASSWORD}" <<SQL
|
||||||
|
STOP REPLICA;
|
||||||
|
CHANGE REPLICATION SOURCE TO
|
||||||
|
SOURCE_HOST='$${MASTER_HOST}',
|
||||||
|
SOURCE_PORT=$${MASTER_PORT},
|
||||||
|
SOURCE_USER='$${MYSQL_REPLICATION_USER}',
|
||||||
|
SOURCE_PASSWORD='$${MYSQL_REPLICATION_PASSWORD}',
|
||||||
|
SOURCE_AUTO_POSITION=1,
|
||||||
|
GET_SOURCE_PUBLIC_KEY=1;
|
||||||
|
START REPLICA;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
configs:
|
||||||
|
mysql_master_init:
|
||||||
|
content: |
|
||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
mysql -uroot -p"$${MYSQL_ROOT_PASSWORD}" <<SQL
|
||||||
|
CREATE USER IF NOT EXISTS '$${MYSQL_REPLICATION_USER}'@'%' IDENTIFIED WITH mysql_native_password BY '$${MYSQL_REPLICATION_PASSWORD}';
|
||||||
|
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO '$${MYSQL_REPLICATION_USER}'@'%';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mysql_master_data:
|
||||||
|
mysql_replica_data:
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
EC2 SSH 连接资料
|
||||||
|
|
||||||
|
服务器名称: hifast-hk-app-01
|
||||||
|
公网 IP: 43.198.248.161
|
||||||
|
登录用户: ubuntu
|
||||||
|
|
||||||
|
私钥文件:
|
||||||
|
- hifast-hk-app-01-reset
|
||||||
|
|
||||||
|
公钥文件:
|
||||||
|
- hifast-hk-app-01-reset.pub
|
||||||
|
|
||||||
|
连接命令:
|
||||||
|
ssh -i hifast-hk-app-01-reset ubuntu@43.198.248.161
|
||||||
|
|
||||||
|
如果在 Mac / Linux 上使用,先执行:
|
||||||
|
chmod 600 hifast-hk-app-01-reset
|
||||||
|
|
||||||
|
如果要给别人使用,只需要把私钥文件 hifast-hk-app-01-reset 发给对方即可。
|
||||||
|
出于安全考虑,建议通过安全渠道传输,并在后续需要时重新轮换密钥。
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||||
|
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||||
|
QyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCgAAAKjy5KDa8uSg
|
||||||
|
2gAAAAtzc2gtZWQyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCg
|
||||||
|
AAAEDwSb0b/0S6Tw8Od5hAtIKqt1JvomqQQS44Ty3xL+FjPtvqawOqZIcu/SZaAI/i9+ND
|
||||||
|
cDnnaq/3m5B2wf3hGegKAAAAIWhpZmFzdC1oay1hcHAtMDEtcmVzZXQtMjAyNi0wNS0xMA
|
||||||
|
ECAwQ=
|
||||||
|
-----END OPENSSH PRIVATE KEY-----
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINvqawOqZIcu/SZaAI/i9+NDcDnnaq/3m5B2wf3hGegK hifast-hk-app-01-reset-2026-05-10
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
# PPanel 香港区新 AWS 账号部署说明
|
||||||
|
|
||||||
|
本目录用于在 **新 AWS 账号** 中按 **香港区 `ap-east-1`** 重建一套全新空环境。
|
||||||
|
|
||||||
|
目标架构:
|
||||||
|
|
||||||
|
`DNS -> ALB -> WAF -> EC2(Nginx + ppanel-server + Redis + observability) -> RDS MySQL`
|
||||||
|
|
||||||
|
## 1. 资源清单
|
||||||
|
|
||||||
|
按下面顺序创建资源:
|
||||||
|
|
||||||
|
1. VPC
|
||||||
|
2. 2 个公有子网 + 2 个私有子网
|
||||||
|
3. Internet Gateway
|
||||||
|
4. 公有 / 私有路由表
|
||||||
|
5. 安全组
|
||||||
|
6. RDS MySQL
|
||||||
|
7. EC2 本机 Redis Docker
|
||||||
|
8. EC2
|
||||||
|
9. ACM 证书
|
||||||
|
10. ALB + Target Group
|
||||||
|
11. WAF Web ACL
|
||||||
|
12. 平行环境域名
|
||||||
|
|
||||||
|
建议命名:
|
||||||
|
|
||||||
|
- VPC: `ppanel-hk-prod`
|
||||||
|
- EC2: `ppanel-app-hk-01`
|
||||||
|
- RDS: `ppanel-mysql-hk`
|
||||||
|
- Redis container: `hifast-redis`
|
||||||
|
- ALB: `ppanel-alb-hk`
|
||||||
|
- WAF: `ppanel-waf-hk`
|
||||||
|
|
||||||
|
## 2. 默认规格
|
||||||
|
|
||||||
|
### EC2
|
||||||
|
|
||||||
|
- Region: `ap-east-1`
|
||||||
|
- OS: Ubuntu 24.04 LTS
|
||||||
|
- Instance type: `t4g.large` 起步
|
||||||
|
- Disk: `gp3 80GB`
|
||||||
|
- Public subnet: 是
|
||||||
|
- IAM Role: 允许读取 CloudWatch / SSM(如使用)
|
||||||
|
- 如果要在 AWS EC2 本机执行 S3 备份:额外允许写入专用备份桶
|
||||||
|
|
||||||
|
### RDS MySQL
|
||||||
|
|
||||||
|
- Engine: MySQL 8.0
|
||||||
|
- Class: `db.r7g.xlarge`
|
||||||
|
- Storage: `gp3 100GB`
|
||||||
|
- DB name: `hifast`
|
||||||
|
- Username: `admin`
|
||||||
|
- Public access: `No`
|
||||||
|
- Charset: `utf8mb4`
|
||||||
|
- Backup: `7-14 days`
|
||||||
|
|
||||||
|
### Redis
|
||||||
|
|
||||||
|
- 部署位置:业务 EC2 本机
|
||||||
|
- 部署方式:Docker
|
||||||
|
- 版本:`redis:8.2.1`
|
||||||
|
- 监听:`0.0.0.0:6379`
|
||||||
|
- 应用连接:`127.0.0.1:6379`
|
||||||
|
- 安全组:仅对白名单备用节点或同机应用开放
|
||||||
|
|
||||||
|
## 3. 网络与安全组
|
||||||
|
|
||||||
|
### 子网布局
|
||||||
|
|
||||||
|
- `public-a`, `public-b`: ALB / EC2
|
||||||
|
- `private-a`, `private-b`: RDS
|
||||||
|
|
||||||
|
### 安全组建议
|
||||||
|
|
||||||
|
#### `sg-alb`
|
||||||
|
|
||||||
|
- Inbound
|
||||||
|
- `80/tcp` from `0.0.0.0/0`
|
||||||
|
- `443/tcp` from `0.0.0.0/0`
|
||||||
|
- Outbound
|
||||||
|
- `80/tcp` to `sg-ec2`
|
||||||
|
|
||||||
|
#### `sg-ec2`
|
||||||
|
|
||||||
|
- Inbound
|
||||||
|
- `80/tcp` from `sg-alb`
|
||||||
|
- `22/tcp` from `你的固定运维 IP`
|
||||||
|
- Outbound
|
||||||
|
- all
|
||||||
|
|
||||||
|
说明:
|
||||||
|
|
||||||
|
- 应用容器监听 `127.0.0.1:8080`
|
||||||
|
- EC2 对外只让 Nginx 监听 `80`
|
||||||
|
- Grafana / Prometheus / Tempo 仅监听 `127.0.0.1`
|
||||||
|
|
||||||
|
#### `sg-rds`
|
||||||
|
|
||||||
|
- Inbound
|
||||||
|
- `3306/tcp` from `sg-ec2`
|
||||||
|
|
||||||
|
#### `sg-ec2` 额外说明
|
||||||
|
|
||||||
|
- 如果需要外部备用节点复制 Redis,再额外放行:
|
||||||
|
- `6379/tcp` from `104.238.220.230/32`
|
||||||
|
|
||||||
|
## 4. ALB / Target Group / 健康检查
|
||||||
|
|
||||||
|
### Target Group
|
||||||
|
|
||||||
|
- Type: `Instance`
|
||||||
|
- Protocol: `HTTP`
|
||||||
|
- Port: `80`
|
||||||
|
- Health check path: `/v1/common/heartbeat`
|
||||||
|
- Success code: `200`
|
||||||
|
|
||||||
|
这个路径已由项目现有接口提供,无需额外改代码。
|
||||||
|
|
||||||
|
### ALB 监听器
|
||||||
|
|
||||||
|
- `80` -> redirect to `443`
|
||||||
|
- `443` -> forward 到 target group
|
||||||
|
|
||||||
|
### ACM
|
||||||
|
|
||||||
|
- 在 `ap-east-1` 申请证书
|
||||||
|
- 先给平行环境域名,例如:
|
||||||
|
- `api-new.hifast.biz`
|
||||||
|
- `logs-new.hifast.biz`
|
||||||
|
|
||||||
|
## 5. WAF 规则
|
||||||
|
|
||||||
|
首版至少启用:
|
||||||
|
|
||||||
|
1. `AWSManagedRulesCommonRuleSet`
|
||||||
|
2. `AWSManagedRulesKnownBadInputsRuleSet`
|
||||||
|
3. `AWSManagedRulesAmazonIpReputationList`
|
||||||
|
4. 全站 rate-based rule
|
||||||
|
5. 针对高风险路径的 rate-based rule
|
||||||
|
|
||||||
|
建议的第一版限流:
|
||||||
|
|
||||||
|
- 全站:每 IP `2000 / 5 分钟`
|
||||||
|
- `/v1/public/user/subscribe`:每 IP `300 / 5 分钟`
|
||||||
|
- 登录 / 注册 / 验证码接口:每 IP `100 / 5 分钟`
|
||||||
|
|
||||||
|
节点上报接口建议后续补:
|
||||||
|
|
||||||
|
- `/v1/server/status`
|
||||||
|
- `/v1/server/online`
|
||||||
|
- `/v1/server/traffic`
|
||||||
|
|
||||||
|
优先用节点出口 IP 白名单;没有固定出口 IP 的节点暂时保留 `secret_key`,但不要把它当成唯一防线。
|
||||||
|
|
||||||
|
## 6. EC2 文件落地
|
||||||
|
|
||||||
|
在 EC2 上建议使用:
|
||||||
|
|
||||||
|
- 应用目录:`/opt/ppanel`
|
||||||
|
- Nginx 配置:`/etc/nginx/sites-available/ppanel-api.conf`
|
||||||
|
|
||||||
|
需要上传这些文件 / 目录:
|
||||||
|
|
||||||
|
- `docker-compose.cloud.yml`
|
||||||
|
- `deploy/aws/ap-east-1/configs/ppanel.yaml.example` -> 重命名为 `configs/ppanel.yaml`
|
||||||
|
- `deploy/aws/ap-east-1/nginx/ppanel-api.conf`
|
||||||
|
- `grafana/`
|
||||||
|
- `loki/`
|
||||||
|
- `prometheus/`
|
||||||
|
- `tempo/`
|
||||||
|
- `.env.example` -> 重命名为 `.env`
|
||||||
|
|
||||||
|
目标目录示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/opt/ppanel/
|
||||||
|
docker-compose.cloud.yml
|
||||||
|
.env
|
||||||
|
configs/ppanel.yaml
|
||||||
|
grafana/
|
||||||
|
loki/
|
||||||
|
prometheus/
|
||||||
|
tempo/
|
||||||
|
logs/
|
||||||
|
cache/
|
||||||
|
tempo_data/
|
||||||
|
```
|
||||||
|
|
||||||
|
## 7. 应用配置
|
||||||
|
|
||||||
|
基线模板见:
|
||||||
|
|
||||||
|
- [`configs/ppanel.yaml.example`](./configs/ppanel.yaml.example)
|
||||||
|
- [`nginx/ppanel-api.conf`](./nginx/ppanel-api.conf)
|
||||||
|
|
||||||
|
关键值必须替换:
|
||||||
|
|
||||||
|
- `MySQL.Addr`
|
||||||
|
- `MySQL.Password`
|
||||||
|
- `Redis.Host`
|
||||||
|
- `Redis.Pass`
|
||||||
|
- `JwtAuth.AccessSecret`
|
||||||
|
- `Administrator.Email`
|
||||||
|
- `Administrator.Password`
|
||||||
|
- `AppSignature.AppSecrets.*`
|
||||||
|
- `device.security_secret`
|
||||||
|
- `Site.Host`
|
||||||
|
- `Site.SiteName`
|
||||||
|
|
||||||
|
Redis 约定保持不变:
|
||||||
|
|
||||||
|
- 业务缓存:DB `0`
|
||||||
|
- Asynq:DB `5`(代码内部已固定使用)
|
||||||
|
|
||||||
|
## 8. 部署步骤
|
||||||
|
|
||||||
|
### 8.1 初始化 EC2
|
||||||
|
|
||||||
|
把脚本上传到 EC2 后执行:
|
||||||
|
|
||||||
|
## 9. 104 灾备节点常用运维脚本
|
||||||
|
|
||||||
|
如果你要在 `104.238.220.230` 上执行数据迁移、主从重拉、主库提升,可以直接复用仓库里的这几份脚本:
|
||||||
|
|
||||||
|
- 数据导出 / 导入交互工具:
|
||||||
|
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
|
||||||
|
- MySQL 主从运维工具:
|
||||||
|
- [`deploy/scripts/mysql_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/mysql_replica_ops.sh)
|
||||||
|
- Redis 主从运维工具:
|
||||||
|
- [`deploy/scripts/redis_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/redis_replica_ops.sh)
|
||||||
|
- 统一总入口:
|
||||||
|
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
|
||||||
|
- 主从运维环境模板:
|
||||||
|
- [`deploy/aws/ap-east-1/configs/replica-ops.env.example`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/aws/ap-east-1/configs/replica-ops.env.example)
|
||||||
|
|
||||||
|
### 9.1 数据迁移工具
|
||||||
|
|
||||||
|
支持:
|
||||||
|
|
||||||
|
- 备份 MySQL 到 S3
|
||||||
|
- 备份 Redis 到 S3
|
||||||
|
- 从正式库导出 MySQL `sql.gz`
|
||||||
|
- 把 `sql.gz` 导入 AWS RDS
|
||||||
|
- 从正式 Redis 导出 `RDB`
|
||||||
|
- 将 `RDB` 导入 Docker Redis 或宿主机 Redis
|
||||||
|
- 查看 MySQL / Redis 当前主从状态
|
||||||
|
- 强制重拉 MySQL / Redis 主从
|
||||||
|
- 把 MySQL / Redis 从库提升为可写主库
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash deploy/scripts/hifast_data_sync_tool.sh /root/replica-ops.env
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod +x deploy/scripts/bootstrap_aws_ec2.sh
|
||||||
|
sudo APP_DIR=/opt/ppanel deploy/scripts/bootstrap_aws_ec2.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 安装 Nginx 配置
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo cp deploy/aws/ap-east-1/nginx/ppanel-api.conf /etc/nginx/sites-available/ppanel-api.conf
|
||||||
|
sudo ln -sf /etc/nginx/sites-available/ppanel-api.conf /etc/nginx/sites-enabled/ppanel-api.conf
|
||||||
|
sudo nginx -t
|
||||||
|
sudo systemctl reload nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.3 启动容器
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/ppanel
|
||||||
|
docker compose -f docker-compose.cloud.yml up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.4 预检
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod +x deploy/scripts/preflight_aws_hk.sh
|
||||||
|
APP_DIR=/opt/ppanel \
|
||||||
|
RDS_HOST=<new-rds-endpoint> \
|
||||||
|
REDIS_HOST=127.0.0.1 \
|
||||||
|
deploy/scripts/preflight_aws_hk.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## 9. 平行环境验证
|
||||||
|
|
||||||
|
先验证 `api-new.hifast.biz`,不要直接切正式域名。
|
||||||
|
|
||||||
|
必测项:
|
||||||
|
|
||||||
|
1. `ALB target` 为 healthy
|
||||||
|
2. `GET /v1/common/heartbeat` 返回 200
|
||||||
|
3. 管理员登录
|
||||||
|
4. 用户注册 / 登录
|
||||||
|
5. 订阅查询
|
||||||
|
6. 节点上报 `/v1/server/status`
|
||||||
|
7. 本机 Redis 可写缓存
|
||||||
|
8. Asynq 可入队并消费
|
||||||
|
|
||||||
|
## 10. 正式切换
|
||||||
|
|
||||||
|
切换前检查:
|
||||||
|
|
||||||
|
1. ALB 5xx 为 0
|
||||||
|
2. EC2 CPU / Memory 正常
|
||||||
|
3. RDS CPU / Connections 正常
|
||||||
|
4. 本机 Redis CPU / Connections / Memory 正常
|
||||||
|
5. WAF 已挂到 ALB
|
||||||
|
6. EC2 安全组没有对公网放 `8080/3333/9090/4317`
|
||||||
|
|
||||||
|
切换方式:
|
||||||
|
|
||||||
|
1. 保持新环境先跑平行域名
|
||||||
|
2. 正式域名切到新 ALB
|
||||||
|
3. 观察至少 1 小时
|
||||||
|
4. 确认无误后再处理旧环境
|
||||||
|
|
||||||
|
## 11. 监控建议
|
||||||
|
|
||||||
|
至少建这些 CloudWatch / Grafana 观测项:
|
||||||
|
|
||||||
|
- ALB `RequestCount`, `HTTPCode_ELB_5XX_Count`, `TargetResponseTime`
|
||||||
|
- EC2 `CPUUtilization`, `NetworkIn`, `NetworkOut`, `StatusCheckFailed`
|
||||||
|
- RDS `CPUUtilization`, `DatabaseConnections`, `ReadLatency`, `WriteLatency`
|
||||||
|
- Redis 容器 CPU / Memory / restart count
|
||||||
|
|
||||||
|
## 12. 这次方案的边界
|
||||||
|
|
||||||
|
本目录交付的是:
|
||||||
|
|
||||||
|
- 香港区新账号的部署模板
|
||||||
|
- 新空环境启动与验证流程
|
||||||
|
- ALB / WAF / EC2 / RDS / 本机 Redis 的落地约定
|
||||||
|
|
||||||
|
不包含:
|
||||||
|
|
||||||
|
- 旧数据迁移
|
||||||
|
- Terraform / CloudFormation 自动建资源
|
||||||
|
- Redis 托管版改造
|
||||||
|
- 多活 / 自动扩缩容
|
||||||
|
|
||||||
|
## 13. S3 备份补强
|
||||||
|
|
||||||
|
当前已落地的 S3 备份桶:
|
||||||
|
|
||||||
|
- `hifast-prod-backups-200810848252-ap-east-1`
|
||||||
|
|
||||||
|
建议与现网结合方式:
|
||||||
|
|
||||||
|
1. `RDS automated backup` 继续保留,作为第一层恢复能力
|
||||||
|
2. `104` 外部 MySQL 从库执行逻辑备份并上传到 S3,作为第二层可下载备份
|
||||||
|
3. `104` 外部 Redis 从库按需导出 `RDB` 到 S3,补齐缓存类灾备材料
|
||||||
|
|
||||||
|
仓库中已补充:
|
||||||
|
|
||||||
|
- 环境变量模板:[`configs/backup-to-s3.env.example`](./configs/backup-to-s3.env.example)
|
||||||
|
- MySQL 备份脚本:[`../../scripts/mysql_backup_to_s3.sh`](../../scripts/mysql_backup_to_s3.sh)
|
||||||
|
- Redis 备份脚本:[`../../scripts/redis_rdb_backup_to_s3.sh`](../../scripts/redis_rdb_backup_to_s3.sh)
|
||||||
|
|
||||||
|
建议把 MySQL 备份脚本优先部署到 `104`,因为它直接连接本地只读从库,对 AWS 主库扰动最小。
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
AWS_REGION=ap-east-1
|
||||||
|
S3_BUCKET=hifast-prod-backups-200810848252-ap-east-1
|
||||||
|
S3_PREFIX=mysql
|
||||||
|
BACKUP_DIR=/var/backups/hifast
|
||||||
|
HOST_TAG=104-standby
|
||||||
|
KEEP_LOCAL_DAYS=3
|
||||||
|
CHECK_REPLICA=1
|
||||||
|
|
||||||
|
MYSQL_HOST=127.0.0.1
|
||||||
|
MYSQL_PORT=3306
|
||||||
|
MYSQL_USER=backup_reader
|
||||||
|
MYSQL_PASSWORD=CHANGE_ME
|
||||||
|
MYSQL_SOCKET=
|
||||||
|
MYSQL_DATABASE=hifast
|
||||||
|
|
||||||
|
REDIS_HOST=127.0.0.1
|
||||||
|
REDIS_PORT=6379
|
||||||
|
REDIS_PASSWORD=CHANGE_ME
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
PRIMARY_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
|
||||||
|
PRIMARY_PORT=3306
|
||||||
|
PRIMARY_USER=admin
|
||||||
|
PRIMARY_PASSWORD=CHANGE_ME
|
||||||
|
PRIMARY_DB=hifast
|
||||||
|
|
||||||
|
PRIMARY_REPL_USER=repl
|
||||||
|
PRIMARY_REPL_PASSWORD=CHANGE_ME
|
||||||
|
PRIMARY_REPL_HOST=104.238.220.230
|
||||||
|
PRIMARY_BINLOG_RETENTION_HOURS=24
|
||||||
|
|
||||||
|
REPLICA_HOST=127.0.0.1
|
||||||
|
REPLICA_PORT=3306
|
||||||
|
REPLICA_USER=root
|
||||||
|
REPLICA_PASSWORD=
|
||||||
|
REPLICA_SOCKET=/var/run/mysqld/mysqld.sock
|
||||||
|
REPLICA_DB=hifast
|
||||||
|
REPLICA_SOURCE_SSL=1
|
||||||
|
|
||||||
|
DUMP_FILE=
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
Host: 0.0.0.0
|
||||||
|
Port: 8080
|
||||||
|
Debug: false
|
||||||
|
|
||||||
|
JwtAuth:
|
||||||
|
AccessSecret: CHANGE_ME_TO_A_LONG_RANDOM_SECRET
|
||||||
|
AccessExpire: 604800
|
||||||
|
|
||||||
|
Logger:
|
||||||
|
ServiceName: PPanel
|
||||||
|
Mode: console
|
||||||
|
Encoding: plain
|
||||||
|
TimeFormat: "2006-01-02 15:04:05.000"
|
||||||
|
Path: logs
|
||||||
|
Level: info
|
||||||
|
MaxContentLength: 0
|
||||||
|
Compress: false
|
||||||
|
Stat: true
|
||||||
|
KeepDays: 7
|
||||||
|
StackCooldownMillis: 100
|
||||||
|
MaxBackups: 7
|
||||||
|
MaxSize: 100
|
||||||
|
Rotation: daily
|
||||||
|
FileTimeFormat: "2006-01-02T15:04:05.000Z07:00"
|
||||||
|
|
||||||
|
MySQL:
|
||||||
|
Addr: YOUR_RDS_ENDPOINT:3306
|
||||||
|
Dbname: hifast
|
||||||
|
Username: admin
|
||||||
|
Password: CHANGE_ME_TO_RDS_PASSWORD
|
||||||
|
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
|
||||||
|
MaxIdleConns: 10
|
||||||
|
MaxOpenConns: 100
|
||||||
|
SlowThreshold: 1000
|
||||||
|
|
||||||
|
Redis:
|
||||||
|
Host: 127.0.0.1:6379
|
||||||
|
Pass: CHANGE_ME_TO_REDIS_PASSWORD
|
||||||
|
DB: 0
|
||||||
|
PoolSize: 100
|
||||||
|
MinIdleConns: 10
|
||||||
|
MaxRetries: 3
|
||||||
|
PoolTimeout: 4
|
||||||
|
IdleTimeout: 300
|
||||||
|
MaxConnAge: 0
|
||||||
|
DialTimeout: 5
|
||||||
|
ReadTimeout: 3
|
||||||
|
WriteTimeout: 3
|
||||||
|
|
||||||
|
Trace:
|
||||||
|
Name: ppanel-server
|
||||||
|
Endpoint: 127.0.0.1:4317
|
||||||
|
Sampler: 0.1
|
||||||
|
Batcher: otlpgrpc
|
||||||
|
|
||||||
|
Site:
|
||||||
|
Host: api-new.hifast.biz
|
||||||
|
SiteName: HiFastVPN
|
||||||
|
|
||||||
|
Administrator:
|
||||||
|
Email: admin@example.com
|
||||||
|
Password: CHANGE_ME_TO_STRONG_ADMIN_PASSWORD
|
||||||
|
|
||||||
|
Telegram:
|
||||||
|
Enable: false
|
||||||
|
BotID: 0
|
||||||
|
BotName: ""
|
||||||
|
BotToken: ""
|
||||||
|
GroupChatID: ""
|
||||||
|
EnableNotify: false
|
||||||
|
WebHookDomain: ""
|
||||||
|
|
||||||
|
Kutt:
|
||||||
|
Enable: false
|
||||||
|
ApiURL: ""
|
||||||
|
ApiKey: ""
|
||||||
|
TargetURL: ""
|
||||||
|
Domain: ""
|
||||||
|
|
||||||
|
OpenInstall:
|
||||||
|
Enable: false
|
||||||
|
AppKey: ""
|
||||||
|
ApiKey: ""
|
||||||
|
|
||||||
|
Loki:
|
||||||
|
Enable: true
|
||||||
|
URL: "http://localhost:3100"
|
||||||
|
|
||||||
|
AppSignature:
|
||||||
|
AppSecrets:
|
||||||
|
android-client: CHANGE_ME_ANDROID_SIGNATURE_SECRET
|
||||||
|
ios-client: CHANGE_ME_IOS_SIGNATURE_SECRET
|
||||||
|
web-client: CHANGE_ME_WEB_SIGNATURE_SECRET
|
||||||
|
ValidWindowSeconds: 300
|
||||||
|
SkipPrefixes:
|
||||||
|
- /v1/notify/
|
||||||
|
- /v1/iap/notifications
|
||||||
|
- /v1/telegram/webhook
|
||||||
|
- /v1/subscribe/config
|
||||||
|
|
||||||
|
Signature:
|
||||||
|
EnableSignature: false
|
||||||
|
|
||||||
|
device:
|
||||||
|
enable: true
|
||||||
|
security_secret: CHANGE_ME_DEVICE_SECURITY_SECRET
|
||||||
|
|
||||||
|
Register:
|
||||||
|
EnableTrial: true
|
||||||
|
EnableTrialEmailWhitelist: true
|
||||||
|
TrialEmailDomainWhitelist: "gmail.com,outlook.com,icloud.com,qq.com,163.com"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
MYSQL_HOST=127.0.0.1
|
||||||
|
MYSQL_PORT=3306
|
||||||
|
MYSQL_USER=root
|
||||||
|
MYSQL_PASSWORD=CHANGE_ME
|
||||||
|
MYSQL_SOCKET=
|
||||||
|
|
||||||
|
REPL_SOURCE_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
|
||||||
|
REPL_SOURCE_PORT=3306
|
||||||
|
REPL_SOURCE_USER=repl
|
||||||
|
REPL_SOURCE_PASSWORD=CHANGE_ME
|
||||||
|
REPL_SOURCE_SSL=1
|
||||||
|
REPL_SOURCE_LOG_FILE=
|
||||||
|
REPL_SOURCE_LOG_POS=
|
||||||
|
REPL_SOURCE_AUTO_POSITION=1
|
||||||
|
|
||||||
|
REDIS_HOST=127.0.0.1
|
||||||
|
REDIS_PORT=6379
|
||||||
|
REDIS_PASSWORD=CHANGE_ME
|
||||||
|
|
||||||
|
REDIS_SOURCE_HOST=18.163.33.75
|
||||||
|
REDIS_SOURCE_PORT=6379
|
||||||
|
REDIS_SOURCE_USER=
|
||||||
|
REDIS_SOURCE_PASSWORD=CHANGE_ME
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
listen [::]:80 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
client_max_body_size 20m;
|
||||||
|
|
||||||
|
access_log /var/log/nginx/ppanel-access.log;
|
||||||
|
error_log /var/log/nginx/ppanel-error.log warn;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_pass http://127.0.0.1:8080;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
|
||||||
|
proxy_connect_timeout 10s;
|
||||||
|
proxy_send_timeout 60s;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /nginx_status {
|
||||||
|
stub_status;
|
||||||
|
access_log off;
|
||||||
|
allow 127.0.0.1;
|
||||||
|
deny all;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,862 @@
|
|||||||
|
# 邀请赠送与购买订阅逻辑说明
|
||||||
|
|
||||||
|
本文档说明当前代码中的购买订阅、订单激活、邀请佣金、邀请赠送时间、家庭组归属逻辑。重点覆盖每个主要分支,方便排查“重复订单/重复订阅/邀请未赠时/赠时落点错误”等问题。
|
||||||
|
|
||||||
|
涉及核心文件:
|
||||||
|
|
||||||
|
- `internal/logic/public/order/purchaseLogic.go`
|
||||||
|
- `queue/logic/order/activateOrderLogic.go`
|
||||||
|
- `internal/logic/common/familyEntitlement.go`
|
||||||
|
- `internal/model/user/model.go`
|
||||||
|
|
||||||
|
## 1. 核心概念
|
||||||
|
|
||||||
|
### 1.1 订单状态
|
||||||
|
|
||||||
|
| 状态 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `1` | pending,已创建未支付 |
|
||||||
|
| `2` | paid,已支付待激活 |
|
||||||
|
| `3` | close,已关闭 |
|
||||||
|
| `4` | failed/claimed,代码里同时用于失败和 worker 临时领取 |
|
||||||
|
| `5` | finished,激活完成 |
|
||||||
|
|
||||||
|
### 1.2 订单类型
|
||||||
|
|
||||||
|
| 类型 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `1` | 新购套餐 |
|
||||||
|
| `2` | 续费/换套餐 |
|
||||||
|
| `3` | 重置流量 |
|
||||||
|
| `4` | 余额充值 |
|
||||||
|
| `5` | 兑换码激活 |
|
||||||
|
|
||||||
|
### 1.3 用户 ID 与订阅归属
|
||||||
|
|
||||||
|
订单有两个重要用户字段:
|
||||||
|
|
||||||
|
| 字段 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `user_id` | 发起订单/付款的用户 |
|
||||||
|
| `subscription_user_id` | 订阅权益归属用户;`0` 表示同 `user_id` |
|
||||||
|
|
||||||
|
家庭组规则:
|
||||||
|
|
||||||
|
- 普通用户下单:`subscription_user_id = user_id`。
|
||||||
|
- 家庭组成员下单:`subscription_user_id = 家主用户 ID`。
|
||||||
|
- 家庭组主账号下单:`subscription_user_id = 家主用户 ID`。
|
||||||
|
|
||||||
|
当前代码使用 `ResolveEntitlementUser` 判断家庭归属:
|
||||||
|
|
||||||
|
- 只有有效家庭组、有效成员关系、角色为 member 时,权益归家主。
|
||||||
|
- 家主本人不会被改写到别人名下。
|
||||||
|
|
||||||
|
## 2. 购买订阅下单逻辑
|
||||||
|
|
||||||
|
入口:`Purchase(req *types.PurchaseOrderRequest)`
|
||||||
|
|
||||||
|
这里只是创建订单和安排关闭任务,不直接发放订阅。真正发放订阅在订单支付后由队列激活处理。
|
||||||
|
|
||||||
|
### 2.1 登录用户检查
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
- 上下文没有当前用户:返回 `InvalidAccess`。
|
||||||
|
- 当前用户存在:继续。
|
||||||
|
|
||||||
|
### 2.2 解析订阅权益归属
|
||||||
|
|
||||||
|
调用 `ResolveEntitlementUser`:
|
||||||
|
|
||||||
|
| 场景 | `effective_user_id` | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 普通用户 | 本人 ID | 订阅归本人 |
|
||||||
|
| 家庭组主账号 | 本人 ID | 订阅归本人 |
|
||||||
|
| 家庭组成员 | 家主 ID | 订阅归家主 |
|
||||||
|
|
||||||
|
后续查询已有订阅、quota、创建订单里的 `subscription_user_id` 都会使用这个归属结果。
|
||||||
|
|
||||||
|
### 2.3 数量校验
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
- `quantity <= 0`:自动改成 `1`。
|
||||||
|
- `quantity > MaxQuantity`:返回参数错误。
|
||||||
|
- 合法:继续。
|
||||||
|
|
||||||
|
### 2.4 单订阅模式路由
|
||||||
|
|
||||||
|
先默认:
|
||||||
|
|
||||||
|
```text
|
||||||
|
order_type = 1
|
||||||
|
target_subscribe_id = req.subscribe_id
|
||||||
|
parent_order_id = 0
|
||||||
|
subscribe_token = ""
|
||||||
|
```
|
||||||
|
|
||||||
|
如果开启 `Subscribe.SingleModel`:
|
||||||
|
|
||||||
|
| 查询结果 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 找到已有 anchor 订阅 | 下单路由为续费:`order_type=2`,保留新请求套餐 ID,设置 parent/order token |
|
||||||
|
| 没找到已有订阅 | 保持新购:`order_type=1` |
|
||||||
|
| 查询异常 | 返回数据库错误 |
|
||||||
|
|
||||||
|
说明:即使是换套餐,只要单订阅模式已有订阅,也走续费语义,后续激活会更新套餐 ID 和流量配置。
|
||||||
|
|
||||||
|
### 2.5 非 SingleModel 的全局单订阅兜底
|
||||||
|
|
||||||
|
如果未开启 `SingleModel`,且当前还是新购 `order_type=1`:
|
||||||
|
|
||||||
|
- 查询 `effective_user_id` 名下已有付费订阅:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
user_id = effective_user_id
|
||||||
|
AND token != ''
|
||||||
|
AND (order_id > 0 OR token LIKE 'iap:%')
|
||||||
|
```
|
||||||
|
|
||||||
|
| 查询结果 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 找到已有订阅 | 路由为续费:`order_type=2`,用已有订阅 token |
|
||||||
|
| 没找到 | 仍然新购 |
|
||||||
|
|
||||||
|
目的:避免同一个权益归属用户购买不同套餐后出现多条订阅权益。
|
||||||
|
|
||||||
|
### 2.6 pending 订单处理
|
||||||
|
|
||||||
|
当前只有一个分支会主动关闭旧 pending 单:
|
||||||
|
|
||||||
|
```text
|
||||||
|
SingleModel = true
|
||||||
|
AND order_type = 1
|
||||||
|
AND 存在同 user_id + subscribe_id + status=1 的订单
|
||||||
|
```
|
||||||
|
|
||||||
|
行为:
|
||||||
|
|
||||||
|
- 关闭旧 pending 订单。
|
||||||
|
- 继续创建新订单。
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- 如果订单已被路由为 `order_type=2`,这里不会关闭旧 pending。
|
||||||
|
- 非 `SingleModel` 下也不会走这段 pending 关闭逻辑。
|
||||||
|
|
||||||
|
### 2.7 套餐校验
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
| 条件 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 套餐不存在 | 返回数据库错误 |
|
||||||
|
| `sell=false` | 返回套餐不可售 |
|
||||||
|
| 新购且库存为 `0` | 返回库存不足 |
|
||||||
|
| 续费/换套餐 | 不检查库存为 0 的拦截分支 |
|
||||||
|
|
||||||
|
### 2.8 新用户优惠与新用户限定
|
||||||
|
|
||||||
|
调用 `resolveNewUserDiscountEligibility`:
|
||||||
|
|
||||||
|
| 分支 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 解析失败 | 返回错误 |
|
||||||
|
| 有折扣且符合条件 | 按折扣计算金额 |
|
||||||
|
| 有折扣但不符合条件 | 按原价 |
|
||||||
|
| 新用户限定且不是新用户窗口 | 新购事务内再次校验,不通过则失败 |
|
||||||
|
|
||||||
|
### 2.9 优惠券逻辑
|
||||||
|
|
||||||
|
如果 `req.coupon` 为空:跳过。
|
||||||
|
|
||||||
|
如果不为空:
|
||||||
|
|
||||||
|
| 校验 | 不通过行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 优惠券存在 | 返回 `CouponNotExist` |
|
||||||
|
| 总使用次数未超限 | 返回使用次数不足 |
|
||||||
|
| 用户使用次数未超限 | 返回用户次数不足 |
|
||||||
|
| 套餐适用 | 返回不适用 |
|
||||||
|
|
||||||
|
通过后计算 `coupon_discount`,从订单金额中扣除。
|
||||||
|
|
||||||
|
### 2.10 支付手续费与礼品余额抵扣
|
||||||
|
|
||||||
|
流程:
|
||||||
|
|
||||||
|
1. 找支付方式。
|
||||||
|
2. 如果金额大于 0,计算手续费并加到订单金额。
|
||||||
|
3. 如果用户 `gift_amount > 0`,继续抵扣订单金额。
|
||||||
|
4. 抵扣金额记录到订单 `gift_amount`。
|
||||||
|
|
||||||
|
事务内如果有礼品余额抵扣:
|
||||||
|
|
||||||
|
- 扣减用户 `gift_amount`。
|
||||||
|
- 写 `system_logs` 的 gift reduce 日志。
|
||||||
|
|
||||||
|
### 2.11 `is_new` 首单标记
|
||||||
|
|
||||||
|
创建订单前调用:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM `order`
|
||||||
|
WHERE user_id = 当前付款用户
|
||||||
|
AND status IN (2, 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
| 结果 | `is_new` |
|
||||||
|
| --- | --- |
|
||||||
|
| count = 0 | `true` |
|
||||||
|
| count > 0 | `false` |
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- 判断口径是付款用户 `user_id`,不是 `subscription_user_id`。
|
||||||
|
- pending/closed 订单不影响 `is_new`。
|
||||||
|
- 续费订单也可能是 `is_new=true`,例如单订阅模式下首次购买被路由为续费。
|
||||||
|
|
||||||
|
### 2.12 事务内创建订单
|
||||||
|
|
||||||
|
事务内执行:
|
||||||
|
|
||||||
|
1. 新购且套餐有 quota 时,再查一次 `effective_user_id` 名下订阅数量防并发。
|
||||||
|
2. 新购且新用户限定时,再查一次新用户资格。
|
||||||
|
3. 如有礼品余额抵扣,扣减余额并写日志。
|
||||||
|
4. 新购且库存不是 `-1` 时扣库存。
|
||||||
|
5. 插入订单。
|
||||||
|
|
||||||
|
订单核心字段:
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| --- | --- |
|
||||||
|
| `user_id` | 当前付款用户 |
|
||||||
|
| `subscription_user_id` | 权益归属用户 |
|
||||||
|
| `type` | 新购 `1` 或续费 `2` |
|
||||||
|
| `subscribe_id` | 本次购买的套餐 ID |
|
||||||
|
| `subscribe_token` | 续费时已有订阅 token |
|
||||||
|
| `is_new` | 首单标记 |
|
||||||
|
| `status` | `1` pending |
|
||||||
|
|
||||||
|
### 2.13 延迟关单任务
|
||||||
|
|
||||||
|
订单创建成功后,发送 `DeferCloseOrder` 任务:
|
||||||
|
|
||||||
|
- 延迟时间:15 分钟。
|
||||||
|
- 作用:未支付订单自动关闭。
|
||||||
|
|
||||||
|
## 3. 订单支付后的激活逻辑
|
||||||
|
|
||||||
|
入口:`ActivateOrderLogic.ProcessTask`
|
||||||
|
|
||||||
|
### 3.1 任务解析和订单领取
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
| 分支 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| payload 解析失败 | 记录错误,不重试 |
|
||||||
|
| 订单不存在 | 返回错误,允许重试 |
|
||||||
|
| 订单已 finished | 幂等跳过 |
|
||||||
|
| 订单不是 paid | 跳过 |
|
||||||
|
| paid 订单 | 原子更新为 claimed 状态后处理 |
|
||||||
|
|
||||||
|
### 3.2 按订单类型分发
|
||||||
|
|
||||||
|
| 订单类型 | 处理函数 |
|
||||||
|
| --- | --- |
|
||||||
|
| 新购 `1` | `NewPurchase` |
|
||||||
|
| 续费 `2` | `Renewal` |
|
||||||
|
| 重置流量 `3` | `ResetTraffic` |
|
||||||
|
| 充值 `4` | `Recharge` |
|
||||||
|
| 兑换码 `5` | `RedemptionActivate` |
|
||||||
|
|
||||||
|
处理成功后:
|
||||||
|
|
||||||
|
1. 执行订阅合并兜底 `reconcilePostOrderSubscriptions`。
|
||||||
|
2. 更新优惠券使用次数。
|
||||||
|
3. 更新订单为 `finished`。
|
||||||
|
|
||||||
|
如果处理失败:
|
||||||
|
|
||||||
|
- 把订单从 claimed 释放回 paid。
|
||||||
|
- 返回错误给队列重试。
|
||||||
|
|
||||||
|
## 4. 新购订单激活与订阅发放
|
||||||
|
|
||||||
|
入口:`NewPurchase`
|
||||||
|
|
||||||
|
### 4.1 获取用户
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
| 订单 user_id | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 不为 0 | 查询已有用户 |
|
||||||
|
| 为 0 | 从 Redis 临时订单创建游客用户 |
|
||||||
|
|
||||||
|
游客订单创建用户时:
|
||||||
|
|
||||||
|
- 创建用户和 auth method。
|
||||||
|
- 生成 refer code。
|
||||||
|
- 把订单 `user_id` 更新为新用户 ID。
|
||||||
|
- 如果临时订单有邀请码,绑定 `referer_id`。
|
||||||
|
|
||||||
|
### 4.2 新用户限定激活时复查
|
||||||
|
|
||||||
|
如果套餐是新用户限定,激活时再次校验:
|
||||||
|
|
||||||
|
- 不符合则激活失败,订单回到 paid 等待重试/处理。
|
||||||
|
- 符合继续。
|
||||||
|
|
||||||
|
### 4.3 SingleModel 下复用 anchor 订阅
|
||||||
|
|
||||||
|
如果 `Subscribe.SingleModel=true`:
|
||||||
|
|
||||||
|
| 分支 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 找到 anchor 订阅 | 更新订单 parent_id;用续费逻辑延长/换套餐 |
|
||||||
|
| 找不到 | 继续后续分支 |
|
||||||
|
| 查询异常 | 记录错误,继续后续分支 |
|
||||||
|
|
||||||
|
家庭组场景下查 anchor 的用户 ID:
|
||||||
|
|
||||||
|
- 优先 `subscription_user_id`。
|
||||||
|
- 没有则用 `user_id`。
|
||||||
|
|
||||||
|
### 4.4 复用赠送订阅
|
||||||
|
|
||||||
|
如果还没有可复用订阅:
|
||||||
|
|
||||||
|
- 查找权益归属用户名下 `order_id=0` 的赠送订阅。
|
||||||
|
- 找到后将它升级为付费订阅:
|
||||||
|
- `order_id` 改为当前订单 ID。
|
||||||
|
- 延长到期时间。
|
||||||
|
- 状态改为 active。
|
||||||
|
- 如果套餐变更,更新套餐 ID、流量额度,并清空已用流量。
|
||||||
|
|
||||||
|
### 4.5 兜底复用已有订阅
|
||||||
|
|
||||||
|
如果仍未复用到订阅:
|
||||||
|
|
||||||
|
- 候选用户 ID:
|
||||||
|
- `order.user_id`
|
||||||
|
- 如果 `subscription_user_id` 存在且不同,也加入候选。
|
||||||
|
- 查找这些用户名下 `token != ''` 的订阅。
|
||||||
|
|
||||||
|
找到后:
|
||||||
|
|
||||||
|
- 如果订阅 owner 不是当前 `subscription_user_id`,先把 `user_id` 修正为权益归属用户。
|
||||||
|
- 用续费逻辑延长/换套餐。
|
||||||
|
|
||||||
|
目的:家庭组绑定前后 owner 变化时,也尽量复用旧记录,避免创建重复订阅。
|
||||||
|
|
||||||
|
### 4.6 创建新订阅
|
||||||
|
|
||||||
|
如果以上都没有复用成功,才创建新 `user_subscribe`:
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| --- | --- |
|
||||||
|
| `user_id` | `subscription_user_id`,没有则 `order.user_id` |
|
||||||
|
| `order_id` | 当前订单 ID |
|
||||||
|
| `subscribe_id` | 当前订单套餐 ID |
|
||||||
|
| `start_time` | 当前时间 |
|
||||||
|
| `expire_time` | 按套餐时间单位和数量计算 |
|
||||||
|
| `traffic` | 套餐流量 |
|
||||||
|
| `token` | 基于订单号生成 |
|
||||||
|
| `uuid` | 新 UUID |
|
||||||
|
| `status` | `1` active |
|
||||||
|
|
||||||
|
创建前如果套餐有 quota,会再按订阅 owner 统计数量。
|
||||||
|
|
||||||
|
### 4.7 新购激活后的异步逻辑
|
||||||
|
|
||||||
|
订阅发放后:
|
||||||
|
|
||||||
|
1. 后台触发用户分组重算。
|
||||||
|
2. 后台异步处理邀请佣金和赠送时间。
|
||||||
|
3. 清套餐缓存。
|
||||||
|
|
||||||
|
注意:邀请逻辑在 goroutine 中执行,不阻塞订单激活。
|
||||||
|
|
||||||
|
## 5. 续费/换套餐激活逻辑
|
||||||
|
|
||||||
|
入口:`Renewal`
|
||||||
|
|
||||||
|
### 5.1 获取用户和订阅
|
||||||
|
|
||||||
|
- 查询订单 `user_id` 对应用户。
|
||||||
|
- 通过 `subscribe_token` 查订阅。
|
||||||
|
- 查询订单 `subscribe_id` 对应套餐。
|
||||||
|
|
||||||
|
### 5.2 Apple IAP 与普通续费分支
|
||||||
|
|
||||||
|
| 分支 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| `iap_expire_at > 0` | 使用 IAP 到期时间兜底,但仍按累计加时语义 |
|
||||||
|
| 普通续费 | `updateSubscriptionForRenewal` |
|
||||||
|
|
||||||
|
### 5.3 普通续费/换套餐规则
|
||||||
|
|
||||||
|
`updateSubscriptionForRenewal`:
|
||||||
|
|
||||||
|
- 如果当前订阅已过期,先把基准时间改为现在。
|
||||||
|
- 如果套餐 ID 变化:
|
||||||
|
- 更新订阅套餐 ID。
|
||||||
|
- 更新流量额度。
|
||||||
|
- 清空已用流量。
|
||||||
|
- 如果套餐没变:
|
||||||
|
- 如果套餐设置 renewal reset,或今天是重置日,则清空已用流量。
|
||||||
|
- 清理 `finished_at`。
|
||||||
|
- `order_id` 改为当前订单 ID。
|
||||||
|
- 按套餐时间单位和数量延长到期时间。
|
||||||
|
- 状态改为 active。
|
||||||
|
- 清空过期流量字段。
|
||||||
|
|
||||||
|
### 5.4 续费后的邀请逻辑
|
||||||
|
|
||||||
|
续费成功后也会调用 `handleCommission`:
|
||||||
|
|
||||||
|
- 是否发佣金由邀请配置和 `order.is_new` 决定。
|
||||||
|
- 是否赠时同样由邀请配置和 `order.is_new` 决定。
|
||||||
|
|
||||||
|
注意:如果 `OnlyFirstPurchase=true`,非首单续费通常不会发佣金,也不会赠首单时间。
|
||||||
|
|
||||||
|
## 6. 邀请关系绑定逻辑
|
||||||
|
|
||||||
|
### 6.1 注册/登录时的邀请码
|
||||||
|
|
||||||
|
新用户注册、游客订单创建用户时,如果带邀请码:
|
||||||
|
|
||||||
|
- 根据邀请码查邀请人。
|
||||||
|
- 设置新用户 `referer_id = 邀请人 ID`。
|
||||||
|
|
||||||
|
### 6.2 用户后绑邀请码
|
||||||
|
|
||||||
|
入口:`BindInviteCode`
|
||||||
|
|
||||||
|
分支:
|
||||||
|
|
||||||
|
| 分支 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 当前用户不存在 | 返回无权限 |
|
||||||
|
| 当前用户已有 `referer_id` | 返回已绑定 |
|
||||||
|
| 邀请码不存在 | 返回邀请码错误 |
|
||||||
|
| 邀请码属于自己 | 返回不允许绑定自己 |
|
||||||
|
| 通过 | 更新当前用户 `referer_id` |
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- `referer_id` 始终记录实际邀请码所有者。
|
||||||
|
- 邀请人是家庭成员时,`referer_id` 仍然是该成员 ID,不自动改为家主 ID。
|
||||||
|
|
||||||
|
## 7. 邀请佣金与赠送时间逻辑
|
||||||
|
|
||||||
|
入口:`handleCommission(userInfo, orderInfo)`
|
||||||
|
|
||||||
|
这里的 `userInfo` 是订单付款用户,也就是被邀请人。
|
||||||
|
|
||||||
|
### 7.1 总入口分支
|
||||||
|
|
||||||
|
先调用 `shouldProcessCommission(userInfo, orderInfo.IsNew)`。
|
||||||
|
|
||||||
|
| 结果 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| `false` | 不发佣金;如果 `is_new=true`,走双方赠时 |
|
||||||
|
| `true` | 发佣金;如果 `is_new=true`,被邀请人赠时 |
|
||||||
|
|
||||||
|
### 7.2 什么时候发佣金
|
||||||
|
|
||||||
|
`shouldProcessCommission` 规则:
|
||||||
|
|
||||||
|
| 条件 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 被邀请人为空 | 不发 |
|
||||||
|
| 被邀请人 `referer_id=0` | 不发 |
|
||||||
|
| 查不到邀请人 | 不发 |
|
||||||
|
| 邀请人自定义 `referral_percentage > 0`,且只首购但不是首单 | 不发 |
|
||||||
|
| 邀请人自定义 `referral_percentage > 0`,且通过首购限制 | 发佣金 |
|
||||||
|
| 邀请人无自定义比例,系统 `ReferralPercentage=0` | 不发 |
|
||||||
|
| 系统 `OnlyFirstPurchase=true` 且不是首单 | 不发 |
|
||||||
|
| 系统有比例且通过首购限制 | 发佣金 |
|
||||||
|
|
||||||
|
### 7.3 发佣金路径
|
||||||
|
|
||||||
|
如果 `shouldProcessCommission=true`:
|
||||||
|
|
||||||
|
1. 查询邀请人,也就是 `userInfo.referer_id` 对应用户。
|
||||||
|
2. 佣金比例:
|
||||||
|
- 邀请人自定义比例优先。
|
||||||
|
- 否则用系统配置 `Invite.ReferralPercentage`。
|
||||||
|
3. 佣金金额:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(order.amount - order.fee_amount) * referral_percentage / 100
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 事务内幂等检查:
|
||||||
|
- 如果已有同订单佣金日志,则跳过。
|
||||||
|
- 否则增加邀请人的 `commission`。
|
||||||
|
- 写 `system_logs type=33` 佣金日志。
|
||||||
|
5. 更新邀请人缓存。
|
||||||
|
6. 如果 `order.is_new=true`:
|
||||||
|
- 给被邀请人赠送订阅时间。
|
||||||
|
|
||||||
|
当前保持不变的行为:
|
||||||
|
|
||||||
|
- 邀请人是家庭成员时,佣金仍然给实际邀请人成员本人。
|
||||||
|
- 佣金不归并到家主。
|
||||||
|
- 有佣金路径下,邀请人不额外赠送订阅时间。
|
||||||
|
|
||||||
|
### 7.4 不发佣金路径
|
||||||
|
|
||||||
|
如果 `shouldProcessCommission=false`:
|
||||||
|
|
||||||
|
| `order.is_new` | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| `true` | 被邀请人和邀请人双方赠送订阅时间 |
|
||||||
|
| `false` | 不赠送时间 |
|
||||||
|
|
||||||
|
双方赠时具体为:
|
||||||
|
|
||||||
|
1. 被邀请人赠时:
|
||||||
|
- 如果被邀请人是家庭成员,加到被邀请人家主套餐。
|
||||||
|
- 否则加到被邀请人本人套餐。
|
||||||
|
2. 邀请人赠时:
|
||||||
|
- 如果邀请人是家庭成员,加到邀请人家主套餐。
|
||||||
|
- 否则加到邀请人本人套餐。
|
||||||
|
|
||||||
|
## 8. 赠送时间目标解析
|
||||||
|
|
||||||
|
入口:`resolveGiftTargetUser(source, forcedOwnerID)`
|
||||||
|
|
||||||
|
### 8.1 强制 owner 分支
|
||||||
|
|
||||||
|
如果 `forcedOwnerID > 0`:
|
||||||
|
|
||||||
|
- 赠送目标直接使用 `forcedOwnerID`。
|
||||||
|
- 典型场景:订单里已有 `subscription_user_id`。
|
||||||
|
- 这保证了家庭成员购买时,被邀请人的赠时落到家主。
|
||||||
|
|
||||||
|
### 8.2 自动家庭组解析分支
|
||||||
|
|
||||||
|
如果没有强制 owner:
|
||||||
|
|
||||||
|
- 调用 `ResolveEntitlementUser(source.Id)`。
|
||||||
|
- 如果 source 是有效家庭成员,目标改为家主。
|
||||||
|
- 否则目标为本人。
|
||||||
|
|
||||||
|
典型场景:
|
||||||
|
|
||||||
|
- 无佣金路径下,邀请人也赠时。
|
||||||
|
- 邀请人如果是家庭成员,赠时会加到邀请人家主套餐。
|
||||||
|
|
||||||
|
### 8.3 目标用户查询失败
|
||||||
|
|
||||||
|
如果解析出来的目标用户查不到:
|
||||||
|
|
||||||
|
- 记录错误日志。
|
||||||
|
- 回退为 source 本人。
|
||||||
|
|
||||||
|
## 9. 赠送时间落库逻辑
|
||||||
|
|
||||||
|
入口:`grantGiftDays(u, days, orderNo, remark)`
|
||||||
|
|
||||||
|
### 9.1 空值和配置分支
|
||||||
|
|
||||||
|
| 条件 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 目标用户为空 | 直接返回,不写日志 |
|
||||||
|
| `days <= 0` | 直接返回,不写日志 |
|
||||||
|
|
||||||
|
### 9.2 幂等检查
|
||||||
|
|
||||||
|
按下面条件查 gift 日志:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
type = 34
|
||||||
|
AND object_id = 目标用户 ID
|
||||||
|
AND content LIKE '%订单号%'
|
||||||
|
```
|
||||||
|
|
||||||
|
| 结果 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| 已存在 | 跳过,不重复赠时 |
|
||||||
|
| 不存在 | 继续 |
|
||||||
|
|
||||||
|
### 9.3 查目标用户活跃订阅
|
||||||
|
|
||||||
|
调用 `FindActiveSubscribe`。
|
||||||
|
|
||||||
|
当前活跃口径:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
user_id = 目标用户 ID
|
||||||
|
AND status IN (0, 1)
|
||||||
|
AND (
|
||||||
|
expire_time > NOW()
|
||||||
|
OR expire_time = FROM_UNIXTIME(0)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
说明:
|
||||||
|
|
||||||
|
- `expire_time > NOW()` 是普通未过期订阅。
|
||||||
|
- `expire_time = FROM_UNIXTIME(0)` 是永久/不限时订阅。
|
||||||
|
|
||||||
|
### 9.4 没有活跃订阅
|
||||||
|
|
||||||
|
如果查不到活跃订阅:
|
||||||
|
|
||||||
|
- 不创建新订阅。
|
||||||
|
- 写一条 `system_logs type=34` 日志。
|
||||||
|
- 日志 remark 为:
|
||||||
|
|
||||||
|
```text
|
||||||
|
邀请赠送 skipped: no active subscription
|
||||||
|
```
|
||||||
|
|
||||||
|
这表示邀请赠时触发过,但目标用户当时没有可加时的套餐。
|
||||||
|
|
||||||
|
### 9.5 找到普通活跃订阅
|
||||||
|
|
||||||
|
如果目标订阅不是永久订阅:
|
||||||
|
|
||||||
|
- `expire_time += days * 24h`
|
||||||
|
- 更新订阅。
|
||||||
|
- 写 `system_logs type=34` gift increase 日志。
|
||||||
|
|
||||||
|
### 9.6 找到永久订阅
|
||||||
|
|
||||||
|
如果目标订阅 `expire_time = FROM_UNIXTIME(0)`:
|
||||||
|
|
||||||
|
- 不改变 `expire_time`,因为永久订阅没有可延长的到期时间。
|
||||||
|
- 仍写 `system_logs type=34` gift increase 日志,表示赠送逻辑已识别并处理。
|
||||||
|
|
||||||
|
### 9.7 赠时失败日志
|
||||||
|
|
||||||
|
发佣金路径和无佣金路径都会检查 `grantGiftDays` 返回错误。
|
||||||
|
|
||||||
|
如果出错,会写应用日志:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Grant invite gift days failed
|
||||||
|
```
|
||||||
|
|
||||||
|
附带字段:
|
||||||
|
|
||||||
|
- `stage`
|
||||||
|
- `target_user_id`
|
||||||
|
- `order_no`
|
||||||
|
- `error`
|
||||||
|
|
||||||
|
## 10. 家庭组下的完整分支示例
|
||||||
|
|
||||||
|
### 10.1 被邀请人是普通用户,邀请人普通用户,有佣金
|
||||||
|
|
||||||
|
条件:
|
||||||
|
|
||||||
|
- 被邀请人 `referer_id != 0`
|
||||||
|
- 系统或邀请人佣金比例大于 0
|
||||||
|
- `order.is_new=true`
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 佣金给邀请人本人。
|
||||||
|
- 被邀请人本人套餐加赠送时间。
|
||||||
|
- 邀请人不加赠送时间。
|
||||||
|
|
||||||
|
### 10.2 被邀请人是家庭成员,邀请人普通用户,有佣金
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 佣金给邀请人本人。
|
||||||
|
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||||
|
- 被邀请人成员本人不单独加订阅时间。
|
||||||
|
|
||||||
|
### 10.3 被邀请人普通用户,邀请人是家庭成员,有佣金
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 佣金给邀请人成员本人。
|
||||||
|
- 被邀请人本人套餐加赠送时间。
|
||||||
|
- 邀请人不加赠送时间。
|
||||||
|
- 邀请人家主不拿佣金,也不因该佣金路径加赠时。
|
||||||
|
|
||||||
|
### 10.4 被邀请人是家庭成员,邀请人也是家庭成员,有佣金
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 佣金给邀请人成员本人。
|
||||||
|
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||||
|
- 邀请人不加赠送时间。
|
||||||
|
- 邀请人家主不拿佣金。
|
||||||
|
|
||||||
|
### 10.5 无佣金路径,被邀请人普通用户,邀请人普通用户
|
||||||
|
|
||||||
|
触发条件示例:
|
||||||
|
|
||||||
|
- `ReferralPercentage=0`
|
||||||
|
- 或因首购限制导致不发佣金
|
||||||
|
- 且 `order.is_new=true`
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 被邀请人本人套餐加赠送时间。
|
||||||
|
- 邀请人本人套餐加赠送时间。
|
||||||
|
|
||||||
|
### 10.6 无佣金路径,被邀请人是家庭成员
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 被邀请人的赠送时间加到被邀请人家主套餐。
|
||||||
|
- 邀请人的赠时按邀请人自己的家庭归属解析。
|
||||||
|
|
||||||
|
### 10.7 无佣金路径,邀请人是家庭成员
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 被邀请人的赠时按被邀请人的家庭归属解析。
|
||||||
|
- 邀请人的赠送时间加到邀请人家主套餐。
|
||||||
|
- 邀请人成员本人不单独加订阅时间。
|
||||||
|
|
||||||
|
### 10.8 被邀请人没有活跃订阅
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 不创建新订阅。
|
||||||
|
- 写 skipped gift 日志。
|
||||||
|
- 后续即使用户后来有订阅,也不会自动补赠,除非另行补偿。
|
||||||
|
|
||||||
|
### 10.9 被邀请人或目标家主是永久订阅
|
||||||
|
|
||||||
|
结果:
|
||||||
|
|
||||||
|
- 识别为活跃订阅。
|
||||||
|
- 不改变到期时间。
|
||||||
|
- 写 gift increase 日志。
|
||||||
|
|
||||||
|
## 11. 排查 SQL
|
||||||
|
|
||||||
|
### 11.1 查邀请配置
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT `key`, `value`, `updated_at`
|
||||||
|
FROM system
|
||||||
|
WHERE category = 'invite'
|
||||||
|
AND `key` IN ('GiftDays', 'OnlyFirstPurchase', 'ReferralPercentage');
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.2 查某邀请人的被邀请用户
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT id, referer_id, created_at
|
||||||
|
FROM `user`
|
||||||
|
WHERE referer_id = 23944
|
||||||
|
ORDER BY id DESC
|
||||||
|
LIMIT 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.3 查被邀请人的订单和首单标记
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT u.id AS invited_user_id,
|
||||||
|
o.id AS order_id,
|
||||||
|
o.order_no,
|
||||||
|
o.type,
|
||||||
|
o.status,
|
||||||
|
o.amount,
|
||||||
|
o.is_new,
|
||||||
|
o.subscribe_id,
|
||||||
|
o.subscription_user_id,
|
||||||
|
o.created_at
|
||||||
|
FROM `user` u
|
||||||
|
LEFT JOIN `order` o
|
||||||
|
ON o.user_id = u.id
|
||||||
|
AND o.type IN (1, 2)
|
||||||
|
WHERE u.referer_id = 23944
|
||||||
|
ORDER BY u.id DESC, o.id ASC
|
||||||
|
LIMIT 200;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.4 查某订单佣金和赠时日志
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT id, type, object_id, content, created_at
|
||||||
|
FROM system_logs
|
||||||
|
WHERE content LIKE '%202604281812556044982351822%'
|
||||||
|
ORDER BY id DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.5 查某用户订阅
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT id, user_id, order_id, subscribe_id, status,
|
||||||
|
expire_time, finished_at, token, created_at, updated_at
|
||||||
|
FROM user_subscribe
|
||||||
|
WHERE user_id = 24425
|
||||||
|
ORDER BY id DESC;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.6 查首单但没有赠时日志的被邀请人
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT first_orders.user_id AS invited_user_id,
|
||||||
|
first_orders.order_no,
|
||||||
|
first_orders.is_new,
|
||||||
|
first_orders.status,
|
||||||
|
first_orders.subscription_user_id,
|
||||||
|
first_orders.created_at,
|
||||||
|
(
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM system_logs sl
|
||||||
|
WHERE sl.type = 34
|
||||||
|
AND sl.content LIKE CONCAT('%', first_orders.order_no, '%')
|
||||||
|
) AS gift_log_count,
|
||||||
|
(
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM system_logs sl
|
||||||
|
WHERE sl.type = 33
|
||||||
|
AND sl.content LIKE CONCAT('%', first_orders.order_no, '%')
|
||||||
|
) AS commission_log_count
|
||||||
|
FROM (
|
||||||
|
SELECT o.*
|
||||||
|
FROM `order` o
|
||||||
|
JOIN (
|
||||||
|
SELECT user_id, MIN(id) AS first_order_id
|
||||||
|
FROM `order`
|
||||||
|
WHERE type IN (1, 2)
|
||||||
|
AND status IN (2, 5)
|
||||||
|
GROUP BY user_id
|
||||||
|
) fo ON fo.first_order_id = o.id
|
||||||
|
) first_orders
|
||||||
|
JOIN `user` u ON u.id = first_orders.user_id
|
||||||
|
WHERE u.referer_id = 23944
|
||||||
|
ORDER BY first_orders.created_at DESC
|
||||||
|
LIMIT 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
## 12. 部署注意事项
|
||||||
|
|
||||||
|
邀请配置存在两层状态:
|
||||||
|
|
||||||
|
1. Redis 缓存:`system:invite_config`
|
||||||
|
2. 服务进程内存:`svc.Config.Invite`
|
||||||
|
|
||||||
|
如果直接修改数据库或 Redis,已经运行的 `ppanel-server` 进程不会自动刷新内存配置。订单激活和赠时发生在服务进程/队列 worker 内,所以修改邀请配置或部署赠时逻辑后,需要重启服务。
|
||||||
|
|
||||||
|
推荐步骤:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker exec ppanel-redis redis-cli DEL system:invite_config system:global_config
|
||||||
|
docker restart ppanel-server
|
||||||
|
```
|
||||||
|
|
||||||
|
确认启动时间:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.Config.Image}}' ppanel-server
|
||||||
|
docker ps --filter name=ppanel-server
|
||||||
|
```
|
||||||
|
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
# TAPI 文件上传接入说明
|
||||||
|
|
||||||
|
本文档说明 `https://tapi.hifast.biz/v1/public/file/upload` 相关上传接口的推荐接入方式、签名规则与常见排查方式。
|
||||||
|
|
||||||
|
## 总览
|
||||||
|
|
||||||
|
上传能力包含两类接入方式:
|
||||||
|
|
||||||
|
- 推荐方式:`init -> S3 PUT -> complete`
|
||||||
|
- 兼容方式:`/upload` multipart 直传
|
||||||
|
|
||||||
|
推荐优先使用预签名三段式,因为:
|
||||||
|
|
||||||
|
- 现有签名串包含 `BODY_SHA256`
|
||||||
|
- `/upload` 是 `multipart/form-data`
|
||||||
|
- multipart 原始 body 的签名和调试成本更高
|
||||||
|
- `init` 和 `complete` 是 JSON,更适合客户端和 Apifox 调试
|
||||||
|
|
||||||
|
## 签名生效逻辑
|
||||||
|
|
||||||
|
项目保持现有旧逻辑,不做强制签名改造:
|
||||||
|
|
||||||
|
- `Signature.EnableSignature = false` 时:不校验签名
|
||||||
|
- `Signature.EnableSignature = true` 且未携带 `X-App-Id` 时:不校验签名,兼容老客户端
|
||||||
|
- `Signature.EnableSignature = true` 且携带 `X-App-Id` 时:必须同时携带并校验
|
||||||
|
- `X-Timestamp`
|
||||||
|
- `X-Nonce`
|
||||||
|
- `X-Signature`
|
||||||
|
|
||||||
|
这意味着:
|
||||||
|
|
||||||
|
- 新客户端建议始终带完整签名头
|
||||||
|
- 老客户端如果没有 `X-App-Id`,仍可按旧逻辑访问
|
||||||
|
|
||||||
|
## 签名头定义
|
||||||
|
|
||||||
|
- `X-App-Id`: 客户端标识,例如 `ios-client`
|
||||||
|
- `X-Timestamp`: Unix 秒级时间戳
|
||||||
|
- `X-Nonce`: 每次请求唯一随机串
|
||||||
|
- `X-Signature`: `HMAC-SHA256` 结果的十六进制小写字符串
|
||||||
|
|
||||||
|
## StringToSign 规则
|
||||||
|
|
||||||
|
StringToSign 由下面 7 段按换行符 `\n` 拼接:
|
||||||
|
|
||||||
|
```text
|
||||||
|
METHOD
|
||||||
|
PATH
|
||||||
|
CANONICAL_QUERY
|
||||||
|
BODY_SHA256
|
||||||
|
X-App-Id
|
||||||
|
X-Timestamp
|
||||||
|
X-Nonce
|
||||||
|
```
|
||||||
|
|
||||||
|
说明:
|
||||||
|
|
||||||
|
- `METHOD`:HTTP 方法大写,例如 `POST`
|
||||||
|
- `PATH`:请求路径,例如 `/v1/public/file/upload/init`
|
||||||
|
- `CANONICAL_QUERY`:按 key 排序后的 query string,没有 query 则为空字符串
|
||||||
|
- `BODY_SHA256`:请求体原始字节的 SHA-256 十六进制小写
|
||||||
|
- 其余三项直接使用请求头值
|
||||||
|
|
||||||
|
签名计算方式:
|
||||||
|
|
||||||
|
```text
|
||||||
|
signature = hex_lower(HMAC_SHA256(app_secret, string_to_sign))
|
||||||
|
```
|
||||||
|
|
||||||
|
时间窗与防重放:
|
||||||
|
|
||||||
|
- `X-Timestamp` 默认有效时间窗是 300 秒
|
||||||
|
- `X-Nonce` 在有效时间窗内不能重复使用
|
||||||
|
|
||||||
|
## 推荐接入:预签名三段式
|
||||||
|
|
||||||
|
### 1. 初始化上传
|
||||||
|
|
||||||
|
请求:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/init' \
|
||||||
|
-H 'Accept: application/json, text/plain, */*' \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'authorization: your-token' \
|
||||||
|
-H 'X-App-Id: ios-client' \
|
||||||
|
-H 'X-Timestamp: 1778776400' \
|
||||||
|
-H 'X-Nonce: nonce-001' \
|
||||||
|
-H 'X-Signature: your-signature' \
|
||||||
|
-d '{
|
||||||
|
"biz_type": "app-package",
|
||||||
|
"file_name": "demo.zip",
|
||||||
|
"content_type": "application/zip",
|
||||||
|
"size": 123456,
|
||||||
|
"sha256": ""
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
典型返回:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 200,
|
||||||
|
"msg": "success",
|
||||||
|
"data": {
|
||||||
|
"file_id": "c29274ee26ab5aa211e0396e",
|
||||||
|
"object_key": "app-upload/app-package/519/2026/05/c29274ee26ab5aa211e0396e_demo.zip",
|
||||||
|
"upload_url": "https://bucket.s3.ap-east-1.amazonaws.com/...",
|
||||||
|
"method": "PUT",
|
||||||
|
"headers": {
|
||||||
|
"Content-Type": "application/zip"
|
||||||
|
},
|
||||||
|
"expired_at": 1778776715
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 直传 S3
|
||||||
|
|
||||||
|
这一步是直接上传二进制文件到 S3,不走业务签名中间件。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
|
||||||
|
-H 'Content-Type: application/zip' \
|
||||||
|
--upload-file '/tmp/demo.zip'
|
||||||
|
```
|
||||||
|
|
||||||
|
说明:
|
||||||
|
|
||||||
|
- `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致
|
||||||
|
- `upload_url` 有过期时间,通常 300 秒
|
||||||
|
- 成功时 S3 常见返回 `200` 或 `204`
|
||||||
|
|
||||||
|
### 3. 完成上传
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
|
||||||
|
-H 'Accept: application/json, text/plain, */*' \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'authorization: your-token' \
|
||||||
|
-H 'X-App-Id: ios-client' \
|
||||||
|
-H 'X-Timestamp: 1778776405' \
|
||||||
|
-H 'X-Nonce: nonce-002' \
|
||||||
|
-H 'X-Signature: your-signature' \
|
||||||
|
-d '{
|
||||||
|
"file_id": "c29274ee26ab5aa211e0396e"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 兼容接入:单接口 multipart 直传
|
||||||
|
|
||||||
|
接口:
|
||||||
|
|
||||||
|
- `POST /v1/public/file/upload`
|
||||||
|
|
||||||
|
表单字段:
|
||||||
|
|
||||||
|
- `biz_type`
|
||||||
|
- `file`
|
||||||
|
|
||||||
|
说明:
|
||||||
|
|
||||||
|
- 该接口继续保留,兼容旧客户端
|
||||||
|
- 如果请求带了 `X-App-Id`,就按现有逻辑验签
|
||||||
|
- 如果没有 `X-App-Id`,仍按旧逻辑放行
|
||||||
|
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
|
||||||
|
|
||||||
|
## 常见错误码
|
||||||
|
|
||||||
|
- `200`: 成功
|
||||||
|
- `400`: 参数错误
|
||||||
|
- `40008`: 缺少签名头
|
||||||
|
- `40009`: 签名已过期
|
||||||
|
- `40010`: 签名无效
|
||||||
|
- `40011`: nonce 重放
|
||||||
|
- `10001`: 上传元数据不存在或对象不存在
|
||||||
|
|
||||||
|
## 排查建议
|
||||||
|
|
||||||
|
- `40008`:确认带了 `X-App-Id` 后,也同时带上 `X-Timestamp / X-Nonce / X-Signature`
|
||||||
|
- `40009`:检查客户端时间是否偏差过大
|
||||||
|
- `40010`:确认 `PATH`、query 排序、body 原始字节、secret 是否完全一致
|
||||||
|
- `40011`:确保每次请求都生成新的 `X-Nonce`
|
||||||
|
- `complete` 失败:确认 S3 `PUT` 已成功,且上传大小与 `init.size` 一致
|
||||||
+23
-136
@@ -6,9 +6,9 @@
|
|||||||
# 4. 运行: docker-compose -f docker-compose.cloud.yml up -d
|
# 4. 运行: docker-compose -f docker-compose.cloud.yml up -d
|
||||||
#
|
#
|
||||||
# 网络说明:
|
# 网络说明:
|
||||||
# ppanel-server 使用 host 网络(可出外网,访问 MySQL/Redis/Tempo 用 127.0.0.1)
|
# ppanel-server 使用 host 网络(可出外网,直接访问 AWS RDS / 本机 Redis)
|
||||||
# 监控服务(MySQL/Redis/Loki/Tempo/Grafana/Prometheus)在 ppanel_net bridge 网络中
|
# 监控服务(Loki/Tempo/Grafana/Prometheus)在 ppanel_net bridge 网络中
|
||||||
# MySQL(3306)/Redis(6379)/Tempo(4317) 将端口映射到 127.0.0.1,ppanel-server 通过 host 网络访问
|
# Tempo(4317) 将端口映射到 127.0.0.1,ppanel-server 通过 host 网络访问
|
||||||
# 监控端口绑定 127.0.0.1,需通过 SSH 隧道或 Nginx 反代访问
|
# 监控端口绑定 127.0.0.1,需通过 SSH 隧道或 Nginx 反代访问
|
||||||
#
|
#
|
||||||
# 未来多开 ppanel-server 时:
|
# 未来多开 ppanel-server 时:
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
services:
|
services:
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 1. 业务后端 (PPanel Server)
|
# 1. 业务后端 (PPanel Server)
|
||||||
# host 网络:可出外网,通过 127.0.0.1 访问 MySQL/Redis/Tempo
|
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
ppanel-server:
|
ppanel-server:
|
||||||
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
|
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
|
||||||
@@ -27,7 +27,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./configs:/app/etc
|
- ./configs:/app/etc
|
||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
- ./cache:/app/cache # GeoLite2-City.mmdb IP 地理位置数据库
|
- ./cache:/app/cache # GeoLite2-City.mmdb IP 地理位置数据库
|
||||||
environment:
|
environment:
|
||||||
- TZ=Asia/Shanghai
|
- TZ=Asia/Shanghai
|
||||||
network_mode: host
|
network_mode: host
|
||||||
@@ -37,10 +37,6 @@ services:
|
|||||||
soft: 65535
|
soft: 65535
|
||||||
hard: 65535
|
hard: 65535
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
|
||||||
condition: service_healthy
|
|
||||||
redis:
|
|
||||||
condition: service_healthy
|
|
||||||
tempo:
|
tempo:
|
||||||
condition: service_started
|
condition: service_started
|
||||||
logging:
|
logging:
|
||||||
@@ -50,81 +46,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 2. MySQL Database
|
# 2. Tempo (链路追踪存储)
|
||||||
# ----------------------------------------------------
|
|
||||||
mysql:
|
|
||||||
image: mysql:8.0
|
|
||||||
container_name: ppanel-mysql
|
|
||||||
restart: always
|
|
||||||
ports:
|
|
||||||
- "3306:3306" # 仅宿主机可访问,ppanel-server(host网络)通过127.0.0.1连接
|
|
||||||
environment:
|
|
||||||
MYSQL_ROOT_PASSWORD: "${MYSQL_ROOT_PASSWORD:?请在 .env 文件中设置 MYSQL_ROOT_PASSWORD}"
|
|
||||||
MYSQL_DATABASE: "ppanel"
|
|
||||||
TZ: Asia/Shanghai
|
|
||||||
command:
|
|
||||||
- --default-authentication-plugin=mysql_native_password
|
|
||||||
- --innodb_buffer_pool_size=16G
|
|
||||||
- --innodb_buffer_pool_instances=16
|
|
||||||
- --innodb_log_file_size=2G
|
|
||||||
- --innodb_flush_log_at_trx_commit=2
|
|
||||||
- --innodb_io_capacity=5000
|
|
||||||
- --max_connections=5000
|
|
||||||
volumes:
|
|
||||||
- mysql_data:/var/lib/mysql
|
|
||||||
ulimits:
|
|
||||||
nproc: 65535
|
|
||||||
nofile:
|
|
||||||
soft: 65535
|
|
||||||
hard: 65535
|
|
||||||
networks:
|
|
||||||
- ppanel_net
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${MYSQL_ROOT_PASSWORD}"]
|
|
||||||
interval: 10s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 5
|
|
||||||
logging:
|
|
||||||
driver: "json-file"
|
|
||||||
options:
|
|
||||||
max-size: "10m"
|
|
||||||
max-file: "3"
|
|
||||||
|
|
||||||
# ----------------------------------------------------
|
|
||||||
# 3. Redis
|
|
||||||
# ----------------------------------------------------
|
|
||||||
redis:
|
|
||||||
image: redis:8.2.1
|
|
||||||
container_name: ppanel-redis
|
|
||||||
restart: always
|
|
||||||
ports:
|
|
||||||
- "127.0.0.1:6379:6379" # 仅宿主机可访问,ppanel-server(host网络)通过127.0.0.1连接
|
|
||||||
command:
|
|
||||||
- redis-server
|
|
||||||
- --tcp-backlog 65535
|
|
||||||
- --maxmemory-policy allkeys-lru
|
|
||||||
volumes:
|
|
||||||
- redis_data:/data
|
|
||||||
ulimits:
|
|
||||||
nproc: 65535
|
|
||||||
nofile:
|
|
||||||
soft: 65535
|
|
||||||
hard: 65535
|
|
||||||
networks:
|
|
||||||
- ppanel_net
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "redis-cli", "ping"]
|
|
||||||
interval: 10s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 5
|
|
||||||
logging:
|
|
||||||
driver: "json-file"
|
|
||||||
options:
|
|
||||||
max-size: "10m"
|
|
||||||
max-file: "3"
|
|
||||||
|
|
||||||
# ----------------------------------------------------
|
|
||||||
# 4. Tempo (链路追踪存储)
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
tempo:
|
tempo:
|
||||||
image: grafana/tempo:2.4.1
|
image: grafana/tempo:2.4.1
|
||||||
@@ -138,7 +60,7 @@ services:
|
|||||||
- ./tempo/tempo-config.yaml:/etc/tempo.yaml
|
- ./tempo/tempo-config.yaml:/etc/tempo.yaml
|
||||||
- ./tempo_data:/var/tempo
|
- ./tempo_data:/var/tempo
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:4317:4317" # OTLP gRPC,ppanel-server(host网络)通过127.0.0.1:4317发送trace
|
- "127.0.0.1:4317:4317" # OTLP gRPC,ppanel-server(host网络)通过127.0.0.1:4317发送trace
|
||||||
networks:
|
networks:
|
||||||
- ppanel_net
|
- ppanel_net
|
||||||
logging:
|
logging:
|
||||||
@@ -148,7 +70,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 5. Loki (日志存储)
|
# 3. Loki (日志存储)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
loki:
|
loki:
|
||||||
image: grafana/loki:3.0.0
|
image: grafana/loki:3.0.0
|
||||||
@@ -168,7 +90,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 6. Promtail (日志采集)
|
# 4. Promtail (日志采集)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
promtail:
|
promtail:
|
||||||
image: grafana/promtail:3.0.0
|
image: grafana/promtail:3.0.0
|
||||||
@@ -192,7 +114,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 7. Grafana (可观测面板)
|
# 5. Grafana (可观测面板)
|
||||||
# 访问: ssh -L 3333:localhost:3333 your-server 后浏览器打开 http://localhost:3333
|
# 访问: ssh -L 3333:localhost:3333 your-server 后浏览器打开 http://localhost:3333
|
||||||
# 或配置 Nginx 反代(建议加认证)
|
# 或配置 Nginx 反代(建议加认证)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
@@ -201,11 +123,18 @@ services:
|
|||||||
container_name: ppanel-grafana
|
container_name: ppanel-grafana
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
|
- "3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
|
||||||
environment:
|
environment:
|
||||||
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:?请在 .env 文件中设置 GRAFANA_PASSWORD}
|
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:?请在 .env 文件中设置 GRAFANA_PASSWORD}
|
||||||
- GF_USERS_ALLOW_SIGN_UP=false
|
- GF_USERS_ALLOW_SIGN_UP=false
|
||||||
|
- GF_SERVER_DOMAIN=${GRAFANA_DOMAIN:-logsx.hifast.biz}
|
||||||
|
- GF_SERVER_ROOT_URL=${GRAFANA_ROOT_URL:-https://logsx.hifast.biz}
|
||||||
- GF_FEATURE_TOGGLES_ENABLE=appObservability
|
- GF_FEATURE_TOGGLES_ENABLE=appObservability
|
||||||
|
- AWS_REGION=${AWS_REGION:-ap-east-1}
|
||||||
|
- AWS_DEFAULT_REGION=${AWS_REGION:-ap-east-1}
|
||||||
|
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-}
|
||||||
|
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-}
|
||||||
|
- AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN:-}
|
||||||
volumes:
|
volumes:
|
||||||
- grafana_data:/var/lib/grafana
|
- grafana_data:/var/lib/grafana
|
||||||
- ./grafana/provisioning:/etc/grafana/provisioning
|
- ./grafana/provisioning:/etc/grafana/provisioning
|
||||||
@@ -222,14 +151,14 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 8. Prometheus (指标采集)
|
# 6. Prometheus (指标采集)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
prometheus:
|
prometheus:
|
||||||
image: prom/prometheus:latest
|
image: prom/prometheus:latest
|
||||||
container_name: ppanel-prometheus
|
container_name: ppanel-prometheus
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:9090:9090" # 仅本机可访问
|
- "127.0.0.1:9090:9090" # 仅本机可访问
|
||||||
volumes:
|
volumes:
|
||||||
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
|
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
|
||||||
- prometheus_data:/prometheus
|
- prometheus_data:/prometheus
|
||||||
@@ -247,26 +176,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 9. Redis Exporter
|
# 7. Nginx Exporter (监控宿主机 Nginx)
|
||||||
# ----------------------------------------------------
|
|
||||||
redis-exporter:
|
|
||||||
image: oliver006/redis_exporter:latest
|
|
||||||
container_name: ppanel-redis-exporter
|
|
||||||
restart: always
|
|
||||||
environment:
|
|
||||||
- REDIS_ADDR=redis://redis:6379
|
|
||||||
networks:
|
|
||||||
- ppanel_net
|
|
||||||
depends_on:
|
|
||||||
- redis
|
|
||||||
logging:
|
|
||||||
driver: "json-file"
|
|
||||||
options:
|
|
||||||
max-size: "10m"
|
|
||||||
max-file: "3"
|
|
||||||
|
|
||||||
# ----------------------------------------------------
|
|
||||||
# 10. Nginx Exporter (监控宿主机 Nginx)
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
nginx-exporter:
|
nginx-exporter:
|
||||||
image: nginx/nginx-prometheus-exporter:latest
|
image: nginx/nginx-prometheus-exporter:latest
|
||||||
@@ -285,28 +195,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 11. MySQL Exporter
|
# 8. Node Exporter (宿主机监控)
|
||||||
# ----------------------------------------------------
|
|
||||||
mysql-exporter:
|
|
||||||
image: prom/mysqld-exporter:latest
|
|
||||||
container_name: ppanel-mysql-exporter
|
|
||||||
restart: always
|
|
||||||
command:
|
|
||||||
- --config.my-cnf=/etc/.my.cnf
|
|
||||||
volumes:
|
|
||||||
- ./mysql/.my.cnf:/etc/.my.cnf:ro
|
|
||||||
networks:
|
|
||||||
- ppanel_net
|
|
||||||
depends_on:
|
|
||||||
- mysql
|
|
||||||
logging:
|
|
||||||
driver: "json-file"
|
|
||||||
options:
|
|
||||||
max-size: "10m"
|
|
||||||
max-file: "3"
|
|
||||||
|
|
||||||
# ----------------------------------------------------
|
|
||||||
# 12. Node Exporter (宿主机监控)
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
node-exporter:
|
node-exporter:
|
||||||
image: prom/node-exporter:latest
|
image: prom/node-exporter:latest
|
||||||
@@ -329,7 +218,7 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 13. cAdvisor (容器监控)
|
# 9. cAdvisor (容器监控)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
cadvisor:
|
cadvisor:
|
||||||
image: gcr.io/cadvisor/cadvisor:latest
|
image: gcr.io/cadvisor/cadvisor:latest
|
||||||
@@ -350,8 +239,6 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql_data:
|
|
||||||
redis_data:
|
|
||||||
loki_data:
|
loki_data:
|
||||||
grafana_data:
|
grafana_data:
|
||||||
prometheus_data:
|
prometheus_data:
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: ppanel-mysql
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: ppanel_dev
|
||||||
|
MYSQL_DATABASE: ppanel
|
||||||
|
MYSQL_USER: ppanel
|
||||||
|
MYSQL_PASSWORD: ppanel_dev
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
|
volumes:
|
||||||
|
- ppanel_mysql_data:/var/lib/mysql
|
||||||
|
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-pppanel_dev"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
container_name: ppanel-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
volumes:
|
||||||
|
- ppanel_redis_data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
ppanel_mysql_data:
|
||||||
|
ppanel_redis_data:
|
||||||
+22
-2
@@ -15,10 +15,10 @@ Logger: # 日志配置
|
|||||||
Level: debug # 日志级别: debug, info, warn, error, panic, fatal
|
Level: debug # 日志级别: debug, info, warn, error, panic, fatal
|
||||||
|
|
||||||
MySQL:
|
MySQL:
|
||||||
Addr: 154.12.35.103:3306 # host 网络模式; bridge 模式改为 mysql:3306
|
Addr: 45.43.29.127:3306 # host 网络模式; bridge 模式改为 mysql:3306
|
||||||
Username: root # MySQL用户名
|
Username: root # MySQL用户名
|
||||||
Password: jpcV41ppanel # MySQL密码,与 .env MYSQL_ROOT_PASSWORD 一致
|
Password: jpcV41ppanel # MySQL密码,与 .env MYSQL_ROOT_PASSWORD 一致
|
||||||
Dbname: ppanel # MySQL数据库名
|
Dbname: hifast # MySQL数据库名
|
||||||
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
|
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
|
||||||
MaxIdleConns: 10
|
MaxIdleConns: 10
|
||||||
MaxOpenConns: 100
|
MaxOpenConns: 100
|
||||||
@@ -61,6 +61,21 @@ Trace: # 链路追踪配置 (OpenTelemetry)
|
|||||||
Batcher: otlpgrpc # 本地开发留空""; 生产填 otlpgrpc
|
Batcher: otlpgrpc # 本地开发留空""; 生产填 otlpgrpc
|
||||||
Endpoint: "127.0.0.1:4317" # host 网络模式; bridge 模式改为 tempo:4317
|
Endpoint: "127.0.0.1:4317" # host 网络模式; bridge 模式改为 tempo:4317
|
||||||
|
|
||||||
|
S3:
|
||||||
|
Enable: false
|
||||||
|
Region: ""
|
||||||
|
Bucket: ""
|
||||||
|
Endpoint: ""
|
||||||
|
AccessKey: ""
|
||||||
|
SecretKey: ""
|
||||||
|
SessionToken: ""
|
||||||
|
Prefix: "app-upload"
|
||||||
|
PublicBaseURL: ""
|
||||||
|
UsePathStyle: false
|
||||||
|
PresignExpireSeconds: 300
|
||||||
|
MaxUploadSize: 104857600
|
||||||
|
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"
|
||||||
|
|
||||||
device:
|
device:
|
||||||
enable: true # 开启设备加密通信
|
enable: true # 开启设备加密通信
|
||||||
security_secret: "" # AES加密密钥,需要和App端一致,key=SHA256(security_secret)[:32]
|
security_secret: "" # AES加密密钥,需要和App端一致,key=SHA256(security_secret)[:32]
|
||||||
@@ -68,3 +83,8 @@ device:
|
|||||||
Administrator:
|
Administrator:
|
||||||
Email: admin@ppanel.dev # 后台登录邮箱,请修改
|
Email: admin@ppanel.dev # 后台登录邮箱,请修改
|
||||||
Password: CHANGE_ME_TO_STRONG_PASSWORD # 后台登录密码,请修改为强密码
|
Password: CHANGE_ME_TO_STRONG_PASSWORD # 后台登录密码,请修改为强密码
|
||||||
|
|
||||||
|
Register:
|
||||||
|
EnableTrial: true
|
||||||
|
EnableTrialEmailWhitelist: true
|
||||||
|
TrialEmailDomainWhitelist: "facebook.com,yahoo.com,qq.com,live.com,outlook.com,msn.com,example.com,go.com,aol.com,free.fr,aliyun.com,163.com,yandex.ru,indiatimes.com,alibaba.com,geocities.com,about.com,naver.com,netscape.com,yahoo.co.jp,earthlink.net,zoho.com,sky.com,mail.ru,angelfire.com,uol.com.br,spb.ru,yandex.com,globo.com,gmail.com,medscape.com,space.com,discovery.com,t-online.de,mac.com,icloud.com,homestead.com,lycos.com,web.id,nus.edu.sg,altavista.com,berlin.de,rambler.ru,pp.ua,comcast.net,sapo.pt,msk.ru,ancestry.com,daum.net,proton.me,law.com,bt.com,techspot.com,icq.com,sina.cn,libero.it,test.com,yourdomain.com,docomo.ne.jp,wp.pl,hotmail.com,orange.fr,onet.pl,me.com,india.com,kansascity.com,wanadoo.fr,fortunecity.com,web.de,terra.com.br,att.net,canada.com,skynet.be,ya.ru,excite.com,detik.com,compuserve.com,ig.com.br,zp.ua,gmx.net,xoom.com,mindspring.com,freeserve.co.uk,interia.pl,excite.co.jp,test.de,shaw.ca,virgilio.it,chez.com,rr.com,freenet.de,ntlworld.com,seznam.cz,arcor.de,tiscali.it,sympatico.ca,sina.com,gazeta.pl,care2.com,yam.com,r7.com,telenet.be,rcn.com,geek.com,sfr.fr,hotbot.com,cox.net,blueyonder.co.uk,tom.com,virginmedia.com,btinternet.com,iinet.net.au,rogers.com,ireland.com,pochta.ru,ozemail.com.au,catholic.org,bluewin.ch,chat.ru,virgin.net,verizon.net,erols.com,lycos.de,lycos.co.uk,protonmail.com,doityourself.com,home.nl,nate.com,casino.com,o2.co.uk,terra.es,mail.com,albawaba.com,126.com,www.com,planet.nl,sanook.com,21cn.com,online.de,name.com,i.ua,centrum.cz,rin.ru,aol.co.uk,voila.fr,walla.co.il,poste.it,netcom.com,parrot.com,charter.net,mydomain.com,mail-tester.com,myway.com,chello.nl,club-internet.fr,sdf.org,tiscali.co.uk,freeuk.com,unican.es,sci.fi,anonymize.com,sify.com,metacrawler.com,go.ro,ivillage.com,telus.net,dailypioneer.com,iespana.es,lycos.es,hey.com,sweb.cz,optusnet.com.au,alice.it,tpg.com.au,hamptonroads.com,saudia.com,lycos.nl,blackplanet.com,frontier.com,looksmart.com,pobox.com,prodigy.net,i.am,freeyellow.com,gmx.com,bigpond.com,crosswinds.net,dejanews.com,wanadoo.es,foxmail.com,eircom.net,islamonline.net,webindia123.com,oath.com,frontiernet.net,hetnet.nl,onmilwaukee.com,ukr.net,bugmenot.com,neuf.fr,kiwibox.com,za.com,iol.it,zonnet.nl,newmail.ru,pacbell.net,cogeco.ca,depechemode.com,concentric.net,aim.com,f5.si,yahoo.jp,terra.com,hot.ee,netzero.net,netins.net,sprynet.com,mailbox.org,mail2web.com,o2.pl,idirect.com,bigfoot.com,netspace.net.au,masrawy.com,supereva.it,yahoo.de,lycos.it,yeah.net,montevideo.com.uy,gmx.de,yahoo.co.uk,yahoofs.com,scubadiving.com,hushmail.com,iprimus.com.au,gportal.hu,swissinfo.org,inbox.com,bolt.com,telstra.com,bellsouth.net,spray.se,c3.hu,attbi.com,talktalk.co.uk,dynu.net,juno.com,yahoo.fr,msn.co.uk,fr.nf,pe.hu,bigpond.net.au,incredimail.com,adelphia.net,elvis.com,interfree.it,starmedia.com,seanet.com,yahoo.com.tw,zip.net,tds.net,she.com,forthnet.gr,land.ru,wow.com,dnsmadeeasy.com,webjump.com,singnet.com.sg,spacewar.com,tin.it,4mg.com,sp.nl,wowway.com,dmv.com,bangkok.com,fastmail.fm,sbcglobal.net,bright.net,usa.com,37.com,aeiou.pt,terra.cl,thirdage.com,btconnect.com,optimum.net,cableone.net,talkcity.com,blogos.com,c2i.net,iwon.com,aver.com,barcelona.com,ddnsfree.com,oi.com.br,lex.bg,roadrunner.com,airmail.net,lawyer.com,yahoo.com.cn,cu.cc,ananzi.co.za,au.ru,pipeline.com,cs.com,3ammagazine.com,gmx.at,qwest.net,btopenworld.com,easypost.com,westnet.com.au,nyc.com,korea.com,front.ru,inbox.lv,yahoo.com.br,ny.com,hispavista.com,abv.bg,mchsi.com,apollo.lv,everyone.net,terra.com.ar,singpost.com,doctor.com,garbage.com,bizhosting.com,go2net.com,clerk.com,games.com,charm.net,onlinehome.de,laposte.net" # 填你的白名单域名,逗号分隔
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
module github.com/perfect-panel/server
|
module github.com/perfect-panel/server
|
||||||
|
|
||||||
go 1.23.3
|
go 1.24
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f
|
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f
|
||||||
github.com/alibabacloud-go/darabonba-openapi v0.1.18
|
github.com/alibabacloud-go/darabonba-openapi v0.1.18
|
||||||
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.18
|
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.18
|
||||||
github.com/alibabacloud-go/tea v1.2.2
|
github.com/alibabacloud-go/tea v1.2.2
|
||||||
github.com/alicebob/miniredis/v2 v2.34.0
|
|
||||||
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72
|
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72
|
||||||
github.com/andybalholm/brotli v1.1.1
|
github.com/andybalholm/brotli v1.1.1
|
||||||
github.com/forgoer/openssl v1.6.0
|
github.com/forgoer/openssl v1.6.0
|
||||||
@@ -32,7 +31,6 @@ require (
|
|||||||
github.com/smartwalle/alipay/v3 v3.2.23
|
github.com/smartwalle/alipay/v3 v3.2.23
|
||||||
github.com/spf13/cast v1.7.0 // indirect
|
github.com/spf13/cast v1.7.0 // indirect
|
||||||
github.com/spf13/cobra v1.8.1
|
github.com/spf13/cobra v1.8.1
|
||||||
github.com/stretchr/testify v1.10.0
|
|
||||||
github.com/stripe/stripe-go/v81 v81.1.0
|
github.com/stripe/stripe-go/v81 v81.1.0
|
||||||
github.com/twilio/twilio-go v1.23.11
|
github.com/twilio/twilio-go v1.23.11
|
||||||
go.opentelemetry.io/otel v1.29.0
|
go.opentelemetry.io/otel v1.29.0
|
||||||
@@ -51,15 +49,19 @@ require (
|
|||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gorm.io/driver/mysql v1.5.7
|
gorm.io/driver/mysql v1.5.7
|
||||||
gorm.io/gorm v1.30.0
|
gorm.io/gorm v1.30.0
|
||||||
gorm.io/plugin/soft_delete v1.2.1
|
|
||||||
k8s.io/apimachinery v0.31.1
|
k8s.io/apimachinery v0.31.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Masterminds/sprig/v3 v3.3.0
|
github.com/Masterminds/sprig/v3 v3.3.0
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.7
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.17
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.16
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
|
||||||
github.com/fatih/color v1.18.0
|
github.com/fatih/color v1.18.0
|
||||||
github.com/goccy/go-json v0.10.4
|
github.com/goccy/go-json v0.10.4
|
||||||
github.com/golang-migrate/migrate/v4 v4.18.2
|
github.com/golang-migrate/migrate/v4 v4.18.2
|
||||||
|
github.com/mojocn/base64Captcha v1.3.8
|
||||||
github.com/oschwald/geoip2-golang v1.13.0
|
github.com/oschwald/geoip2-golang v1.13.0
|
||||||
github.com/spaolacci/murmur3 v1.1.0
|
github.com/spaolacci/murmur3 v1.1.0
|
||||||
google.golang.org/grpc v1.64.1
|
google.golang.org/grpc v1.64.1
|
||||||
@@ -79,8 +81,21 @@ require (
|
|||||||
github.com/alibabacloud-go/tea-utils v1.4.5 // indirect
|
github.com/alibabacloud-go/tea-utils v1.4.5 // indirect
|
||||||
github.com/alibabacloud-go/tea-utils/v2 v2.0.7 // indirect
|
github.com/alibabacloud-go/tea-utils/v2 v2.0.7 // indirect
|
||||||
github.com/alibabacloud-go/tea-xml v1.1.3 // indirect
|
github.com/alibabacloud-go/tea-xml v1.1.3 // indirect
|
||||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect
|
|
||||||
github.com/aliyun/credentials-go v1.3.10 // indirect
|
github.com/aliyun/credentials-go v1.3.10 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect
|
||||||
|
github.com/aws/smithy-go v1.25.1 // indirect
|
||||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
||||||
github.com/bytedance/sonic v1.12.7 // indirect
|
github.com/bytedance/sonic v1.12.7 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.2.3 // indirect
|
github.com/bytedance/sonic/loader v0.2.3 // indirect
|
||||||
@@ -88,7 +103,6 @@ require (
|
|||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/clbanning/mxj/v2 v2.5.6 // indirect
|
github.com/clbanning/mxj/v2 v2.5.6 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
|
||||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||||
github.com/gin-contrib/sse v1.0.0 // indirect
|
github.com/gin-contrib/sse v1.0.0 // indirect
|
||||||
@@ -114,27 +128,22 @@ require (
|
|||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
|
||||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/mojocn/base64Captcha v1.3.8 // indirect
|
|
||||||
github.com/openzipkin/zipkin-go v0.4.2 // indirect
|
github.com/openzipkin/zipkin-go v0.4.2 // indirect
|
||||||
github.com/oschwald/maxminddb-golang v1.13.0 // indirect
|
github.com/oschwald/maxminddb-golang v1.13.0 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
|
||||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
github.com/shopspring/decimal v1.4.0 // indirect
|
github.com/shopspring/decimal v1.4.0 // indirect
|
||||||
github.com/smartwalle/ncrypto v1.0.4 // indirect
|
github.com/smartwalle/ncrypto v1.0.4 // indirect
|
||||||
github.com/smartwalle/ngx v1.0.9 // indirect
|
github.com/smartwalle/ngx v1.0.9 // indirect
|
||||||
github.com/smartwalle/nsign v1.0.9 // indirect
|
github.com/smartwalle/nsign v1.0.9 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
github.com/stretchr/objx v0.5.2 // indirect
|
|
||||||
github.com/tjfoc/gmsm v1.4.1 // indirect
|
github.com/tjfoc/gmsm v1.4.1 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.29.0 // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.29.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.29.0 // indirect
|
go.opentelemetry.io/otel/metric v1.29.0 // indirect
|
||||||
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
|
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
|
||||||
@@ -150,5 +159,4 @@ require (
|
|||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 // indirect
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||||
gorm.io/driver/sqlite v1.6.0 // indirect
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -52,10 +52,6 @@ github.com/alibabacloud-go/tea-utils/v2 v2.0.7/go.mod h1:qxn986l+q33J5VkialKMqT/
|
|||||||
github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
||||||
github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzYtqw7dgt0=
|
github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzYtqw7dgt0=
|
||||||
github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
|
||||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE=
|
|
||||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
|
||||||
github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0=
|
|
||||||
github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8=
|
|
||||||
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
|
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
|
||||||
github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM=
|
github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM=
|
||||||
github.com/aliyun/credentials-go v1.3.10 h1:45Xxrae/evfzQL9V10zL3xX31eqgLWEaIdCoPipOEQA=
|
github.com/aliyun/credentials-go v1.3.10 h1:45Xxrae/evfzQL9V10zL3xX31eqgLWEaIdCoPipOEQA=
|
||||||
@@ -64,6 +60,42 @@ github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72 h1:
|
|||||||
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72/go.mod h1:PsJICrlruG9QcJDYuZ0dO/2KtMDALzRbony8NkxZ2nE=
|
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72/go.mod h1:PsJICrlruG9QcJDYuZ0dO/2KtMDALzRbony8NkxZ2nE=
|
||||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.17 h1:FpL4/758/diKwqbytU0prpuiu60fgXKUWCpDJtApclU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.17/go.mod h1:OXqUMzgXytfoF9JaKkhrOYsyh72t9G+MJH8mMRaexOE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 h1:+1Kl1zx6bWi4X7cKi3VYh29h8BvsCoHQEQ6ST9X8w7w=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=
|
||||||
|
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
|
||||||
|
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||||
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
|
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
|
||||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
||||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
||||||
@@ -226,8 +258,6 @@ github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
|
|||||||
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
||||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
|
||||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
|
||||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
@@ -258,9 +288,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
|
|||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
|
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
|
||||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
|
||||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||||
@@ -365,8 +392,6 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
|
|||||||
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
|
||||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
||||||
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||||
@@ -578,20 +603,9 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
||||||
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||||
gorm.io/driver/sqlite v1.1.3/go.mod h1:AKDgRWk8lcSQSw+9kxCJnX/yySj8G3rdwYlU57cB45c=
|
|
||||||
gorm.io/driver/sqlite v1.4.4 h1:gIufGoR0dQzjkyqDyYSCvsYR6fba1Gw5YKDqKeChxFc=
|
|
||||||
gorm.io/driver/sqlite v1.4.4/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
|
|
||||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
|
||||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
|
||||||
gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
|
|
||||||
gorm.io/gorm v1.23.0/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
|
||||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
|
||||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
|
||||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||||
gorm.io/plugin/soft_delete v1.2.1 h1:qx9D/c4Xu6w5KT8LviX8DgLcB9hkKl6JC9f44Tj7cGU=
|
|
||||||
gorm.io/plugin/soft_delete v1.2.1/go.mod h1:Zv7vQctOJTGOsJ/bWgrN1n3od0GBAZgnLjEx+cApLGk=
|
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
k8s.io/apimachinery v0.31.1 h1:mhcUBbj7KUjaVhyXILglcVjuS4nYXiwC+KKFBgIVy7U=
|
k8s.io/apimachinery v0.31.1 h1:mhcUBbj7KUjaVhyXILglcVjuS4nYXiwC+KKFBgIVy7U=
|
||||||
|
|||||||
@@ -0,0 +1,272 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
groups:
|
||||||
|
- orgId: 1
|
||||||
|
name: ppanel-core
|
||||||
|
folder: PPanel
|
||||||
|
interval: 1m
|
||||||
|
rules:
|
||||||
|
- uid: ppanel-target-down
|
||||||
|
title: PPanel monitoring target down
|
||||||
|
condition: C
|
||||||
|
for: 2m
|
||||||
|
noDataState: Alerting
|
||||||
|
execErrState: Error
|
||||||
|
annotations:
|
||||||
|
summary: "Monitoring target is down"
|
||||||
|
description: "{{ $labels.job }} on {{ $labels.instance }} has been down for more than 2 minutes."
|
||||||
|
labels:
|
||||||
|
severity: critical
|
||||||
|
service: ppanel
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 300
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
datasource:
|
||||||
|
type: prometheus
|
||||||
|
uid: prometheus
|
||||||
|
editorMode: code
|
||||||
|
expr: 'up{job=~"grafana|prometheus|node-exporter|cadvisor|nginx-exporter|loki|tempo"}'
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params:
|
||||||
|
- 1
|
||||||
|
type: lt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params:
|
||||||
|
- A
|
||||||
|
reducer:
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
|
||||||
|
- uid: ppanel-host-disk-high
|
||||||
|
title: PPanel host disk usage high
|
||||||
|
condition: C
|
||||||
|
for: 10m
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
annotations:
|
||||||
|
summary: "Host disk usage is high"
|
||||||
|
description: "{{ $labels.instance }} {{ $labels.mountpoint }} disk usage is above 85% for 10 minutes."
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
service: ppanel
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 900
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
datasource:
|
||||||
|
type: prometheus
|
||||||
|
uid: prometheus
|
||||||
|
editorMode: code
|
||||||
|
expr: '100 - (node_filesystem_avail_bytes{fstype!~"tmpfs|overlay|squashfs|aufs",mountpoint!~"/run.*|/var/lib/docker.*"} / node_filesystem_size_bytes{fstype!~"tmpfs|overlay|squashfs|aufs",mountpoint!~"/run.*|/var/lib/docker.*"} * 100)'
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params:
|
||||||
|
- 85
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params:
|
||||||
|
- A
|
||||||
|
reducer:
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
|
||||||
|
- uid: ppanel-host-memory-high
|
||||||
|
title: PPanel host memory usage high
|
||||||
|
condition: C
|
||||||
|
for: 10m
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
annotations:
|
||||||
|
summary: "Host memory usage is high"
|
||||||
|
description: "{{ $labels.instance }} memory usage is above 90% for 10 minutes."
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
service: ppanel
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 900
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
datasource:
|
||||||
|
type: prometheus
|
||||||
|
uid: prometheus
|
||||||
|
editorMode: code
|
||||||
|
expr: '(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100'
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params:
|
||||||
|
- 90
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params:
|
||||||
|
- A
|
||||||
|
reducer:
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
|
||||||
|
- uid: ppanel-host-cpu-high
|
||||||
|
title: PPanel host CPU usage high
|
||||||
|
condition: C
|
||||||
|
for: 10m
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
annotations:
|
||||||
|
summary: "Host CPU usage is high"
|
||||||
|
description: "{{ $labels.instance }} CPU usage is above 90% for 10 minutes."
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
service: ppanel
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 900
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
datasource:
|
||||||
|
type: prometheus
|
||||||
|
uid: prometheus
|
||||||
|
editorMode: code
|
||||||
|
expr: '100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)'
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params:
|
||||||
|
- 90
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params:
|
||||||
|
- A
|
||||||
|
reducer:
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
|
||||||
|
- uid: ppanel-container-restarts
|
||||||
|
title: PPanel container restarted
|
||||||
|
condition: C
|
||||||
|
for: 1m
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
annotations:
|
||||||
|
summary: "Container restarted"
|
||||||
|
description: "{{ $labels.name }} restarted or changed start time in the last hour."
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
service: ppanel
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 3600
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
datasource:
|
||||||
|
type: prometheus
|
||||||
|
uid: prometheus
|
||||||
|
editorMode: code
|
||||||
|
expr: 'sum by (name) (changes(container_start_time_seconds{name!=""}[1h]))'
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params:
|
||||||
|
- 0
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params:
|
||||||
|
- A
|
||||||
|
reducer:
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
providers:
|
||||||
|
- name: PPanel
|
||||||
|
orgId: 1
|
||||||
|
folder: PPanel
|
||||||
|
folderUid: ppanel
|
||||||
|
type: file
|
||||||
|
disableDeletion: false
|
||||||
|
allowUiUpdates: true
|
||||||
|
updateIntervalSeconds: 30
|
||||||
|
options:
|
||||||
|
path: /etc/grafana/provisioning/dashboards/json
|
||||||
|
foldersFromFilesStructure: false
|
||||||
@@ -0,0 +1,520 @@
|
|||||||
|
{
|
||||||
|
"annotations": {
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"builtIn": 1,
|
||||||
|
"datasource": {
|
||||||
|
"type": "grafana",
|
||||||
|
"uid": "-- Grafana --"
|
||||||
|
},
|
||||||
|
"enable": true,
|
||||||
|
"hide": true,
|
||||||
|
"iconColor": "rgba(0, 211, 255, 1)",
|
||||||
|
"name": "Annotations & Alerts",
|
||||||
|
"type": "dashboard"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"editable": true,
|
||||||
|
"fiscalYearStartMonth": 0,
|
||||||
|
"graphTooltip": 0,
|
||||||
|
"id": null,
|
||||||
|
"links": [],
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 3,
|
||||||
|
"w": 24,
|
||||||
|
"x": 0,
|
||||||
|
"y": 0
|
||||||
|
},
|
||||||
|
"id": 1,
|
||||||
|
"options": {
|
||||||
|
"content": "<b>AWS CloudWatch overview</b><br/>Region: ap-east-1 (Hong Kong)<br/>RDS DBInstanceIdentifier: hifast-mysql-prod-v2<br/>Redis: current production uses a local Docker Redis container (<code>hifast-redis</code>) on EC2 rather than AWS ElastiCache.<br/><br/>This dashboard keeps the RDS CloudWatch panels. Redis should be observed from the local ops dashboard via Prometheus/cAdvisor instead of ElastiCache metrics.",
|
||||||
|
"mode": "html"
|
||||||
|
},
|
||||||
|
"pluginVersion": "11.0.0",
|
||||||
|
"title": "Read Me",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 0,
|
||||||
|
"y": 3
|
||||||
|
},
|
||||||
|
"id": 2,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "CPUUtilization",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RDS CPU",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 8,
|
||||||
|
"y": 3
|
||||||
|
},
|
||||||
|
"id": 3,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "DatabaseConnections",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RDS Connections",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 16,
|
||||||
|
"y": 3
|
||||||
|
},
|
||||||
|
"id": 4,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "FreeStorageSpace",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Minimum"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RDS Free Storage",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 11
|
||||||
|
},
|
||||||
|
"id": 5,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "ReadLatency",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "WriteLatency",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "B",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RDS Read / Write Latency",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "iops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 11
|
||||||
|
},
|
||||||
|
"id": 6,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "ReadIOPS",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
|
||||||
|
},
|
||||||
|
"metricName": "WriteIOPS",
|
||||||
|
"namespace": "AWS/RDS",
|
||||||
|
"period": "",
|
||||||
|
"refId": "B",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "RDS Read / Write IOPS",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 6,
|
||||||
|
"x": 0,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 7,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"ReplicationGroupId": "hifastapp-redis"
|
||||||
|
},
|
||||||
|
"metricName": "CPUUtilization",
|
||||||
|
"namespace": "AWS/ElastiCache",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Redis Host CPU (Legacy ElastiCache)",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 6,
|
||||||
|
"x": 6,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 8,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"ReplicationGroupId": "hifastapp-redis"
|
||||||
|
},
|
||||||
|
"metricName": "EngineCPUUtilization",
|
||||||
|
"namespace": "AWS/ElastiCache",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Redis Engine CPU (Legacy ElastiCache)",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 6,
|
||||||
|
"x": 12,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 9,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"ReplicationGroupId": "hifastapp-redis"
|
||||||
|
},
|
||||||
|
"metricName": "CurrConnections",
|
||||||
|
"namespace": "AWS/ElastiCache",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Redis Connections (Legacy ElastiCache)",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 6,
|
||||||
|
"x": 18,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 10,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "cloudwatch",
|
||||||
|
"uid": "cloudwatch"
|
||||||
|
},
|
||||||
|
"dimensions": {
|
||||||
|
"ReplicationGroupId": "hifastapp-redis"
|
||||||
|
},
|
||||||
|
"metricName": "DatabaseMemoryUsagePercentage",
|
||||||
|
"namespace": "AWS/ElastiCache",
|
||||||
|
"period": "",
|
||||||
|
"refId": "A",
|
||||||
|
"region": "ap-east-1",
|
||||||
|
"statistic": "Average"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Redis Memory Usage % (Legacy ElastiCache)",
|
||||||
|
"type": "timeseries"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"refresh": "30s",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"style": "dark",
|
||||||
|
"tags": [
|
||||||
|
"aws",
|
||||||
|
"cloudwatch",
|
||||||
|
"rds",
|
||||||
|
"redis"
|
||||||
|
],
|
||||||
|
"templating": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"time": {
|
||||||
|
"from": "now-6h",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"timepicker": {},
|
||||||
|
"timezone": "browser",
|
||||||
|
"title": "AWS RDS & Redis Overview",
|
||||||
|
"uid": "aws-rds-redis-overview",
|
||||||
|
"version": 1,
|
||||||
|
"weekStart": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,565 @@
|
|||||||
|
{
|
||||||
|
"annotations": {
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"builtIn": 1,
|
||||||
|
"datasource": {
|
||||||
|
"type": "grafana",
|
||||||
|
"uid": "-- Grafana --"
|
||||||
|
},
|
||||||
|
"enable": true,
|
||||||
|
"hide": true,
|
||||||
|
"iconColor": "rgba(0, 211, 255, 1)",
|
||||||
|
"name": "Annotations & Alerts",
|
||||||
|
"type": "dashboard"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"editable": true,
|
||||||
|
"fiscalYearStartMonth": 0,
|
||||||
|
"graphTooltip": 0,
|
||||||
|
"id": null,
|
||||||
|
"links": [],
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"color": {
|
||||||
|
"mode": "thresholds"
|
||||||
|
},
|
||||||
|
"mappings": [
|
||||||
|
{
|
||||||
|
"options": {
|
||||||
|
"0": {
|
||||||
|
"text": "DOWN"
|
||||||
|
},
|
||||||
|
"1": {
|
||||||
|
"text": "UP"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "value"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "red",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 4,
|
||||||
|
"w": 24,
|
||||||
|
"x": 0,
|
||||||
|
"y": 0
|
||||||
|
},
|
||||||
|
"id": 1,
|
||||||
|
"options": {
|
||||||
|
"colorMode": "background",
|
||||||
|
"graphMode": "none",
|
||||||
|
"justifyMode": "center",
|
||||||
|
"orientation": "horizontal",
|
||||||
|
"reduceOptions": {
|
||||||
|
"calcs": [
|
||||||
|
"lastNotNull"
|
||||||
|
],
|
||||||
|
"fields": "",
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"showPercentChange": false,
|
||||||
|
"textMode": "auto",
|
||||||
|
"wideLayout": true
|
||||||
|
},
|
||||||
|
"pluginVersion": "13.0.1",
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "up{job=~\"prometheus|grafana|node-exporter|cadvisor|nginx-exporter|loki|tempo\"}",
|
||||||
|
"instant": true,
|
||||||
|
"legendFormat": "{{job}}",
|
||||||
|
"range": false,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Service Availability",
|
||||||
|
"type": "stat"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"max": 100,
|
||||||
|
"min": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "orange",
|
||||||
|
"value": 75
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "red",
|
||||||
|
"value": 90
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 0,
|
||||||
|
"y": 4
|
||||||
|
},
|
||||||
|
"id": 2,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "100 - (avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m])) * 100)",
|
||||||
|
"legendFormat": "{{instance}} CPU",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Host CPU Usage",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"max": 100,
|
||||||
|
"min": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "orange",
|
||||||
|
"value": 80
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "red",
|
||||||
|
"value": 90
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 8,
|
||||||
|
"y": 4
|
||||||
|
},
|
||||||
|
"id": 3,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100",
|
||||||
|
"legendFormat": "{{instance}} memory",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Host Memory Usage",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"max": 100,
|
||||||
|
"min": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "orange",
|
||||||
|
"value": 80
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "red",
|
||||||
|
"value": 90
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"unit": "percent"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 16,
|
||||||
|
"y": 4
|
||||||
|
},
|
||||||
|
"id": 4,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "100 - (node_filesystem_avail_bytes{fstype!~\"tmpfs|overlay|squashfs|aufs\",mountpoint!~\"/run.*|/var/lib/docker.*\"} / node_filesystem_size_bytes{fstype!~\"tmpfs|overlay|squashfs|aufs\",mountpoint!~\"/run.*|/var/lib/docker.*\"} * 100)",
|
||||||
|
"legendFormat": "{{mountpoint}}",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Host Disk Usage",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 0,
|
||||||
|
"y": 12
|
||||||
|
},
|
||||||
|
"id": 5,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum by (name) (rate(container_cpu_usage_seconds_total{name!=\"\"}[5m]))",
|
||||||
|
"legendFormat": "{{name}}",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Container CPU",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 8,
|
||||||
|
"y": 12
|
||||||
|
},
|
||||||
|
"id": 6,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum by (name) (container_memory_working_set_bytes{name!=\"\"})",
|
||||||
|
"legendFormat": "{{name}}",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Container Memory",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 16,
|
||||||
|
"y": 12
|
||||||
|
},
|
||||||
|
"id": 7,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum by (name) (changes(container_start_time_seconds{name!=\"\"}[1h]))",
|
||||||
|
"legendFormat": "{{name}}",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Container Restarts / Changes",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 0,
|
||||||
|
"y": 20
|
||||||
|
},
|
||||||
|
"id": 8,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "single"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "rate(nginx_http_requests_total[5m])",
|
||||||
|
"legendFormat": "requests",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Nginx Requests",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 8,
|
||||||
|
"y": 20
|
||||||
|
},
|
||||||
|
"id": 9,
|
||||||
|
"options": {
|
||||||
|
"dedupStrategy": "none",
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"prettifyLogMessage": false,
|
||||||
|
"showCommonLabels": false,
|
||||||
|
"showLabels": true,
|
||||||
|
"showTime": true,
|
||||||
|
"sortOrder": "Descending",
|
||||||
|
"wrapLogMessage": true
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "{job=~\"ppanel-server|nginx|docker\"} |~ \"(?i)(error|panic|fatal|timeout|exception|failed)\"",
|
||||||
|
"queryType": "range",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Recent Errors",
|
||||||
|
"type": "logs"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 8,
|
||||||
|
"x": 16,
|
||||||
|
"y": 20
|
||||||
|
},
|
||||||
|
"id": 10,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum by (service_name) (rate(traces_spanmetrics_calls_total[5m]))",
|
||||||
|
"legendFormat": "{{service_name}}",
|
||||||
|
"range": true,
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Trace Span Calls",
|
||||||
|
"type": "timeseries"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"refresh": "30s",
|
||||||
|
"schemaVersion": 42,
|
||||||
|
"tags": [
|
||||||
|
"ppanel",
|
||||||
|
"ops",
|
||||||
|
"prometheus",
|
||||||
|
"loki",
|
||||||
|
"tempo"
|
||||||
|
],
|
||||||
|
"templating": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"time": {
|
||||||
|
"from": "now-6h",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"timepicker": {},
|
||||||
|
"timezone": "browser",
|
||||||
|
"title": "PPanel Ops Overview",
|
||||||
|
"uid": "ppanel-ops-overview",
|
||||||
|
"version": 1,
|
||||||
|
"weekStart": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
{
|
||||||
|
"annotations": {
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"builtIn": 1,
|
||||||
|
"datasource": {
|
||||||
|
"type": "grafana",
|
||||||
|
"uid": "-- Grafana --"
|
||||||
|
},
|
||||||
|
"enable": true,
|
||||||
|
"hide": true,
|
||||||
|
"iconColor": "rgba(0, 211, 255, 1)",
|
||||||
|
"name": "Annotations & Alerts",
|
||||||
|
"type": "dashboard"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"editable": true,
|
||||||
|
"fiscalYearStartMonth": 0,
|
||||||
|
"graphTooltip": 0,
|
||||||
|
"id": null,
|
||||||
|
"links": [],
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"color": {
|
||||||
|
"mode": "palette-classic"
|
||||||
|
},
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 7,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 0
|
||||||
|
},
|
||||||
|
"id": 1,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"}[5m]))",
|
||||||
|
"queryType": "range",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Matched Log Volume",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"color": {
|
||||||
|
"mode": "palette-classic"
|
||||||
|
},
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 7,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 0
|
||||||
|
},
|
||||||
|
"id": 2,
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "table",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\" [5m]))",
|
||||||
|
"queryType": "range",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Matched Error Volume",
|
||||||
|
"type": "timeseries"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 12,
|
||||||
|
"w": 24,
|
||||||
|
"x": 0,
|
||||||
|
"y": 7
|
||||||
|
},
|
||||||
|
"id": 3,
|
||||||
|
"options": {
|
||||||
|
"dedupStrategy": "none",
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"prettifyLogMessage": false,
|
||||||
|
"showCommonLabels": false,
|
||||||
|
"showLabels": true,
|
||||||
|
"showTime": true,
|
||||||
|
"sortOrder": "Descending",
|
||||||
|
"wrapLogMessage": true
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "{compose_service=\"ppanel-server\"}",
|
||||||
|
"queryType": "range",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Filtered Server Logs",
|
||||||
|
"type": "logs"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 10,
|
||||||
|
"w": 24,
|
||||||
|
"x": 0,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 4,
|
||||||
|
"options": {
|
||||||
|
"dedupStrategy": "none",
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"prettifyLogMessage": false,
|
||||||
|
"showCommonLabels": false,
|
||||||
|
"showLabels": true,
|
||||||
|
"showTime": true,
|
||||||
|
"sortOrder": "Descending",
|
||||||
|
"wrapLogMessage": true
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "P8E80F9AEF21F6940"
|
||||||
|
},
|
||||||
|
"editorMode": "code",
|
||||||
|
"expr": "{compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\"",
|
||||||
|
"queryType": "range",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Filtered Server Errors",
|
||||||
|
"type": "logs"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"refresh": "30s",
|
||||||
|
"schemaVersion": 42,
|
||||||
|
"tags": [
|
||||||
|
"ppanel",
|
||||||
|
"logs",
|
||||||
|
"server",
|
||||||
|
"loki"
|
||||||
|
],
|
||||||
|
"templating": {
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"current": {
|
||||||
|
"selected": false,
|
||||||
|
"text": ".",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
"description": "输入用户 ID;默认 . 表示不过滤",
|
||||||
|
"hide": 0,
|
||||||
|
"label": "用户ID",
|
||||||
|
"name": "user_id",
|
||||||
|
"options": [],
|
||||||
|
"query": ".",
|
||||||
|
"skipUrlSync": false,
|
||||||
|
"type": "textbox"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"current": {
|
||||||
|
"selected": false,
|
||||||
|
"text": ".",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
"description": "输入邮箱或邮箱片段;默认 . 表示不过滤",
|
||||||
|
"hide": 0,
|
||||||
|
"label": "邮箱",
|
||||||
|
"name": "email",
|
||||||
|
"options": [],
|
||||||
|
"query": ".",
|
||||||
|
"skipUrlSync": false,
|
||||||
|
"type": "textbox"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"current": {
|
||||||
|
"selected": false,
|
||||||
|
"text": ".",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
"description": "输入订单号/支付单号/交易号片段;默认 . 表示不过滤",
|
||||||
|
"hide": 0,
|
||||||
|
"label": "订单",
|
||||||
|
"name": "order",
|
||||||
|
"options": [],
|
||||||
|
"query": ".",
|
||||||
|
"skipUrlSync": false,
|
||||||
|
"type": "textbox"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"current": {
|
||||||
|
"selected": true,
|
||||||
|
"text": "All",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
"description": "日志等级",
|
||||||
|
"hide": 0,
|
||||||
|
"includeAll": false,
|
||||||
|
"label": "等级",
|
||||||
|
"multi": false,
|
||||||
|
"name": "level",
|
||||||
|
"options": [
|
||||||
|
{
|
||||||
|
"selected": true,
|
||||||
|
"text": "All",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "debug",
|
||||||
|
"value": "debug"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "info",
|
||||||
|
"value": "info"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "warn",
|
||||||
|
"value": "warn"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "error",
|
||||||
|
"value": "error"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "slow",
|
||||||
|
"value": "slow"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "panic",
|
||||||
|
"value": "panic"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selected": false,
|
||||||
|
"text": "fatal",
|
||||||
|
"value": "fatal"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"query": "All : .,debug,info,warn,error,slow,panic,fatal",
|
||||||
|
"queryValue": "",
|
||||||
|
"skipUrlSync": false,
|
||||||
|
"type": "custom"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"current": {
|
||||||
|
"selected": false,
|
||||||
|
"text": ".",
|
||||||
|
"value": "."
|
||||||
|
},
|
||||||
|
"description": "任意关键字;默认 . 表示不过滤",
|
||||||
|
"hide": 0,
|
||||||
|
"label": "关键字",
|
||||||
|
"name": "keyword",
|
||||||
|
"options": [],
|
||||||
|
"query": ".",
|
||||||
|
"skipUrlSync": false,
|
||||||
|
"type": "textbox"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"time": {
|
||||||
|
"from": "now-1h",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"timepicker": {},
|
||||||
|
"timezone": "browser",
|
||||||
|
"title": "PPanel Server Logs",
|
||||||
|
"uid": "ppanel-server-logs",
|
||||||
|
"version": 5,
|
||||||
|
"weekStart": ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: true
|
||||||
|
jsonData:
|
||||||
|
httpMethod: POST
|
||||||
|
manageAlerts: true
|
||||||
|
prometheusType: Prometheus
|
||||||
|
prometheusVersion: 2.50.0
|
||||||
|
timeInterval: 15s
|
||||||
|
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: http://loki:3100
|
||||||
|
editable: true
|
||||||
|
jsonData:
|
||||||
|
derivedFields:
|
||||||
|
- datasourceUid: tempo
|
||||||
|
matcherRegex: '"(?:trace|traceID|trace_id)"\s*:\s*"([a-f0-9]{32})"'
|
||||||
|
name: TraceID
|
||||||
|
url: '$${__value.raw}'
|
||||||
|
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: http://tempo:3200
|
||||||
|
editable: true
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
filterByTraceID: true
|
||||||
|
filterBySpanID: false
|
||||||
|
tags:
|
||||||
|
- key: service.name
|
||||||
|
value: service_name
|
||||||
|
tracesToMetrics:
|
||||||
|
datasourceUid: prometheus
|
||||||
|
serviceMap:
|
||||||
|
datasourceUid: prometheus
|
||||||
|
|
||||||
|
- name: CloudWatch
|
||||||
|
uid: cloudwatch
|
||||||
|
type: cloudwatch
|
||||||
|
access: proxy
|
||||||
|
editable: true
|
||||||
|
jsonData:
|
||||||
|
authType: default
|
||||||
|
defaultRegion: ap-east-1
|
||||||
@@ -449,7 +449,7 @@ CREATE TABLE IF NOT EXISTS `user_device`
|
|||||||
`subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID',
|
`subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID',
|
||||||
`ip` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Ip.',
|
`ip` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Ip.',
|
||||||
`Identifier` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Identifier.',
|
`Identifier` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Identifier.',
|
||||||
`user_agent` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
|
`user_agent` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
|
||||||
`online` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Online',
|
`online` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Online',
|
||||||
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber',
|
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber',
|
||||||
`created_at` datetime(3) DEFAULT NULL COMMENT 'Creation Time',
|
`created_at` datetime(3) DEFAULT NULL COMMENT 'Creation Time',
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE `user_device` DROP COLUMN `base_payload`;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE `user_device` ADD COLUMN `base_payload` TEXT DEFAULT NULL COMMENT 'Base Payload' AFTER `short_code`;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS `order_recovery_claims`;
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS `order_recovery_claims` (
|
||||||
|
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||||
|
`order_no` VARCHAR(255) NOT NULL COMMENT 'Recovered Order No',
|
||||||
|
`email` VARCHAR(255) NOT NULL COMMENT 'Claim Email',
|
||||||
|
`user_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'User ID',
|
||||||
|
`subscribe_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'Subscribe ID',
|
||||||
|
`order_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'Recovered Order ID',
|
||||||
|
`user_subscribe_id` BIGINT NOT NULL DEFAULT 0 COMMENT 'User Subscribe ID',
|
||||||
|
`claimed_at` DATETIME(3) NOT NULL COMMENT 'Claimed Time',
|
||||||
|
`created_at` DATETIME(3) DEFAULT NULL COMMENT 'Creation Time',
|
||||||
|
`updated_at` DATETIME(3) DEFAULT NULL COMMENT 'Update Time',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `idx_order_recovery_claim_order_no` (`order_no`),
|
||||||
|
KEY `idx_order_recovery_claim_email` (`email`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ALTER TABLE `log_message`
|
||||||
|
MODIFY COLUMN `app_version` VARCHAR(32) NULL,
|
||||||
|
MODIFY COLUMN `os_name` VARCHAR(32) NULL,
|
||||||
|
MODIFY COLUMN `os_version` VARCHAR(32) NULL,
|
||||||
|
MODIFY COLUMN `device_id` VARCHAR(64) NULL,
|
||||||
|
MODIFY COLUMN `session_id` VARCHAR(64) NULL,
|
||||||
|
MODIFY COLUMN `error_code` VARCHAR(64) NULL;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ALTER TABLE `log_message`
|
||||||
|
MODIFY COLUMN `app_version` VARCHAR(64) NULL,
|
||||||
|
MODIFY COLUMN `os_name` VARCHAR(64) NULL,
|
||||||
|
MODIFY COLUMN `os_version` VARCHAR(64) NULL,
|
||||||
|
MODIFY COLUMN `device_id` VARCHAR(255) NULL,
|
||||||
|
MODIFY COLUMN `session_id` VARCHAR(255) NULL,
|
||||||
|
MODIFY COLUMN `error_code` VARCHAR(128) NULL;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE `user_device`
|
||||||
|
MODIFY COLUMN `user_agent` VARCHAR(64) NULL COMMENT 'Device User Agent.';
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE `user_device`
|
||||||
|
MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/config"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/pkg/tool"
|
"github.com/perfect-panel/server/pkg/tool"
|
||||||
)
|
)
|
||||||
@@ -17,7 +16,7 @@ func Register(ctx *svc.ServiceContext) {
|
|||||||
logger.Errorf("[Init Register Config] Get Register Config Error: %s", err.Error())
|
logger.Errorf("[Init Register Config] Get Register Config Error: %s", err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var registerConfig config.RegisterConfig
|
registerConfig := ctx.Config.Register
|
||||||
tool.SystemConfigSliceReflectToStruct(configs, ®isterConfig)
|
tool.SystemConfigSliceReflectToStruct(configs, ®isterConfig)
|
||||||
ctx.Config.Register = registerConfig
|
ctx.Config.Register = registerConfig
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,14 @@ type schemaColumnPatch struct {
|
|||||||
ddl string
|
ddl string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type schemaColumnDefinitionPatch struct {
|
||||||
|
table string
|
||||||
|
column string
|
||||||
|
dataType string
|
||||||
|
characterMaxLen *int64
|
||||||
|
ddl string
|
||||||
|
}
|
||||||
|
|
||||||
func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
||||||
tablePatches := []schemaTablePatch{
|
tablePatches := []schemaTablePatch{
|
||||||
{
|
{
|
||||||
@@ -142,6 +150,17 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
varchar255 := int64(255)
|
||||||
|
columnDefinitionPatches := []schemaColumnDefinitionPatch{
|
||||||
|
{
|
||||||
|
table: "user_device",
|
||||||
|
column: "user_agent",
|
||||||
|
dataType: "varchar",
|
||||||
|
characterMaxLen: &varchar255,
|
||||||
|
ddl: "ALTER TABLE `user_device` MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
for _, patch := range tablePatches {
|
for _, patch := range tablePatches {
|
||||||
exists, err := tableExists(ctx.DB, patch.table)
|
exists, err := tableExists(ctx.DB, patch.table)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -199,6 +218,27 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
|
|||||||
logger.Infof("[SchemaCompat] created missing index: %s.%s", patch.table, patch.index)
|
logger.Infof("[SchemaCompat] created missing index: %s.%s", patch.table, patch.index)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, patch := range columnDefinitionPatches {
|
||||||
|
tblExists, err := tableExists(ctx.DB, patch.table)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "check table %s failed", patch.table)
|
||||||
|
}
|
||||||
|
if !tblExists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
matches, err := columnDefinitionMatches(ctx.DB, patch.table, patch.column, patch.dataType, patch.characterMaxLen)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "check column definition %s.%s failed", patch.table, patch.column)
|
||||||
|
}
|
||||||
|
if matches {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = ctx.DB.Exec(patch.ddl).Error; err != nil {
|
||||||
|
return errors.Wrapf(err, "modify column %s.%s failed", patch.table, patch.column)
|
||||||
|
}
|
||||||
|
logger.Infof("[SchemaCompat] repaired column definition: %s.%s", patch.table, patch.column)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,6 +277,38 @@ func indexExists(db *gorm.DB, table, index string) (bool, error) {
|
|||||||
return count > 0, nil
|
return count > 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func columnDefinitionMatches(db *gorm.DB, table, column, dataType string, characterMaxLen *int64) (bool, error) {
|
||||||
|
type columnMeta struct {
|
||||||
|
DataType string
|
||||||
|
CharacterMaximumLen *int64
|
||||||
|
}
|
||||||
|
|
||||||
|
var meta columnMeta
|
||||||
|
err := db.Raw(
|
||||||
|
`SELECT DATA_TYPE AS data_type, CHARACTER_MAXIMUM_LENGTH AS character_maximum_len
|
||||||
|
FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
|
||||||
|
table,
|
||||||
|
column,
|
||||||
|
).Scan(&meta).Error
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if meta.DataType == "" {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if meta.DataType != dataType {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if characterMaxLen == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if meta.CharacterMaximumLen == nil {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return *meta.CharacterMaximumLen == *characterMaxLen, nil
|
||||||
|
}
|
||||||
|
|
||||||
func _schemaCompatDebug(table, column string) string {
|
func _schemaCompatDebug(table, column string) string {
|
||||||
if column == "" {
|
if column == "" {
|
||||||
return table
|
return table
|
||||||
|
|||||||
+34
-15
@@ -38,12 +38,29 @@ type Config struct {
|
|||||||
Log Log `yaml:"Log"`
|
Log Log `yaml:"Log"`
|
||||||
Currency Currency `yaml:"Currency"`
|
Currency Currency `yaml:"Currency"`
|
||||||
Trace trace.Config `yaml:"Trace"`
|
Trace trace.Config `yaml:"Trace"`
|
||||||
|
S3 S3Config `yaml:"S3"`
|
||||||
Administrator struct {
|
Administrator struct {
|
||||||
Email string `yaml:"Email" default:"admin@ppanel.dev"`
|
Email string `yaml:"Email" default:"admin@ppanel.dev"`
|
||||||
Password string `yaml:"Password" default:"password"`
|
Password string `yaml:"Password" default:"password"`
|
||||||
} `yaml:"Administrator"`
|
} `yaml:"Administrator"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type S3Config struct {
|
||||||
|
Enable bool `yaml:"Enable" default:"false"`
|
||||||
|
Region string `yaml:"Region" default:""`
|
||||||
|
Bucket string `yaml:"Bucket" default:""`
|
||||||
|
Endpoint string `yaml:"Endpoint" default:""`
|
||||||
|
AccessKey string `yaml:"AccessKey" default:""`
|
||||||
|
SecretKey string `yaml:"SecretKey" default:""`
|
||||||
|
SessionToken string `yaml:"SessionToken" default:""`
|
||||||
|
Prefix string `yaml:"Prefix" default:"app-upload"`
|
||||||
|
PublicBaseURL string `yaml:"PublicBaseURL" default:""`
|
||||||
|
UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
|
||||||
|
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
|
||||||
|
MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"`
|
||||||
|
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"`
|
||||||
|
}
|
||||||
|
|
||||||
type RedisConfig struct {
|
type RedisConfig struct {
|
||||||
Host string `yaml:"Host" default:"localhost:6379"`
|
Host string `yaml:"Host" default:"localhost:6379"`
|
||||||
Pass string `yaml:"Pass" default:""`
|
Pass string `yaml:"Pass" default:""`
|
||||||
@@ -82,15 +99,17 @@ type SubscribeConfig struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type RegisterConfig struct {
|
type RegisterConfig struct {
|
||||||
StopRegister bool `yaml:"StopRegister" default:"false"`
|
StopRegister bool `yaml:"StopRegister" default:"false"`
|
||||||
EnableTrial bool `yaml:"EnableTrial" default:"false"`
|
EnableTrial bool `yaml:"EnableTrial" default:"false"`
|
||||||
TrialSubscribe int64 `yaml:"TrialSubscribe" default:"0"`
|
EnableTrialEmailWhitelist bool `yaml:"EnableTrialEmailWhitelist" default:"true"`
|
||||||
TrialTime int64 `yaml:"TrialTime" default:"0"`
|
TrialSubscribe int64 `yaml:"TrialSubscribe" default:"0"`
|
||||||
TrialTimeUnit string `yaml:"TrialTimeUnit" default:""`
|
TrialTime int64 `yaml:"TrialTime" default:"0"`
|
||||||
IpRegisterLimit int64 `yaml:"IpRegisterLimit" default:"0"`
|
TrialTimeUnit string `yaml:"TrialTimeUnit" default:""`
|
||||||
IpRegisterLimitDuration int64 `yaml:"IpRegisterLimitDuration" default:"0"`
|
TrialEmailDomainWhitelist string `yaml:"TrialEmailDomainWhitelist" default:""`
|
||||||
EnableIpRegisterLimit bool `yaml:"EnableIpRegisterLimit" default:"false"`
|
IpRegisterLimit int64 `yaml:"IpRegisterLimit" default:"0"`
|
||||||
DeviceLimit int64 `yaml:"DeviceLimit" default:"2"`
|
IpRegisterLimitDuration int64 `yaml:"IpRegisterLimitDuration" default:"0"`
|
||||||
|
EnableIpRegisterLimit bool `yaml:"EnableIpRegisterLimit" default:"false"`
|
||||||
|
DeviceLimit int64 `yaml:"DeviceLimit" default:"2"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type EmailConfig struct {
|
type EmailConfig struct {
|
||||||
@@ -101,12 +120,12 @@ type EmailConfig struct {
|
|||||||
EnableNotify bool `yaml:"enable_notify"`
|
EnableNotify bool `yaml:"enable_notify"`
|
||||||
EnableDomainSuffix bool `yaml:"enable_domain_suffix"`
|
EnableDomainSuffix bool `yaml:"enable_domain_suffix"`
|
||||||
DomainSuffixList string `yaml:"domain_suffix_list"`
|
DomainSuffixList string `yaml:"domain_suffix_list"`
|
||||||
VerifyEmailTemplate string `yaml:"verify_email_template"`
|
VerifyEmailTemplate string `yaml:"verify_email_template"`
|
||||||
VerifyEmailTemplates map[string]string `yaml:"verify_email_templates"`
|
VerifyEmailTemplates map[string]string `yaml:"verify_email_templates"`
|
||||||
ExpirationEmailTemplate string `yaml:"expiration_email_template"`
|
ExpirationEmailTemplate string `yaml:"expiration_email_template"`
|
||||||
MaintenanceEmailTemplate string `yaml:"maintenance_email_template"`
|
MaintenanceEmailTemplate string `yaml:"maintenance_email_template"`
|
||||||
TrafficExceedEmailTemplate string `yaml:"traffic_exceed_email_template"`
|
TrafficExceedEmailTemplate string `yaml:"traffic_exceed_email_template"`
|
||||||
DeleteAccountEmailTemplate string `yaml:"delete_account_email_template"`
|
DeleteAccountEmailTemplate string `yaml:"delete_account_email_template"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type MobileConfig struct {
|
type MobileConfig struct {
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/log"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
func FilterOrderRefundLogHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.FilterOrderRefundLogRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := log.NewFilterOrderRefundLogLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.FilterOrderRefundLog(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package order
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/order"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RefundOrderHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.RefundOrderRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := order.NewRefundOrderLogic(c.Request.Context(), svcCtx)
|
||||||
|
err := l.RefundOrder(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Approve withdrawal
|
||||||
|
func ApproveWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.ApproveWithdrawalRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := user.NewApproveWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||||
|
err := l.ApproveWithdrawal(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Get withdrawal list
|
||||||
|
func GetWithdrawalListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.GetWithdrawalListRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := user.NewGetWithdrawalListLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.GetWithdrawalList(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Reject withdrawal
|
||||||
|
func RejectWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.RejectWithdrawalRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := user.NewRejectWithdrawalLogic(c.Request.Context(), svcCtx)
|
||||||
|
err := l.RejectWithdrawal(&req)
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Complete file upload
|
||||||
|
func FileUploadCompleteHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.FileUploadCompleteRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := file.NewFileUploadCompleteLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.FileUploadComplete(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"mime/multipart"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Upload file to RustFS
|
||||||
|
func FileUploadHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.FileUploadRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileHeader, err := c.FormFile("file")
|
||||||
|
if err != nil {
|
||||||
|
result.ParamErrorResult(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileReader, err := fileHeader.Open()
|
||||||
|
if err != nil {
|
||||||
|
result.HttpResult(c, nil, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func(file multipart.File) {
|
||||||
|
_ = file.Close()
|
||||||
|
}(fileReader)
|
||||||
|
|
||||||
|
l := file.NewFileUploadLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.FileUpload(&req, fileHeader, fileReader)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/public/file"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Init file upload
|
||||||
|
func FileUploadInitHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.FileUploadInitRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := file.NewFileUploadInitLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.FileUploadInit(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package recovery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/public/recovery"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RecoverOrderHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.RecoverOrderRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := recovery.NewRecoverOrderLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.RecoverOrder(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package recovery
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/perfect-panel/server/internal/logic/public/recovery"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/result"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SendCodeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
var req types.RecoverySendCodeRequest
|
||||||
|
_ = c.ShouldBind(&req)
|
||||||
|
validateErr := svcCtx.Validate(&req)
|
||||||
|
if validateErr != nil {
|
||||||
|
result.ParamErrorResult(c, validateErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l := recovery.NewSendCodeLogic(c.Request.Context(), svcCtx)
|
||||||
|
resp, err := l.SendCode(&req)
|
||||||
|
result.HttpResult(c, resp, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,10 +30,12 @@ import (
|
|||||||
common "github.com/perfect-panel/server/internal/handler/common"
|
common "github.com/perfect-panel/server/internal/handler/common"
|
||||||
publicAnnouncement "github.com/perfect-panel/server/internal/handler/public/announcement"
|
publicAnnouncement "github.com/perfect-panel/server/internal/handler/public/announcement"
|
||||||
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
|
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
|
||||||
|
publicFile "github.com/perfect-panel/server/internal/handler/public/file"
|
||||||
publicIapApple "github.com/perfect-panel/server/internal/handler/public/iap/apple"
|
publicIapApple "github.com/perfect-panel/server/internal/handler/public/iap/apple"
|
||||||
publicOrder "github.com/perfect-panel/server/internal/handler/public/order"
|
publicOrder "github.com/perfect-panel/server/internal/handler/public/order"
|
||||||
publicPayment "github.com/perfect-panel/server/internal/handler/public/payment"
|
publicPayment "github.com/perfect-panel/server/internal/handler/public/payment"
|
||||||
publicPortal "github.com/perfect-panel/server/internal/handler/public/portal"
|
publicPortal "github.com/perfect-panel/server/internal/handler/public/portal"
|
||||||
|
publicRecovery "github.com/perfect-panel/server/internal/handler/public/recovery"
|
||||||
publicRedemption "github.com/perfect-panel/server/internal/handler/public/redemption"
|
publicRedemption "github.com/perfect-panel/server/internal/handler/public/redemption"
|
||||||
publicSubscribe "github.com/perfect-panel/server/internal/handler/public/subscribe"
|
publicSubscribe "github.com/perfect-panel/server/internal/handler/public/subscribe"
|
||||||
publicTicket "github.com/perfect-panel/server/internal/handler/public/ticket"
|
publicTicket "github.com/perfect-panel/server/internal/handler/public/ticket"
|
||||||
@@ -248,6 +250,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
// Filter commission log
|
// Filter commission log
|
||||||
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
|
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
|
||||||
|
|
||||||
|
// Filter order refund log
|
||||||
|
adminLogGroupRouter.GET("/order/refund/list", adminLog.FilterOrderRefundLogHandler(serverCtx))
|
||||||
|
|
||||||
// Filter email log
|
// Filter email log
|
||||||
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
|
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
|
||||||
|
|
||||||
@@ -339,6 +344,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
// Update order status
|
// Update order status
|
||||||
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
|
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
|
||||||
|
|
||||||
|
// Refund order
|
||||||
|
adminOrderGroupRouter.POST("/refund", adminOrder.RefundOrderHandler(serverCtx))
|
||||||
|
|
||||||
// Manually activate order
|
// Manually activate order
|
||||||
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
|
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
|
||||||
}
|
}
|
||||||
@@ -705,6 +713,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
|
|
||||||
// Get admin user invite list
|
// Get admin user invite list
|
||||||
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx))
|
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx))
|
||||||
|
|
||||||
|
// Get withdrawal list
|
||||||
|
adminUserGroupRouter.GET("/withdrawal/list", adminUser.GetWithdrawalListHandler(serverCtx))
|
||||||
|
|
||||||
|
// Approve withdrawal
|
||||||
|
adminUserGroupRouter.POST("/withdrawal/approve", adminUser.ApproveWithdrawalHandler(serverCtx))
|
||||||
|
|
||||||
|
// Reject withdrawal
|
||||||
|
adminUserGroupRouter.POST("/withdrawal/reject", adminUser.RejectWithdrawalHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
authGroupRouter := router.Group("/v1/auth")
|
authGroupRouter := router.Group("/v1/auth")
|
||||||
@@ -864,6 +881,20 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
publicDocumentGroupRouter.GET("/list", publicDocument.QueryDocumentListHandler(serverCtx))
|
publicDocumentGroupRouter.GET("/list", publicDocument.QueryDocumentListHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
publicFileGroupRouter := router.Group("/v1/public/file")
|
||||||
|
publicFileGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
|
{
|
||||||
|
// Upload file to RustFS
|
||||||
|
publicFileGroupRouter.POST("/upload", publicFile.FileUploadHandler(serverCtx))
|
||||||
|
|
||||||
|
// Init file upload
|
||||||
|
publicFileGroupRouter.POST("/upload/init", publicFile.FileUploadInitHandler(serverCtx))
|
||||||
|
|
||||||
|
// Complete file upload
|
||||||
|
publicFileGroupRouter.POST("/upload/complete", publicFile.FileUploadCompleteHandler(serverCtx))
|
||||||
|
}
|
||||||
|
|
||||||
publicOrderGroupRouter := router.Group("/v1/public/order")
|
publicOrderGroupRouter := router.Group("/v1/public/order")
|
||||||
publicOrderGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
publicOrderGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
@@ -932,6 +963,17 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
publicRedemptionGroupRouter.POST("/", publicRedemption.RedeemCodeHandler(serverCtx))
|
publicRedemptionGroupRouter.POST("/", publicRedemption.RedeemCodeHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
publicRecoveryGroupRouter := router.Group("/v1/public/recovery")
|
||||||
|
publicRecoveryGroupRouter.Use(middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
|
{
|
||||||
|
// Send recovery verification code
|
||||||
|
publicRecoveryGroupRouter.POST("/send_code", publicRecovery.SendCodeHandler(serverCtx))
|
||||||
|
|
||||||
|
// Recover order subscription
|
||||||
|
publicRecoveryGroupRouter.POST("/order", publicRecovery.RecoverOrderHandler(serverCtx))
|
||||||
|
}
|
||||||
|
|
||||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||||
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package log
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
modellog "github.com/perfect-panel/server/internal/model/log"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FilterOrderRefundLogLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFilterOrderRefundLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterOrderRefundLogLogic {
|
||||||
|
return &FilterOrderRefundLogLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *FilterOrderRefundLogLogic) FilterOrderRefundLog(req *types.FilterOrderRefundLogRequest) (resp *types.FilterOrderRefundLogResponse, err error) {
|
||||||
|
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &modellog.FilterParams{
|
||||||
|
Page: req.Page,
|
||||||
|
Size: req.Size,
|
||||||
|
Data: req.Date,
|
||||||
|
Search: req.Search,
|
||||||
|
Type: modellog.TypeOrderRefund.Uint8(),
|
||||||
|
ObjectID: req.OrderId,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("Query order refund log failed", logger.Field("error", err.Error()))
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query order refund log failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
var list []types.OrderRefundLog
|
||||||
|
for _, item := range data {
|
||||||
|
var content modellog.OrderRefund
|
||||||
|
if err := content.Unmarshal([]byte(item.Content)); err != nil {
|
||||||
|
l.Errorf("unmarshal order refund log content failed: %v", err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if req.UserId > 0 && content.TargetUserId != req.UserId && content.RefererUserId != req.UserId && content.OperatorUserId != req.UserId {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
list = append(list, types.OrderRefundLog{
|
||||||
|
OrderId: content.OrderId,
|
||||||
|
OrderNo: content.OrderNo,
|
||||||
|
OperatorUserId: content.OperatorUserId,
|
||||||
|
OperatorAuthIdentifier: content.OperatorAuthIdentifier,
|
||||||
|
TargetUserId: content.TargetUserId,
|
||||||
|
UserSubscribeId: content.UserSubscribeId,
|
||||||
|
RefererUserId: content.RefererUserId,
|
||||||
|
CommissionAmount: content.CommissionAmount,
|
||||||
|
Reason: content.Reason,
|
||||||
|
OrderStatusBefore: content.OrderStatusBefore,
|
||||||
|
OrderStatusAfter: content.OrderStatusAfter,
|
||||||
|
SubscribeStatusBefore: content.SubscribeStatusBefore,
|
||||||
|
SubscribeStatusAfter: content.SubscribeStatusAfter,
|
||||||
|
SubscribeExpireBefore: content.SubscribeExpireBefore,
|
||||||
|
SubscribeExpireAfter: content.SubscribeExpireAfter,
|
||||||
|
CommissionBefore: content.CommissionBefore,
|
||||||
|
CommissionAfter: content.CommissionAfter,
|
||||||
|
Timestamp: content.Timestamp,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return &types.FilterOrderRefundLogResponse{
|
||||||
|
Total: total,
|
||||||
|
List: list,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -35,6 +35,28 @@ func (l *GetOrderListLogic) GetOrderList(req *types.GetOrderListRequest) (resp *
|
|||||||
resp = &types.GetOrderListResponse{}
|
resp = &types.GetOrderListResponse{}
|
||||||
resp.List = make([]types.Order, 0)
|
resp.List = make([]types.Order, 0)
|
||||||
tool.DeepCopy(&resp.List, list)
|
tool.DeepCopy(&resp.List, list)
|
||||||
|
for i := range resp.List {
|
||||||
|
resp.List[i].StatusName = orderStatusName(resp.List[i].Status)
|
||||||
|
}
|
||||||
resp.Total = total
|
resp.Total = total
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func orderStatusName(status uint8) string {
|
||||||
|
switch status {
|
||||||
|
case 1:
|
||||||
|
return "pending"
|
||||||
|
case 2:
|
||||||
|
return "paid"
|
||||||
|
case 3:
|
||||||
|
return "closed"
|
||||||
|
case 4:
|
||||||
|
return "failed"
|
||||||
|
case 5:
|
||||||
|
return "finished"
|
||||||
|
case 6:
|
||||||
|
return "refunded"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
package order
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
|
modelorder "github.com/perfect-panel/server/internal/model/order"
|
||||||
|
modeluser "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/constant"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
orderStatusRefunded = 6
|
||||||
|
)
|
||||||
|
|
||||||
|
type RefundOrderLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRefundOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefundOrderLogic {
|
||||||
|
return &RefundOrderLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RefundOrderLogic) RefundOrder(req *types.RefundOrderRequest) error {
|
||||||
|
operator, ok := l.ctx.Value(constant.CtxKeyUser).(*modeluser.User)
|
||||||
|
if !ok {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||||
|
}
|
||||||
|
|
||||||
|
reason := strings.TrimSpace(req.Reason)
|
||||||
|
var cachesToClear []*modeluser.Subscribe
|
||||||
|
var planCacheIDs []int64
|
||||||
|
var userCacheTargets []*modeluser.User
|
||||||
|
|
||||||
|
err := l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
var orderInfo modelorder.Order
|
||||||
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Model(&modelorder.Order{}).
|
||||||
|
Where("id = ?", req.Id).
|
||||||
|
First(&orderInfo).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order %d not found", req.Id)
|
||||||
|
}
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query order failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if orderInfo.Status == orderStatusRefunded {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.OrderAlreadyRefunded), "order %d already refunded", orderInfo.Id)
|
||||||
|
}
|
||||||
|
if orderInfo.Status != 2 && orderInfo.Status != 5 {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order %d status %d is not refundable", orderInfo.Id, orderInfo.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
orderStatusBefore := orderInfo.Status
|
||||||
|
subStatusBefore := userSub.Status
|
||||||
|
subExpireBefore := userSub.ExpireTime
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
referer, commissionAmount, err := l.lockCommissionSource(tx, orderInfo.OrderNo, orderInfo.Commission)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var commissionBefore int64
|
||||||
|
var commissionAfter int64
|
||||||
|
if referer != nil {
|
||||||
|
commissionBefore = referer.Commission
|
||||||
|
commissionAfter = referer.Commission - commissionAmount
|
||||||
|
if err := tx.Model(&modeluser.User{}).
|
||||||
|
Where("id = ?", referer.Id).
|
||||||
|
UpdateColumn("commission", gorm.Expr("commission - ?", commissionAmount)).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
commissionLog := log.Commission{
|
||||||
|
Type: log.CommissionTypeRefund,
|
||||||
|
Amount: -commissionAmount,
|
||||||
|
OrderNo: orderInfo.OrderNo,
|
||||||
|
Timestamp: now.UnixMilli(),
|
||||||
|
}
|
||||||
|
content, marshalErr := commissionLog.Marshal()
|
||||||
|
if marshalErr != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal commission refund log failed: %v", marshalErr)
|
||||||
|
}
|
||||||
|
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
|
||||||
|
Type: log.TypeCommission.Uint8(),
|
||||||
|
Date: now.Format(time.DateOnly),
|
||||||
|
ObjectID: referer.Id,
|
||||||
|
Content: string(content),
|
||||||
|
CreatedAt: now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert commission refund log failed: %v", err)
|
||||||
|
}
|
||||||
|
referer.Commission = commissionAfter
|
||||||
|
userCacheTargets = append(userCacheTargets, referer)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Model(&modelorder.Order{}).
|
||||||
|
Where("id = ? AND status IN ?", orderInfo.Id, []int{2, 5}).
|
||||||
|
Update("status", orderStatusRefunded).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund order status update failed: %v", err)
|
||||||
|
}
|
||||||
|
orderInfo.Status = orderStatusRefunded
|
||||||
|
|
||||||
|
userSub.Status = 3
|
||||||
|
userSub.ExpireTime = now.Add(-time.Second)
|
||||||
|
userSub.FinishedAt = &now
|
||||||
|
if err := tx.Model(&modeluser.Subscribe{}).
|
||||||
|
Where("id = ?", userSub.Id).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"status": userSub.Status,
|
||||||
|
"expire_time": userSub.ExpireTime,
|
||||||
|
"finished_at": userSub.FinishedAt,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update subscription failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
refundLog, err := l.buildRefundAuditLog(operator, &orderInfo, userSub, referer, commissionAmount, reason, orderStatusBefore, subStatusBefore, subExpireBefore, commissionBefore, commissionAfter, now)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logContent, err := refundLog.Marshal()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal refund audit log failed: %v", err)
|
||||||
|
}
|
||||||
|
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
|
||||||
|
Type: log.TypeOrderRefund.Uint8(),
|
||||||
|
Date: now.Format(time.DateOnly),
|
||||||
|
ObjectID: orderInfo.Id,
|
||||||
|
Content: string(logContent),
|
||||||
|
CreatedAt: now,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert refund audit log failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cachesToClear = append(cachesToClear, userSub)
|
||||||
|
if userSub.SubscribeId > 0 {
|
||||||
|
planCacheIDs = append(planCacheIDs, userSub.SubscribeId)
|
||||||
|
}
|
||||||
|
if orderInfo.UserId > 0 {
|
||||||
|
orderUser := &modeluser.User{Id: orderInfo.UserId}
|
||||||
|
userCacheTargets = append(userCacheTargets, orderUser)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("[RefundOrder] refund failed", logger.Field("error", err.Error()), logger.Field("order_id", req.Id))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cachesToClear) > 0 {
|
||||||
|
if clearErr := l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, cachesToClear...); clearErr != nil {
|
||||||
|
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("order_id", req.Id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, subscribeID := range planCacheIDs {
|
||||||
|
if clearErr := l.svcCtx.SubscribeModel.ClearCache(l.ctx, subscribeID); clearErr != nil {
|
||||||
|
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("subscribe_id", subscribeID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(userCacheTargets) > 0 {
|
||||||
|
if clearErr := l.svcCtx.UserModel.ClearUserCache(l.ctx, userCacheTargets...); clearErr != nil {
|
||||||
|
l.Errorw("[RefundOrder] clear user cache failed", logger.Field("error", clearErr.Error()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RefundOrderLogic) lockRefundTargetSubscription(tx *gorm.DB, orderInfo *modelorder.Order) (*modeluser.Subscribe, error) {
|
||||||
|
var userSub modeluser.Subscribe
|
||||||
|
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Model(&modeluser.Subscribe{}).
|
||||||
|
Where("order_id = ?", orderInfo.Id).
|
||||||
|
First(&userSub).Error
|
||||||
|
if err == nil {
|
||||||
|
return &userSub, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query refund subscription failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if orderInfo.Type != 2 {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "order %d has no linked subscription", orderInfo.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
if orderInfo.ParentId == 0 {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d has no parent order", orderInfo.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Model(&modeluser.Subscribe{}).
|
||||||
|
Where("order_id = ?", orderInfo.ParentId).
|
||||||
|
First(&userSub).Error
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d parent subscription not found", orderInfo.Id)
|
||||||
|
}
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query renewal subscription failed: %v", err)
|
||||||
|
}
|
||||||
|
return &userSub, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, orderCommission int64) (*modeluser.User, int64, error) {
|
||||||
|
var commissionLogs []log.SystemLog
|
||||||
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Model(&log.SystemLog{}).
|
||||||
|
Where("type = ? AND content LIKE ?", log.TypeCommission.Uint8(), fmt.Sprintf("%%\"order_no\":\"%s\"%%", orderNo)).
|
||||||
|
Order("id DESC").
|
||||||
|
Find(&commissionLogs).Error; err != nil {
|
||||||
|
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission log failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range commissionLogs {
|
||||||
|
var content log.Commission
|
||||||
|
if err := content.Unmarshal([]byte(item.Content)); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if content.Type != log.CommissionTypePurchase && content.Type != log.CommissionTypeRenewal {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var referer modeluser.User
|
||||||
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Model(&modeluser.User{}).
|
||||||
|
Where("id = ?", item.ObjectID).
|
||||||
|
First(&referer).Error; err != nil {
|
||||||
|
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission owner failed: %v", err)
|
||||||
|
}
|
||||||
|
return &referer, content.Amount, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if orderCommission > 0 {
|
||||||
|
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundCommissionMismatch), "order %s commission owner not found", orderNo)
|
||||||
|
}
|
||||||
|
return nil, 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RefundOrderLogic) buildRefundAuditLog(
|
||||||
|
operator *modeluser.User,
|
||||||
|
orderInfo *modelorder.Order,
|
||||||
|
userSub *modeluser.Subscribe,
|
||||||
|
referer *modeluser.User,
|
||||||
|
commissionAmount int64,
|
||||||
|
reason string,
|
||||||
|
orderStatusBefore uint8,
|
||||||
|
subStatusBefore uint8,
|
||||||
|
subExpireBefore time.Time,
|
||||||
|
commissionBefore int64,
|
||||||
|
commissionAfter int64,
|
||||||
|
now time.Time,
|
||||||
|
) (*log.OrderRefund, error) {
|
||||||
|
refundLog := &log.OrderRefund{
|
||||||
|
OrderId: orderInfo.Id,
|
||||||
|
OrderNo: orderInfo.OrderNo,
|
||||||
|
OperatorUserId: operator.Id,
|
||||||
|
TargetUserId: userSub.UserId,
|
||||||
|
UserSubscribeId: userSub.Id,
|
||||||
|
CommissionAmount: commissionAmount,
|
||||||
|
Reason: reason,
|
||||||
|
OrderStatusBefore: orderStatusBefore,
|
||||||
|
OrderStatusAfter: orderInfo.Status,
|
||||||
|
SubscribeStatusBefore: subStatusBefore,
|
||||||
|
SubscribeStatusAfter: userSub.Status,
|
||||||
|
SubscribeExpireBefore: subExpireBefore.UnixMilli(),
|
||||||
|
SubscribeExpireAfter: userSub.ExpireTime.UnixMilli(),
|
||||||
|
CommissionBefore: commissionBefore,
|
||||||
|
CommissionAfter: commissionAfter,
|
||||||
|
Timestamp: now.UnixMilli(),
|
||||||
|
}
|
||||||
|
if referer != nil {
|
||||||
|
refundLog.RefererUserId = referer.Id
|
||||||
|
}
|
||||||
|
if len(operator.AuthMethods) > 0 {
|
||||||
|
refundLog.OperatorAuthIdentifier = operator.AuthMethods[0].AuthIdentifier
|
||||||
|
}
|
||||||
|
return refundLog, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package order
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
modelorder "github.com/perfect-panel/server/internal/model/order"
|
||||||
|
modeluser "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOrderStatusName(t *testing.T) {
|
||||||
|
tests := map[uint8]string{
|
||||||
|
1: "pending",
|
||||||
|
2: "paid",
|
||||||
|
3: "closed",
|
||||||
|
4: "failed",
|
||||||
|
5: "finished",
|
||||||
|
6: "refunded",
|
||||||
|
7: "unknown",
|
||||||
|
}
|
||||||
|
|
||||||
|
for input, want := range tests {
|
||||||
|
if got := orderStatusName(input); got != want {
|
||||||
|
t.Fatalf("status %d: got %q want %q", input, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildRefundAuditLog(t *testing.T) {
|
||||||
|
logic := &RefundOrderLogic{}
|
||||||
|
now := time.Unix(1710000000, 0)
|
||||||
|
expireBefore := now.Add(24 * time.Hour)
|
||||||
|
expireAfter := now.Add(-time.Second)
|
||||||
|
operator := &modeluser.User{
|
||||||
|
Id: 100,
|
||||||
|
AuthMethods: []modeluser.AuthMethods{
|
||||||
|
{AuthIdentifier: "admin@example.com"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
orderInfo := &modelorder.Order{Id: 10, OrderNo: "ORD-1", Status: orderStatusRefunded}
|
||||||
|
userSub := &modeluser.Subscribe{Id: 20, UserId: 30, Status: 3, ExpireTime: expireAfter}
|
||||||
|
referer := &modeluser.User{Id: 40}
|
||||||
|
|
||||||
|
got, err := logic.buildRefundAuditLog(
|
||||||
|
operator,
|
||||||
|
orderInfo,
|
||||||
|
userSub,
|
||||||
|
referer,
|
||||||
|
500,
|
||||||
|
"manual refund",
|
||||||
|
5,
|
||||||
|
1,
|
||||||
|
expireBefore,
|
||||||
|
900,
|
||||||
|
400,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("buildRefundAuditLog error: %v", err)
|
||||||
|
}
|
||||||
|
if got.OrderId != 10 || got.OrderNo != "ORD-1" {
|
||||||
|
t.Fatalf("unexpected order info: %+v", got)
|
||||||
|
}
|
||||||
|
if got.OperatorUserId != 100 || got.OperatorAuthIdentifier != "admin@example.com" {
|
||||||
|
t.Fatalf("unexpected operator info: %+v", got)
|
||||||
|
}
|
||||||
|
if got.TargetUserId != 30 || got.UserSubscribeId != 20 {
|
||||||
|
t.Fatalf("unexpected subscription info: %+v", got)
|
||||||
|
}
|
||||||
|
if got.RefererUserId != 40 || got.CommissionAmount != 500 {
|
||||||
|
t.Fatalf("unexpected commission info: %+v", got)
|
||||||
|
}
|
||||||
|
if got.OrderStatusBefore != 5 || got.OrderStatusAfter != orderStatusRefunded {
|
||||||
|
t.Fatalf("unexpected order status: %+v", got)
|
||||||
|
}
|
||||||
|
if got.SubscribeStatusBefore != 1 || got.SubscribeStatusAfter != 3 {
|
||||||
|
t.Fatalf("unexpected subscribe status: %+v", got)
|
||||||
|
}
|
||||||
|
if got.SubscribeExpireBefore != expireBefore.UnixMilli() || got.SubscribeExpireAfter != expireAfter.UnixMilli() {
|
||||||
|
t.Fatalf("unexpected expire transition: %+v", got)
|
||||||
|
}
|
||||||
|
if got.CommissionBefore != 900 || got.CommissionAfter != 400 {
|
||||||
|
t.Fatalf("unexpected commission transition: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,19 @@ func NewGetRegisterConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *GetRegisterConfigLogic) GetRegisterConfig() (*types.RegisterConfig, error) {
|
func (l *GetRegisterConfigLogic) GetRegisterConfig() (*types.RegisterConfig, error) {
|
||||||
resp := &types.RegisterConfig{}
|
resp := &types.RegisterConfig{
|
||||||
|
StopRegister: l.svcCtx.Config.Register.StopRegister,
|
||||||
|
EnableTrial: l.svcCtx.Config.Register.EnableTrial,
|
||||||
|
EnableTrialEmailWhitelist: l.svcCtx.Config.Register.EnableTrialEmailWhitelist,
|
||||||
|
TrialSubscribe: l.svcCtx.Config.Register.TrialSubscribe,
|
||||||
|
TrialTime: l.svcCtx.Config.Register.TrialTime,
|
||||||
|
TrialTimeUnit: l.svcCtx.Config.Register.TrialTimeUnit,
|
||||||
|
TrialEmailDomainWhitelist: l.svcCtx.Config.Register.TrialEmailDomainWhitelist,
|
||||||
|
EnableIpRegisterLimit: l.svcCtx.Config.Register.EnableIpRegisterLimit,
|
||||||
|
IpRegisterLimit: l.svcCtx.Config.Register.IpRegisterLimit,
|
||||||
|
IpRegisterLimitDuration: l.svcCtx.Config.Register.IpRegisterLimitDuration,
|
||||||
|
DeviceLimit: l.svcCtx.Config.Register.DeviceLimit,
|
||||||
|
}
|
||||||
|
|
||||||
// get register config from database
|
// get register config from database
|
||||||
configs, err := l.svcCtx.SystemModel.GetRegisterConfig(l.ctx)
|
configs, err := l.svcCtx.SystemModel.GetRegisterConfig(l.ctx)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
|
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/initialize"
|
"github.com/perfect-panel/server/initialize"
|
||||||
"github.com/perfect-panel/server/internal/config"
|
"github.com/perfect-panel/server/internal/config"
|
||||||
@@ -44,8 +45,28 @@ func (l *UpdateRegisterConfigLogic) UpdateRegisterConfig(req *types.RegisterConf
|
|||||||
fieldName := t.Field(i).Name
|
fieldName := t.Field(i).Name
|
||||||
// Get the field value to string
|
// Get the field value to string
|
||||||
fieldValue := tool.ConvertValueToString(v.Field(i))
|
fieldValue := tool.ConvertValueToString(v.Field(i))
|
||||||
// Update the site config
|
|
||||||
err = db.Model(&system.System{}).Where("`category` = 'register' and `key` = ?", fieldName).Update("value", fieldValue).Error
|
var existing system.System
|
||||||
|
queryErr := db.Where("`category` = ? and `key` = ?", "register", fieldName).First(&existing).Error
|
||||||
|
if queryErr != nil && !errors.Is(queryErr, gorm.ErrRecordNotFound) {
|
||||||
|
return queryErr
|
||||||
|
}
|
||||||
|
if errors.Is(queryErr, gorm.ErrRecordNotFound) {
|
||||||
|
fieldValue = l.defaultRegisterFieldValue(fieldName, fieldValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
record := &system.System{
|
||||||
|
Category: "register",
|
||||||
|
Key: fieldName,
|
||||||
|
}
|
||||||
|
assignments := map[string]interface{}{
|
||||||
|
"value": fieldValue,
|
||||||
|
"type": inferRegisterSystemValueType(t.Field(i).Type.Kind()),
|
||||||
|
"desc": fieldName,
|
||||||
|
}
|
||||||
|
err = db.Where("`category` = ? and `key` = ?", "register", fieldName).
|
||||||
|
Assign(assignments).
|
||||||
|
FirstOrCreate(record).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -63,3 +84,28 @@ func (l *UpdateRegisterConfigLogic) UpdateRegisterConfig(req *types.RegisterConf
|
|||||||
initialize.Register(l.svcCtx)
|
initialize.Register(l.svcCtx)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func inferRegisterSystemValueType(kind reflect.Kind) string {
|
||||||
|
switch kind {
|
||||||
|
case reflect.Bool:
|
||||||
|
return "bool"
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return "int"
|
||||||
|
default:
|
||||||
|
return "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *UpdateRegisterConfigLogic) defaultRegisterFieldValue(fieldName, fieldValue string) string {
|
||||||
|
switch fieldName {
|
||||||
|
case "EnableTrialEmailWhitelist":
|
||||||
|
return "true"
|
||||||
|
case "TrialEmailDomainWhitelist":
|
||||||
|
if strings.TrimSpace(fieldValue) != "" {
|
||||||
|
return fieldValue
|
||||||
|
}
|
||||||
|
return l.svcCtx.Config.Register.TrialEmailDomainWhitelist
|
||||||
|
default:
|
||||||
|
return fieldValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ApproveWithdrawalLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewApproveWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApproveWithdrawalLogic {
|
||||||
|
return &ApproveWithdrawalLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *ApproveWithdrawalLogic) ApproveWithdrawal(req *types.ApproveWithdrawalRequest) error {
|
||||||
|
return approveWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId)
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetWithdrawalListLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGetWithdrawalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWithdrawalListLogic {
|
||||||
|
return &GetWithdrawalListLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListRequest) (*types.GetWithdrawalListResponse, error) {
|
||||||
|
page := req.Page
|
||||||
|
size := req.Size
|
||||||
|
if page <= 0 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size <= 0 {
|
||||||
|
size = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
query := l.svcCtx.DB.WithContext(l.ctx).Model(&usermodel.Withdrawal{})
|
||||||
|
if req.UserId != nil {
|
||||||
|
query = query.Where("user_id = ?", *req.UserId)
|
||||||
|
}
|
||||||
|
if req.Status != nil {
|
||||||
|
query = query.Where("status = ?", *req.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawals failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows []usermodel.Withdrawal
|
||||||
|
if err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawals failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
list := make([]types.WithdrawalLog, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
list = append(list, types.WithdrawalLog{
|
||||||
|
Id: row.Id,
|
||||||
|
UserId: row.UserId,
|
||||||
|
Amount: row.Amount,
|
||||||
|
Content: row.Content,
|
||||||
|
Status: row.Status,
|
||||||
|
Reason: row.Reason,
|
||||||
|
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||||
|
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return &types.GetWithdrawalListResponse{
|
||||||
|
List: list,
|
||||||
|
Total: total,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RejectWithdrawalLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRejectWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RejectWithdrawalLogic {
|
||||||
|
return &RejectWithdrawalLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *RejectWithdrawalLogic) RejectWithdrawal(req *types.RejectWithdrawalRequest) error {
|
||||||
|
return rejectWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId, req.Reason)
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/internal/model/log"
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
@@ -100,28 +101,41 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
|||||||
}
|
}
|
||||||
|
|
||||||
if req.Commission != userInfo.Commission {
|
if req.Commission != userInfo.Commission {
|
||||||
|
if isWithdrawalScene(req.Remark) {
|
||||||
commentLog := log.Commission{
|
logWithdrawalGuard(l.Logger, userInfo.Id)
|
||||||
Type: log.CommissionTypeAdjust,
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
|
||||||
Amount: req.Commission - userInfo.Commission,
|
|
||||||
Timestamp: time.Now().UnixMilli(),
|
|
||||||
}
|
}
|
||||||
|
change := req.Commission - userInfo.Commission
|
||||||
content, _ := commentLog.Marshal()
|
if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
|
||||||
err = tx.Create(&log.SystemLog{
|
return err
|
||||||
Type: log.TypeCommission.Uint8(),
|
}
|
||||||
Date: time.Now().Format(time.DateOnly),
|
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
||||||
ObjectID: userInfo.Id,
|
|
||||||
Content: string(content),
|
|
||||||
}).Error
|
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
userInfo.Commission = req.Commission
|
userInfo.Commission = req.Commission
|
||||||
}
|
}
|
||||||
tool.DeepCopy(userInfo, req)
|
if req.Avatar != "" {
|
||||||
userInfo.OnlyFirstPurchase = &req.OnlyFirstPurchase
|
userInfo.Avatar = req.Avatar
|
||||||
userInfo.ReferralPercentage = req.ReferralPercentage
|
}
|
||||||
|
if req.ReferCode != "" {
|
||||||
|
userInfo.ReferCode = req.ReferCode
|
||||||
|
}
|
||||||
|
userInfo.RefererId = req.RefererId
|
||||||
|
if req.Enable != nil {
|
||||||
|
userInfo.Enable = req.Enable
|
||||||
|
}
|
||||||
|
if req.IsAdmin != nil {
|
||||||
|
userInfo.IsAdmin = req.IsAdmin
|
||||||
|
}
|
||||||
|
if req.Remark != "" {
|
||||||
|
userInfo.Remark = req.Remark
|
||||||
|
}
|
||||||
|
if req.OnlyFirstPurchase != nil {
|
||||||
|
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
|
||||||
|
}
|
||||||
|
if req.ReferralPercentage != 0 {
|
||||||
|
userInfo.ReferralPercentage = req.ReferralPercentage
|
||||||
|
}
|
||||||
|
|
||||||
if req.Password != "" {
|
if req.Password != "" {
|
||||||
if userInfo.Id == 2 && isDemo {
|
if userInfo.Id == 2 && isDemo {
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
logicCommon "github.com/perfect-panel/server/internal/logic/common"
|
||||||
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
|
||||||
|
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||||
|
if err != nil {
|
||||||
|
if err.Error() == "withdrawal status invalid" {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
||||||
|
}
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||||
|
Where("id = ? AND status = 0", withdrawalID).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"status": 1,
|
||||||
|
"reason": "",
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "approve withdrawal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdraw, withdrawal.Amount, ""); err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64, reason string) error {
|
||||||
|
reason = strings.TrimSpace(reason)
|
||||||
|
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||||
|
if err != nil {
|
||||||
|
if err.Error() == "withdrawal status invalid" {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
||||||
|
}
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||||
|
Where("id = ? AND status = 0", withdrawalID).
|
||||||
|
Updates(map[string]interface{}{
|
||||||
|
"status": 2,
|
||||||
|
"reason": reason,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "reject withdrawal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svcCtx.UserModel.UpdateCommission(ctx, withdrawal.UserId, withdrawal.Amount, tx); err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdrawReject, withdrawal.Amount, ""); err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func isWithdrawalScene(remark string) bool {
|
||||||
|
normalized := strings.ToLower(strings.TrimSpace(remark))
|
||||||
|
return strings.Contains(normalized, "withdraw") || strings.Contains(normalized, "提现")
|
||||||
|
}
|
||||||
|
|
||||||
|
func logWithdrawalGuard(l logger.Logger, userID int64) {
|
||||||
|
l.Errorw("blocked commission overwrite in withdrawal scene", logger.Field("user_id", userID))
|
||||||
|
}
|
||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
"github.com/perfect-panel/server/pkg/jwt"
|
"github.com/perfect-panel/server/pkg/jwt"
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
"github.com/perfect-panel/server/pkg/tool"
|
|
||||||
"github.com/perfect-panel/server/pkg/uuidx"
|
"github.com/perfect-panel/server/pkg/uuidx"
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
@@ -97,6 +96,17 @@ func (l *DeviceLoginLogic) DeviceLogin(req *types.DeviceLoginRequest) (resp *typ
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user failed: %v", err.Error())
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user failed: %v", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update base_payload if provided
|
||||||
|
if req.BasePayload != "" && req.BasePayload != deviceInfo.BasePayload {
|
||||||
|
deviceInfo.BasePayload = req.BasePayload
|
||||||
|
if updateErr := l.svcCtx.UserModel.UpdateDevice(l.ctx, deviceInfo); updateErr != nil {
|
||||||
|
l.Errorw("update device base_payload failed",
|
||||||
|
logger.Field("device_id", deviceInfo.Id),
|
||||||
|
logger.Field("error", updateErr.Error()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 注销后 device auth_method 被删除,重新登录时需要补回
|
// 注销后 device auth_method 被删除,重新登录时需要补回
|
||||||
hasDeviceAuth := false
|
hasDeviceAuth := false
|
||||||
for _, am := range userInfo.AuthMethods {
|
for _, am := range userInfo.AuthMethods {
|
||||||
@@ -180,7 +190,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
|||||||
)
|
)
|
||||||
|
|
||||||
var userInfo *user.User
|
var userInfo *user.User
|
||||||
var trialSubscribe *user.Subscribe
|
|
||||||
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
err := l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
|
||||||
// Create new user
|
// Create new user
|
||||||
userInfo = &user.User{
|
userInfo = &user.User{
|
||||||
@@ -222,13 +231,14 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
|||||||
|
|
||||||
// Insert device record
|
// Insert device record
|
||||||
deviceInfo := &user.Device{
|
deviceInfo := &user.Device{
|
||||||
Ip: req.IP,
|
Ip: req.IP,
|
||||||
UserId: userInfo.Id,
|
UserId: userInfo.Id,
|
||||||
UserAgent: req.UserAgent,
|
UserAgent: req.UserAgent,
|
||||||
Identifier: req.Identifier,
|
Identifier: req.Identifier,
|
||||||
ShortCode: req.ShortCode,
|
ShortCode: req.ShortCode,
|
||||||
Enabled: true,
|
BasePayload: req.BasePayload,
|
||||||
Online: false,
|
Enabled: true,
|
||||||
|
Online: false,
|
||||||
}
|
}
|
||||||
if err := db.Create(deviceInfo).Error; err != nil {
|
if err := db.Create(deviceInfo).Error; err != nil {
|
||||||
l.Errorw("failed to insert device",
|
l.Errorw("failed to insert device",
|
||||||
@@ -239,15 +249,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
|||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert device failed: %v", err)
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert device failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activate trial if enabled
|
|
||||||
if l.svcCtx.Config.Register.EnableTrial {
|
|
||||||
var trialErr error
|
|
||||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id, db)
|
|
||||||
if trialErr != nil {
|
|
||||||
return trialErr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -259,25 +260,6 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear cache after transaction success
|
|
||||||
if l.svcCtx.Config.Register.EnableTrial && trialSubscribe != nil {
|
|
||||||
// Clear user subscription cache
|
|
||||||
if err = l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, trialSubscribe); err != nil {
|
|
||||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("userSubscribeId", trialSubscribe.Id))
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
// Clear subscription cache
|
|
||||||
if err = l.svcCtx.SubscribeModel.ClearCache(l.ctx, trialSubscribe.SubscribeId); err != nil {
|
|
||||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("subscribeId", trialSubscribe.SubscribeId))
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
// Clear all server cache
|
|
||||||
if err = l.svcCtx.NodeModel.ClearServerAllCache(l.ctx); err != nil {
|
|
||||||
l.Errorf("ClearServerAllCache error: %v", err.Error())
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
l.Infow("device registration completed successfully",
|
l.Infow("device registration completed successfully",
|
||||||
logger.Field("user_id", userInfo.Id),
|
logger.Field("user_id", userInfo.Id),
|
||||||
logger.Field("identifier", req.Identifier),
|
logger.Field("identifier", req.Identifier),
|
||||||
@@ -309,51 +291,3 @@ func (l *DeviceLoginLogic) registerUserAndDevice(req *types.DeviceLoginRequest)
|
|||||||
|
|
||||||
return userInfo, nil
|
return userInfo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *DeviceLoginLogic) activeTrial(userId int64, db *gorm.DB) (*user.Subscribe, error) {
|
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("failed to find trial subscription template",
|
|
||||||
logger.Field("user_id", userId),
|
|
||||||
logger.Field("trial_subscribe_id", l.svcCtx.Config.Register.TrialSubscribe),
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
startTime := time.Now()
|
|
||||||
expireTime := tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, startTime)
|
|
||||||
subscribeToken := uuidx.NewUUID().String()
|
|
||||||
subscribeUUID := uuidx.NewUUID().String()
|
|
||||||
|
|
||||||
userSub := &user.Subscribe{
|
|
||||||
UserId: userId,
|
|
||||||
OrderId: 0,
|
|
||||||
SubscribeId: sub.Id,
|
|
||||||
StartTime: startTime,
|
|
||||||
ExpireTime: expireTime,
|
|
||||||
Traffic: sub.Traffic,
|
|
||||||
Download: 0,
|
|
||||||
Upload: 0,
|
|
||||||
Token: subscribeToken,
|
|
||||||
UUID: subscribeUUID,
|
|
||||||
Status: 1,
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := db.Create(userSub).Error; err != nil {
|
|
||||||
l.Errorw("failed to insert trial subscription",
|
|
||||||
logger.Field("user_id", userId),
|
|
||||||
logger.Field("error", err.Error()),
|
|
||||||
)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
l.Infow("trial subscription activated successfully",
|
|
||||||
logger.Field("user_id", userId),
|
|
||||||
logger.Field("subscribe_id", sub.Id),
|
|
||||||
logger.Field("expire_time", expireTime),
|
|
||||||
logger.Field("traffic", sub.Traffic),
|
|
||||||
)
|
|
||||||
|
|
||||||
return userSub, nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,13 +2,11 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/config"
|
"github.com/perfect-panel/server/internal/config"
|
||||||
"github.com/perfect-panel/server/internal/logic/common"
|
|
||||||
"github.com/perfect-panel/server/internal/model/log"
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
@@ -47,29 +45,6 @@ func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.
|
|||||||
req.Code = strings.TrimSpace(req.Code)
|
req.Code = strings.TrimSpace(req.Code)
|
||||||
|
|
||||||
// Verify Code
|
// Verify Code
|
||||||
scenes := []string{constant.Security.String(), constant.Register.String(), "unknown"}
|
|
||||||
var verified bool
|
|
||||||
var cacheKeyUsed string
|
|
||||||
var payload common.CacheKeyPayload
|
|
||||||
for _, scene := range scenes {
|
|
||||||
cacheKey := fmt.Sprintf("%s:%s:%s", config.AuthCodeCacheKey, scene, req.Email)
|
|
||||||
value, err := l.svcCtx.Redis.Get(l.ctx, cacheKey).Result()
|
|
||||||
if err != nil || value == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal([]byte(value), &payload); err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if payload.Code == req.Code && time.Now().Unix()-payload.LastAt <= l.svcCtx.Config.VerifyCode.VerifyCodeExpireTime {
|
|
||||||
verified = true
|
|
||||||
cacheKeyUsed = cacheKey
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !verified {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.VerifyCodeError), "verification code error or expired")
|
|
||||||
}
|
|
||||||
l.svcCtx.Redis.Del(l.ctx, cacheKeyUsed)
|
|
||||||
|
|
||||||
// Check User
|
// Check User
|
||||||
userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
|
||||||
@@ -125,7 +100,10 @@ func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.
|
|||||||
if err = db.Create(authInfo).Error; err != nil {
|
if err = db.Create(authInfo).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if l.svcCtx.Config.Register.EnableTrial {
|
rc := l.svcCtx.Config.Register
|
||||||
|
if ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
|
||||||
|
ShouldGrantTrialForEmail(rc, req.Email) &&
|
||||||
|
!NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, req.Email, rc.TrialSubscribe) {
|
||||||
if err = l.activeTrial(userInfo.Id); err != nil {
|
if err = l.activeTrial(userInfo.Id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/config"
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
authlogic "github.com/perfect-panel/server/internal/logic/auth"
|
||||||
"github.com/perfect-panel/server/internal/model/auth"
|
"github.com/perfect-panel/server/internal/model/auth"
|
||||||
"github.com/perfect-panel/server/internal/model/log"
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
@@ -393,10 +395,17 @@ func (l *OAuthLoginGetTokenLogic) register(email, avatar, method, openid, reques
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if l.svcCtx.Config.Register.EnableTrial {
|
rc := l.svcCtx.Config.Register
|
||||||
|
shouldActivateTrial := email != "" &&
|
||||||
|
authlogic.ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
|
||||||
|
authlogic.ShouldGrantTrialForEmail(rc, email) &&
|
||||||
|
!authlogic.NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, email, rc.TrialSubscribe)
|
||||||
|
|
||||||
|
if shouldActivateTrial {
|
||||||
l.Debugw("activating trial subscription",
|
l.Debugw("activating trial subscription",
|
||||||
logger.Field("request_id", requestID),
|
logger.Field("request_id", requestID),
|
||||||
logger.Field("user_id", userInfo.Id),
|
logger.Field("user_id", userInfo.Id),
|
||||||
|
logger.Field("email", email),
|
||||||
)
|
)
|
||||||
var trialErr error
|
var trialErr error
|
||||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id, requestID)
|
trialSubscribe, trialErr = l.activeTrial(userInfo.Id, requestID)
|
||||||
@@ -882,3 +891,22 @@ func (l *OAuthLoginGetTokenLogic) activeTrial(uid int64, requestID string) (*use
|
|||||||
)
|
)
|
||||||
return userSub, nil
|
return userSub, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isEmailDomainWhitelisted checks if the email's domain is in the comma-separated whitelist.
|
||||||
|
// Returns false if the email format is invalid.
|
||||||
|
func (l *OAuthLoginGetTokenLogic) isEmailDomainWhitelisted(email, whitelistCSV string) bool {
|
||||||
|
if whitelistCSV == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(email, "@", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
domain := strings.ToLower(strings.TrimSpace(parts[1]))
|
||||||
|
for _, d := range strings.Split(whitelistCSV, ",") {
|
||||||
|
if strings.ToLower(strings.TrimSpace(d)) == domain {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ func NewTelephoneUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceConte
|
|||||||
|
|
||||||
func (l *TelephoneUserRegisterLogic) TelephoneUserRegister(req *types.TelephoneRegisterRequest) (resp *types.LoginResponse, err error) {
|
func (l *TelephoneUserRegisterLogic) TelephoneUserRegister(req *types.TelephoneRegisterRequest) (resp *types.LoginResponse, err error) {
|
||||||
c := l.svcCtx.Config.Register
|
c := l.svcCtx.Config.Register
|
||||||
var trialSubscribe *user.Subscribe
|
|
||||||
// Check if the registration is stopped
|
// Check if the registration is stopped
|
||||||
if c.StopRegister {
|
if c.StopRegister {
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.StopRegister), "stop register")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.StopRegister), "stop register")
|
||||||
@@ -141,39 +140,12 @@ func (l *TelephoneUserRegisterLogic) TelephoneUserRegister(req *types.TelephoneR
|
|||||||
if err := db.Model(&user.User{}).Where("id = ?", userInfo.Id).Update("refer_code", userInfo.ReferCode).Error; err != nil {
|
if err := db.Model(&user.User{}).Where("id = ?", userInfo.Id).Update("refer_code", userInfo.ReferCode).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if l.svcCtx.Config.Register.EnableTrial {
|
|
||||||
// Active trial
|
|
||||||
var trialErr error
|
|
||||||
trialSubscribe, trialErr = l.activeTrial(userInfo.Id)
|
|
||||||
if trialErr != nil {
|
|
||||||
return trialErr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear cache after transaction success
|
|
||||||
if l.svcCtx.Config.Register.EnableTrial && trialSubscribe != nil {
|
|
||||||
// Clear user subscription cache
|
|
||||||
if err = l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, trialSubscribe); err != nil {
|
|
||||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("userSubscribeId", trialSubscribe.Id))
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
// Clear subscription cache
|
|
||||||
if err = l.svcCtx.SubscribeModel.ClearCache(l.ctx, trialSubscribe.SubscribeId); err != nil {
|
|
||||||
l.Errorw("ClearSubscribeCache failed", logger.Field("error", err.Error()), logger.Field("subscribeId", trialSubscribe.SubscribeId))
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
// Clear all server cache
|
|
||||||
if err = l.svcCtx.NodeModel.ClearServerAllCache(l.ctx); err != nil {
|
|
||||||
l.Errorf("ClearServerAllCache error: %v", err.Error())
|
|
||||||
// Don't return error, just log it
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bind device to user if identifier is provided
|
// Bind device to user if identifier is provided
|
||||||
if req.Identifier != "" {
|
if req.Identifier != "" {
|
||||||
bindLogic := NewBindDeviceLogic(l.ctx, l.svcCtx)
|
bindLogic := NewBindDeviceLogic(l.ctx, l.svcCtx)
|
||||||
@@ -261,32 +233,6 @@ func (l *TelephoneUserRegisterLogic) TelephoneUserRegister(req *types.TelephoneR
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *TelephoneUserRegisterLogic) activeTrial(uid int64) (*user.Subscribe, error) {
|
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
userSub := &user.Subscribe{
|
|
||||||
Id: 0,
|
|
||||||
UserId: uid,
|
|
||||||
OrderId: 0,
|
|
||||||
SubscribeId: sub.Id,
|
|
||||||
StartTime: time.Now(),
|
|
||||||
ExpireTime: tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, time.Now()),
|
|
||||||
Traffic: sub.Traffic,
|
|
||||||
Download: 0,
|
|
||||||
Upload: 0,
|
|
||||||
Token: uuidx.NewUUID().String(),
|
|
||||||
UUID: uuidx.NewUUID().String(),
|
|
||||||
Status: 1,
|
|
||||||
}
|
|
||||||
err = l.svcCtx.UserModel.InsertSubscribe(l.ctx, userSub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return userSub, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *TelephoneUserRegisterLogic) verifyCaptcha(req *types.TelephoneRegisterRequest) error {
|
func (l *TelephoneUserRegisterLogic) verifyCaptcha(req *types.TelephoneRegisterRequest) error {
|
||||||
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
verifyCfg, err := l.svcCtx.SystemModel.GetVerifyConfig(l.ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/mail"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/config"
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsEmailDomainWhitelisted checks if the email's domain is in the comma-separated whitelist.
|
||||||
|
// Returns false if the email format is invalid.
|
||||||
|
func IsEmailDomainWhitelisted(email, whitelistCSV string) bool {
|
||||||
|
if whitelistCSV == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, domain, ok := parseStrictEmail(email)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, d := range strings.Split(whitelistCSV, ",") {
|
||||||
|
if strings.ToLower(strings.TrimSpace(d)) == domain {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func ShouldGrantTrialForEmail(register config.RegisterConfig, email string) bool {
|
||||||
|
if !register.EnableTrial {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !IsValidTrialEmail(email) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// 无论白名单是否启用,泛域名邮箱(含 + 别名或 Gmail 点号)始终拒绝赠送
|
||||||
|
if IsDisposableAlias(email) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if isConfusableGmailDomain(emailDomain(email)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !register.EnableTrialEmailWhitelist {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if register.TrialEmailDomainWhitelist == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !IsEmailDomainWhitelisted(email, register.TrialEmailDomainWhitelist) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTrialConfigReady verifies that trial auto-grant has all required config.
|
||||||
|
func IsTrialConfigReady(register config.RegisterConfig) bool {
|
||||||
|
return register.EnableTrial &&
|
||||||
|
register.TrialSubscribe > 0 &&
|
||||||
|
register.TrialTime > 0 &&
|
||||||
|
strings.TrimSpace(register.TrialTimeUnit) != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldAutoGrantTrialOnPublicEmailFlows defines whether browser/email-originated
|
||||||
|
// flows may auto-create a trial subscription. Email-specific abuse protection
|
||||||
|
// is still handled by ShouldGrantTrialForEmail and NormalizedEmailHasTrial.
|
||||||
|
func ShouldAutoGrantTrialOnPublicEmailFlows(register config.RegisterConfig) bool {
|
||||||
|
return IsTrialConfigReady(register)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsDisposableAlias detects Gmail dot trick and + alias abuse.
|
||||||
|
// For Gmail-like domains, local part containing "." or "+" is rejected.
|
||||||
|
// For all other domains, only "+" alias is rejected.
|
||||||
|
func IsDisposableAlias(email string) bool {
|
||||||
|
local, domain, ok := parseStrictEmail(email)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// All domains: reject + alias
|
||||||
|
if strings.ContainsRune(local, '+') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Gmail-like domains: reject dots in local part
|
||||||
|
if isGmailLikeDomain(domain) && strings.ContainsRune(local, '.') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeEmail returns a canonical form of the email for trial deduplication.
|
||||||
|
// Strips "+" aliases universally (user+tag@any.com → user@any.com).
|
||||||
|
// Removes dots from local part for Gmail-like providers (gmail.com, googlemail.com).
|
||||||
|
func NormalizeEmail(email string) string {
|
||||||
|
email = strings.ToLower(strings.TrimSpace(email))
|
||||||
|
local, domain, ok := parseStrictEmail(email)
|
||||||
|
if !ok {
|
||||||
|
return email
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip + alias
|
||||||
|
if idx := strings.IndexByte(local, '+'); idx != -1 {
|
||||||
|
local = local[:idx]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove dots for Gmail-like providers that ignore dots in local part
|
||||||
|
if isGmailLikeDomain(domain) {
|
||||||
|
local = strings.ReplaceAll(local, ".", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
return local + "@" + domain
|
||||||
|
}
|
||||||
|
|
||||||
|
func isGmailLikeDomain(domain string) bool {
|
||||||
|
switch domain {
|
||||||
|
case "gmail.com", "googlemail.com":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsValidTrialEmail(email string) bool {
|
||||||
|
local, domain, ok := parseStrictEmail(email)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return local != "" && domain != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseStrictEmail(email string) (local, domain string, ok bool) {
|
||||||
|
email = strings.ToLower(strings.TrimSpace(email))
|
||||||
|
if email == "" || strings.ContainsAny(email, " \t\r\n") {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
addr, err := mail.ParseAddress(email)
|
||||||
|
if err != nil || addr.Address != email || addr.Name != "" {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
parts := strings.Split(addr.Address, "@")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
local = strings.TrimSpace(parts[0])
|
||||||
|
domain = strings.Trim(strings.TrimSpace(parts[1]), ".")
|
||||||
|
if local == "" || domain == "" || strings.Contains(domain, "..") || !strings.Contains(domain, ".") {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
return local, domain, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func emailDomain(email string) string {
|
||||||
|
_, domain, ok := parseStrictEmail(email)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return domain
|
||||||
|
}
|
||||||
|
|
||||||
|
func isConfusableGmailDomain(domain string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(domain)) {
|
||||||
|
case "gmaial.com", "gmial.com", "gmai.com", "gamil.com", "gmal.com", "gmail.co", "gmail.con":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizedEmailHasTrial returns true if any user with the same normalized email
|
||||||
|
// already holds a trial subscription. Only performs the cross-user DB check when
|
||||||
|
// normalization actually changes the email (i.e., dots removed or + alias stripped).
|
||||||
|
func NormalizedEmailHasTrial(ctx context.Context, db *gorm.DB, email string, trialSubscribeId int64) bool {
|
||||||
|
normalized := NormalizeEmail(email)
|
||||||
|
if normalized == strings.ToLower(strings.TrimSpace(email)) {
|
||||||
|
return false // normalization changed nothing, skip cross-user check
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.SplitN(normalized, "@", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
domain := parts[1]
|
||||||
|
|
||||||
|
var authMethods []usermodel.AuthMethods
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Model(&usermodel.AuthMethods{}).
|
||||||
|
Select("user_id, auth_identifier").
|
||||||
|
Where("auth_type = ? AND auth_identifier LIKE ?", "email", "%@"+domain).
|
||||||
|
Find(&authMethods).Error; err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, am := range authMethods {
|
||||||
|
if NormalizeEmail(am.AuthIdentifier) != normalized {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
if err := db.WithContext(ctx).
|
||||||
|
Model(&usermodel.Subscribe{}).
|
||||||
|
Where("user_id = ? AND subscribe_id = ?", am.UserId, trialSubscribeId).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -147,7 +147,10 @@ func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Activate trial subscription after transaction success (moved outside transaction to reduce lock time)
|
// Activate trial subscription after transaction success (moved outside transaction to reduce lock time)
|
||||||
if l.svcCtx.Config.Register.EnableTrial {
|
rc := l.svcCtx.Config.Register
|
||||||
|
if ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
|
||||||
|
ShouldGrantTrialForEmail(rc, req.Email) &&
|
||||||
|
!NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, req.Email, rc.TrialSubscribe) {
|
||||||
trialSubscribe, err = l.activeTrial(userInfo.Id)
|
trialSubscribe, err = l.activeTrial(userInfo.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("Failed to activate trial subscription", logger.Field("error", err.Error()))
|
l.Errorw("Failed to activate trial subscription", logger.Field("error", err.Error()))
|
||||||
@@ -156,7 +159,7 @@ func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Clear cache after transaction success
|
// Clear cache after transaction success
|
||||||
if l.svcCtx.Config.Register.EnableTrial && trialSubscribe != nil {
|
if trialSubscribe != nil {
|
||||||
// Trigger user group recalculation (runs in background)
|
// Trigger user group recalculation (runs in background)
|
||||||
go func() {
|
go func() {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
|||||||
@@ -1,108 +1,120 @@
|
|||||||
package common
|
package common
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ReportLogMessageLogic struct {
|
type ReportLogMessageLogic struct {
|
||||||
logger.Logger
|
logger.Logger
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
svcCtx *svc.ServiceContext
|
svcCtx *svc.ServiceContext
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReportLogMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReportLogMessageLogic {
|
func NewReportLogMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReportLogMessageLogic {
|
||||||
return &ReportLogMessageLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx }
|
return &ReportLogMessageLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ReportLogMessageLogic) ReportLogMessage(req *types.ReportLogMessageRequest, c *gin.Context) (resp *types.ReportLogMessageResponse, err error) {
|
func (l *ReportLogMessageLogic) ReportLogMessage(req *types.ReportLogMessageRequest, c *gin.Context) (resp *types.ReportLogMessageResponse, err error) {
|
||||||
ip := clientIP(c)
|
ip := clientIP(c)
|
||||||
ua := c.GetHeader("User-Agent")
|
ua := c.GetHeader("User-Agent")
|
||||||
locale := c.GetHeader("Accept-Language")
|
locale := c.GetHeader("Accept-Language")
|
||||||
|
|
||||||
// 简单限流:设备ID优先,其次IP
|
// 简单限流:设备ID优先,其次IP
|
||||||
limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId)
|
limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId)
|
||||||
if limitKey == "logmsg:" { limitKey = "logmsg:" + ip }
|
if limitKey == "logmsg:" {
|
||||||
count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result()
|
limitKey = "logmsg:" + ip
|
||||||
if count == 1 { _ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err() }
|
}
|
||||||
if count > 120 { // 每分钟最多120条
|
count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result()
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports")
|
if count == 1 {
|
||||||
}
|
_ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err()
|
||||||
|
}
|
||||||
|
if count > 120 { // 每分钟最多120条
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports")
|
||||||
|
}
|
||||||
|
|
||||||
// 指纹生成
|
// 指纹生成
|
||||||
h := sha256.New()
|
h := sha256.New()
|
||||||
h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|")))
|
h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|")))
|
||||||
digest := hex.EncodeToString(h.Sum(nil))
|
digest := hex.EncodeToString(h.Sum(nil))
|
||||||
|
|
||||||
var ctxStr string
|
var ctxStr string
|
||||||
if req.Context != nil {
|
if req.Context != nil {
|
||||||
if b, e := json.Marshal(req.Context); e == nil {
|
if b, e := json.Marshal(req.Context); e == nil {
|
||||||
ctxStr = string(b)
|
ctxStr = string(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var occurredAt *time.Time
|
var occurredAt *time.Time
|
||||||
if req.OccurredAt > 0 {
|
if req.OccurredAt > 0 {
|
||||||
t := time.UnixMilli(req.OccurredAt)
|
t := time.UnixMilli(req.OccurredAt)
|
||||||
occurredAt = &t
|
occurredAt = &t
|
||||||
}
|
}
|
||||||
|
|
||||||
var userIdPtr *int64
|
var userIdPtr *int64
|
||||||
if req.UserId > 0 { userIdPtr = &req.UserId }
|
if req.UserId > 0 {
|
||||||
|
userIdPtr = &req.UserId
|
||||||
|
}
|
||||||
|
|
||||||
row := &logmessage.LogMessage{
|
row := &logmessage.LogMessage{
|
||||||
Platform: req.Platform,
|
Platform: safeTruncate(req.Platform, 32),
|
||||||
AppVersion: req.AppVersion,
|
AppVersion: safeTruncate(req.AppVersion, 64),
|
||||||
OsName: req.OsName,
|
OsName: safeTruncate(req.OsName, 64),
|
||||||
OsVersion: req.OsVersion,
|
OsVersion: safeTruncate(req.OsVersion, 64),
|
||||||
DeviceId: req.DeviceId,
|
DeviceId: safeTruncate(req.DeviceId, 255),
|
||||||
UserId: userIdPtr,
|
UserId: userIdPtr,
|
||||||
SessionId: req.SessionId,
|
SessionId: safeTruncate(req.SessionId, 255),
|
||||||
Level: req.Level,
|
Level: req.Level,
|
||||||
ErrorCode: req.ErrorCode,
|
ErrorCode: safeTruncate(req.ErrorCode, 128),
|
||||||
Message: safeTruncate(req.Message, 1024*64),
|
Message: safeTruncate(req.Message, 1024*64),
|
||||||
Stack: safeTruncate(req.Stack, 1024*1024),
|
Stack: safeTruncate(req.Stack, 1024*1024),
|
||||||
Context: ctxStr,
|
Context: ctxStr,
|
||||||
ClientIP: ip,
|
ClientIP: ip,
|
||||||
UserAgent: safeTruncate(ua, 255),
|
UserAgent: safeTruncate(ua, 255),
|
||||||
Locale: safeTruncate(locale, 16),
|
Locale: safeTruncate(locale, 16),
|
||||||
Digest: digest,
|
Digest: digest,
|
||||||
OccurredAt: occurredAt,
|
OccurredAt: occurredAt,
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil {
|
if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil {
|
||||||
// 唯一指纹冲突时尝试查询已有记录返回ID
|
// 唯一指纹冲突时尝试查询已有记录返回ID
|
||||||
ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{ Keyword: req.Message, Page: 1, Size: 1 })
|
ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{Keyword: req.Message, Page: 1, Size: 1})
|
||||||
if findErr == nil && len(ex) > 0 {
|
if findErr == nil && len(ex) > 0 {
|
||||||
return &types.ReportLogMessageResponse{ Id: ex[0].Id }, nil
|
return &types.ReportLogMessageResponse{Id: ex[0].Id}, nil
|
||||||
}
|
}
|
||||||
l.Errorf("[ReportLogMessage] insert error: %v", err)
|
l.Errorf("[ReportLogMessage] insert error: %v", err)
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err)
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err)
|
||||||
}
|
}
|
||||||
return &types.ReportLogMessageResponse{ Id: row.Id }, nil
|
return &types.ReportLogMessageResponse{Id: row.Id}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeTruncate(s string, n int) string {
|
func safeTruncate(s string, n int) string {
|
||||||
if len(s) <= n { return s }
|
if len(s) <= n {
|
||||||
return s[:n]
|
return s
|
||||||
|
}
|
||||||
|
return s[:n]
|
||||||
}
|
}
|
||||||
|
|
||||||
func clientIP(c *gin.Context) string {
|
func clientIP(c *gin.Context) string {
|
||||||
ip := c.ClientIP()
|
ip := c.ClientIP()
|
||||||
if ip != "" { return ip }
|
if ip != "" {
|
||||||
host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
return ip
|
||||||
if err == nil && host != "" { return host }
|
}
|
||||||
return ""
|
host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
||||||
|
if err == nil && host != "" {
|
||||||
|
return host
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
modelOrder "github.com/perfect-panel/server/internal/model/order"
|
||||||
|
modelUser "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
NewUserEligibilitySourceDeviceCreatedAt = "device_created_at"
|
||||||
|
NewUserEligibilitySourceUserCreatedAtFallback = "user_created_at_fallback"
|
||||||
|
NewUserEligibilityJoinSourceBindEmail = "bind_email_with_verification"
|
||||||
|
NewUserEligibilityWindow = 24 * time.Hour
|
||||||
|
)
|
||||||
|
|
||||||
|
type NewUserEligibilityContext struct {
|
||||||
|
ScopeUserIDs []int64
|
||||||
|
EligibilityStartAt time.Time
|
||||||
|
Source string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *NewUserEligibilityContext) IsNewUserAt(now time.Time) bool {
|
||||||
|
if c == nil || c.EligibilityStartAt.IsZero() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return now.Sub(c.EligibilityStartAt) <= NewUserEligibilityWindow
|
||||||
|
}
|
||||||
|
|
||||||
|
type newUserEligibilityRelation struct {
|
||||||
|
FamilyID int64 `gorm:"column:family_id"`
|
||||||
|
Role uint8 `gorm:"column:role"`
|
||||||
|
JoinSource string `gorm:"column:join_source"`
|
||||||
|
OwnerUserID int64 `gorm:"column:owner_user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveNewUserEligibility(ctx context.Context, db *gorm.DB, currentUserID int64) (*NewUserEligibilityContext, error) {
|
||||||
|
if currentUserID <= 0 {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "current user id is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
scopeUserIDs, err := resolveNewUserEligibilityScope(ctx, db, currentUserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
startAt, source, err := resolveNewUserEligibilityStartAt(ctx, db, scopeUserIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &NewUserEligibilityContext{
|
||||||
|
ScopeUserIDs: scopeUserIDs,
|
||||||
|
EligibilityStartAt: startAt,
|
||||||
|
Source: source,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func CountScopedSubscribePurchaseOrders(
|
||||||
|
ctx context.Context,
|
||||||
|
db *gorm.DB,
|
||||||
|
scopeUserIDs []int64,
|
||||||
|
subscribeID int64,
|
||||||
|
statuses []int64,
|
||||||
|
excludeOrderNo string,
|
||||||
|
) (int64, error) {
|
||||||
|
if len(scopeUserIDs) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
query := db.WithContext(ctx).
|
||||||
|
Model(&modelOrder.Order{}).
|
||||||
|
Where("user_id IN ? AND type IN ?", scopeUserIDs, []int64{1, 2})
|
||||||
|
if subscribeID > 0 {
|
||||||
|
query = query.Where("subscribe_id = ?", subscribeID)
|
||||||
|
}
|
||||||
|
if len(statuses) > 0 {
|
||||||
|
query = query.Where("status IN ?", statuses)
|
||||||
|
}
|
||||||
|
if excludeOrderNo != "" {
|
||||||
|
query = query.Where("order_no != ?", excludeOrderNo)
|
||||||
|
}
|
||||||
|
if err := query.Count(&count).Error; err != nil {
|
||||||
|
return 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count scoped subscribe purchase orders failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveNewUserEligibilityScope(ctx context.Context, db *gorm.DB, currentUserID int64) ([]int64, error) {
|
||||||
|
defaultScope := []int64{currentUserID}
|
||||||
|
|
||||||
|
var relation newUserEligibilityRelation
|
||||||
|
err := db.WithContext(ctx).
|
||||||
|
Table("user_family_member AS ufm").
|
||||||
|
Select("ufm.family_id, ufm.role, ufm.join_source, uf.owner_user_id").
|
||||||
|
Joins("JOIN user_family AS uf ON uf.id = ufm.family_id AND uf.deleted_at IS NULL AND uf.status = ?", modelUser.FamilyStatusActive).
|
||||||
|
Where("ufm.user_id = ? AND ufm.deleted_at IS NULL AND ufm.status = ?", currentUserID, modelUser.FamilyMemberActive).
|
||||||
|
Limit(1).
|
||||||
|
Take(&relation).Error
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return defaultScope, nil
|
||||||
|
}
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query new user eligibility family relation failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
if relation.Role != modelUser.FamilyRoleOwner && relation.JoinSource != NewUserEligibilityJoinSourceBindEmail {
|
||||||
|
return defaultScope, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var scopedUserIDs []int64
|
||||||
|
if err = db.WithContext(ctx).
|
||||||
|
Table("user_family_member AS ufm").
|
||||||
|
Select("ufm.user_id").
|
||||||
|
Joins("JOIN user_family AS uf ON uf.id = ufm.family_id AND uf.deleted_at IS NULL AND uf.status = ?", modelUser.FamilyStatusActive).
|
||||||
|
Where(
|
||||||
|
"ufm.family_id = ? AND ufm.deleted_at IS NULL AND ufm.status = ? AND (ufm.role = ? OR ufm.join_source = ?)",
|
||||||
|
relation.FamilyID,
|
||||||
|
modelUser.FamilyMemberActive,
|
||||||
|
modelUser.FamilyRoleOwner,
|
||||||
|
NewUserEligibilityJoinSourceBindEmail,
|
||||||
|
).
|
||||||
|
Pluck("ufm.user_id", &scopedUserIDs).Error; err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query new user eligibility scope failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
scopedUserIDs = append(scopedUserIDs, currentUserID)
|
||||||
|
return uniqueSortedInt64(scopedUserIDs), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveNewUserEligibilityStartAt(ctx context.Context, db *gorm.DB, scopeUserIDs []int64) (time.Time, string, error) {
|
||||||
|
var earliestDevice modelUser.Device
|
||||||
|
err := db.WithContext(ctx).
|
||||||
|
Model(&modelUser.Device{}).
|
||||||
|
Where("user_id IN ?", scopeUserIDs).
|
||||||
|
Order("created_at ASC").
|
||||||
|
Limit(1).
|
||||||
|
Take(&earliestDevice).Error
|
||||||
|
switch {
|
||||||
|
case err == nil && !earliestDevice.CreatedAt.IsZero():
|
||||||
|
return earliestDevice.CreatedAt, NewUserEligibilitySourceDeviceCreatedAt, nil
|
||||||
|
case err != nil && !errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
return time.Time{}, "", errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query new user eligibility device start failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
var earliestUser modelUser.User
|
||||||
|
err = db.WithContext(ctx).
|
||||||
|
Model(&modelUser.User{}).
|
||||||
|
Where("id IN ?", scopeUserIDs).
|
||||||
|
Order("created_at ASC").
|
||||||
|
Limit(1).
|
||||||
|
Take(&earliestUser).Error
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, "", errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query new user eligibility fallback start failed")
|
||||||
|
}
|
||||||
|
if earliestUser.CreatedAt.IsZero() {
|
||||||
|
return time.Time{}, "", errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "new user eligibility start time not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return earliestUser.CreatedAt, NewUserEligibilitySourceUserCreatedAtFallback, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniqueSortedInt64(values []int64) []int64 {
|
||||||
|
if len(values) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := make(map[int64]struct{}, len(values))
|
||||||
|
result := make([]int64, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if value == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seen[value]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[value] = struct{}{}
|
||||||
|
result = append(result, value)
|
||||||
|
}
|
||||||
|
sort.Slice(result, func(i, j int) bool {
|
||||||
|
return result[i] < result[j]
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -52,12 +52,8 @@ func ResolvePurchaseRoute(
|
|||||||
return decision, nil
|
return decision, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if requestedSubscribeID != anchorSub.SubscribeId {
|
|
||||||
return nil, ErrSingleModePlanMismatch
|
|
||||||
}
|
|
||||||
|
|
||||||
decision.Route = PurchaseRoutePurchaseToRenewal
|
decision.Route = PurchaseRoutePurchaseToRenewal
|
||||||
decision.ResolvedSubscribeID = anchorSub.SubscribeId
|
decision.ResolvedSubscribeID = requestedSubscribeID
|
||||||
decision.Anchor = anchorSub
|
decision.Anchor = anchorSub
|
||||||
return decision, nil
|
return decision, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
ordermodel "github.com/perfect-panel/server/internal/model/order"
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
SubscriptionTraceType = "subscription_flow"
|
||||||
|
SubscriptionTraceFlowOrder = "order_subscription"
|
||||||
|
SubscriptionTraceFlowEmailBind = "email_bind_subscription"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SubscriptionTraceFields(flow string, stage string, fields ...logger.LogField) []logger.LogField {
|
||||||
|
base := []logger.LogField{
|
||||||
|
logger.Field("trace_type", SubscriptionTraceType),
|
||||||
|
logger.Field("flow", flow),
|
||||||
|
logger.Field("stage", stage),
|
||||||
|
}
|
||||||
|
|
||||||
|
return append(base, fields...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscriptionTraceInfo(log logger.Logger, flow string, stage string, msg string, fields ...logger.LogField) {
|
||||||
|
log.Infow(msg, SubscriptionTraceFields(flow, stage, fields...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscriptionTraceError(log logger.Logger, flow string, stage string, msg string, fields ...logger.LogField) {
|
||||||
|
log.Errorw(msg, SubscriptionTraceFields(flow, stage, fields...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func OrderTraceFields(orderInfo *ordermodel.Order) []logger.LogField {
|
||||||
|
if orderInfo == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
effectiveUserID := orderInfo.UserId
|
||||||
|
if orderInfo.SubscriptionUserId > 0 {
|
||||||
|
effectiveUserID = orderInfo.SubscriptionUserId
|
||||||
|
}
|
||||||
|
|
||||||
|
fields := []logger.LogField{
|
||||||
|
logger.Field("order_id", orderInfo.Id),
|
||||||
|
logger.Field("order_no", orderInfo.OrderNo),
|
||||||
|
logger.Field("order_type", orderInfo.Type),
|
||||||
|
logger.Field("order_status", orderInfo.Status),
|
||||||
|
logger.Field("user_id", orderInfo.UserId),
|
||||||
|
logger.Field("subscription_user_id", orderInfo.SubscriptionUserId),
|
||||||
|
logger.Field("effective_user_id", effectiveUserID),
|
||||||
|
logger.Field("order_subscribe_id", orderInfo.SubscribeId),
|
||||||
|
logger.Field("payment_id", orderInfo.PaymentId),
|
||||||
|
logger.Field("payment_method", orderInfo.Method),
|
||||||
|
logger.Field("parent_order_id", orderInfo.ParentId),
|
||||||
|
logger.Field("quantity", orderInfo.Quantity),
|
||||||
|
logger.Field("is_new_order", orderInfo.IsNew),
|
||||||
|
}
|
||||||
|
|
||||||
|
if tail := SensitiveTail(orderInfo.SubscribeToken); tail != "" {
|
||||||
|
fields = append(fields, logger.Field("subscribe_token_tail", tail))
|
||||||
|
}
|
||||||
|
if tail := SensitiveTail(orderInfo.TradeNo); tail != "" {
|
||||||
|
fields = append(fields, logger.Field("trade_no_tail", tail))
|
||||||
|
}
|
||||||
|
if tail := SensitiveTail(orderInfo.AppAccountToken); tail != "" {
|
||||||
|
fields = append(fields, logger.Field("app_account_token_tail", tail))
|
||||||
|
}
|
||||||
|
|
||||||
|
return fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserSubscribeTraceFields(userSub *usermodel.Subscribe) []logger.LogField {
|
||||||
|
if userSub == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fields := []logger.LogField{
|
||||||
|
logger.Field("user_subscribe_id", userSub.Id),
|
||||||
|
logger.Field("subscribe_owner_user_id", userSub.UserId),
|
||||||
|
logger.Field("user_subscribe_plan_id", userSub.SubscribeId),
|
||||||
|
logger.Field("subscribe_order_id", userSub.OrderId),
|
||||||
|
logger.Field("subscribe_status", userSub.Status),
|
||||||
|
logger.Field("expire_time", userSub.ExpireTime),
|
||||||
|
}
|
||||||
|
|
||||||
|
if tail := SensitiveTail(userSub.Token); tail != "" {
|
||||||
|
fields = append(fields, logger.Field("subscribe_token_tail", tail))
|
||||||
|
}
|
||||||
|
if tail := SensitiveTail(userSub.UUID); tail != "" {
|
||||||
|
fields = append(fields, logger.Field("subscribe_uuid_tail", tail))
|
||||||
|
}
|
||||||
|
|
||||||
|
return fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func SensitiveTail(value string) string {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if len(value) <= 8 {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
return value[len(value)-8:]
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/model/log"
|
||||||
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
func WriteCommissionLog(tx *gorm.DB, objectID int64, logType uint16, amount int64, orderNo string) error {
|
||||||
|
logInfo := log.Commission{
|
||||||
|
Type: logType,
|
||||||
|
Amount: amount,
|
||||||
|
OrderNo: orderNo,
|
||||||
|
Timestamp: time.Now().UnixMilli(),
|
||||||
|
}
|
||||||
|
|
||||||
|
content, err := logInfo.Marshal()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Model(log.SystemLog{}).Create(&log.SystemLog{
|
||||||
|
Type: log.TypeCommission.Uint8(),
|
||||||
|
Date: time.Now().Format(time.DateOnly),
|
||||||
|
ObjectID: objectID,
|
||||||
|
Content: string(content),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadPendingWithdrawalForUpdate(ctx context.Context, tx *gorm.DB, withdrawalID int64) (*usermodel.Withdrawal, error) {
|
||||||
|
var withdrawal usermodel.Withdrawal
|
||||||
|
if err := tx.WithContext(ctx).
|
||||||
|
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||||
|
Where("id = ?", withdrawalID).
|
||||||
|
First(&withdrawal).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if withdrawal.Status != 0 {
|
||||||
|
return nil, errors.New("withdrawal status invalid")
|
||||||
|
}
|
||||||
|
return &withdrawal, nil
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
"github.com/perfect-panel/server/pkg/constant"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
@@ -56,6 +57,12 @@ func (l *AlipayNotifyLogic) AlipayNotify(r *http.Request) error {
|
|||||||
l.Logger.Error("[AlipayNotify] Decode notification failed", logger.Field("error", err.Error()))
|
l.Logger.Error("[AlipayNotify] Decode notification failed", logger.Field("error", err.Error()))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_notify_received",
|
||||||
|
"[SubscriptionFlow] alipay notify received",
|
||||||
|
logger.Field("order_no", notify.OrderNo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
logger.Field("notify_status", string(notify.Status)),
|
||||||
|
)
|
||||||
if notify.Status == alipay.Success {
|
if notify.Status == alipay.Success {
|
||||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, notify.OrderNo)
|
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, notify.OrderNo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -73,6 +80,12 @@ func (l *AlipayNotifyLogic) AlipayNotify(r *http.Request) error {
|
|||||||
l.Logger.Error("[AlipayNotify] Update order status failed", logger.Field("error", err.Error()), logger.Field("orderNo", notify.OrderNo))
|
l.Logger.Error("[AlipayNotify] Update order status failed", logger.Field("error", err.Error()), logger.Field("orderNo", notify.OrderNo))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_settled",
|
||||||
|
"[SubscriptionFlow] alipay notify marked order as paid",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
l.Logger.Info("[AlipayNotify] Notify status success", logger.Field("orderNo", notify.OrderNo))
|
l.Logger.Info("[AlipayNotify] Notify status success", logger.Field("orderNo", notify.OrderNo))
|
||||||
payload := types.ForthwithActivateOrderPayload{
|
payload := types.ForthwithActivateOrderPayload{
|
||||||
OrderNo: notify.OrderNo,
|
OrderNo: notify.OrderNo,
|
||||||
@@ -88,6 +101,13 @@ func (l *AlipayNotifyLogic) AlipayNotify(r *http.Request) error {
|
|||||||
l.Logger.Error("[AlipayNotify] Enqueue task failed", logger.Field("error", err.Error()))
|
l.Logger.Error("[AlipayNotify] Enqueue task failed", logger.Field("error", err.Error()))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "activation_task_enqueued",
|
||||||
|
"[SubscriptionFlow] activation task enqueued from alipay notify",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
logger.Field("queue_task_id", taskInfo.ID),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
l.Logger.Info("[AlipayNotify] Enqueue task success", logger.Field("taskInfo", taskInfo))
|
l.Logger.Info("[AlipayNotify] Enqueue task success", logger.Field("taskInfo", taskInfo))
|
||||||
} else {
|
} else {
|
||||||
l.Logger.Error("[AlipayNotify] Notify status failed", logger.Field("status", string(notify.Status)))
|
l.Logger.Error("[AlipayNotify] Notify status failed", logger.Field("status", string(notify.Status)))
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
@@ -57,6 +58,13 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
}
|
}
|
||||||
// 验签通过,记录通知类型与关键交易标识
|
// 验签通过,记录通知类型与关键交易标识
|
||||||
l.Infow("iap notify verified", logger.Field("type", ntype), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
|
l.Infow("iap notify verified", logger.Field("type", ntype), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_notify_received",
|
||||||
|
"[SubscriptionFlow] apple iap server notification received",
|
||||||
|
logger.Field("notify_type", ntype),
|
||||||
|
logger.Field("product_id", txPayload.ProductId),
|
||||||
|
logger.Field("original_transaction_tail", commonLogic.SensitiveTail(txPayload.OriginalTransactionId)),
|
||||||
|
logger.Field("transaction_id_tail", commonLogic.SensitiveTail(txPayload.TransactionId)),
|
||||||
|
)
|
||||||
return l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
return l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
|
||||||
var existing *iapmodel.Transaction
|
var existing *iapmodel.Transaction
|
||||||
existing, _ = iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByOriginalId(l.ctx, txPayload.OriginalTransactionId)
|
existing, _ = iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByOriginalId(l.ctx, txPayload.OriginalTransactionId)
|
||||||
@@ -201,6 +209,13 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
l.Infow("iap notify fallback updated subscribe", logger.Field("userSubscribeId", candidate.Id), logger.Field("status", candidate.Status))
|
l.Infow("iap notify fallback updated subscribe", logger.Field("userSubscribeId", candidate.Id), logger.Field("status", candidate.Status))
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "subscription_updated_from_notify",
|
||||||
|
"[SubscriptionFlow] apple iap notify updated fallback subscription candidate",
|
||||||
|
append(commonLogic.UserSubscribeTraceFields(candidate),
|
||||||
|
logger.Field("notify_type", ntype),
|
||||||
|
logger.Field("product_id", txPayload.ProductId),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -226,6 +241,13 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
}
|
}
|
||||||
// 更新成功,输出订阅状态
|
// 更新成功,输出订阅状态
|
||||||
l.Infow("iap notify updated subscribe", logger.Field("userSubscribeId", sub.Id), logger.Field("status", sub.Status))
|
l.Infow("iap notify updated subscribe", logger.Field("userSubscribeId", sub.Id), logger.Field("status", sub.Status))
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "subscription_updated_from_notify",
|
||||||
|
"[SubscriptionFlow] apple iap notify updated subscription",
|
||||||
|
append(commonLogic.UserSubscribeTraceFields(sub),
|
||||||
|
logger.Field("notify_type", ntype),
|
||||||
|
logger.Field("product_id", txPayload.ProductId),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
||||||
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
"github.com/perfect-panel/server/pkg/constant"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
@@ -44,12 +45,18 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
|||||||
l.Logger.Error("[EPayNotify] Payment not found in context")
|
l.Logger.Error("[EPayNotify] Payment not found in context")
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "payment config not found")
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "payment config not found")
|
||||||
}
|
}
|
||||||
l.Infof("[EPayNotify] Payment config: %+v", data)
|
|
||||||
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OutTradeNo)
|
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OutTradeNo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Logger.Error("[EPayNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
|
l.Logger.Error("[EPayNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", req.OutTradeNo)
|
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", req.OutTradeNo)
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_notify_received",
|
||||||
|
"[SubscriptionFlow] epay notify received",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
logger.Field("trade_status", req.TradeStatus),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
|
|
||||||
var config payment.EPayConfig
|
var config payment.EPayConfig
|
||||||
if err := json.Unmarshal([]byte(data.Config), &config); err != nil {
|
if err := json.Unmarshal([]byte(data.Config), &config); err != nil {
|
||||||
@@ -75,6 +82,12 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
|||||||
l.Logger.Error("[EPayNotify] Update order status failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
|
l.Logger.Error("[EPayNotify] Update order status failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_settled",
|
||||||
|
"[SubscriptionFlow] epay notify marked order as paid",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
// Create activate order task
|
// Create activate order task
|
||||||
payload := queueType.ForthwithActivateOrderPayload{
|
payload := queueType.ForthwithActivateOrderPayload{
|
||||||
OrderNo: req.OutTradeNo,
|
OrderNo: req.OutTradeNo,
|
||||||
@@ -90,6 +103,13 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
|
|||||||
l.Logger.Error("[EPayNotify] Enqueue task failed", logger.Field("error", err.Error()))
|
l.Logger.Error("[EPayNotify] Enqueue task failed", logger.Field("error", err.Error()))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "activation_task_enqueued",
|
||||||
|
"[SubscriptionFlow] activation task enqueued from epay notify",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", data.Platform),
|
||||||
|
logger.Field("queue_task_id", taskInfo.ID),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
l.Logger.Info("[EPayNotify] Enqueue task success", logger.Field("taskInfo", taskInfo))
|
l.Logger.Info("[EPayNotify] Enqueue task success", logger.Field("taskInfo", taskInfo))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
"github.com/perfect-panel/server/pkg/constant"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
@@ -67,6 +68,13 @@ func (l *StripeNotifyLogic) StripeNotify(r *http.Request, w http.ResponseWriter)
|
|||||||
l.Logger.Error("[StripeNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", notify.OrderNo))
|
l.Logger.Error("[StripeNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", notify.OrderNo))
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", notify.OrderNo)
|
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", notify.OrderNo)
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_notify_received",
|
||||||
|
"[SubscriptionFlow] stripe notify received",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", stripeConfig.Platform),
|
||||||
|
logger.Field("stripe_event_type", notify.EventType),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
if notify.EventType == "payment_intent.succeeded" {
|
if notify.EventType == "payment_intent.succeeded" {
|
||||||
if orderInfo.Status == 5 {
|
if orderInfo.Status == 5 {
|
||||||
return nil
|
return nil
|
||||||
@@ -76,6 +84,13 @@ func (l *StripeNotifyLogic) StripeNotify(r *http.Request, w http.ResponseWriter)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "payment_settled",
|
||||||
|
"[SubscriptionFlow] stripe notify marked order as paid",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", stripeConfig.Platform),
|
||||||
|
logger.Field("stripe_event_type", notify.EventType),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
// create ActivateOrder task
|
// create ActivateOrder task
|
||||||
payload := types.ForthwithActivateOrderPayload{
|
payload := types.ForthwithActivateOrderPayload{
|
||||||
OrderNo: notify.OrderNo,
|
OrderNo: notify.OrderNo,
|
||||||
@@ -86,11 +101,19 @@ func (l *StripeNotifyLogic) StripeNotify(r *http.Request, w http.ResponseWriter)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
task := asynq.NewTask(types.ForthwithActivateOrder, bytes, asynq.MaxRetry(5))
|
task := asynq.NewTask(types.ForthwithActivateOrder, bytes, asynq.MaxRetry(5))
|
||||||
_, err = l.svcCtx.Queue.Enqueue(task)
|
taskInfo, err := l.svcCtx.Queue.Enqueue(task)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[StripeNotify] Enqueue error", logger.Field("errors", err.Error()))
|
l.Errorw("[StripeNotify] Enqueue error", logger.Field("errors", err.Error()))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "activation_task_enqueued",
|
||||||
|
"[SubscriptionFlow] activation task enqueued from stripe notify",
|
||||||
|
append(commonLogic.OrderTraceFields(orderInfo),
|
||||||
|
logger.Field("payment_platform", stripeConfig.Platform),
|
||||||
|
logger.Field("stripe_event_type", notify.EventType),
|
||||||
|
logger.Field("queue_task_id", taskInfo.ID),
|
||||||
|
)...,
|
||||||
|
)
|
||||||
l.Infow("[StripeNotify] success", logger.Field("orderNo", notify.OrderNo))
|
l.Infow("[StripeNotify] success", logger.Field("orderNo", notify.OrderNo))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/pkg/constant"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
fileUploadInitStatus = "init"
|
||||||
|
fileUploadCompleteStatus = "completed"
|
||||||
|
fileUploadRedisPrefix = "file:upload:"
|
||||||
|
)
|
||||||
|
|
||||||
|
var safeFileNameRegexp = regexp.MustCompile(`[^a-zA-Z0-9._-]+`)
|
||||||
|
|
||||||
|
type uploadMeta struct {
|
||||||
|
FileID string `json:"file_id"`
|
||||||
|
UserID int64 `json:"user_id"`
|
||||||
|
BizType string `json:"biz_type"`
|
||||||
|
FileName string `json:"file_name"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Sha256 string `json:"sha256"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Etag string `json:"etag,omitempty"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
CompletedAt int64 `json:"completed_at,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentUserFromContext(ctx context.Context) (*user.User, error) {
|
||||||
|
u, ok := ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||||
|
if !ok || u == nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||||
|
}
|
||||||
|
return u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func allowedContentTypeSet(csv string) map[string]struct{} {
|
||||||
|
set := make(map[string]struct{})
|
||||||
|
for _, item := range strings.Split(csv, ",") {
|
||||||
|
item = strings.TrimSpace(strings.ToLower(item))
|
||||||
|
if item == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
set[item] = struct{}{}
|
||||||
|
}
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateInitRequest(svcCtx *svc.ServiceContext, bizType, fileName, contentType string, size int64) error {
|
||||||
|
if svcCtx.S3Store == nil || !svcCtx.Config.S3.Enable {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "S3 upload is not enabled")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(bizType) == "" {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "biz_type is required")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(fileName) == "" {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "file_name is required")
|
||||||
|
}
|
||||||
|
if size <= 0 {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "size must be greater than 0")
|
||||||
|
}
|
||||||
|
if svcCtx.Config.S3.MaxUploadSize > 0 && size > svcCtx.Config.S3.MaxUploadSize {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "file size exceeds max limit")
|
||||||
|
}
|
||||||
|
allowed := allowedContentTypeSet(svcCtx.Config.S3.AllowedContentTypes)
|
||||||
|
if len(allowed) > 0 {
|
||||||
|
if _, ok := allowed[strings.ToLower(strings.TrimSpace(contentType))]; !ok {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "content_type is not allowed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildFileID(userID int64, bizType, fileName string) string {
|
||||||
|
h := sha1.New()
|
||||||
|
_, _ = h.Write([]byte(fmt.Sprintf("%d:%s:%s:%d", userID, bizType, fileName, time.Now().UnixNano())))
|
||||||
|
return hex.EncodeToString(h.Sum(nil))[:24]
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeFileName(name string) string {
|
||||||
|
base := filepath.Base(strings.TrimSpace(name))
|
||||||
|
if base == "." || base == "/" || base == "" {
|
||||||
|
return "file.bin"
|
||||||
|
}
|
||||||
|
safe := safeFileNameRegexp.ReplaceAllString(base, "_")
|
||||||
|
if safe == "" {
|
||||||
|
return "file.bin"
|
||||||
|
}
|
||||||
|
return safe
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildObjectKey(prefix string, userID int64, bizType, fileID, fileName string, now time.Time) string {
|
||||||
|
prefix = strings.Trim(prefix, "/")
|
||||||
|
if prefix == "" {
|
||||||
|
prefix = "app-upload"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s/%04d/%02d/%02d/%d/%s__%s",
|
||||||
|
prefix,
|
||||||
|
now.Year(),
|
||||||
|
int(now.Month()),
|
||||||
|
now.Day(),
|
||||||
|
userID,
|
||||||
|
safeFileName(fileName),
|
||||||
|
fileID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadRedisKey(fileID string) string {
|
||||||
|
return fileUploadRedisPrefix + fileID
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveUploadMeta(ctx context.Context, svcCtx *svc.ServiceContext, meta *uploadMeta, ttl time.Duration) error {
|
||||||
|
data, err := json.Marshal(meta)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal upload meta failed")
|
||||||
|
}
|
||||||
|
if err := svcCtx.Redis.Set(ctx, uploadRedisKey(meta.FileID), data, ttl).Err(); err != nil {
|
||||||
|
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "save upload meta failed")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadUploadMeta(ctx context.Context, svcCtx *svc.ServiceContext, fileID string) (*uploadMeta, error) {
|
||||||
|
val, err := svcCtx.Redis.Get(ctx, uploadRedisKey(fileID)).Result()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "upload meta not found")
|
||||||
|
}
|
||||||
|
var meta uploadMeta
|
||||||
|
if err := json.Unmarshal([]byte(val), &meta); err != nil {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "parse upload meta failed")
|
||||||
|
}
|
||||||
|
return &meta, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// Code scaffolded by goctl. Safe to edit.
|
||||||
|
// goctl 1.9.2
|
||||||
|
|
||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileUploadCompleteLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Complete file upload
|
||||||
|
func NewFileUploadCompleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileUploadCompleteLogic {
|
||||||
|
return &FileUploadCompleteLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *FileUploadCompleteLogic) FileUploadComplete(req *types.FileUploadCompleteRequest) (resp *types.FileUploadCompleteResponse, err error) {
|
||||||
|
u, err := currentUserFromContext(l.ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
meta, err := loadUploadMeta(l.ctx, l.svcCtx, req.FileId)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if meta.UserID != u.Id {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||||
|
}
|
||||||
|
|
||||||
|
head, err := l.svcCtx.S3Store.HeadObject(l.ctx, meta.ObjectKey)
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("head object failed", logger.Field("error", err.Error()), logger.Field("file_id", meta.FileID))
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "uploaded file not found")
|
||||||
|
}
|
||||||
|
if meta.Size > 0 && head.ContentLength != meta.Size {
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "uploaded file size mismatch")
|
||||||
|
}
|
||||||
|
|
||||||
|
meta.Status = fileUploadCompleteStatus
|
||||||
|
meta.Etag = head.ETag
|
||||||
|
meta.ContentType = head.ContentType
|
||||||
|
meta.CompletedAt = time.Now().Unix()
|
||||||
|
if err := saveUploadMeta(l.ctx, l.svcCtx, meta, 7*24*time.Hour); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &types.FileUploadCompleteResponse{
|
||||||
|
FileId: meta.FileID,
|
||||||
|
ObjectKey: meta.ObjectKey,
|
||||||
|
Size: head.ContentLength,
|
||||||
|
ContentType: head.ContentType,
|
||||||
|
Etag: head.ETag,
|
||||||
|
Status: meta.Status,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// Code scaffolded by goctl. Safe to edit.
|
||||||
|
// goctl 1.9.2
|
||||||
|
|
||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"github.com/perfect-panel/server/internal/types"
|
||||||
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileUploadInitLogic struct {
|
||||||
|
logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
svcCtx *svc.ServiceContext
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init file upload
|
||||||
|
func NewFileUploadInitLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileUploadInitLogic {
|
||||||
|
return &FileUploadInitLogic{
|
||||||
|
Logger: logger.WithContext(ctx),
|
||||||
|
ctx: ctx,
|
||||||
|
svcCtx: svcCtx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *FileUploadInitLogic) FileUploadInit(req *types.FileUploadInitRequest) (resp *types.FileUploadInitResponse, err error) {
|
||||||
|
u, err := currentUserFromContext(l.ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := validateInitRequest(l.svcCtx, req.BizType, req.FileName, req.ContentType, req.Size); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
fileID := buildFileID(u.Id, req.BizType, req.FileName)
|
||||||
|
objectKey := buildObjectKey(l.svcCtx.Config.S3.Prefix, u.Id, req.BizType, fileID, req.FileName, now)
|
||||||
|
expireSeconds := l.svcCtx.Config.S3.PresignExpireSeconds
|
||||||
|
if expireSeconds <= 0 {
|
||||||
|
expireSeconds = 300
|
||||||
|
}
|
||||||
|
|
||||||
|
presigned, err := l.svcCtx.S3Store.PresignPutObject(l.ctx, objectKey, req.ContentType, time.Duration(expireSeconds)*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
l.Errorw("presign put object failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
meta := &uploadMeta{
|
||||||
|
FileID: fileID,
|
||||||
|
UserID: u.Id,
|
||||||
|
BizType: req.BizType,
|
||||||
|
FileName: req.FileName,
|
||||||
|
ContentType: req.ContentType,
|
||||||
|
ObjectKey: objectKey,
|
||||||
|
Size: req.Size,
|
||||||
|
Sha256: req.Sha256,
|
||||||
|
Status: fileUploadInitStatus,
|
||||||
|
CreatedAt: now.Unix(),
|
||||||
|
}
|
||||||
|
if err := saveUploadMeta(l.ctx, l.svcCtx, meta, 24*time.Hour); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &types.FileUploadInitResponse{
|
||||||
|
FileId: fileID,
|
||||||
|
ObjectKey: objectKey,
|
||||||
|
UploadURL: presigned.URL,
|
||||||
|
Method: presigned.Method,
|
||||||
|
Headers: map[string]string{
|
||||||
|
"Content-Type": req.ContentType,
|
||||||
|
},
|
||||||
|
ExpiredAt: presigned.ExpiresAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user