Compare commits
32 Commits
3806264343
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 511ce4ff65 | |||
| 64fe23f877 | |||
| 09c5216f60 | |||
| 4d84095af2 | |||
| d66b664198 | |||
| a7d89acc7f | |||
| 2a3d5a3234 | |||
| 100b641552 | |||
| aeca20ad1e | |||
| d1697bed75 | |||
| 14d4c5f36f | |||
| 37ceb5adfc | |||
| 71aaa08230 | |||
| cad75b92bc | |||
| 11c3ce26a6 | |||
| 65641838f9 | |||
| d8b65c6d82 | |||
| 55c78276fb | |||
| ce6ab4f05b | |||
| 750cab5cc9 | |||
| 3e2873fb90 | |||
| 644b20ebef | |||
| 7400137b3c | |||
| de87133061 | |||
| dd30b8eb8b | |||
| e6c2370d02 | |||
| 785c832e02 | |||
| 5a493fce67 | |||
| 5019f76a73 | |||
| 8d0ddbb5ef | |||
| ef54d2479d | |||
| d6616c5859 |
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__serena__get_symbols_overview",
|
||||
"mcp__serena__find_symbol",
|
||||
"Bash(pnpm:*)",
|
||||
"Bash(bun run:*)",
|
||||
"mcp__serena__list_dir",
|
||||
"Bash(npx --filter apps/admin tsr generate --config apps/admin/tsr.config.json 2>&1 | head -20)",
|
||||
"Bash(ls apps/admin/tsr.config.json 2>/dev/null || echo \"no tsr config\"; ls apps/admin/vite.config.* 2>/dev/null; cat apps/admin/package.json | grep -E '\"\\(dev|build|generate\\)\"' | head -5)",
|
||||
"Bash(npx tsc:*)",
|
||||
"Bash(curl -s 'http://127.0.0.1:8080/v1/admin/user/family/list?page=1&size=10' \\\\\n -H 'Accept: application/json' \\\\\n -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA' 2>&1)",
|
||||
"Bash(find apps/admin/src -name \"*.json\" -path \"*locale*\" -o -name \"*.json\" -path \"*i18n*\" -o -name \"*.json\" -path \"*zh*\" -o -name \"*.json\" -path \"*lang*\" 2>/dev/null | head -30)",
|
||||
"Bash(find apps/admin/src -name \"*.json\" 2>/dev/null | head -20; echo \"---\"; find apps/admin -name \"i18n*\" -o -name \"locale*\" 2>/dev/null | head -20; echo \"---\"; grep -r \"i18n\\\\|i18next\\\\|useTranslation\" apps/admin/src/main.tsx apps/admin/src/App.tsx 2>/dev/null | head -10)",
|
||||
"Bash(git log:*)",
|
||||
"Bash(for key:*)",
|
||||
"Bash(node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/zh-CN/user.json','utf8'\\)\\); console.log\\('zh-CN OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/en-US/user.json','utf8'\\)\\); console.log\\('en-US OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/zh-CN/system.json','utf8'\\)\\); console.log\\('zh-CN system OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/en-US/system.json','utf8'\\)\\); console.log\\('en-US system OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/zh-CN/menu.json','utf8'\\)\\); console.log\\('zh-CN menu OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/en-US/menu.json','utf8'\\)\\); console.log\\('en-US menu OK'\\)\")",
|
||||
"mcp__sequential-thinking__sequentialthinking",
|
||||
"Bash(find packages/ui/src/components -name \"alert*\" 2>/dev/null | head -5)",
|
||||
"Bash(node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/zh-CN/user.json','utf8'\\)\\); console.log\\('zh-CN OK'\\)\" && node -e \"JSON.parse\\(require\\('fs'\\).readFileSync\\('apps/admin/public/assets/locales/en-US/user.json','utf8'\\)\\); console.log\\('en-US OK'\\)\")",
|
||||
"Bash(grep -rn \"device_no\\\\|DeviceNo\\\\|device_identifier\\\\|DeviceIdentifier\\\\|sha256\\\\|SHA256\" /Users/Apple/code_vpn/vpn/ppanel-server --include=\"*.go\" 2>/dev/null | head -30)",
|
||||
"Bash(find /Users/Apple/code_vpn/vpn/ppanel-server -name \"*.sql\" -o -name \"*migration*\" -o -name \"*migrate*\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -rn \"FindOneDeviceByIdentifier\\\\|DeviceByIdentifier\" /Users/Apple/code_vpn/vpn/ppanel-server --include=\"*.go\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -rn \"device_no\\\\|DeviceNo\" /Users/Apple/code_vpn/vpn/ppanel-server --include=\"*.go\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -rn \"DeviceLoginRequest\\\\|device.*identifier\\\\|identifier.*device\" /Users/Apple/code_vpn/vpn/ppanel-server/apis --include=\"*.api\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -rn \"ShortCode\\\\|short_code\" /Users/Apple/code_vpn/vpn/ppanel-server/internal --include=\"*.go\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -n -i \"device\" /Users/Apple/code_vpn/vpn/ppanel-server/apis/auth/*.api 2>/dev/null; ls /Users/Apple/code_vpn/vpn/ppanel-server/apis/auth/)",
|
||||
"Bash(grep -n \"GetCacheKeys\\\\|ClearDeviceCache\" /Users/Apple/code_vpn/vpn/ppanel-server/internal/model/user/*.go | head -10)",
|
||||
"Bash(grep -rn \"identifier\\\\|Identifier\\\\|device_id\\\\|deviceId\" apps/admin/src/sections/user/ --include=\"*.tsx\" --include=\"*.ts\" 2>/dev/null | grep -v node_modules | grep -v \".d.ts\" | head -20)",
|
||||
"Bash(grep -rn \"device\\\\|Device\\\\|identifier\\\\|Identifier\" apps/user/src/ --include=\"*.tsx\" --include=\"*.ts\" 2>/dev/null | grep -v node_modules | grep -v \".d.ts\" | grep -v \"//\\\\|languageDetector\\\\|DevicePixel\\\\|device-width\" | head -30)",
|
||||
"Bash(grep -rn \"user/info\\\\|UserInfo\\\\|getUserInfo\\\\|GetUserInfo\" /Users/Apple/code_vpn/vpn/ppanel-server/apis/ --include=\"*.api\" 2>/dev/null | head -10)",
|
||||
"Bash(grep -l \"SelectTrigger\\\\|SelectContent\\\\|SelectItem\" packages/ui/src/components/select.tsx 2>/dev/null; echo \"---\"; grep -rn \"from.*@workspace/ui/components/select\" apps/admin/src/ --include=\"*.tsx\" 2>/dev/null | head -3)",
|
||||
"Bash(grep -ohP 't\\\\\\(\"\\([^\"]+\\)\"' apps/admin/src/sections/user/index.tsx | sed 's/t\\(\"//' | sed 's/\"$//' | sort -u | while read key; do if ! grep -q \"\\\\\"$key\\\\\"\" apps/admin/public/assets/locales/zh-CN/user.json 2>/dev/null; then echo \"MISSING: $key\"; fi; done)",
|
||||
"Bash(grep -o 't\\(\"[^\"]*\"' apps/admin/src/sections/user/index.tsx | sed 's/t\\(\"//' | sed 's/\"$//' | sort -u | while read key; do if ! grep -q \"\\\\\"$key\\\\\"\" apps/admin/public/assets/locales/zh-CN/user.json 2>/dev/null; then echo \"MISSING: $key\"; fi; done)",
|
||||
"Bash(grep -roh 't\\(\"[^\"]*\"' apps/admin/src/sections/user/ --include=\"*.tsx\" | sed 's/t\\(\"//' | sed 's/\"$//' | sort -u | while read key; do\n if ! grep -q \"\\\\\"$key\\\\\"\" apps/admin/public/assets/locales/zh-CN/user.json 2>/dev/null; then\n echo \"MISSING zh-CN user: $key\"\n fi\ndone)",
|
||||
"Bash(grep -o 't\\(\"[^\"]*\"' apps/admin/src/sections/system/user-security/signature-form.tsx apps/admin/src/sections/system/user-security/subscribe-mode-form.tsx | sed 's/.*t\\(\"//' | sed 's/\"$//' | sort -u | while read key; do\n if ! grep -q \"\\\\\"$key\\\\\"\" apps/admin/public/assets/locales/zh-CN/system.json 2>/dev/null; then\n echo \"MISSING system zh-CN: $key\"\n fi\ndone)",
|
||||
"Bash(grep -rn \"EnhancedInput\\\\|enhanced-input\" packages/ui/src/composed/enhanced-input.tsx 2>/dev/null | head -3; find packages/ui/src -name \"enhanced-input*\" 2>/dev/null)",
|
||||
"Bash(curl -s 'http://127.0.0.1:8080/v1/admin/system/getSignatureConfig' -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA' 2>&1 | head -5)",
|
||||
"Bash(curl -s 'http://127.0.0.1:8080/v1/admin/system/signature_config' -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA' 2>&1)",
|
||||
"Bash(curl -s 'http://127.0.0.1:8080/v1/admin/system/subscribe_config' -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA' 2>&1)",
|
||||
"Bash(curl -s -X PUT 'http://127.0.0.1:8080/v1/admin/system/signature_config' \\\\\n -H 'Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA' \\\\\n -H 'Content-Type: application/json' \\\\\n -d '{\"enable_signature\":true}' 2>&1)",
|
||||
"Bash(AUTH='Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA'\n\necho \"=== 1. GET before ===\"\ncurl -s 'http://127.0.0.1:8080/v1/admin/system/signature_config' -H \"$AUTH\"\n\necho \"\"\necho \"=== 2. PUT enable=true ===\"\ncurl -s -X PUT 'http://127.0.0.1:8080/v1/admin/system/signature_config' -H \"$AUTH\" -H 'Content-Type: application/json' -d '{\"enable_signature\":true}'\n\necho \"\"\necho \"=== 3. GET after ===\"\ncurl -s 'http://127.0.0.1:8080/v1/admin/system/signature_config' -H \"$AUTH\")",
|
||||
"Bash(grep -rn \"signature_config\\\\|SignatureConfig\\\\|getSignatureConfig\\\\|updateSignatureConfig\" /Users/Apple/code_vpn/vpn/ppanel-server/apis/ /Users/Apple/code_vpn/vpn/ppanel-server/internal/logic/ --include=\"*.go\" --include=\"*.api\" 2>/dev/null | head -20)",
|
||||
"Bash(grep -n \"GetSignatureConfig\\\\|func.*Signature\" /Users/Apple/code_vpn/vpn/ppanel-server/internal/model/system/*.go 2>/dev/null | head -10)",
|
||||
"Bash(AUTH='Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDdHhMb2dpblR5cGUiOiIiLCJTZXNzaW9uSWQiOiIwMTljZjAyYi05YTcwLTcyMDItYTlmZS1jNzE1NmZkYjIzYzYiLCJVc2VySWQiOjI1OCwiZXhwIjoxODA1MDkxOTE1LCJpYXQiOjE3NzM1NTU5MTUsImlkZW50aWZpZXIiOiIifQ.rnm_y9DOsjvFC2XecRQ8BNUkWZcfiGzXIh5Dgwh99lA'\nAPI='https://tapi.hifast.biz'\n\necho \"=== 用户信息 ===\"\ncurl -s \"$API/v1/public/user/info\" -H \"$AUTH\" | python3 -c \"\nimport sys,json\nd=json.load\\(sys.stdin\\)\nif 'data' in d:\n print\\('user_id:', d['data']['id']\\)\n devs = d['data'].get\\('user_devices', []\\)\n print\\('device count:', len\\(devs\\)\\)\n for dev in devs[:3]:\n print\\(' device:', json.dumps\\(dev\\)\\)\nelse:\n print\\(json.dumps\\(d\\)\\)\n\")",
|
||||
"Bash(API='https://tapi.hifast.biz'\nDEVICE_ID=\"devicetest$\\(openssl rand -hex 32\\)\"\n\necho \"Device ID: $DEVICE_ID\"\necho \"=== 设备登录 ===\"\ncurl -s -X POST \"$API/v1/auth/login/device\" \\\\\n -H 'Content-Type: application/json' \\\\\n -d \"{\\\\\"identifier\\\\\":\\\\\"$DEVICE_ID\\\\\",\\\\\"user_agent\\\\\":\\\\\"Mozilla/5.0 \\(Macintosh; Intel Mac OS X 10_15_7\\)\\\\\"}\" | python3 -m json.tool 2>/dev/null)",
|
||||
"Bash(find /Users/Apple/code_vpn/vpn/frontend/packages/ui/src -name \"request*\" -o -name \"token*\" -o -name \"auth*\" -o -name \"store*\" 2>/dev/null | head -30)",
|
||||
"Bash(grep -r \"SessionIdKey\" /Users/Apple/code_vpn/vpn/ppanel-server --include=\"*.go\" -n 2>/dev/null | head -10)",
|
||||
"Bash(ls /Users/Apple/code_vpn/vpn/ppanel-server/etc/ 2>/dev/null; ls /Users/Apple/code_vpn/vpn/ppanel-server/*.yaml 2>/dev/null; ls /Users/Apple/code_vpn/vpn/ppanel-server/*.yml 2>/dev/null)",
|
||||
"Bash(find /Users/Apple/code_vpn/vpn/ppanel-server/internal/svc -type f -name \"*.go\" | xargs ls -la)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git reset:*)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git push:*)",
|
||||
"Bash(git fetch:*)",
|
||||
"Bash(git branch:*)",
|
||||
"Bash(git merge:*)",
|
||||
"Bash(node:*)",
|
||||
"Bash(git stash:*)",
|
||||
"Bash(npx biome:*)",
|
||||
"Bash(chmod:*)",
|
||||
"Bash(bash -n /Users/Apple/code_vpn/vpn/frontend/scripts/sync-upstream.sh && echo \"语法检查通过\")",
|
||||
"Bash(grep:*)",
|
||||
"Bash(git checkout:*)",
|
||||
"Bash(python3:*)",
|
||||
"Bash(find:*)",
|
||||
"Bash(cd:*)",
|
||||
"Read(//Users/Apple/.claude/**)",
|
||||
"Bash(2)",
|
||||
"Bash(claude mcp:*)",
|
||||
"Bash(mysql:*)"
|
||||
]
|
||||
},
|
||||
"enabledMcpjsonServers": ["mysql"],
|
||||
"enableAllProjectMcpServers": true
|
||||
}
|
||||
@@ -1,30 +1,29 @@
|
||||
name: Dependabot Auto Merge
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [labeled, edited]
|
||||
types: [opened, reopened, synchronize, ready_for_review, labeled]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: dependabot-auto-merge-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
merge:
|
||||
if: contains(github.event.pull_request.labels.*.name, 'dependencies')
|
||||
if: >
|
||||
github.actor == 'dependabot[bot]' &&
|
||||
github.event.pull_request.user.login == 'dependabot[bot]' &&
|
||||
contains(github.event.pull_request.labels.*.name, 'dependencies')
|
||||
name: Dependabot Auto Merge
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js environment
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install deps
|
||||
run: pnpm install
|
||||
|
||||
- name: Merge
|
||||
uses: ahmadnassri/action-dependabot-auto-merge@v2
|
||||
with:
|
||||
command: merge
|
||||
target: minor
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
- name: Enable auto-merge
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_URL: ${{ github.event.pull_request.html_url }}
|
||||
run: gh pr merge "$PR_URL" --auto --merge
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
name: PR Check
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- internal
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- internal
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: pr-check-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Lint, Check, Test and Build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: '1.3.1'
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Check
|
||||
run: bun run check
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Build
|
||||
run: bun run build
|
||||
@@ -9,20 +9,25 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 'latest'
|
||||
bun-version: '1.3.1'
|
||||
|
||||
- name: Cache Bun dependencies
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.bun
|
||||
@@ -32,7 +37,7 @@ jobs:
|
||||
${{ runner.os }}-bun-cache-
|
||||
|
||||
- name: Install deps
|
||||
run: bun install
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: bun run build
|
||||
|
||||
@@ -34,3 +34,4 @@ npm-debug.log*
|
||||
# Misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
.mcp.json
|
||||
|
||||
Binary file not shown.
@@ -4,7 +4,21 @@
|
||||
"noImage": "No Image",
|
||||
"placeholder": "Enter captcha code...",
|
||||
"refresh": "Refresh captcha",
|
||||
"required": "Please enter captcha code"
|
||||
"required": "Please enter captcha code",
|
||||
"sliderRequired": "Please complete the slider verification",
|
||||
"slider": {
|
||||
"clickToVerify": "Click to verify",
|
||||
"fail": "Try again",
|
||||
"hint": "Drag the piece to fit the puzzle",
|
||||
"success": "Verified",
|
||||
"title": "Security Verification"
|
||||
},
|
||||
"turnstile": {
|
||||
"cancel": "Cancel",
|
||||
"clickToVerify": "Click to verify",
|
||||
"success": "Verified",
|
||||
"title": "Security Verification"
|
||||
}
|
||||
},
|
||||
"check": {
|
||||
"description": "Verify your identity",
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"pending": "Pending",
|
||||
"pendingTickets": "Pending Tickets",
|
||||
"register": "Register",
|
||||
"repurchase": "Repurchase",
|
||||
"repurchase": "Renewal",
|
||||
"revenueTitle": "Revenue Statistics",
|
||||
"selectTypePlaceholder": "Select Type",
|
||||
"today": "Today",
|
||||
@@ -29,5 +29,6 @@
|
||||
"users": "Users",
|
||||
"userTitle": "User Statistics",
|
||||
"userTraffic": "User Traffic",
|
||||
"withdrawalManagement": "Withdrawal Management",
|
||||
"yesterday": "Yesterday"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"commission": "Commission",
|
||||
"days": "{{count}} days",
|
||||
"disabled": "Disabled",
|
||||
"empty": "No invite records",
|
||||
"enabled": "Enabled",
|
||||
"hasPurchased": "Purchased",
|
||||
"invitee": "Invitee",
|
||||
"inviteeGiftDays": "Invitee Gift Days",
|
||||
"inviteeId": "Invitee ID",
|
||||
"invitedAt": "Invited At",
|
||||
"inviter": "Inviter",
|
||||
"inviterGiftDays": "Inviter Gift Days",
|
||||
"inviterId": "Inviter ID",
|
||||
"loadErrorDescription": "Refresh the table or try again later.",
|
||||
"loadErrorTitle": "Failed to load invites",
|
||||
"no": "No",
|
||||
"orderCount": "Orders",
|
||||
"searchPlaceholder": "Email or phone",
|
||||
"status": "Status",
|
||||
"title": "Invite Management",
|
||||
"yes": "Yes"
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
"Email": "Email",
|
||||
"Gift": "Gift",
|
||||
"Group Management": "Group Management",
|
||||
"Invite Management": "Invite Management",
|
||||
"Login": "Login",
|
||||
"Logs & Analytics": "Logs & Analytics",
|
||||
"Maintenance": "Maintenance",
|
||||
@@ -20,6 +21,7 @@
|
||||
"Order Management": "Order Management",
|
||||
"Payment Config": "Payment Config",
|
||||
"Product Management": "Product Management",
|
||||
"Promo Management": "Promo Management",
|
||||
"Redemption Management": "Redemption Management",
|
||||
"Register": "Register",
|
||||
"Reset Subscribe": "Reset Subscribe",
|
||||
@@ -34,5 +36,6 @@
|
||||
"Traffic Details": "Traffic Details",
|
||||
"Device Group": "Device Group",
|
||||
"User Management": "User Management",
|
||||
"Users & Support": "Users & Support"
|
||||
"Users & Support": "Users & Support",
|
||||
"Withdrawal Management": "Withdrawal Management"
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
"confirmDeleteTitle": "Delete this node?",
|
||||
"copied": "Copied",
|
||||
"copy": "Copy",
|
||||
"create": "Create",
|
||||
"create": "Create Landing Node",
|
||||
"created": "Created",
|
||||
"delete": "Delete",
|
||||
"deleted": "Deleted",
|
||||
"drawerCreateTitle": "Create Node",
|
||||
"drawerCreateTitle": "Create Landing Node",
|
||||
"drawerEditTitle": "Edit Node",
|
||||
"edit": "Edit",
|
||||
"enabled": "Enabled",
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
{
|
||||
"amount": "Amount",
|
||||
"couponDiscount": "Coupon Discount",
|
||||
"confirmRefund": "Confirm refund",
|
||||
"discount": "Discount Amount",
|
||||
"feeAmount": "Fee Amount",
|
||||
"method": "Payment Method",
|
||||
"orderNumber": "Order Number",
|
||||
"refund": "Refund",
|
||||
"refundConfirmDescription": "This refund will immediately invalidate the user's subscription and deduct the related agent commission.",
|
||||
"refundConfirmTitle": "Confirm refund",
|
||||
"refundConfirmWarning": "This action cannot be repeated after the order is refunded.",
|
||||
"refundSubmitting": "Refunding...",
|
||||
"refundSuccess": "Refund completed.",
|
||||
"status": {
|
||||
"0": "Status",
|
||||
"1": "Pending",
|
||||
"2": "Paid",
|
||||
"3": "Cancelled",
|
||||
"4": "Closed",
|
||||
"5": "Completed"
|
||||
"5": "Completed",
|
||||
"6": "Refunded"
|
||||
},
|
||||
"subscribe": "Subscribe",
|
||||
"subscribePrice": "Subscription Price",
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"discount_price": "Discount Price",
|
||||
"discountDescription": "Set discount based on unit price",
|
||||
"discountPercent": "Discount Percentage",
|
||||
"appleProductId": "Apple Product ID",
|
||||
"Hour": "Hour",
|
||||
"inventory": "Subscription Limit",
|
||||
"language": "Language",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"cancel": "Cancel",
|
||||
"confirm": "Confirm",
|
||||
"confirmDelete": "Are you sure you want to delete?",
|
||||
"createPrice": "Create Promo Price",
|
||||
"createRule": "Create Rule",
|
||||
"createSuccess": "Create Success",
|
||||
"delete": "Delete",
|
||||
"deleteSuccess": "Delete Success",
|
||||
"deleteWarning": "Once deleted, data cannot be recovered. Please proceed with caution.",
|
||||
"detail": "Detail",
|
||||
"edit": "Edit",
|
||||
"editRule": "Edit Rule",
|
||||
"emptyPrices": "No promo prices",
|
||||
"emptyRules": "No promo rules",
|
||||
"emptyUsage": "No promo usage records",
|
||||
"enabled": "Enabled",
|
||||
"endTime": "End Time",
|
||||
"form": {
|
||||
"enterPromoPrice": "Enter price",
|
||||
"inactiveMonths": "Inactive Months",
|
||||
"inactiveMonthsPlaceholder": "Months without purchase",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "Rule name",
|
||||
"noDiscounts": "This subscribe has no discount quantities and cannot be configured.",
|
||||
"promoPriceLessThanOriginalPrice": "Promo price must be lower than original price",
|
||||
"promoPriceLessThanUnitPrice": "Promo price must be lower than unit price",
|
||||
"selectEndTime": "Select time",
|
||||
"selectRule": "Select rule",
|
||||
"selectStartTime": "Select time",
|
||||
"selectQuantity": "Select discount quantity",
|
||||
"selectSubscribe": "Select subscribe",
|
||||
"type": "Rule Type",
|
||||
"windowHours": "Window Hours",
|
||||
"windowHoursPlaceholder": "Hours after registration"
|
||||
},
|
||||
"loadErrorDescription": "Refresh the table or try again later.",
|
||||
"loadPricesError": "Failed to load promo prices",
|
||||
"loadRulesError": "Failed to load promo rules",
|
||||
"loadUsageError": "Failed to load promo usage",
|
||||
"name": "Name",
|
||||
"no": "No",
|
||||
"orderNo": "Order No.",
|
||||
"originalPriceHint": "Original price",
|
||||
"params": "Params",
|
||||
"prices": "Prices",
|
||||
"priority": "Priority",
|
||||
"promoPrice": "Promo Price",
|
||||
"quantity": "Quantity",
|
||||
"rule": "Rule",
|
||||
"ruleDetail": "Rule Detail",
|
||||
"rules": "Rules",
|
||||
"searchRule": "Rule name",
|
||||
"startTime": "Start Time",
|
||||
"subscribe": "Subscribe",
|
||||
"type": "Type",
|
||||
"types": {
|
||||
"campaign": "Campaign",
|
||||
"inactive_user": "Inactive User",
|
||||
"new_user": "New User"
|
||||
},
|
||||
"unitPrice": "Unit Price",
|
||||
"unitPriceHint": "Unit price",
|
||||
"updateSuccess": "Update Success",
|
||||
"usage": "Usage",
|
||||
"usedAt": "Used At",
|
||||
"userId": "User ID",
|
||||
"validityPeriod": "Validity Period",
|
||||
"yes": "Yes"
|
||||
}
|
||||
@@ -126,9 +126,10 @@
|
||||
"userSecuritySettings": "User & Security",
|
||||
"verify": {
|
||||
"captchaType": "Captcha Type",
|
||||
"captchaTypeDescription": "Choose between local image captcha (offline) or Cloudflare Turnstile",
|
||||
"captchaTypeDescription": "Choose between local image captcha, local slider captcha (offline) or Cloudflare Turnstile",
|
||||
"captchaTypeLocal": "Local Image Captcha",
|
||||
"captchaTypePlaceholder": "Select captcha type",
|
||||
"captchaTypeSlider": "Local Slider Captcha",
|
||||
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
||||
"description": "Configure captcha type and verification settings",
|
||||
"enableAdminLoginCaptcha": "Enable Admin Authentication Captcha",
|
||||
|
||||
@@ -100,10 +100,12 @@
|
||||
"manager": "Administrator",
|
||||
"memberCount": "Member Count",
|
||||
"more": "More",
|
||||
"neverLoggedIn": "Never logged in",
|
||||
"normal": "Normal",
|
||||
"next": "Next",
|
||||
"noInvitedUsers": "No invited users yet",
|
||||
"notifySettingsTitle": "Notify Settings",
|
||||
"inactive": "Inactive",
|
||||
"offline": "Offline",
|
||||
"online": "Online",
|
||||
"onlineDevices": "Online Devices",
|
||||
@@ -189,6 +191,7 @@
|
||||
"groupUpdated": "Group updated successfully",
|
||||
"upload": "Upload",
|
||||
"uploadTraffic": "Upload Traffic",
|
||||
"userStatus": "User Status",
|
||||
"userAgent": "User Agent",
|
||||
"userEmail": "Email",
|
||||
"userEmailPlaceholder": "Enter email",
|
||||
@@ -198,6 +201,7 @@
|
||||
"userName": "Username",
|
||||
"userProfile": "User Profile",
|
||||
"userGroup": "User Group",
|
||||
"active": "Active",
|
||||
"verified": "Verified",
|
||||
"viewDeviceGroup": "View Device Group",
|
||||
"viewOwner": "View Owner",
|
||||
|
||||
@@ -4,7 +4,21 @@
|
||||
"noImage": "无图片",
|
||||
"placeholder": "请输入验证码...",
|
||||
"refresh": "刷新验证码",
|
||||
"required": "请输入验证码"
|
||||
"required": "请输入验证码",
|
||||
"sliderRequired": "请完成滑块验证",
|
||||
"slider": {
|
||||
"clickToVerify": "点击进行验证",
|
||||
"fail": "请重试",
|
||||
"hint": "拖动拼图块到对应位置",
|
||||
"success": "验证成功",
|
||||
"title": "安全验证"
|
||||
},
|
||||
"turnstile": {
|
||||
"cancel": "取消",
|
||||
"clickToVerify": "点击进行验证",
|
||||
"success": "验证成功",
|
||||
"title": "安全验证"
|
||||
}
|
||||
},
|
||||
"check": {
|
||||
"description": "验证您的身份",
|
||||
|
||||
@@ -29,5 +29,6 @@
|
||||
"users": "用户",
|
||||
"userTitle": "用户统计",
|
||||
"userTraffic": "用户流量",
|
||||
"withdrawalManagement": "提现管理",
|
||||
"yesterday": "昨日"
|
||||
}
|
||||
|
||||
@@ -198,4 +198,3 @@
|
||||
"nodeGroupUsedBySubscribe": "该节点组已被订阅商品设置为默认节点组,不能设为过期节点组",
|
||||
"expiredGroupForCalculationDescription": "过期专用节点组不能参与分组计算"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"commission": "佣金",
|
||||
"days": "{{count}} 天",
|
||||
"disabled": "禁用",
|
||||
"empty": "暂无邀请记录",
|
||||
"enabled": "启用",
|
||||
"hasPurchased": "已购买",
|
||||
"invitee": "被邀请人",
|
||||
"inviteeGiftDays": "被邀请人赠送天数",
|
||||
"inviteeId": "被邀请人 ID",
|
||||
"invitedAt": "邀请时间",
|
||||
"inviter": "邀请人",
|
||||
"inviterGiftDays": "邀请人赠送天数",
|
||||
"inviterId": "邀请人 ID",
|
||||
"loadErrorDescription": "刷新表格或稍后重试。",
|
||||
"loadErrorTitle": "邀请记录加载失败",
|
||||
"no": "否",
|
||||
"orderCount": "订单数",
|
||||
"searchPlaceholder": "邮箱/手机号关键词",
|
||||
"status": "状态",
|
||||
"title": "邀请管理",
|
||||
"yes": "是"
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
"Email": "邮件",
|
||||
"Gift": "赠送",
|
||||
"Group Management": "分组管理",
|
||||
"Invite Management": "邀请管理",
|
||||
"Login": "登录",
|
||||
"Logs & Analytics": "日志与分析",
|
||||
"Maintenance": "维护",
|
||||
@@ -20,6 +21,7 @@
|
||||
"Order Management": "订单管理",
|
||||
"Payment Config": "支付配置",
|
||||
"Product Management": "商品管理",
|
||||
"Promo Management": "促销管理",
|
||||
"Redemption Management": "兑换码管理",
|
||||
"Register": "注册",
|
||||
"Reset Subscribe": "重置订阅",
|
||||
@@ -34,5 +36,6 @@
|
||||
"Traffic Details": "流量详情",
|
||||
"Device Group": "设备组",
|
||||
"User Management": "用户管理",
|
||||
"Users & Support": "用户与支持"
|
||||
"Users & Support": "用户与支持",
|
||||
"Withdrawal Management": "提现管理"
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
"confirmDeleteTitle": "删除此节点?",
|
||||
"copied": "已复制",
|
||||
"copy": "复制",
|
||||
"create": "创建",
|
||||
"create": "创建落地节点",
|
||||
"created": "已创建",
|
||||
"delete": "删除",
|
||||
"deleted": "已删除",
|
||||
"drawerCreateTitle": "创建节点",
|
||||
"drawerCreateTitle": "创建落地节点",
|
||||
"drawerEditTitle": "编辑节点",
|
||||
"edit": "编辑",
|
||||
"enabled": "已启用",
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
{
|
||||
"amount": "金额",
|
||||
"couponDiscount": "优惠券折扣",
|
||||
"confirmRefund": "确认退费",
|
||||
"discount": "折扣金额",
|
||||
"feeAmount": "手续费",
|
||||
"method": "支付方式",
|
||||
"orderNumber": "订单编号",
|
||||
"refund": "退费",
|
||||
"refundConfirmDescription": "该退费操作会使用户订阅立即失效,并扣减关联代理佣金。",
|
||||
"refundConfirmTitle": "确认退费",
|
||||
"refundConfirmWarning": "订单退费后不可再次重复执行,请谨慎操作。",
|
||||
"refundSubmitting": "退费中...",
|
||||
"refundSuccess": "退费成功。",
|
||||
"status": {
|
||||
"0": "状态",
|
||||
"1": "待支付",
|
||||
"2": "已支付",
|
||||
"3": "已取消",
|
||||
"4": "已关闭",
|
||||
"5": "已完成"
|
||||
"5": "已完成",
|
||||
"6": "已退费"
|
||||
},
|
||||
"subscribe": "订阅",
|
||||
"subscribePrice": "订阅价格",
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"discount_price": "折扣价格",
|
||||
"discountDescription": "根据单价设置折扣",
|
||||
"discountPercent": "折扣百分比",
|
||||
"appleProductId": "苹果商品ID",
|
||||
"Hour": "小时",
|
||||
"inventory": "订阅库存",
|
||||
"language": "语言",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"cancel": "取消",
|
||||
"confirm": "确认",
|
||||
"confirmDelete": "确定要删除吗?",
|
||||
"createPrice": "创建促销价",
|
||||
"createRule": "创建规则",
|
||||
"createSuccess": "创建成功",
|
||||
"delete": "删除",
|
||||
"deleteSuccess": "删除成功",
|
||||
"deleteWarning": "删除后数据无法恢复,请谨慎操作。",
|
||||
"detail": "详情",
|
||||
"edit": "编辑",
|
||||
"editRule": "编辑规则",
|
||||
"emptyPrices": "暂无商品促销价",
|
||||
"emptyRules": "暂无促销规则",
|
||||
"emptyUsage": "暂无促销使用记录",
|
||||
"enabled": "启用",
|
||||
"endTime": "结束时间",
|
||||
"form": {
|
||||
"enterPromoPrice": "输入价格",
|
||||
"inactiveMonths": "未活跃月数",
|
||||
"inactiveMonthsPlaceholder": "未购买的月数",
|
||||
"name": "名称",
|
||||
"namePlaceholder": "规则名称",
|
||||
"noDiscounts": "该订阅没有 discount 档位,不能配置促销价。",
|
||||
"promoPriceLessThanOriginalPrice": "促销价必须低于原价",
|
||||
"promoPriceLessThanUnitPrice": "促销价必须低于原价",
|
||||
"selectEndTime": "选择时间",
|
||||
"selectRule": "选择规则",
|
||||
"selectStartTime": "选择时间",
|
||||
"selectQuantity": "选择 discount 档位",
|
||||
"selectSubscribe": "选择订阅",
|
||||
"type": "规则类型",
|
||||
"windowHours": "新用户窗口小时数",
|
||||
"windowHoursPlaceholder": "注册后的小时数"
|
||||
},
|
||||
"loadErrorDescription": "请刷新表格或稍后重试。",
|
||||
"loadPricesError": "促销价加载失败",
|
||||
"loadRulesError": "促销规则加载失败",
|
||||
"loadUsageError": "促销使用记录加载失败",
|
||||
"name": "名称",
|
||||
"no": "否",
|
||||
"orderNo": "订单号",
|
||||
"originalPriceHint": "原价",
|
||||
"params": "参数",
|
||||
"prices": "商品促销价",
|
||||
"priority": "优先级",
|
||||
"promoPrice": "促销价",
|
||||
"quantity": "档位",
|
||||
"rule": "规则",
|
||||
"ruleDetail": "规则详情",
|
||||
"rules": "促销规则",
|
||||
"searchRule": "规则名称",
|
||||
"startTime": "开始时间",
|
||||
"subscribe": "订阅",
|
||||
"type": "类型",
|
||||
"types": {
|
||||
"campaign": "活动",
|
||||
"inactive_user": "回归用户",
|
||||
"new_user": "新用户"
|
||||
},
|
||||
"unitPrice": "原价",
|
||||
"unitPriceHint": "原价",
|
||||
"updateSuccess": "更新成功",
|
||||
"usage": "使用记录",
|
||||
"usedAt": "使用时间",
|
||||
"userId": "用户 ID",
|
||||
"validityPeriod": "有效期",
|
||||
"yes": "是"
|
||||
}
|
||||
@@ -126,9 +126,10 @@
|
||||
"userSecuritySettings": "用户与安全",
|
||||
"verify": {
|
||||
"captchaType": "验证码类型",
|
||||
"captchaTypeDescription": "选择本地图形验证码(离线)或 Cloudflare Turnstile",
|
||||
"captchaTypeDescription": "选择本地图形验证码、本地滑块验证码(均可离线)或 Cloudflare Turnstile",
|
||||
"captchaTypeLocal": "本地图形验证码",
|
||||
"captchaTypePlaceholder": "选择验证码类型",
|
||||
"captchaTypeSlider": "本地滑块验证码",
|
||||
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
||||
"description": "配置验证码类型和验证设置",
|
||||
"enableAdminLoginCaptcha": "启用管理端认证验证码",
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"0": "状态",
|
||||
"1": "待跟进",
|
||||
"2": "待回复",
|
||||
"3": "已解决",
|
||||
"3": "已取消",
|
||||
"4": "已关闭"
|
||||
},
|
||||
"ticketList": "工单列表",
|
||||
|
||||
@@ -34,7 +34,6 @@
|
||||
"deleteDescription": "此操作无法撤销。",
|
||||
"deleteSubscriptionDescription": "此操作无法撤销。",
|
||||
"deleteSuccess": "删除成功",
|
||||
"isDeleted": "状态",
|
||||
"deviceGroup": "设备组",
|
||||
"deviceLimit": "IP限制",
|
||||
"deviceNo": "设备编号",
|
||||
@@ -102,10 +101,12 @@
|
||||
"manager": "管理员",
|
||||
"memberCount": "成员数量",
|
||||
"more": "更多",
|
||||
"neverLoggedIn": "从未登录",
|
||||
"normal": "正常",
|
||||
"next": "下一页",
|
||||
"noInvitedUsers": "暂无邀请用户",
|
||||
"notifySettingsTitle": "通知设置",
|
||||
"inactive": "未活跃",
|
||||
"offline": "离线",
|
||||
"online": "在线",
|
||||
"onlineDevices": "在线设备",
|
||||
@@ -191,6 +192,7 @@
|
||||
"groupUpdated": "分组更新成功",
|
||||
"upload": "上传",
|
||||
"uploadTraffic": "上传流量",
|
||||
"userStatus": "用户状态",
|
||||
"userAgent": "用户代理",
|
||||
"userEmail": "邮箱",
|
||||
"userEmailPlaceholder": "输入邮箱",
|
||||
@@ -200,6 +202,7 @@
|
||||
"userName": "用户名",
|
||||
"userProfile": "用户资料",
|
||||
"userGroup": "用户分组",
|
||||
"active": "活跃",
|
||||
"verified": "已验证",
|
||||
"viewDeviceGroup": "查看设备组",
|
||||
"viewOwner": "查看所有者",
|
||||
|
||||
@@ -38,7 +38,7 @@ export function Display<T extends number | undefined | null>({
|
||||
}
|
||||
|
||||
if (type === "trafficSpeed") {
|
||||
return value ? `${formatBytes(value).replace("B", "b")}ps` : "0";
|
||||
return value ? `${value} Mbps` : "0";
|
||||
}
|
||||
|
||||
if (type === "number") {
|
||||
|
||||
@@ -49,6 +49,11 @@ export function useNavs() {
|
||||
url: "/dashboard/product",
|
||||
icon: "flat-color-icons:shop",
|
||||
},
|
||||
{
|
||||
title: t("Promo Management", "Promo Management"),
|
||||
url: "/dashboard/promo",
|
||||
icon: "flat-color-icons:briefcase",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -93,6 +98,16 @@ export function useNavs() {
|
||||
url: "/dashboard/user",
|
||||
icon: "flat-color-icons:conference-call",
|
||||
},
|
||||
{
|
||||
title: t("Withdrawal Management", "Withdrawal Management"),
|
||||
url: "/dashboard/withdrawal",
|
||||
icon: "flat-color-icons:money-transfer",
|
||||
},
|
||||
{
|
||||
title: t("Invite Management", "Invite Management"),
|
||||
url: "/dashboard/invite-management",
|
||||
icon: "flat-color-icons:add-user",
|
||||
},
|
||||
{
|
||||
title: t("Device Group", "Device Group"),
|
||||
url: "/dashboard/family",
|
||||
|
||||
@@ -35,12 +35,14 @@ initializeI18n({
|
||||
"coupon",
|
||||
"dashboard",
|
||||
"document",
|
||||
"invite",
|
||||
"log",
|
||||
"marketing",
|
||||
"menu",
|
||||
"nodes",
|
||||
"order",
|
||||
"payment",
|
||||
"promo",
|
||||
"product",
|
||||
"servers",
|
||||
"subscribe",
|
||||
|
||||
@@ -15,8 +15,14 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
const DashboardRouteLazyRouteImport = createFileRoute('/dashboard')()
|
||||
const IndexLazyRouteImport = createFileRoute('/')()
|
||||
const DashboardIndexLazyRouteImport = createFileRoute('/dashboard/')()
|
||||
const DashboardWithdrawalLazyRouteImport = createFileRoute(
|
||||
'/dashboard/withdrawal',
|
||||
)()
|
||||
const DashboardServersLazyRouteImport = createFileRoute('/dashboard/servers')()
|
||||
const DashboardNodesLazyRouteImport = createFileRoute('/dashboard/nodes')()
|
||||
const DashboardWithdrawalIndexLazyRouteImport = createFileRoute(
|
||||
'/dashboard/withdrawal/',
|
||||
)()
|
||||
const DashboardUserIndexLazyRouteImport = createFileRoute('/dashboard/user/')()
|
||||
const DashboardTicketIndexLazyRouteImport =
|
||||
createFileRoute('/dashboard/ticket/')()
|
||||
@@ -28,6 +34,8 @@ const DashboardSubscribeIndexLazyRouteImport = createFileRoute(
|
||||
const DashboardRedemptionIndexLazyRouteImport = createFileRoute(
|
||||
'/dashboard/redemption/',
|
||||
)()
|
||||
const DashboardPromoIndexLazyRouteImport =
|
||||
createFileRoute('/dashboard/promo/')()
|
||||
const DashboardProductIndexLazyRouteImport = createFileRoute(
|
||||
'/dashboard/product/',
|
||||
)()
|
||||
@@ -39,6 +47,9 @@ const DashboardOrderIndexLazyRouteImport =
|
||||
const DashboardMarketingIndexLazyRouteImport = createFileRoute(
|
||||
'/dashboard/marketing/',
|
||||
)()
|
||||
const DashboardInviteManagementIndexLazyRouteImport = createFileRoute(
|
||||
'/dashboard/invite-management/',
|
||||
)()
|
||||
const DashboardGroupIndexLazyRouteImport =
|
||||
createFileRoute('/dashboard/group/')()
|
||||
const DashboardFamilyIndexLazyRouteImport =
|
||||
@@ -109,6 +120,13 @@ const DashboardIndexLazyRoute = DashboardIndexLazyRouteImport.update({
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardWithdrawalLazyRoute = DashboardWithdrawalLazyRouteImport.update({
|
||||
id: '/withdrawal',
|
||||
path: '/withdrawal',
|
||||
getParentRoute: () => DashboardRouteLazyRoute,
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/withdrawal.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardServersLazyRoute = DashboardServersLazyRouteImport.update({
|
||||
id: '/servers',
|
||||
path: '/servers',
|
||||
@@ -123,6 +141,14 @@ const DashboardNodesLazyRoute = DashboardNodesLazyRouteImport.update({
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/nodes.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardWithdrawalIndexLazyRoute =
|
||||
DashboardWithdrawalIndexLazyRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => DashboardWithdrawalLazyRoute,
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/withdrawal/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardUserIndexLazyRoute = DashboardUserIndexLazyRouteImport.update({
|
||||
id: '/user/',
|
||||
path: '/user/',
|
||||
@@ -162,6 +188,13 @@ const DashboardRedemptionIndexLazyRoute =
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/redemption/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardPromoIndexLazyRoute = DashboardPromoIndexLazyRouteImport.update({
|
||||
id: '/promo/',
|
||||
path: '/promo/',
|
||||
getParentRoute: () => DashboardRouteLazyRoute,
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/promo/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardProductIndexLazyRoute =
|
||||
DashboardProductIndexLazyRouteImport.update({
|
||||
id: '/product/',
|
||||
@@ -193,6 +226,16 @@ const DashboardMarketingIndexLazyRoute =
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/marketing/index.lazy').then((d) => d.Route),
|
||||
)
|
||||
const DashboardInviteManagementIndexLazyRoute =
|
||||
DashboardInviteManagementIndexLazyRouteImport.update({
|
||||
id: '/invite-management/',
|
||||
path: '/invite-management/',
|
||||
getParentRoute: () => DashboardRouteLazyRoute,
|
||||
} as any).lazy(() =>
|
||||
import('./routes/dashboard/invite-management/index.lazy').then(
|
||||
(d) => d.Route,
|
||||
),
|
||||
)
|
||||
const DashboardGroupIndexLazyRoute = DashboardGroupIndexLazyRouteImport.update({
|
||||
id: '/group/',
|
||||
path: '/group/',
|
||||
@@ -346,6 +389,7 @@ export interface FileRoutesByFullPath {
|
||||
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
||||
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
||||
'/dashboard/servers': typeof DashboardServersLazyRoute
|
||||
'/dashboard/withdrawal': typeof DashboardWithdrawalLazyRouteWithChildren
|
||||
'/dashboard/': typeof DashboardIndexLazyRoute
|
||||
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
||||
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
||||
@@ -366,15 +410,18 @@ export interface FileRoutesByFullPath {
|
||||
'/dashboard/document': typeof DashboardDocumentIndexLazyRoute
|
||||
'/dashboard/family': typeof DashboardFamilyIndexLazyRoute
|
||||
'/dashboard/group': typeof DashboardGroupIndexLazyRoute
|
||||
'/dashboard/invite-management': typeof DashboardInviteManagementIndexLazyRoute
|
||||
'/dashboard/marketing': typeof DashboardMarketingIndexLazyRoute
|
||||
'/dashboard/order': typeof DashboardOrderIndexLazyRoute
|
||||
'/dashboard/payment': typeof DashboardPaymentIndexLazyRoute
|
||||
'/dashboard/product': typeof DashboardProductIndexLazyRoute
|
||||
'/dashboard/promo': typeof DashboardPromoIndexLazyRoute
|
||||
'/dashboard/redemption': typeof DashboardRedemptionIndexLazyRoute
|
||||
'/dashboard/subscribe': typeof DashboardSubscribeIndexLazyRoute
|
||||
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
||||
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
||||
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
||||
'/dashboard/withdrawal/': typeof DashboardWithdrawalIndexLazyRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexLazyRoute
|
||||
@@ -400,15 +447,18 @@ export interface FileRoutesByTo {
|
||||
'/dashboard/document': typeof DashboardDocumentIndexLazyRoute
|
||||
'/dashboard/family': typeof DashboardFamilyIndexLazyRoute
|
||||
'/dashboard/group': typeof DashboardGroupIndexLazyRoute
|
||||
'/dashboard/invite-management': typeof DashboardInviteManagementIndexLazyRoute
|
||||
'/dashboard/marketing': typeof DashboardMarketingIndexLazyRoute
|
||||
'/dashboard/order': typeof DashboardOrderIndexLazyRoute
|
||||
'/dashboard/payment': typeof DashboardPaymentIndexLazyRoute
|
||||
'/dashboard/product': typeof DashboardProductIndexLazyRoute
|
||||
'/dashboard/promo': typeof DashboardPromoIndexLazyRoute
|
||||
'/dashboard/redemption': typeof DashboardRedemptionIndexLazyRoute
|
||||
'/dashboard/subscribe': typeof DashboardSubscribeIndexLazyRoute
|
||||
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
||||
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
||||
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
||||
'/dashboard/withdrawal': typeof DashboardWithdrawalIndexLazyRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
@@ -416,6 +466,7 @@ export interface FileRoutesById {
|
||||
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
||||
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
||||
'/dashboard/servers': typeof DashboardServersLazyRoute
|
||||
'/dashboard/withdrawal': typeof DashboardWithdrawalLazyRouteWithChildren
|
||||
'/dashboard/': typeof DashboardIndexLazyRoute
|
||||
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
||||
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
||||
@@ -436,15 +487,18 @@ export interface FileRoutesById {
|
||||
'/dashboard/document/': typeof DashboardDocumentIndexLazyRoute
|
||||
'/dashboard/family/': typeof DashboardFamilyIndexLazyRoute
|
||||
'/dashboard/group/': typeof DashboardGroupIndexLazyRoute
|
||||
'/dashboard/invite-management/': typeof DashboardInviteManagementIndexLazyRoute
|
||||
'/dashboard/marketing/': typeof DashboardMarketingIndexLazyRoute
|
||||
'/dashboard/order/': typeof DashboardOrderIndexLazyRoute
|
||||
'/dashboard/payment/': typeof DashboardPaymentIndexLazyRoute
|
||||
'/dashboard/product/': typeof DashboardProductIndexLazyRoute
|
||||
'/dashboard/promo/': typeof DashboardPromoIndexLazyRoute
|
||||
'/dashboard/redemption/': typeof DashboardRedemptionIndexLazyRoute
|
||||
'/dashboard/subscribe/': typeof DashboardSubscribeIndexLazyRoute
|
||||
'/dashboard/system/': typeof DashboardSystemIndexLazyRoute
|
||||
'/dashboard/ticket/': typeof DashboardTicketIndexLazyRoute
|
||||
'/dashboard/user/': typeof DashboardUserIndexLazyRoute
|
||||
'/dashboard/withdrawal/': typeof DashboardWithdrawalIndexLazyRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
@@ -453,6 +507,7 @@ export interface FileRouteTypes {
|
||||
| '/dashboard'
|
||||
| '/dashboard/nodes'
|
||||
| '/dashboard/servers'
|
||||
| '/dashboard/withdrawal'
|
||||
| '/dashboard/'
|
||||
| '/dashboard/log/balance'
|
||||
| '/dashboard/log/commission'
|
||||
@@ -473,15 +528,18 @@ export interface FileRouteTypes {
|
||||
| '/dashboard/document'
|
||||
| '/dashboard/family'
|
||||
| '/dashboard/group'
|
||||
| '/dashboard/invite-management'
|
||||
| '/dashboard/marketing'
|
||||
| '/dashboard/order'
|
||||
| '/dashboard/payment'
|
||||
| '/dashboard/product'
|
||||
| '/dashboard/promo'
|
||||
| '/dashboard/redemption'
|
||||
| '/dashboard/subscribe'
|
||||
| '/dashboard/system'
|
||||
| '/dashboard/ticket'
|
||||
| '/dashboard/user'
|
||||
| '/dashboard/withdrawal/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/'
|
||||
@@ -507,21 +565,25 @@ export interface FileRouteTypes {
|
||||
| '/dashboard/document'
|
||||
| '/dashboard/family'
|
||||
| '/dashboard/group'
|
||||
| '/dashboard/invite-management'
|
||||
| '/dashboard/marketing'
|
||||
| '/dashboard/order'
|
||||
| '/dashboard/payment'
|
||||
| '/dashboard/product'
|
||||
| '/dashboard/promo'
|
||||
| '/dashboard/redemption'
|
||||
| '/dashboard/subscribe'
|
||||
| '/dashboard/system'
|
||||
| '/dashboard/ticket'
|
||||
| '/dashboard/user'
|
||||
| '/dashboard/withdrawal'
|
||||
id:
|
||||
| '__root__'
|
||||
| '/'
|
||||
| '/dashboard'
|
||||
| '/dashboard/nodes'
|
||||
| '/dashboard/servers'
|
||||
| '/dashboard/withdrawal'
|
||||
| '/dashboard/'
|
||||
| '/dashboard/log/balance'
|
||||
| '/dashboard/log/commission'
|
||||
@@ -542,15 +604,18 @@ export interface FileRouteTypes {
|
||||
| '/dashboard/document/'
|
||||
| '/dashboard/family/'
|
||||
| '/dashboard/group/'
|
||||
| '/dashboard/invite-management/'
|
||||
| '/dashboard/marketing/'
|
||||
| '/dashboard/order/'
|
||||
| '/dashboard/payment/'
|
||||
| '/dashboard/product/'
|
||||
| '/dashboard/promo/'
|
||||
| '/dashboard/redemption/'
|
||||
| '/dashboard/subscribe/'
|
||||
| '/dashboard/system/'
|
||||
| '/dashboard/ticket/'
|
||||
| '/dashboard/user/'
|
||||
| '/dashboard/withdrawal/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
@@ -581,6 +646,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof DashboardIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/withdrawal': {
|
||||
id: '/dashboard/withdrawal'
|
||||
path: '/withdrawal'
|
||||
fullPath: '/dashboard/withdrawal'
|
||||
preLoaderRoute: typeof DashboardWithdrawalLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/servers': {
|
||||
id: '/dashboard/servers'
|
||||
path: '/servers'
|
||||
@@ -595,6 +667,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof DashboardNodesLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/withdrawal/': {
|
||||
id: '/dashboard/withdrawal/'
|
||||
path: '/'
|
||||
fullPath: '/dashboard/withdrawal/'
|
||||
preLoaderRoute: typeof DashboardWithdrawalIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardWithdrawalLazyRoute
|
||||
}
|
||||
'/dashboard/user/': {
|
||||
id: '/dashboard/user/'
|
||||
path: '/user'
|
||||
@@ -630,6 +709,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof DashboardRedemptionIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/promo/': {
|
||||
id: '/dashboard/promo/'
|
||||
path: '/promo'
|
||||
fullPath: '/dashboard/promo'
|
||||
preLoaderRoute: typeof DashboardPromoIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/product/': {
|
||||
id: '/dashboard/product/'
|
||||
path: '/product'
|
||||
@@ -658,6 +744,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof DashboardMarketingIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/invite-management/': {
|
||||
id: '/dashboard/invite-management/'
|
||||
path: '/invite-management'
|
||||
fullPath: '/dashboard/invite-management'
|
||||
preLoaderRoute: typeof DashboardInviteManagementIndexLazyRouteImport
|
||||
parentRoute: typeof DashboardRouteLazyRoute
|
||||
}
|
||||
'/dashboard/group/': {
|
||||
id: '/dashboard/group/'
|
||||
path: '/group'
|
||||
@@ -794,9 +887,24 @@ declare module '@tanstack/react-router' {
|
||||
}
|
||||
}
|
||||
|
||||
interface DashboardWithdrawalLazyRouteChildren {
|
||||
DashboardWithdrawalIndexLazyRoute: typeof DashboardWithdrawalIndexLazyRoute
|
||||
}
|
||||
|
||||
const DashboardWithdrawalLazyRouteChildren: DashboardWithdrawalLazyRouteChildren =
|
||||
{
|
||||
DashboardWithdrawalIndexLazyRoute: DashboardWithdrawalIndexLazyRoute,
|
||||
}
|
||||
|
||||
const DashboardWithdrawalLazyRouteWithChildren =
|
||||
DashboardWithdrawalLazyRoute._addFileChildren(
|
||||
DashboardWithdrawalLazyRouteChildren,
|
||||
)
|
||||
|
||||
interface DashboardRouteLazyRouteChildren {
|
||||
DashboardNodesLazyRoute: typeof DashboardNodesLazyRoute
|
||||
DashboardServersLazyRoute: typeof DashboardServersLazyRoute
|
||||
DashboardWithdrawalLazyRoute: typeof DashboardWithdrawalLazyRouteWithChildren
|
||||
DashboardIndexLazyRoute: typeof DashboardIndexLazyRoute
|
||||
DashboardLogBalanceLazyRoute: typeof DashboardLogBalanceLazyRoute
|
||||
DashboardLogCommissionLazyRoute: typeof DashboardLogCommissionLazyRoute
|
||||
@@ -817,10 +925,12 @@ interface DashboardRouteLazyRouteChildren {
|
||||
DashboardDocumentIndexLazyRoute: typeof DashboardDocumentIndexLazyRoute
|
||||
DashboardFamilyIndexLazyRoute: typeof DashboardFamilyIndexLazyRoute
|
||||
DashboardGroupIndexLazyRoute: typeof DashboardGroupIndexLazyRoute
|
||||
DashboardInviteManagementIndexLazyRoute: typeof DashboardInviteManagementIndexLazyRoute
|
||||
DashboardMarketingIndexLazyRoute: typeof DashboardMarketingIndexLazyRoute
|
||||
DashboardOrderIndexLazyRoute: typeof DashboardOrderIndexLazyRoute
|
||||
DashboardPaymentIndexLazyRoute: typeof DashboardPaymentIndexLazyRoute
|
||||
DashboardProductIndexLazyRoute: typeof DashboardProductIndexLazyRoute
|
||||
DashboardPromoIndexLazyRoute: typeof DashboardPromoIndexLazyRoute
|
||||
DashboardRedemptionIndexLazyRoute: typeof DashboardRedemptionIndexLazyRoute
|
||||
DashboardSubscribeIndexLazyRoute: typeof DashboardSubscribeIndexLazyRoute
|
||||
DashboardSystemIndexLazyRoute: typeof DashboardSystemIndexLazyRoute
|
||||
@@ -831,6 +941,7 @@ interface DashboardRouteLazyRouteChildren {
|
||||
const DashboardRouteLazyRouteChildren: DashboardRouteLazyRouteChildren = {
|
||||
DashboardNodesLazyRoute: DashboardNodesLazyRoute,
|
||||
DashboardServersLazyRoute: DashboardServersLazyRoute,
|
||||
DashboardWithdrawalLazyRoute: DashboardWithdrawalLazyRouteWithChildren,
|
||||
DashboardIndexLazyRoute: DashboardIndexLazyRoute,
|
||||
DashboardLogBalanceLazyRoute: DashboardLogBalanceLazyRoute,
|
||||
DashboardLogCommissionLazyRoute: DashboardLogCommissionLazyRoute,
|
||||
@@ -851,10 +962,13 @@ const DashboardRouteLazyRouteChildren: DashboardRouteLazyRouteChildren = {
|
||||
DashboardDocumentIndexLazyRoute: DashboardDocumentIndexLazyRoute,
|
||||
DashboardFamilyIndexLazyRoute: DashboardFamilyIndexLazyRoute,
|
||||
DashboardGroupIndexLazyRoute: DashboardGroupIndexLazyRoute,
|
||||
DashboardInviteManagementIndexLazyRoute:
|
||||
DashboardInviteManagementIndexLazyRoute,
|
||||
DashboardMarketingIndexLazyRoute: DashboardMarketingIndexLazyRoute,
|
||||
DashboardOrderIndexLazyRoute: DashboardOrderIndexLazyRoute,
|
||||
DashboardPaymentIndexLazyRoute: DashboardPaymentIndexLazyRoute,
|
||||
DashboardProductIndexLazyRoute: DashboardProductIndexLazyRoute,
|
||||
DashboardPromoIndexLazyRoute: DashboardPromoIndexLazyRoute,
|
||||
DashboardRedemptionIndexLazyRoute: DashboardRedemptionIndexLazyRoute,
|
||||
DashboardSubscribeIndexLazyRoute: DashboardSubscribeIndexLazyRoute,
|
||||
DashboardSystemIndexLazyRoute: DashboardSystemIndexLazyRoute,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createLazyFileRoute } from "@tanstack/react-router";
|
||||
import InviteManagement from "@/sections/invite";
|
||||
|
||||
export const Route = createLazyFileRoute("/dashboard/invite-management/")({
|
||||
component: InviteManagement,
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createLazyFileRoute } from "@tanstack/react-router";
|
||||
import PromoPage from "@/sections/promo";
|
||||
|
||||
export const Route = createLazyFileRoute("/dashboard/promo/")({
|
||||
component: PromoPage,
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createLazyFileRoute } from "@tanstack/react-router";
|
||||
import WithdrawalManagementPage from "@/sections/withdrawal";
|
||||
|
||||
export const Route = createLazyFileRoute("/dashboard/withdrawal")({
|
||||
component: WithdrawalManagementPage,
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createLazyFileRoute } from "@tanstack/react-router";
|
||||
import WithdrawalPage from "@/sections/withdrawal";
|
||||
|
||||
export const Route = createLazyFileRoute("/dashboard/withdrawal/")({
|
||||
component: WithdrawalPage,
|
||||
});
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import {
|
||||
resetPassword,
|
||||
userLogin,
|
||||
userRegister,
|
||||
} from "@workspace/ui/services/common/auth";
|
||||
adminLogin,
|
||||
adminResetPassword,
|
||||
} from "@workspace/ui/services/admin/auth";
|
||||
import { userRegister } from "@workspace/ui/services/common/auth";
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -42,7 +42,7 @@ export default function EmailAuthForm() {
|
||||
try {
|
||||
switch (type) {
|
||||
case "login": {
|
||||
const login = await userLogin(params);
|
||||
const login = await adminLogin(params);
|
||||
toast.success(t("login.success", "Login successful!"));
|
||||
onLogin(login.data.data?.token);
|
||||
break;
|
||||
@@ -54,7 +54,7 @@ export default function EmailAuthForm() {
|
||||
break;
|
||||
}
|
||||
case "reset":
|
||||
await resetPassword(params);
|
||||
await adminResetPassword(params);
|
||||
toast.success(t("reset.success", "Password reset successful!"));
|
||||
setType("login");
|
||||
break;
|
||||
|
||||
@@ -15,8 +15,9 @@ import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import { useGlobalStore } from "@/stores/global";
|
||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
||||
|
||||
export default function LoginForm({
|
||||
loading,
|
||||
@@ -38,6 +39,7 @@ export default function LoginForm({
|
||||
|
||||
const isTurnstile = verify.captcha_type === "turnstile";
|
||||
const isLocal = verify.captcha_type === "local";
|
||||
const isSlider = verify.captcha_type === "slider";
|
||||
const captchaEnabled = verify.enable_admin_login_captcha;
|
||||
|
||||
const formSchema = z.object({
|
||||
@@ -53,14 +55,26 @@ export default function LoginForm({
|
||||
captchaEnabled && isLocal
|
||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||
: z.string().optional(),
|
||||
slider_token:
|
||||
captchaEnabled && isSlider
|
||||
? z
|
||||
.string()
|
||||
.min(1, t("captcha.sliderRequired", "Please complete the slider"))
|
||||
: z.string().optional(),
|
||||
});
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: initialValues,
|
||||
defaultValues: {
|
||||
cf_token: "",
|
||||
captcha_code: "",
|
||||
slider_token: "",
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
|
||||
const turnstile = useRef<TurnstileRef>(null);
|
||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||
const handleSubmit = form.handleSubmit((data) => {
|
||||
try {
|
||||
// Add captcha_id for local captcha
|
||||
@@ -71,6 +85,7 @@ export default function LoginForm({
|
||||
} catch (_error) {
|
||||
turnstile.current?.reset();
|
||||
localCaptcha.current?.reset();
|
||||
sliderCaptcha.current?.reset();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -143,8 +158,8 @@ export default function LoginForm({
|
||||
<FormControl>
|
||||
<LocalCaptcha
|
||||
{...field}
|
||||
ref={localCaptcha}
|
||||
onCaptchaIdChange={setCaptchaId}
|
||||
ref={localCaptcha}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -152,6 +167,20 @@ export default function LoginForm({
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{captchaEnabled && isSlider && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slider_token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SliderCaptcha {...field} ref={sliderCaptcha} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Button disabled={loading} type="submit">
|
||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||
{t("login.title", "Login")}
|
||||
|
||||
@@ -15,9 +15,10 @@ import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import { useGlobalStore } from "@/stores/global";
|
||||
import SendCode from "../send-code";
|
||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||
import SendCode from "../send-code";
|
||||
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
||||
|
||||
export default function ResetForm({
|
||||
loading,
|
||||
@@ -40,6 +41,7 @@ export default function ResetForm({
|
||||
|
||||
const isTurnstile = verify.captcha_type === "turnstile";
|
||||
const isLocal = verify.captcha_type === "local";
|
||||
const isSlider = verify.captcha_type === "slider";
|
||||
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
||||
|
||||
const formSchema = z.object({
|
||||
@@ -56,14 +58,26 @@ export default function ResetForm({
|
||||
captchaEnabled && isLocal
|
||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||
: z.string().nullish(),
|
||||
slider_token:
|
||||
captchaEnabled && isSlider
|
||||
? z
|
||||
.string()
|
||||
.min(1, t("captcha.sliderRequired", "Please complete the slider"))
|
||||
: z.string().optional(),
|
||||
});
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: initialValues,
|
||||
defaultValues: {
|
||||
cf_token: "",
|
||||
captcha_code: "",
|
||||
slider_token: "",
|
||||
...initialValues,
|
||||
},
|
||||
});
|
||||
|
||||
const turnstile = useRef<TurnstileRef>(null);
|
||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||
const handleSubmit = form.handleSubmit((data) => {
|
||||
try {
|
||||
// Add captcha_id for local captcha
|
||||
@@ -74,6 +88,7 @@ export default function ResetForm({
|
||||
} catch (_error) {
|
||||
turnstile.current?.reset();
|
||||
localCaptcha.current?.reset();
|
||||
sliderCaptcha.current?.reset();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -173,8 +188,8 @@ export default function ResetForm({
|
||||
<FormControl>
|
||||
<LocalCaptcha
|
||||
{...field}
|
||||
ref={localCaptcha}
|
||||
onCaptchaIdChange={setCaptchaId}
|
||||
ref={localCaptcha}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
@@ -182,6 +197,20 @@ export default function ResetForm({
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{captchaEnabled && isSlider && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slider_token"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormControl>
|
||||
<SliderCaptcha {...field} ref={sliderCaptcha} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<Button disabled={loading} type="submit">
|
||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||
{t("reset.title", "Reset Password")}
|
||||
|
||||
@@ -2,7 +2,13 @@ import { Button } from "@workspace/ui/components/button";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
import { adminGenerateCaptcha } from "@workspace/ui/services/admin/auth";
|
||||
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
|
||||
|
||||
import {
|
||||
type RefObject,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export interface LocalCaptchaRef {
|
||||
@@ -15,80 +21,85 @@ interface LocalCaptchaProps {
|
||||
onCaptchaIdChange?: (id: string) => void;
|
||||
}
|
||||
|
||||
const LocalCaptcha = forwardRef<LocalCaptchaRef, LocalCaptchaProps>(
|
||||
({ value, onChange, onCaptchaIdChange }, ref) => {
|
||||
const { t } = useTranslation("auth");
|
||||
const [captchaImage, setCaptchaImage] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const LocalCaptcha = ({
|
||||
value,
|
||||
onChange,
|
||||
onCaptchaIdChange,
|
||||
ref,
|
||||
}: LocalCaptchaProps & { ref?: RefObject<LocalCaptchaRef | null> }) => {
|
||||
const { t } = useTranslation("auth");
|
||||
const [captchaImage, setCaptchaImage] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetchCaptcha = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await adminGenerateCaptcha();
|
||||
const captchaData = res.data?.data;
|
||||
if (captchaData) {
|
||||
setCaptchaImage(captchaData.image);
|
||||
onCaptchaIdChange?.(captchaData.id);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to generate captcha:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const fetchCaptcha = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await adminGenerateCaptcha();
|
||||
const captchaData = res.data?.data;
|
||||
if (captchaData) {
|
||||
setCaptchaImage(captchaData.image);
|
||||
onCaptchaIdChange?.(captchaData.id);
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to generate captcha:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
useEffect(() => {
|
||||
fetchCaptcha();
|
||||
}, []);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
reset: () => {
|
||||
onChange?.("");
|
||||
fetchCaptcha();
|
||||
}, []);
|
||||
},
|
||||
}));
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
reset: () => {
|
||||
onChange?.("");
|
||||
fetchCaptcha();
|
||||
},
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
||||
value={value || ""}
|
||||
onChange={(e) => onChange?.(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<div className="relative h-10 w-32 flex-shrink-0">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center bg-muted">
|
||||
<Icon className="animate-spin" icon="mdi:loading" />
|
||||
</div>
|
||||
) : captchaImage ? (
|
||||
<img
|
||||
src={captchaImage}
|
||||
alt="captcha"
|
||||
className="h-full w-full cursor-pointer object-contain"
|
||||
onClick={fetchCaptcha}
|
||||
title={t("captcha.clickToRefresh", "Click to refresh")}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center bg-muted text-xs text-muted-foreground">
|
||||
{t("captcha.noImage", "No Image")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={fetchCaptcha}
|
||||
disabled={loading}
|
||||
title={t("captcha.refresh", "Refresh captcha")}
|
||||
>
|
||||
<Icon icon="mdi:refresh" />
|
||||
</Button>
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
className="flex-1"
|
||||
onChange={(e) => onChange?.(e.target.value)}
|
||||
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
||||
value={value || ""}
|
||||
/>
|
||||
<div className="relative h-10 w-32 flex-shrink-0">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center bg-muted">
|
||||
<Icon className="animate-spin" icon="mdi:loading" />
|
||||
</div>
|
||||
) : captchaImage ? (
|
||||
<img
|
||||
alt="captcha"
|
||||
className="h-full w-full cursor-pointer object-contain"
|
||||
height={40}
|
||||
onClick={fetchCaptcha}
|
||||
src={captchaImage}
|
||||
title={t("captcha.clickToRefresh", "Click to refresh")}
|
||||
width={120}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center bg-muted text-muted-foreground text-xs">
|
||||
{t("captcha.noImage", "No Image")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={fetchCaptcha}
|
||||
size="icon"
|
||||
title={t("captcha.refresh", "Refresh captcha")}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Icon icon="mdi:refresh" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
LocalCaptcha.displayName = "LocalCaptcha";
|
||||
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@workspace/ui/components/dialog";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
import {
|
||||
adminGenerateCaptcha,
|
||||
adminVerifyCaptchaSlider,
|
||||
} from "@workspace/ui/services/admin/auth";
|
||||
|
||||
import {
|
||||
type RefObject,
|
||||
useCallback,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export interface SliderCaptchaRef {
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
interface SliderCaptchaProps {
|
||||
value?: string;
|
||||
onChange?: (value: string) => void;
|
||||
}
|
||||
|
||||
interface TrailPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
t: number;
|
||||
}
|
||||
|
||||
const BLOCK_SIZE = 100;
|
||||
const BG_NATURAL_WIDTH = 560;
|
||||
const BG_NATURAL_HEIGHT = 280;
|
||||
|
||||
const SliderCaptcha = ({
|
||||
onChange,
|
||||
ref,
|
||||
}: SliderCaptchaProps & { ref?: RefObject<SliderCaptchaRef | null> }) => {
|
||||
const { t } = useTranslation("auth");
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [captchaId, setCaptchaId] = useState("");
|
||||
const [bgImage, setBgImage] = useState("");
|
||||
const [blockImage, setBlockImage] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [verified, setVerified] = useState(false);
|
||||
const [status, setStatus] = useState<"idle" | "success" | "fail">("idle");
|
||||
const [blockPos, setBlockPos] = useState({ x: 0, y: 50 });
|
||||
const [shaking, setShaking] = useState(false);
|
||||
|
||||
const dragging = useRef(false);
|
||||
const startPointer = useRef({ x: 0, y: 0 });
|
||||
const startBlock = useRef({ x: 0, y: 50 });
|
||||
const dragStartTime = useRef(0);
|
||||
const trail = useRef<TrailPoint[]>([]);
|
||||
|
||||
const getContainerSize = () => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return { w: BG_NATURAL_WIDTH, h: BG_NATURAL_HEIGHT };
|
||||
return { w: el.clientWidth, h: el.clientHeight };
|
||||
};
|
||||
|
||||
const fetchCaptcha = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setStatus("idle");
|
||||
setBlockPos({ x: 0, y: 50 });
|
||||
trail.current = [];
|
||||
try {
|
||||
const res = await adminGenerateCaptcha();
|
||||
const data = res.data?.data;
|
||||
if (data) {
|
||||
setCaptchaId(data.id);
|
||||
setBgImage(data.image);
|
||||
setBlockImage(data.block_image ?? "");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to generate slider captcha:", e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleOpen = () => {
|
||||
if (verified) return;
|
||||
setOpen(true);
|
||||
fetchCaptcha();
|
||||
};
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
reset: () => {
|
||||
setVerified(false);
|
||||
onChange?.("");
|
||||
setOpen(false);
|
||||
trail.current = [];
|
||||
},
|
||||
}));
|
||||
|
||||
const onPointerDown = (e: React.PointerEvent) => {
|
||||
if (status === "success" || loading) return;
|
||||
dragging.current = true;
|
||||
dragStartTime.current = Date.now();
|
||||
trail.current = [];
|
||||
startPointer.current = { x: e.clientX, y: e.clientY };
|
||||
startBlock.current = { ...blockPos };
|
||||
(e.target as HTMLElement).setPointerCapture(e.pointerId);
|
||||
e.preventDefault();
|
||||
|
||||
const { w: _w, h: _h } = getContainerSize();
|
||||
trail.current.push({
|
||||
x: Math.round(startBlock.current.x),
|
||||
y: Math.round(startBlock.current.y),
|
||||
t: 0,
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerMove = (e: React.PointerEvent) => {
|
||||
if (!dragging.current) return;
|
||||
const { w, h } = getContainerSize();
|
||||
const scaleX = BG_NATURAL_WIDTH / w;
|
||||
const scaleY = BG_NATURAL_HEIGHT / h;
|
||||
const dx = (e.clientX - startPointer.current.x) * scaleX;
|
||||
const dy = (e.clientY - startPointer.current.y) * scaleY;
|
||||
const newX = Math.max(
|
||||
0,
|
||||
Math.min(startBlock.current.x + dx, BG_NATURAL_WIDTH - BLOCK_SIZE)
|
||||
);
|
||||
const newY = Math.max(
|
||||
0,
|
||||
Math.min(startBlock.current.y + dy, BG_NATURAL_HEIGHT - BLOCK_SIZE)
|
||||
);
|
||||
setBlockPos({ x: newX, y: newY });
|
||||
|
||||
trail.current.push({
|
||||
x: Math.round(newX),
|
||||
y: Math.round(newY),
|
||||
t: Date.now() - dragStartTime.current,
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerUp = async (e: React.PointerEvent) => {
|
||||
if (!dragging.current) return;
|
||||
dragging.current = false;
|
||||
const { w, h } = getContainerSize();
|
||||
const scaleX = BG_NATURAL_WIDTH / w;
|
||||
const scaleY = BG_NATURAL_HEIGHT / h;
|
||||
const dx = (e.clientX - startPointer.current.x) * scaleX;
|
||||
const dy = (e.clientY - startPointer.current.y) * scaleY;
|
||||
const finalX = Math.round(
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(startBlock.current.x + dx, BG_NATURAL_WIDTH - BLOCK_SIZE)
|
||||
)
|
||||
);
|
||||
const finalY = Math.round(
|
||||
Math.max(
|
||||
0,
|
||||
Math.min(startBlock.current.y + dy, BG_NATURAL_HEIGHT - BLOCK_SIZE)
|
||||
)
|
||||
);
|
||||
setBlockPos({ x: finalX, y: finalY });
|
||||
|
||||
trail.current.push({
|
||||
x: finalX,
|
||||
y: finalY,
|
||||
t: Date.now() - dragStartTime.current,
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await adminVerifyCaptchaSlider({
|
||||
id: captchaId,
|
||||
x: finalX,
|
||||
y: finalY,
|
||||
trail: JSON.stringify(trail.current),
|
||||
});
|
||||
const token = res.data?.data?.token;
|
||||
if (token) {
|
||||
setStatus("success");
|
||||
setTimeout(() => {
|
||||
setVerified(true);
|
||||
onChange?.(token);
|
||||
setOpen(false);
|
||||
}, 600);
|
||||
} else {
|
||||
triggerFail();
|
||||
}
|
||||
} catch {
|
||||
triggerFail();
|
||||
}
|
||||
};
|
||||
|
||||
const triggerFail = () => {
|
||||
setStatus("fail");
|
||||
setShaking(true);
|
||||
setTimeout(() => {
|
||||
setShaking(false);
|
||||
fetchCaptcha();
|
||||
}, 800);
|
||||
};
|
||||
|
||||
const blockLeftPct = (blockPos.x / BG_NATURAL_WIDTH) * 100;
|
||||
const blockTopPct = (blockPos.y / BG_NATURAL_HEIGHT) * 100;
|
||||
const blockSizeWPct = (BLOCK_SIZE / BG_NATURAL_WIDTH) * 100;
|
||||
const blockSizeHPct = (BLOCK_SIZE / BG_NATURAL_HEIGHT) * 100;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Trigger button */}
|
||||
<button
|
||||
className={`relative flex w-full items-center gap-3 rounded-md border px-4 py-3 text-sm transition-colors ${
|
||||
verified
|
||||
? "border-green-400 bg-green-50 text-green-700 dark:bg-green-950/30"
|
||||
: "border-input bg-background hover:bg-muted"
|
||||
}`}
|
||||
onClick={handleOpen}
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
className={`relative flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${
|
||||
verified ? "bg-green-500" : "bg-primary"
|
||||
}`}
|
||||
>
|
||||
{verified ? (
|
||||
<Icon className="text-white text-xs" icon="mdi:check" />
|
||||
) : (
|
||||
<>
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60" />
|
||||
<span className="relative inline-flex h-3 w-3 rounded-full bg-primary" />
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
<span className={verified ? "font-medium" : "text-muted-foreground"}>
|
||||
{verified
|
||||
? t("captcha.slider.success", "Verified")
|
||||
: t("captcha.slider.clickToVerify", "Click to verify")}
|
||||
</span>
|
||||
{verified && (
|
||||
<Icon className="ml-auto text-green-500" icon="mdi:check-circle" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Slider dialog */}
|
||||
<Dialog
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setOpen(false);
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<DialogContent className="select-none p-6 sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t("captcha.slider.title", "Security Verification")}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div
|
||||
className={`relative w-full overflow-hidden rounded-md bg-muted ${
|
||||
shaking ? "animate-[shake_0.4s_ease-in-out]" : ""
|
||||
}`}
|
||||
ref={containerRef}
|
||||
style={{
|
||||
paddingTop: `${(BG_NATURAL_HEIGHT / BG_NATURAL_WIDTH) * 100}%`,
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<Icon className="animate-spin text-2xl" icon="mdi:loading" />
|
||||
</div>
|
||||
) : bgImage ? (
|
||||
<>
|
||||
<img
|
||||
alt="captcha background"
|
||||
className="absolute inset-0 h-full w-full"
|
||||
draggable={false}
|
||||
height={BG_NATURAL_HEIGHT}
|
||||
src={bgImage}
|
||||
width={BG_NATURAL_WIDTH}
|
||||
/>
|
||||
{blockImage && (
|
||||
<img
|
||||
alt="captcha block"
|
||||
className="absolute cursor-grab active:cursor-grabbing"
|
||||
draggable={false}
|
||||
height={BG_NATURAL_HEIGHT}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={onPointerUp}
|
||||
src={blockImage}
|
||||
style={{
|
||||
filter:
|
||||
status === "success"
|
||||
? "drop-shadow(0 0 3px rgba(74,222,128,0.9))"
|
||||
: status === "fail"
|
||||
? "drop-shadow(0 0 3px rgba(248,113,113,0.9))"
|
||||
: "drop-shadow(0 0 2px rgba(255,255,255,0.7))",
|
||||
left: `${blockLeftPct}%`,
|
||||
top: `${blockTopPct}%`,
|
||||
width: `${blockSizeWPct}%`,
|
||||
height: `${blockSizeHPct}%`,
|
||||
touchAction: "none",
|
||||
}}
|
||||
width={BG_NATURAL_WIDTH}
|
||||
/>
|
||||
)}
|
||||
{status !== "idle" && (
|
||||
<div
|
||||
className={`absolute inset-0 flex items-center justify-center font-medium text-sm ${
|
||||
status === "success"
|
||||
? "bg-green-500/20 text-green-700"
|
||||
: "bg-red-500/20 text-red-700"
|
||||
}`}
|
||||
>
|
||||
{status === "success"
|
||||
? t("captcha.slider.success", "Verified")
|
||||
: t("captcha.slider.fail", "Try again")}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-muted-foreground text-xs">
|
||||
{t("captcha.slider.hint", "Drag the piece to fit the puzzle")}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
className="w-full"
|
||||
disabled={loading}
|
||||
onClick={fetchCaptcha}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<Icon icon="mdi:refresh" />
|
||||
{t("captcha.clickToRefresh", "Refresh")}
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<style>{`
|
||||
@keyframes shake {
|
||||
0%, 100% { transform: translateX(0); }
|
||||
20% { transform: translateX(-8px); }
|
||||
40% { transform: translateX(8px); }
|
||||
60% { transform: translateX(-6px); }
|
||||
80% { transform: translateX(6px); }
|
||||
}
|
||||
`}</style>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
SliderCaptcha.displayName = "SliderCaptcha";
|
||||
|
||||
export default SliderCaptcha;
|
||||
@@ -1,5 +1,18 @@
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@workspace/ui/components/dialog";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
import { useTheme } from "next-themes";
|
||||
import { type RefObject, useEffect, useImperativeHandle } from "react";
|
||||
import {
|
||||
type RefObject,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Turnstile, { useTurnstile } from "react-turnstile";
|
||||
|
||||
@@ -23,43 +36,119 @@ const CloudFlareTurnstile = function CloudFlareTurnstile({
|
||||
const { common } = useGlobalStore();
|
||||
const { verify } = common;
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { i18n } = useTranslation();
|
||||
const { i18n, t } = useTranslation("auth");
|
||||
const locale = i18n.language;
|
||||
const turnstile = useTurnstile();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [verified, setVerified] = useState(false);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
reset: () => turnstile.reset(),
|
||||
reset: () => {
|
||||
setVerified(false);
|
||||
onChange("");
|
||||
turnstile.reset();
|
||||
},
|
||||
}),
|
||||
[turnstile]
|
||||
[turnstile, onChange]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (value === "") {
|
||||
setVerified(false);
|
||||
turnstile.reset();
|
||||
}
|
||||
}, [turnstile, value]);
|
||||
|
||||
const handleOpen = () => {
|
||||
if (verified) return;
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
if (!verify.turnstile_site_key) return null;
|
||||
|
||||
return (
|
||||
verify.turnstile_site_key && (
|
||||
<Turnstile
|
||||
fixedSize
|
||||
id={id}
|
||||
language={locale.toLowerCase()}
|
||||
onExpire={() => {
|
||||
onChange();
|
||||
turnstile.reset();
|
||||
<>
|
||||
{/* Trigger button */}
|
||||
<button
|
||||
className={`relative flex w-full items-center gap-3 rounded-md border px-4 py-3 text-sm transition-colors ${
|
||||
verified
|
||||
? "border-green-400 bg-green-50 text-green-700 dark:bg-green-950/30"
|
||||
: "border-input bg-background hover:bg-muted"
|
||||
}`}
|
||||
onClick={handleOpen}
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
className={`relative flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${
|
||||
verified ? "bg-green-500" : "bg-primary"
|
||||
}`}
|
||||
>
|
||||
{verified ? (
|
||||
<Icon className="text-white text-xs" icon="mdi:check" />
|
||||
) : (
|
||||
<>
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60" />
|
||||
<span className="relative inline-flex h-3 w-3 rounded-full bg-primary" />
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
<span className={verified ? "font-medium" : "text-muted-foreground"}>
|
||||
{verified
|
||||
? t("captcha.turnstile.success", "Verified")
|
||||
: t("captcha.turnstile.clickToVerify", "Click to verify")}
|
||||
</span>
|
||||
{verified && (
|
||||
<Icon className="ml-auto text-green-500" icon="mdi:check-circle" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Turnstile dialog */}
|
||||
<Dialog
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setOpen(false);
|
||||
}}
|
||||
onTimeout={() => {
|
||||
onChange();
|
||||
turnstile.reset();
|
||||
}}
|
||||
onVerify={(token) => onChange(token)}
|
||||
sitekey={verify.turnstile_site_key}
|
||||
theme={resolvedTheme as "light" | "dark"}
|
||||
/>
|
||||
)
|
||||
open={open}
|
||||
>
|
||||
<DialogContent className="flex w-auto flex-col items-center gap-4 p-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t("captcha.turnstile.title", "Security Verification")}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Turnstile
|
||||
fixedSize
|
||||
id={id}
|
||||
language={locale.toLowerCase()}
|
||||
onExpire={() => {
|
||||
onChange("");
|
||||
turnstile.reset();
|
||||
}}
|
||||
onTimeout={() => {
|
||||
onChange("");
|
||||
turnstile.reset();
|
||||
}}
|
||||
onVerify={(token) => {
|
||||
setVerified(true);
|
||||
onChange(token);
|
||||
setTimeout(() => setOpen(false), 400);
|
||||
}}
|
||||
sitekey={verify.turnstile_site_key}
|
||||
theme={resolvedTheme as "light" | "dark"}
|
||||
/>
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={() => setOpen(false)}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
{t("captcha.turnstile.cancel", "Cancel")}
|
||||
</Button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -241,11 +241,11 @@ export default function Statistics() {
|
||||
iconBg: "bg-green-100 dark:bg-green-900/30",
|
||||
},
|
||||
{
|
||||
title: t("pendingTickets", "Pending Tickets"),
|
||||
title: t("withdrawalManagement", "提现管理"),
|
||||
value: TicketTotal || 0,
|
||||
subtitle: t("pending", "Pending"),
|
||||
icon: "uil:clipboard-notes",
|
||||
href: "/dashboard/ticket",
|
||||
href: "/dashboard/withdrawal",
|
||||
color: "text-red-600 dark:text-red-400",
|
||||
iconBg: "bg-red-100 dark:bg-red-900/30",
|
||||
},
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
@@ -11,17 +12,16 @@ import {
|
||||
} from "@workspace/ui/components/card";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { Label } from "@workspace/ui/components/label";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getGroupConfig,
|
||||
getNodeGroupList,
|
||||
getRecalculationStatus,
|
||||
recalculateGroup,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function AverageModeTab() {
|
||||
const { t } = useTranslation("group");
|
||||
@@ -147,7 +147,9 @@ export default function AverageModeTab() {
|
||||
{/* Configuration Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("averageModeConfig", "Average Mode Configuration")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("averageModeConfig", "Average Mode Configuration")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"averageModeDescription",
|
||||
@@ -162,15 +164,18 @@ export default function AverageModeTab() {
|
||||
{t("availableNodeGroups", "Available Node Groups")}
|
||||
</Label>
|
||||
<Input
|
||||
id="node_group_count"
|
||||
type="number"
|
||||
min={1}
|
||||
value={averageConfig.node_group_count}
|
||||
readOnly
|
||||
className="bg-muted"
|
||||
id="node_group_count"
|
||||
min={1}
|
||||
readOnly
|
||||
type="number"
|
||||
value={averageConfig.node_group_count}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("nodeGroupCountAutoCalculated", "Auto-calculated from actual node groups")}
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(
|
||||
"nodeGroupCountAutoCalculated",
|
||||
"Auto-calculated from actual node groups"
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -180,7 +185,9 @@ export default function AverageModeTab() {
|
||||
{/* Recalculation Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("groupRecalculation", "Group Recalculation")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"groupRecalculationDescription",
|
||||
@@ -192,7 +199,7 @@ export default function AverageModeTab() {
|
||||
{/* Current Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
<span className="font-medium text-sm">
|
||||
{t("currentStatus", "Current Status")}
|
||||
</span>
|
||||
{loadingStatus ? (
|
||||
@@ -224,14 +231,20 @@ export default function AverageModeTab() {
|
||||
)}
|
||||
|
||||
{status?.state === "completed" && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"recalculationCompleted",
|
||||
"Recalculation completed successfully"
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status?.state === "failed" && (
|
||||
<div className="text-sm text-destructive">
|
||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
||||
<div className="text-destructive text-sm">
|
||||
{t(
|
||||
"recalculationFailed",
|
||||
"Recalculation failed. Please try again."
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -239,8 +252,8 @@ export default function AverageModeTab() {
|
||||
{/* Recalculate Button */}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleRecalculate}
|
||||
disabled={recalculating || status?.state === "running"}
|
||||
onClick={handleRecalculate}
|
||||
>
|
||||
{recalculating && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -18,12 +19,14 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@workspace/ui/components/select";
|
||||
import {
|
||||
bindNodeGroups,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { getNodeGroupList, bindNodeGroups } from "@workspace/ui/services/admin/group";
|
||||
|
||||
interface BindNodeGroupsDialogProps {
|
||||
userGroupIds: number[];
|
||||
@@ -41,7 +44,9 @@ export default function BindNodeGroupsDialog({
|
||||
const { t } = useTranslation("group");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedNodeGroupId, setSelectedNodeGroupId] = useState<number | undefined>();
|
||||
const [selectedNodeGroupId, setSelectedNodeGroupId] = useState<
|
||||
number | undefined
|
||||
>();
|
||||
|
||||
const { data: nodeGroupsData, isLoading } = useQuery({
|
||||
queryKey: ["nodeGroups"],
|
||||
@@ -78,10 +83,10 @@ export default function BindNodeGroupsDialog({
|
||||
} as API.BindNodeGroupsRequest);
|
||||
|
||||
toast.success(
|
||||
t("bindSuccess", "Successfully bound {{userGroupCount}} user groups to node group").replace(
|
||||
/{{userGroupCount}}/g,
|
||||
String(userGroupIds.length)
|
||||
)
|
||||
t(
|
||||
"bindSuccess",
|
||||
"Successfully bound {{userGroupCount}} user groups to node group"
|
||||
).replace(/{{userGroupCount}}/g, String(userGroupIds.length))
|
||||
);
|
||||
|
||||
setOpen(false);
|
||||
@@ -101,12 +106,15 @@ export default function BindNodeGroupsDialog({
|
||||
: userGroupNames.join(", ");
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(newOpen) => {
|
||||
setOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
}}>
|
||||
<Dialog
|
||||
onOpenChange={(newOpen) => {
|
||||
setOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Button size="sm" variant="outline">
|
||||
{t("bindNodeGroup", "Bind Node Group")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
@@ -129,18 +137,25 @@ export default function BindNodeGroupsDialog({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="node-group">{t("selectNodeGroup", "Select Node Group")}</Label>
|
||||
<Label htmlFor="node-group">
|
||||
{t("selectNodeGroup", "Select Node Group")}
|
||||
</Label>
|
||||
<Select
|
||||
onValueChange={(val) =>
|
||||
setSelectedNodeGroupId(Number.parseInt(val, 10) || undefined)
|
||||
}
|
||||
value={selectedNodeGroupId?.toString() || ""}
|
||||
onValueChange={(val) => setSelectedNodeGroupId(parseInt(val) || undefined)}
|
||||
>
|
||||
<SelectTrigger id="node-group" className="w-full">
|
||||
<SelectValue placeholder={t("selectNodeGroupPlaceholder", "Select a node group...")} />
|
||||
<SelectTrigger className="w-full" id="node-group">
|
||||
<SelectValue
|
||||
placeholder={t(
|
||||
"selectNodeGroupPlaceholder",
|
||||
"Select a node group..."
|
||||
)}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">
|
||||
{t("unbound", "Unbound")}
|
||||
</SelectItem>
|
||||
<SelectItem value="0">{t("unbound", "Unbound")}</SelectItem>
|
||||
{nodeGroupsData?.map((nodeGroup) => (
|
||||
<SelectItem key={nodeGroup.id} value={String(nodeGroup.id)}>
|
||||
{nodeGroup.name}
|
||||
@@ -154,16 +169,19 @@ export default function BindNodeGroupsDialog({
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onOpenChange?.(false);
|
||||
}}
|
||||
disabled={saving}
|
||||
variant="outline"
|
||||
>
|
||||
{t("cancel", "Cancel")}
|
||||
</Button>
|
||||
<Button onClick={handleBind} disabled={saving || selectedNodeGroupId === undefined}>
|
||||
<Button
|
||||
disabled={saving || selectedNodeGroupId === undefined}
|
||||
onClick={handleBind}
|
||||
>
|
||||
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t("confirm", "Confirm")}
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -22,11 +23,14 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@workspace/ui/components/table";
|
||||
import {
|
||||
getGroupHistory,
|
||||
getGroupHistoryDetail,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getGroupHistory, getGroupHistoryDetail, getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
|
||||
export default function CurrentGroupResults() {
|
||||
const { t } = useTranslation("group");
|
||||
@@ -37,7 +41,8 @@ export default function CurrentGroupResults() {
|
||||
|
||||
// User list dialog state
|
||||
const [userListOpen, setUserListOpen] = useState(false);
|
||||
const [selectedNodeGroupName, setSelectedNodeGroupName] = useState<string>("");
|
||||
const [selectedNodeGroupName, setSelectedNodeGroupName] =
|
||||
useState<string>("");
|
||||
const [userList, setUserList] = useState<any[]>([]);
|
||||
const [userListLoading, setUserListLoading] = useState(false);
|
||||
const [userListTotal, setUserListTotal] = useState(0);
|
||||
@@ -94,7 +99,10 @@ export default function CurrentGroupResults() {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
const handleShowUserList = async (nodeGroupId: number, nodeGroupName: string) => {
|
||||
const handleShowUserList = async (
|
||||
nodeGroupId: number,
|
||||
nodeGroupName: string
|
||||
) => {
|
||||
setSelectedNodeGroupName(nodeGroupName);
|
||||
setUserListOpen(true);
|
||||
setUserListLoading(true);
|
||||
@@ -132,10 +140,10 @@ export default function CurrentGroupResults() {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("currentGroupingResult", "Current Grouping Result")}</CardTitle>
|
||||
<CardDescription>
|
||||
{t("loading", "Loading...")}
|
||||
</CardDescription>
|
||||
<CardTitle>
|
||||
{t("currentGroupingResult", "Current Grouping Result")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t("loading", "Loading...")}</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
@@ -144,110 +152,144 @@ export default function CurrentGroupResults() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Latest Result Card */}
|
||||
{!latestResult ? (
|
||||
{latestResult ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("currentGroupingResult", "Current Grouping Result")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-center py-8 text-sm text-muted-foreground">
|
||||
{t("noDetails", "No details available")}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("currentGroupingResult", "Current Grouping Result")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("currentGroupingResult", "Current Grouping Result")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t("latestGroupingCalculation", "Latest grouping calculation details")}
|
||||
{t(
|
||||
"latestGroupingCalculation",
|
||||
"Latest grouping calculation details"
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Calculation Info */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium">{t("calculationInfo", "Calculation Information")}</h3>
|
||||
<h3 className="font-medium text-sm">
|
||||
{t("calculationInfo", "Calculation Information")}
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-4 rounded-lg bg-muted/50 p-4">
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("groupMode", "Group Mode")}</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.GroupMode || latestResult.group_mode) === "average"
|
||||
? t("averageMode", "Average Mode")
|
||||
: (latestResult.GroupMode || latestResult.group_mode) === "subscribe"
|
||||
? t("subscribeMode", "Subscribe Mode")
|
||||
: t("trafficMode", "Traffic Mode")}
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("groupMode", "Group Mode")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.GroupMode || latestResult.group_mode) ===
|
||||
"average"
|
||||
? t("averageMode", "Average Mode")
|
||||
: (latestResult.GroupMode || latestResult.group_mode) ===
|
||||
"subscribe"
|
||||
? t("subscribeMode", "Subscribe Mode")
|
||||
: t("trafficMode", "Traffic Mode")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("state", "State")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.State || latestResult.state) === "completed"
|
||||
? t("completed", "Completed")
|
||||
: (latestResult.State || latestResult.state) === "running"
|
||||
? t("running", "Running")
|
||||
: (latestResult.State || latestResult.state) ===
|
||||
"failed"
|
||||
? t("failed", "Failed")
|
||||
: t("idle", "Idle")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("triggerType", "Trigger Type")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.TriggerType || latestResult.trigger_type) ===
|
||||
"manual"
|
||||
? t("manualTrigger", "Manual")
|
||||
: (latestResult.TriggerType ||
|
||||
latestResult.trigger_type) === "auto"
|
||||
? t("autoTrigger", "Auto")
|
||||
: t("scheduleTrigger", "Schedule")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("successFailedCount", "Success/Failed")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.SuccessCount ||
|
||||
latestResult.success_count ||
|
||||
0}{" "}
|
||||
/{" "}
|
||||
{latestResult.FailedCount || latestResult.failed_count || 0}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("startTime", "Start Time")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.StartTime || latestResult.start_time
|
||||
? new Date(
|
||||
(latestResult.StartTime || latestResult.start_time) *
|
||||
1000
|
||||
).toLocaleString()
|
||||
: "-"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("endTime", "End Time")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.EndTime || latestResult.end_time
|
||||
? new Date(
|
||||
(latestResult.EndTime || latestResult.end_time) * 1000
|
||||
).toLocaleString()
|
||||
: "-"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("state", "State")}</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.State || latestResult.state) === "completed"
|
||||
? t("completed", "Completed")
|
||||
: (latestResult.State || latestResult.state) === "running"
|
||||
? t("running", "Running")
|
||||
: (latestResult.State || latestResult.state) === "failed"
|
||||
? t("failed", "Failed")
|
||||
: t("idle", "Idle")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("triggerType", "Trigger Type")}</div>
|
||||
<div className="font-medium">
|
||||
{(latestResult.TriggerType || latestResult.trigger_type) === "manual"
|
||||
? t("manualTrigger", "Manual")
|
||||
: (latestResult.TriggerType || latestResult.trigger_type) === "auto"
|
||||
? t("autoTrigger", "Auto")
|
||||
: t("scheduleTrigger", "Schedule")}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("successFailedCount", "Success/Failed")}</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.SuccessCount || latestResult.success_count || 0} / {latestResult.FailedCount || latestResult.failed_count || 0}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("startTime", "Start Time")}</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.StartTime || latestResult.start_time
|
||||
? new Date((latestResult.StartTime || latestResult.start_time) * 1000).toLocaleString()
|
||||
: "-"}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">{t("endTime", "End Time")}</div>
|
||||
<div className="font-medium">
|
||||
{latestResult.EndTime || latestResult.end_time
|
||||
? new Date((latestResult.EndTime || latestResult.end_time) * 1000).toLocaleString()
|
||||
: "-"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grouping Details */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium">{t("groupingDetailsStatistics", "Grouping Details Statistics")}</h3>
|
||||
<h3 className="font-medium text-sm">
|
||||
{t("groupingDetailsStatistics", "Grouping Details Statistics")}
|
||||
</h3>
|
||||
<div className="grid grid-cols-3 gap-4 rounded-lg bg-muted/50 p-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">
|
||||
{latestDetails.reduce((sum: number, d: any) => sum + (d.UserCount || d.user_count || 0), 0)}
|
||||
<div className="font-bold text-2xl">
|
||||
{latestDetails.reduce(
|
||||
(sum: number, d: any) =>
|
||||
sum + (d.UserCount || d.user_count || 0),
|
||||
0
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalUsers", "Total Users")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">
|
||||
{latestDetails.reduce((sum: number, d: any) => sum + (d.NodeCount || d.node_count || 0), 0)}
|
||||
<div className="font-bold text-2xl">
|
||||
{latestDetails.reduce(
|
||||
(sum: number, d: any) =>
|
||||
sum + (d.NodeCount || d.node_count || 0),
|
||||
0
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalNodes", "Total Nodes")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">{latestDetails.length}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="font-bold text-2xl">
|
||||
{latestDetails.length}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalNodeGroups", "Total Node Groups")}
|
||||
</div>
|
||||
</div>
|
||||
@@ -257,7 +299,7 @@ export default function CurrentGroupResults() {
|
||||
{detailsLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
{t("loading", "Loading...")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -281,26 +323,41 @@ export default function CurrentGroupResults() {
|
||||
</thead>
|
||||
<tbody>
|
||||
{latestDetails.map((detail: any, index: number) => {
|
||||
const nodeGroupId = detail.NodeGroupId || detail.node_group_id;
|
||||
const nodeGroup = nodeGroups?.find((ng) => ng.id === nodeGroupId);
|
||||
const nodeGroupName = nodeGroup?.name || `${t("idPrefix", "#")}${nodeGroupId}`;
|
||||
const userCount = detail.UserCount || detail.user_count || 0;
|
||||
const nodeGroupId =
|
||||
detail.NodeGroupId || detail.node_group_id;
|
||||
const nodeGroup = nodeGroups?.find(
|
||||
(ng) => ng.id === nodeGroupId
|
||||
);
|
||||
const nodeGroupName =
|
||||
nodeGroup?.name ||
|
||||
`${t("idPrefix", "#")}${nodeGroupId}`;
|
||||
const userCount =
|
||||
detail.UserCount || detail.user_count || 0;
|
||||
|
||||
return (
|
||||
<tr key={index}>
|
||||
<td className="border-b px-4 py-2">
|
||||
<div>
|
||||
<div className="font-medium">{nodeGroupName}</div>
|
||||
<div className="text-xs text-muted-foreground">{t("id", "ID")}: {nodeGroupId}</div>
|
||||
<div className="font-medium">
|
||||
{nodeGroupName}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("id", "ID")}: {nodeGroupId}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="border-b px-4 py-2 text-right">
|
||||
<button
|
||||
className={`font-semibold hover:underline ${
|
||||
userCount === 0 ? 'text-muted-foreground cursor-not-allowed' : 'cursor-pointer'
|
||||
userCount === 0
|
||||
? "cursor-not-allowed text-muted-foreground"
|
||||
: "cursor-pointer"
|
||||
}`}
|
||||
onClick={() => handleShowUserList(nodeGroupId, nodeGroupName)}
|
||||
disabled={userCount === 0}
|
||||
onClick={() =>
|
||||
handleShowUserList(nodeGroupId, nodeGroupName)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
{userCount}
|
||||
</button>
|
||||
@@ -316,17 +373,30 @@ export default function CurrentGroupResults() {
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-8 text-sm text-muted-foreground">
|
||||
<div className="py-8 text-center text-muted-foreground text-sm">
|
||||
{t("noDetails", "No details available")}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{t("currentGroupingResult", "Current Grouping Result")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="py-8 text-center text-muted-foreground text-sm">
|
||||
{t("noDetails", "No details available")}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* User List Dialog */}
|
||||
<Dialog open={userListOpen} onOpenChange={setUserListOpen}>
|
||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
||||
<Dialog onOpenChange={setUserListOpen} open={userListOpen}>
|
||||
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedNodeGroupName} - {t("userList", "User List")}
|
||||
@@ -339,7 +409,7 @@ export default function CurrentGroupResults() {
|
||||
{userListLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
{t("loading", "Loading...")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -355,15 +425,13 @@ export default function CurrentGroupResults() {
|
||||
{userList.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.id}</TableCell>
|
||||
<TableCell>
|
||||
{user.email || "-"}
|
||||
</TableCell>
|
||||
<TableCell>{user.email || "-"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<div className="text-center py-8 text-sm text-muted-foreground">
|
||||
<div className="py-8 text-center text-muted-foreground text-sm">
|
||||
{t("noUsers", "No users found")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,22 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@workspace/ui/components/card";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getGroupConfig,
|
||||
updateGroupConfig,
|
||||
resetGroups,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -28,6 +11,23 @@ import {
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@workspace/ui/components/alert-dialog";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@workspace/ui/components/card";
|
||||
import {
|
||||
getGroupConfig,
|
||||
resetGroups,
|
||||
updateGroupConfig,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function GroupConfig() {
|
||||
const { t } = useTranslation("group");
|
||||
@@ -47,8 +47,11 @@ export default function GroupConfig() {
|
||||
const { data } = await getGroupConfig();
|
||||
if (data.data) {
|
||||
setConfig({
|
||||
enabled: data.data.enabled || false,
|
||||
mode: (data.data.mode || "average") as "average" | "subscribe" | "traffic",
|
||||
enabled: data.data.enabled,
|
||||
mode: (data.data.mode || "average") as
|
||||
| "average"
|
||||
| "subscribe"
|
||||
| "traffic",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -79,7 +82,9 @@ export default function GroupConfig() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateMode = async (mode: "average" | "subscribe" | "traffic") => {
|
||||
const handleUpdateMode = async (
|
||||
mode: "average" | "subscribe" | "traffic"
|
||||
) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload: any = {
|
||||
@@ -101,7 +106,9 @@ export default function GroupConfig() {
|
||||
setResetting(true);
|
||||
try {
|
||||
await resetGroups({ confirm: true });
|
||||
toast.success(t("resetSuccess", "All groups have been reset successfully"));
|
||||
toast.success(
|
||||
t("resetSuccess", "All groups have been reset successfully")
|
||||
);
|
||||
setShowResetDialog(false);
|
||||
// Reload config after reset
|
||||
await loadConfig();
|
||||
@@ -129,10 +136,10 @@ export default function GroupConfig() {
|
||||
{/* Enable/Disable */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<label htmlFor="enabled" className="font-medium">
|
||||
<label className="font-medium" htmlFor="enabled">
|
||||
{t("enableGrouping", "Enable Grouping")}
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"enableGroupingDescription",
|
||||
"When enabled, users will only see nodes from their assigned group"
|
||||
@@ -140,36 +147,36 @@ export default function GroupConfig() {
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
id="enabled"
|
||||
type="checkbox"
|
||||
checked={config.enabled}
|
||||
onChange={(e) => handleUpdateEnabled(e.target.checked)}
|
||||
disabled={saving}
|
||||
className="h-4 w-4"
|
||||
disabled={saving}
|
||||
id="enabled"
|
||||
onChange={(e) => handleUpdateEnabled(e.target.checked)}
|
||||
type="checkbox"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Mode Selection */}
|
||||
{config.enabled && (
|
||||
<div className="space-y-2">
|
||||
<label className="font-medium">
|
||||
<p className="font-medium">
|
||||
{t("groupingMode", "Grouping Mode")}
|
||||
</label>
|
||||
</p>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleUpdateMode("average")}
|
||||
disabled={saving}
|
||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||
config.mode === "average"
|
||||
? "border-primary bg-primary/10"
|
||||
: "border-border hover:bg-muted"
|
||||
} ${saving ? "opacity-50 cursor-not-allowed" : ""}`}
|
||||
} ${saving ? "cursor-not-allowed opacity-50" : ""}`}
|
||||
disabled={saving}
|
||||
onClick={() => handleUpdateMode("average")}
|
||||
type="button"
|
||||
>
|
||||
<div className="font-medium">
|
||||
{t("averageMode", "Average Mode")}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"averageModeDescription",
|
||||
"Distribute users evenly across groups"
|
||||
@@ -178,19 +185,19 @@ export default function GroupConfig() {
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleUpdateMode("subscribe")}
|
||||
disabled={saving}
|
||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||
config.mode === "subscribe"
|
||||
? "border-primary bg-primary/10"
|
||||
: "border-border hover:bg-muted"
|
||||
} ${saving ? "opacity-50 cursor-not-allowed" : ""}`}
|
||||
} ${saving ? "cursor-not-allowed opacity-50" : ""}`}
|
||||
disabled={saving}
|
||||
onClick={() => handleUpdateMode("subscribe")}
|
||||
type="button"
|
||||
>
|
||||
<div className="font-medium">
|
||||
{t("subscribeMode", "Subscribe Mode")}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"subscribeModeDescription",
|
||||
"Group users by their subscription plan"
|
||||
@@ -199,19 +206,19 @@ export default function GroupConfig() {
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleUpdateMode("traffic")}
|
||||
disabled={saving}
|
||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||
config.mode === "traffic"
|
||||
? "border-primary bg-primary/10"
|
||||
: "border-border hover:bg-muted"
|
||||
} ${saving ? "opacity-50 cursor-not-allowed" : ""}`}
|
||||
} ${saving ? "cursor-not-allowed opacity-50" : ""}`}
|
||||
disabled={saving}
|
||||
onClick={() => handleUpdateMode("traffic")}
|
||||
type="button"
|
||||
>
|
||||
<div className="font-medium">
|
||||
{t("trafficMode", "Traffic Mode")}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"trafficModeDescription",
|
||||
"Group users by their traffic usage"
|
||||
@@ -223,8 +230,11 @@ export default function GroupConfig() {
|
||||
)}
|
||||
|
||||
{/* Reset Button */}
|
||||
<div className="flex justify-end pt-4 border-t">
|
||||
<AlertDialog open={showResetDialog} onOpenChange={setShowResetDialog}>
|
||||
<div className="flex justify-end border-t pt-4">
|
||||
<AlertDialog
|
||||
onOpenChange={setShowResetDialog}
|
||||
open={showResetDialog}
|
||||
>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="destructive">
|
||||
{t("resetGroups", "Reset All Groups")}
|
||||
@@ -243,14 +253,14 @@ export default function GroupConfig() {
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("cancel", "Cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogCancel>{t("cancel", "Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleResetGroups}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={handleResetGroups}
|
||||
>
|
||||
{resetting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{resetting && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
{t("confirm", "Confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
@@ -33,24 +34,27 @@ import {
|
||||
getGroupHistoryDetail,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
export default function GroupHistory() {
|
||||
const { t } = useTranslation("group");
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [selectedHistory, setSelectedHistory] = useState<API.GroupHistory | null>(null);
|
||||
const [selectedHistory, setSelectedHistory] =
|
||||
useState<API.GroupHistory | null>(null);
|
||||
const [details, setDetails] = useState<any[]>([]);
|
||||
const [nodeGroupMap, setNodeGroupMap] = useState<Map<number, string>>(new Map());
|
||||
const [nodeGroupMap, setNodeGroupMap] = useState<Map<number, string>>(
|
||||
new Map()
|
||||
);
|
||||
|
||||
// User list dialog state
|
||||
const [userListOpen, setUserListOpen] = useState(false);
|
||||
const [selectedNodeGroupName, setSelectedNodeGroupName] = useState<string>("");
|
||||
const [selectedNodeGroupName, setSelectedNodeGroupName] =
|
||||
useState<string>("");
|
||||
const [userList, setUserList] = useState<any[]>([]);
|
||||
const [userListTotal, setUserListTotal] = useState(0);
|
||||
|
||||
@@ -130,7 +134,10 @@ export default function GroupHistory() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleShowUserList = async (nodeGroupId: number, nodeGroupName: string) => {
|
||||
const handleShowUserList = async (
|
||||
nodeGroupId: number,
|
||||
nodeGroupName: string
|
||||
) => {
|
||||
setSelectedNodeGroupName(nodeGroupName);
|
||||
setUserListOpen(true);
|
||||
|
||||
@@ -166,23 +173,30 @@ export default function GroupHistory() {
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("groupHistory", "Group Calculation History")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("groupHistory", "Group Calculation History")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t("groupHistoryDescription", "View group recalculation history and results")}
|
||||
{t(
|
||||
"groupHistoryDescription",
|
||||
"View group recalculation history and results"
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ProTable<API.GroupHistory, API.GetGroupHistoryRequest>
|
||||
action={ref}
|
||||
request={async (params) => {
|
||||
const { data } = await getGroupHistory({
|
||||
page: params.page || 1,
|
||||
size: params.size || 10,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
actions={{
|
||||
render: (row: any) => [
|
||||
<Button
|
||||
key="detail"
|
||||
onClick={() => handleViewDetail(row)}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{t("viewDetail", "View Detail")}
|
||||
</Button>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
@@ -191,7 +205,8 @@ export default function GroupHistory() {
|
||||
header: t("id", "ID"),
|
||||
cell: ({ row }: { row: any }) => (
|
||||
<span className="text-muted-foreground">
|
||||
{t("idPrefix", "#")}{row.getValue("id")}
|
||||
{t("idPrefix", "#")}
|
||||
{row.getValue("id")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
@@ -220,7 +235,9 @@ export default function GroupHistory() {
|
||||
accessorKey: "total_users",
|
||||
header: t("totalUsers", "Total Users"),
|
||||
cell: ({ row }: { row: any }) => (
|
||||
<span className="font-semibold">{row.getValue("total_users")}</span>
|
||||
<span className="font-semibold">
|
||||
{row.getValue("total_users")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -231,10 +248,10 @@ export default function GroupHistory() {
|
||||
const record = row.original;
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t("successCount", "Success")}: {record.success_count}
|
||||
{" "}{t("separator", "/")}{" "}
|
||||
{t("failedCount", "Failed")}: {record.failed_count}
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("successCount", "Success")}: {record.success_count}{" "}
|
||||
{t("separator", "/")} {t("failedCount", "Failed")}:{" "}
|
||||
{record.failed_count}
|
||||
</div>
|
||||
{record.error_log && (
|
||||
<Badge variant="destructive">
|
||||
@@ -254,31 +271,30 @@ export default function GroupHistory() {
|
||||
id: "created_at",
|
||||
accessorKey: "created_at",
|
||||
header: t("createdAt", "Created At"),
|
||||
cell: ({ row }: { row: any }) => formatDate(row.getValue("created_at")),
|
||||
cell: ({ row }: { row: any }) =>
|
||||
formatDate(row.getValue("created_at")),
|
||||
},
|
||||
]}
|
||||
actions={{
|
||||
render: (row: any) => [
|
||||
<Button
|
||||
key="detail"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleViewDetail(row)}
|
||||
>
|
||||
{t("viewDetail", "View Detail")}
|
||||
</Button>,
|
||||
],
|
||||
}}
|
||||
header={{
|
||||
title: t("groupHistory", "Group Calculation History"),
|
||||
}}
|
||||
request={async (params) => {
|
||||
const { data } = await getGroupHistory({
|
||||
page: params.page || 1,
|
||||
size: params.size || 10,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Detail Dialog */}
|
||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
||||
<Dialog onOpenChange={setDetailOpen} open={detailOpen}>
|
||||
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t("groupHistoryDetail", "Group Calculation Detail")}
|
||||
@@ -292,7 +308,7 @@ export default function GroupHistory() {
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("groupMode", "Group Mode")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
@@ -300,7 +316,7 @@ export default function GroupHistory() {
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("triggerType", "Trigger Type")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
@@ -308,24 +324,27 @@ export default function GroupHistory() {
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("totalUsers", "Total Users")}
|
||||
</div>
|
||||
<div className="font-medium">{selectedHistory.total_users}</div>
|
||||
<div className="font-medium">
|
||||
{selectedHistory.total_users}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("result", "Result")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
{t("successCount", "Success")}: {selectedHistory.success_count}
|
||||
{" "}{t("separator", "/")}{" "}
|
||||
{t("failedCount", "Failed")}: {selectedHistory.failed_count}
|
||||
{t("successCount", "Success")}:{" "}
|
||||
{selectedHistory.success_count} {t("separator", "/")}{" "}
|
||||
{t("failedCount", "Failed")}:{" "}
|
||||
{selectedHistory.failed_count}
|
||||
</div>
|
||||
</div>
|
||||
{selectedHistory.start_time && (
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("startTime", "Start Time")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
@@ -335,7 +354,7 @@ export default function GroupHistory() {
|
||||
)}
|
||||
{selectedHistory.end_time && (
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("endTime", "End Time")}
|
||||
</div>
|
||||
<div className="font-medium">
|
||||
@@ -347,10 +366,10 @@ export default function GroupHistory() {
|
||||
|
||||
{selectedHistory.error_log && (
|
||||
<div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("errorMessage", "Error Message")}
|
||||
</div>
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-destructive text-sm">
|
||||
{selectedHistory.error_log}
|
||||
</div>
|
||||
</div>
|
||||
@@ -359,13 +378,13 @@ export default function GroupHistory() {
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-medium">
|
||||
<div className="mb-2 font-medium text-sm">
|
||||
{t("groupDetails", "Group Details")}
|
||||
</div>
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
{t("loading", "Loading...")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -374,24 +393,32 @@ export default function GroupHistory() {
|
||||
{/* 统计信息 */}
|
||||
<div className="mb-4 grid grid-cols-3 gap-4 rounded-lg bg-muted/50 p-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">
|
||||
{details.reduce((sum: number, d: any) => sum + (d.UserCount || d.user_count || 0), 0)}
|
||||
<div className="font-bold text-2xl">
|
||||
{details.reduce(
|
||||
(sum: number, d: any) =>
|
||||
sum + (d.UserCount || d.user_count || 0),
|
||||
0
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalUsers", "Total Users")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">
|
||||
{details.reduce((sum: number, d: any) => sum + (d.NodeCount || d.node_count || 0), 0)}
|
||||
<div className="font-bold text-2xl">
|
||||
{details.reduce(
|
||||
(sum: number, d: any) =>
|
||||
sum + (d.NodeCount || d.node_count || 0),
|
||||
0
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalNodes", "Total Nodes")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-bold">{details.length}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="font-bold text-2xl">{details.length}</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("totalNodeGroups", "Total Node Groups")}
|
||||
</div>
|
||||
</div>
|
||||
@@ -415,22 +442,39 @@ export default function GroupHistory() {
|
||||
</thead>
|
||||
<tbody>
|
||||
{details.map((detail: any, index: number) => {
|
||||
const nodeGroupId = detail.NodeGroupId || detail.node_group_id;
|
||||
const nodeGroupName = nodeGroupMap.get(nodeGroupId) || `${t("idPrefix", "#")}${nodeGroupId}`;
|
||||
const nodeGroupId =
|
||||
detail.NodeGroupId || detail.node_group_id;
|
||||
const nodeGroupName =
|
||||
nodeGroupMap.get(nodeGroupId) ||
|
||||
`${t("idPrefix", "#")}${nodeGroupId}`;
|
||||
|
||||
return (
|
||||
<tr key={index}>
|
||||
<td className="border-b px-4 py-2">
|
||||
<div>
|
||||
<div className="font-medium">{nodeGroupName}</div>
|
||||
<div className="text-xs text-muted-foreground">{t("id", "ID")}: {nodeGroupId}</div>
|
||||
<div className="font-medium">
|
||||
{nodeGroupName}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("id", "ID")}: {nodeGroupId}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="border-b px-4 py-2 text-right">
|
||||
<button
|
||||
className="font-semibold hover:underline cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={() => handleShowUserList(nodeGroupId, nodeGroupName)}
|
||||
disabled={(detail.UserCount || detail.user_count || 0) === 0}
|
||||
className="cursor-pointer font-semibold hover:underline disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={
|
||||
(detail.UserCount ||
|
||||
detail.user_count ||
|
||||
0) === 0
|
||||
}
|
||||
onClick={() =>
|
||||
handleShowUserList(
|
||||
nodeGroupId,
|
||||
nodeGroupName
|
||||
)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
{detail.UserCount || detail.user_count || 0}
|
||||
</button>
|
||||
@@ -446,7 +490,7 @@ export default function GroupHistory() {
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-8 text-sm text-muted-foreground">
|
||||
<div className="py-8 text-center text-muted-foreground text-sm">
|
||||
{t("noDetails", "No details available")}
|
||||
</div>
|
||||
)}
|
||||
@@ -456,8 +500,8 @@ export default function GroupHistory() {
|
||||
</Dialog>
|
||||
|
||||
{/* User List Dialog */}
|
||||
<Dialog open={userListOpen} onOpenChange={setUserListOpen}>
|
||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
||||
<Dialog onOpenChange={setUserListOpen} open={userListOpen}>
|
||||
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedNodeGroupName} - {t("userList", "User List")}
|
||||
@@ -479,15 +523,13 @@ export default function GroupHistory() {
|
||||
{userList.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.id}</TableCell>
|
||||
<TableCell>
|
||||
{user.email || "-"}
|
||||
</TableCell>
|
||||
<TableCell>{user.email || "-"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
) : (
|
||||
<div className="text-center py-8 text-sm text-muted-foreground">
|
||||
<div className="py-8 text-center text-muted-foreground text-sm">
|
||||
{t("noUsers", "No users found")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -9,14 +9,14 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@workspace/ui/components/card";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getRecalculationStatus,
|
||||
recalculateGroup,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function GroupRecalculate() {
|
||||
const { t } = useTranslation("group");
|
||||
@@ -54,7 +54,9 @@ export default function GroupRecalculate() {
|
||||
return () => clearInterval(interval);
|
||||
}, [status?.state]);
|
||||
|
||||
const handleRecalculate = async (mode: "average" | "subscribe" | "traffic") => {
|
||||
const handleRecalculate = async (
|
||||
mode: "average" | "subscribe" | "traffic"
|
||||
) => {
|
||||
setRecalculating(mode);
|
||||
try {
|
||||
await recalculateGroup({ mode });
|
||||
@@ -98,7 +100,9 @@ export default function GroupRecalculate() {
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("groupRecalculation", "Group Recalculation")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"groupRecalculationDescription",
|
||||
@@ -110,7 +114,7 @@ export default function GroupRecalculate() {
|
||||
{/* Current Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
<span className="font-medium text-sm">
|
||||
{t("currentStatus", "Current Status")}
|
||||
</span>
|
||||
{loadingStatus ? (
|
||||
@@ -142,14 +146,20 @@ export default function GroupRecalculate() {
|
||||
)}
|
||||
|
||||
{status?.state === "completed" && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"recalculationCompleted",
|
||||
"Recalculation completed successfully"
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status?.state === "failed" && (
|
||||
<div className="text-sm text-destructive">
|
||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
||||
<div className="text-destructive text-sm">
|
||||
{t(
|
||||
"recalculationFailed",
|
||||
"Recalculation failed. Please try again."
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -163,9 +173,11 @@ export default function GroupRecalculate() {
|
||||
{t("averageMode", "Average Mode")}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleRecalculate("average")}
|
||||
disabled={recalculating === "average" || status?.state === "running"}
|
||||
className="w-full"
|
||||
disabled={
|
||||
recalculating === "average" || status?.state === "running"
|
||||
}
|
||||
onClick={() => handleRecalculate("average")}
|
||||
variant="outline"
|
||||
>
|
||||
{recalculating === "average" && (
|
||||
@@ -181,9 +193,11 @@ export default function GroupRecalculate() {
|
||||
{t("subscribeMode", "Subscribe Mode")}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleRecalculate("subscribe")}
|
||||
disabled={recalculating === "subscribe" || status?.state === "running"}
|
||||
className="w-full"
|
||||
disabled={
|
||||
recalculating === "subscribe" || status?.state === "running"
|
||||
}
|
||||
onClick={() => handleRecalculate("subscribe")}
|
||||
variant="outline"
|
||||
>
|
||||
{recalculating === "subscribe" && (
|
||||
@@ -199,9 +213,11 @@ export default function GroupRecalculate() {
|
||||
{t("trafficMode", "Traffic Mode")}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => handleRecalculate("traffic")}
|
||||
disabled={recalculating === "traffic" || status?.state === "running"}
|
||||
className="w-full"
|
||||
disabled={
|
||||
recalculating === "traffic" || status?.state === "running"
|
||||
}
|
||||
onClick={() => handleRecalculate("traffic")}
|
||||
variant="outline"
|
||||
>
|
||||
{recalculating === "traffic" && (
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@workspace/ui/components/tabs";
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@workspace/ui/components/tabs";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AverageModeTab from "./average-mode-tab";
|
||||
import CurrentGroupResults from "./current-group-results";
|
||||
import GroupConfig from "./group-config";
|
||||
import GroupHistory from "./group-history";
|
||||
// import UserGroups from "./user-groups";
|
||||
import NodeGroups from "./node-groups";
|
||||
import GroupHistory from "./group-history";
|
||||
import GroupConfig from "./group-config";
|
||||
import AverageModeTab from "./average-mode-tab";
|
||||
import SubscribeModeTab from "./subscribe-mode-tab";
|
||||
import TrafficModeTab from "./traffic-mode-tab";
|
||||
import CurrentGroupResults from "./current-group-results";
|
||||
|
||||
export default function Group() {
|
||||
const { t } = useTranslation("group");
|
||||
@@ -22,9 +27,7 @@ export default function Group() {
|
||||
|
||||
<Tabs defaultValue="config">
|
||||
<TabsList className="flex flex-wrap gap-2">
|
||||
<TabsTrigger value="config">
|
||||
{t("config", "Config")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="config">{t("config", "Config")}</TabsTrigger>
|
||||
{/* <TabsTrigger value="user">
|
||||
{t("userGroups", "User Groups")}
|
||||
</TabsTrigger> */}
|
||||
@@ -43,12 +46,10 @@ export default function Group() {
|
||||
<TabsTrigger value="results">
|
||||
{t("currentGroupingResult", "Current Grouping Result")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="history">
|
||||
{t("history", "History")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="history">{t("history", "History")}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="config" className="mt-4">
|
||||
<TabsContent className="mt-4" value="config">
|
||||
<GroupConfig />
|
||||
</TabsContent>
|
||||
|
||||
@@ -56,27 +57,27 @@ export default function Group() {
|
||||
<UserGroups />
|
||||
</TabsContent> */}
|
||||
|
||||
<TabsContent value="node" className="mt-4">
|
||||
<TabsContent className="mt-4" value="node">
|
||||
<NodeGroups />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="average" className="mt-4">
|
||||
<TabsContent className="mt-4" value="average">
|
||||
<AverageModeTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="subscribe" className="mt-4">
|
||||
<TabsContent className="mt-4" value="subscribe">
|
||||
<SubscribeModeTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="traffic" className="mt-4">
|
||||
<TabsContent className="mt-4" value="traffic">
|
||||
<TrafficModeTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="results" className="mt-4">
|
||||
<TabsContent className="mt-4" value="results">
|
||||
<CurrentGroupResults />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" className="mt-4">
|
||||
<TabsContent className="mt-4" value="history">
|
||||
<GroupHistory />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
} from "@workspace/ui/components/dialog";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { Label } from "@workspace/ui/components/label";
|
||||
import { Textarea } from "@workspace/ui/components/textarea";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { Textarea } from "@workspace/ui/components/textarea";
|
||||
import { AlertCircle, Loader2 } from "lucide-react";
|
||||
import { forwardRef, useEffect, useState } from "react";
|
||||
import { type RefObject, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface NodeGroupFormProps {
|
||||
@@ -26,10 +26,16 @@ interface NodeGroupFormProps {
|
||||
trigger: React.ReactNode;
|
||||
}
|
||||
|
||||
const NodeGroupForm = forwardRef<
|
||||
HTMLButtonElement,
|
||||
NodeGroupFormProps
|
||||
>(({ initialValues, allNodeGroups = [], currentGroupId, loading, onSubmit, title, trigger }, ref) => {
|
||||
const NodeGroupForm = ({
|
||||
initialValues,
|
||||
allNodeGroups = [],
|
||||
currentGroupId,
|
||||
loading,
|
||||
onSubmit,
|
||||
title,
|
||||
trigger,
|
||||
ref,
|
||||
}: NodeGroupFormProps & { ref?: RefObject<HTMLButtonElement | null> }) => {
|
||||
const { t } = useTranslation("group");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
@@ -82,7 +88,10 @@ const NodeGroupForm = forwardRef<
|
||||
}, [initialValues, open]);
|
||||
|
||||
// 检测流量区间冲突
|
||||
const checkTrafficRangeConflict = (minTraffic: number, maxTraffic: number): string => {
|
||||
const checkTrafficRangeConflict = (
|
||||
minTraffic: number,
|
||||
maxTraffic: number
|
||||
): string => {
|
||||
// 如果 min=0 且 max=0,表示不参与流量分组,跳过所有验证
|
||||
if (minTraffic === 0 && maxTraffic === 0) {
|
||||
return "";
|
||||
@@ -111,12 +120,14 @@ const NodeGroupForm = forwardRef<
|
||||
}
|
||||
|
||||
// 处理现有节点组 max=0 的情况
|
||||
const actualExistingMax = existingMax === 0 ? Number.MAX_VALUE : existingMax;
|
||||
const actualExistingMax =
|
||||
existingMax === 0 ? Number.MAX_VALUE : existingMax;
|
||||
|
||||
// 检测区间重叠
|
||||
// 两个区间 [min1, max1] 和 [min2, max2] 重叠的条件:
|
||||
// max1 > min2 && max2 > min1
|
||||
const hasOverlap = actualMax > existingMin && actualExistingMax > minTraffic;
|
||||
const hasOverlap =
|
||||
actualMax > existingMin && actualExistingMax > minTraffic;
|
||||
|
||||
if (hasOverlap) {
|
||||
return t("rangeConflict", {
|
||||
@@ -131,7 +142,9 @@ const NodeGroupForm = forwardRef<
|
||||
};
|
||||
|
||||
// 检测过期节点组冲突
|
||||
const checkExpiredGroupConflict = async (isExpiredGroup: boolean): Promise<string> => {
|
||||
const checkExpiredGroupConflict = async (
|
||||
isExpiredGroup: boolean
|
||||
): Promise<string> => {
|
||||
if (!isExpiredGroup) {
|
||||
return "";
|
||||
}
|
||||
@@ -142,21 +155,29 @@ const NodeGroupForm = forwardRef<
|
||||
);
|
||||
|
||||
if (existingExpiredGroup) {
|
||||
return t("expiredGroupExists", `System already has an expired node group: ${existingExpiredGroup.name}`);
|
||||
return t(
|
||||
"expiredGroupExists",
|
||||
`System already has an expired node group: ${existingExpiredGroup.name}`
|
||||
);
|
||||
}
|
||||
|
||||
// 检查当前节点组是否被订阅商品使用
|
||||
if (currentGroupId) {
|
||||
try {
|
||||
const { getSubscribeList } = await import("@workspace/ui/services/admin/subscribe");
|
||||
const { getSubscribeList } = await import(
|
||||
"@workspace/ui/services/admin/subscribe"
|
||||
);
|
||||
const { data } = await getSubscribeList({
|
||||
page: 1,
|
||||
size: 1,
|
||||
node_group_id: currentGroupId
|
||||
node_group_id: currentGroupId,
|
||||
});
|
||||
|
||||
if (data.data && data.data.total > 0) {
|
||||
return t("nodeGroupUsedBySubscribe", "This node group is used as default node group in subscription products, cannot set as expired group");
|
||||
return t(
|
||||
"nodeGroupUsedBySubscribe",
|
||||
"This node group is used as default node group in subscription products, cannot set as expired group"
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to check subscribe usage:", error);
|
||||
@@ -178,7 +199,9 @@ const NodeGroupForm = forwardRef<
|
||||
e.preventDefault();
|
||||
|
||||
// 检测过期节点组冲突
|
||||
const expiredGroupConflict = await checkExpiredGroupConflict(values.is_expired_group);
|
||||
const expiredGroupConflict = await checkExpiredGroupConflict(
|
||||
values.is_expired_group
|
||||
);
|
||||
if (expiredGroupConflict) {
|
||||
setConflictError(expiredGroupConflict);
|
||||
return;
|
||||
@@ -186,7 +209,10 @@ const NodeGroupForm = forwardRef<
|
||||
|
||||
// 仅在非过期节点组时检测流量区间冲突
|
||||
if (!values.is_expired_group) {
|
||||
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, values.max_traffic_gb);
|
||||
const conflict = checkTrafficRangeConflict(
|
||||
values.min_traffic_gb,
|
||||
values.max_traffic_gb
|
||||
);
|
||||
if (conflict) {
|
||||
setConflictError(conflict);
|
||||
return;
|
||||
@@ -215,7 +241,7 @@ const NodeGroupForm = forwardRef<
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<Dialog onOpenChange={setOpen} open={open}>
|
||||
<DialogTrigger asChild ref={ref}>
|
||||
{trigger}
|
||||
</DialogTrigger>
|
||||
@@ -226,19 +252,15 @@ const NodeGroupForm = forwardRef<
|
||||
{t("nodeGroupFormDescription", "Configure node group settings")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<form className="space-y-4" onSubmit={handleSubmit}>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">
|
||||
{t("name", "Name")} *
|
||||
</Label>
|
||||
<Label htmlFor="name">{t("name", "Name")} *</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={values.name}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, name: e.target.value })
|
||||
}
|
||||
onChange={(e) => setValues({ ...values, name: e.target.value })}
|
||||
placeholder={t("namePlaceholder", "Enter name")}
|
||||
required
|
||||
value={values.name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -248,12 +270,12 @@ const NodeGroupForm = forwardRef<
|
||||
</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={values.description}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, description: e.target.value })
|
||||
}
|
||||
placeholder={t("descriptionPlaceholder", "Enter description")}
|
||||
rows={3}
|
||||
value={values.description}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -261,12 +283,15 @@ const NodeGroupForm = forwardRef<
|
||||
<Label htmlFor="sort">{t("sort", "Sort Order")}</Label>
|
||||
<Input
|
||||
id="sort"
|
||||
min={0}
|
||||
onChange={(e) =>
|
||||
setValues({
|
||||
...values,
|
||||
sort: Number.parseInt(e.target.value, 10) || 0,
|
||||
})
|
||||
}
|
||||
type="number"
|
||||
value={values.sort}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, sort: parseInt(e.target.value) || 0 })
|
||||
}
|
||||
min={0}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -275,16 +300,22 @@ const NodeGroupForm = forwardRef<
|
||||
<Label htmlFor="for_calculation">
|
||||
{t("forCalculation", "For Calculation")}
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{values.is_expired_group
|
||||
? t("expiredGroupForCalculationDescription", "Expired-only node groups cannot participate in group calculation")
|
||||
: t("forCalculationDescription", "Whether this node group participates in grouping calculation")}
|
||||
? t(
|
||||
"expiredGroupForCalculationDescription",
|
||||
"Expired-only node groups cannot participate in group calculation"
|
||||
)
|
||||
: t(
|
||||
"forCalculationDescription",
|
||||
"Whether this node group participates in grouping calculation"
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="for_calculation"
|
||||
checked={values.for_calculation}
|
||||
disabled={values.is_expired_group}
|
||||
id="for_calculation"
|
||||
onCheckedChange={(checked) =>
|
||||
setValues({ ...values, for_calculation: checked })
|
||||
}
|
||||
@@ -298,13 +329,16 @@ const NodeGroupForm = forwardRef<
|
||||
<Label htmlFor="is_expired_group">
|
||||
{t("isExpiredGroup", "Expired Node Group")}
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("isExpiredGroupDescription", "Allow expired users to use limited nodes")}
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"isExpiredGroupDescription",
|
||||
"Allow expired users to use limited nodes"
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="is_expired_group"
|
||||
checked={values.is_expired_group}
|
||||
id="is_expired_group"
|
||||
onCheckedChange={async (checked) => {
|
||||
setValues({
|
||||
...values,
|
||||
@@ -327,50 +361,70 @@ const NodeGroupForm = forwardRef<
|
||||
<Label htmlFor="expired_days_limit">
|
||||
{t("expiredDaysLimit", "Expired Days Limit")}
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("expiredDaysLimitDescription", "Number of days after expiration that users can still access nodes")}
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"expiredDaysLimitDescription",
|
||||
"Number of days after expiration that users can still access nodes"
|
||||
)}
|
||||
</p>
|
||||
<Input
|
||||
id="expired_days_limit"
|
||||
type="number"
|
||||
min={1}
|
||||
value={values.expired_days_limit}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, expired_days_limit: parseInt(e.target.value) || 7 })
|
||||
setValues({
|
||||
...values,
|
||||
expired_days_limit:
|
||||
Number.parseInt(e.target.value, 10) || 7,
|
||||
})
|
||||
}
|
||||
type="number"
|
||||
value={values.expired_days_limit}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max_traffic_gb_expired">
|
||||
{t("maxTrafficGBExpired", "Max Traffic for Expired Users (GB)")}
|
||||
{t(
|
||||
"maxTrafficGBExpired",
|
||||
"Max Traffic for Expired Users (GB)"
|
||||
)}
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("maxTrafficGBExpiredDescription", "Maximum traffic allowed for expired users (0 = unlimited)")}
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"maxTrafficGBExpiredDescription",
|
||||
"Maximum traffic allowed for expired users (0 = unlimited)"
|
||||
)}
|
||||
</p>
|
||||
<Input
|
||||
id="max_traffic_gb_expired"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.max_traffic_gb_expired}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, max_traffic_gb_expired: parseInt(e.target.value) || 0 })
|
||||
setValues({
|
||||
...values,
|
||||
max_traffic_gb_expired:
|
||||
Number.parseInt(e.target.value, 10) || 0,
|
||||
})
|
||||
}
|
||||
type="number"
|
||||
value={values.max_traffic_gb_expired}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="speed_limit">
|
||||
{t("speedLimit", "Speed Limit (KB/s)")}
|
||||
{t("speedLimit", "Speed Limit (Mbps)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="speed_limit"
|
||||
type="number"
|
||||
min={0}
|
||||
value={values.speed_limit}
|
||||
onChange={(e) =>
|
||||
setValues({ ...values, speed_limit: parseInt(e.target.value) || 0 })
|
||||
setValues({
|
||||
...values,
|
||||
speed_limit: Number.parseInt(e.target.value, 10) || 0,
|
||||
})
|
||||
}
|
||||
type="number"
|
||||
value={values.speed_limit}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
@@ -381,48 +435,61 @@ const NodeGroupForm = forwardRef<
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>{t("trafficRangeGB", "Traffic Range (GB)")}</Label>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("trafficRangeDescription", "Users with traffic >= Min and < Max will be assigned to this node group")}
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"trafficRangeDescription",
|
||||
"Users with traffic >= Min and < Max will be assigned to this node group"
|
||||
)}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="min_traffic_gb">{t("minTrafficGB", "Min Traffic (GB)")}</Label>
|
||||
<Label htmlFor="min_traffic_gb">
|
||||
{t("minTrafficGB", "Min Traffic (GB)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="min_traffic_gb"
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={values.min_traffic_gb}
|
||||
onChange={(e) => {
|
||||
const newValue = parseFloat(e.target.value) || 0;
|
||||
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||
setValues({ ...values, min_traffic_gb: newValue });
|
||||
// 实时检测冲突
|
||||
const conflict = checkTrafficRangeConflict(newValue, values.max_traffic_gb);
|
||||
const conflict = checkTrafficRangeConflict(
|
||||
newValue,
|
||||
values.max_traffic_gb
|
||||
);
|
||||
setConflictError(conflict);
|
||||
}}
|
||||
step={1}
|
||||
type="number"
|
||||
value={values.min_traffic_gb}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max_traffic_gb">{t("maxTrafficGB", "Max Traffic (GB)")}</Label>
|
||||
<Label htmlFor="max_traffic_gb">
|
||||
{t("maxTrafficGB", "Max Traffic (GB)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="max_traffic_gb"
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={values.max_traffic_gb}
|
||||
onChange={(e) => {
|
||||
const newValue = parseFloat(e.target.value) || 0;
|
||||
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||
setValues({ ...values, max_traffic_gb: newValue });
|
||||
// 实时检测冲突
|
||||
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, newValue);
|
||||
const conflict = checkTrafficRangeConflict(
|
||||
values.min_traffic_gb,
|
||||
newValue
|
||||
);
|
||||
setConflictError(conflict);
|
||||
}}
|
||||
step={1}
|
||||
type="number"
|
||||
value={values.max_traffic_gb}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* 显示冲突错误 */}
|
||||
{conflictError && (
|
||||
<div className="flex items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
|
||||
<div className="flex items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-destructive text-sm">
|
||||
<AlertCircle className="h-4 w-4 flex-shrink-0" />
|
||||
<span>{conflictError}</span>
|
||||
</div>
|
||||
@@ -432,17 +499,17 @@ const NodeGroupForm = forwardRef<
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="rounded-md border px-4 py-2 text-sm"
|
||||
disabled={submitting || loading}
|
||||
onClick={() => setOpen(false)}
|
||||
type="button"
|
||||
>
|
||||
{t("cancel", "Cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-primary-foreground text-sm disabled:opacity-50"
|
||||
disabled={submitting || loading || !!conflictError}
|
||||
className="flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground disabled:opacity-50"
|
||||
type="submit"
|
||||
>
|
||||
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
{t("save", "Save")}
|
||||
@@ -452,7 +519,7 @@ const NodeGroupForm = forwardRef<
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
NodeGroupForm.displayName = "NodeGroupForm";
|
||||
|
||||
|
||||
@@ -50,28 +50,91 @@ export default function NodeGroups() {
|
||||
<CardHeader>
|
||||
<CardTitle>{t("nodeGroups", "Node Groups")}</CardTitle>
|
||||
<CardDescription>
|
||||
{t("nodeGroupsDescription", "Manage node groups for user access control")}
|
||||
{t(
|
||||
"nodeGroupsDescription",
|
||||
"Manage node groups for user access control"
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ProTable<API.NodeGroup, API.GetNodeGroupListRequest>
|
||||
action={ref}
|
||||
request={async (params) => {
|
||||
const { data } = await getNodeGroupList({
|
||||
page: params.page || 1,
|
||||
size: params.size || 10,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
actions={{
|
||||
render: (row: any) => [
|
||||
<NodeGroupForm
|
||||
allNodeGroups={allNodeGroups}
|
||||
currentGroupId={row.id}
|
||||
initialValues={row}
|
||||
key={`edit-${row.id}`}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateNodeGroup({
|
||||
id: row.id,
|
||||
...values,
|
||||
} as API.UpdateNodeGroupRequest);
|
||||
toast.success(t("updated", "Updated successfully"));
|
||||
// 刷新节点组列表
|
||||
const { data } = await getNodeGroupList({
|
||||
page: 1,
|
||||
size: 1000,
|
||||
});
|
||||
setAllNodeGroups(data.data?.list || []);
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
title={t("editNodeGroup", "Edit Node Group")}
|
||||
trigger={
|
||||
<Button size="sm" variant="outline">
|
||||
{t("edit", "Edit")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
"deleteNodeGroupConfirm",
|
||||
"This will delete the node group. Nodes in this group will be reassigned."
|
||||
)}
|
||||
key="delete"
|
||||
onConfirm={async () => {
|
||||
await deleteNodeGroup({ id: row.id });
|
||||
toast.success(t("deleted", "Deleted successfully"));
|
||||
// 刷新节点组列表
|
||||
const { data } = await getNodeGroupList({
|
||||
page: 1,
|
||||
size: 1000,
|
||||
});
|
||||
setAllNodeGroups(data.data?.list || []);
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
}}
|
||||
title={t("confirmDelete", "Confirm Delete")}
|
||||
trigger={
|
||||
<Button size="sm" variant="destructive">
|
||||
{t("delete", "Delete")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
id: "id",
|
||||
accessorKey: "id",
|
||||
header: t("id", "ID"),
|
||||
cell: ({ row }: { row: any }) => <span className="text-muted-foreground">#{row.getValue("id")}</span>,
|
||||
cell: ({ row }: { row: any }) => (
|
||||
<span className="text-muted-foreground">
|
||||
#{row.getValue("id")}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
@@ -95,7 +158,8 @@ export default function NodeGroups() {
|
||||
id: "description",
|
||||
accessorKey: "description",
|
||||
header: t("description", "Description"),
|
||||
cell: ({ row }: { row: any }) => row.getValue("description") || "--",
|
||||
cell: ({ row }: { row: any }) =>
|
||||
row.getValue("description") || "--",
|
||||
},
|
||||
{
|
||||
id: "for_calculation",
|
||||
@@ -134,82 +198,27 @@ export default function NodeGroups() {
|
||||
header: t("sort", "Sort"),
|
||||
},
|
||||
]}
|
||||
actions={{
|
||||
render: (row: any) => [
|
||||
<NodeGroupForm
|
||||
key={`edit-${row.id}`}
|
||||
initialValues={row}
|
||||
allNodeGroups={allNodeGroups}
|
||||
currentGroupId={row.id}
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updateNodeGroup({
|
||||
id: row.id,
|
||||
...values,
|
||||
} as API.UpdateNodeGroupRequest);
|
||||
toast.success(t("updated", "Updated successfully"));
|
||||
// 刷新节点组列表
|
||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
||||
setAllNodeGroups(data.data?.list || []);
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
title={t("editNodeGroup", "Edit Node Group")}
|
||||
trigger={
|
||||
<Button variant="outline" size="sm">
|
||||
{t("edit", "Edit")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
key="delete"
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
"deleteNodeGroupConfirm",
|
||||
"This will delete the node group. Nodes in this group will be reassigned."
|
||||
)}
|
||||
onConfirm={async () => {
|
||||
await deleteNodeGroup({ id: row.id });
|
||||
toast.success(t("deleted", "Deleted successfully"));
|
||||
// 刷新节点组列表
|
||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
||||
setAllNodeGroups(data.data?.list || []);
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
}}
|
||||
title={t("confirmDelete", "Confirm Delete")}
|
||||
trigger={
|
||||
<Button variant="destructive" size="sm">
|
||||
{t("delete", "Delete")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
header={{
|
||||
title: t("nodeGroups", "Node Groups"),
|
||||
toolbar: (
|
||||
<NodeGroupForm
|
||||
key="create"
|
||||
initialValues={undefined}
|
||||
allNodeGroups={allNodeGroups}
|
||||
currentGroupId={undefined}
|
||||
initialValues={undefined}
|
||||
key="create"
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createNodeGroup(values as API.CreateNodeGroupRequest);
|
||||
await createNodeGroup(
|
||||
values as API.CreateNodeGroupRequest
|
||||
);
|
||||
toast.success(t("created", "Created successfully"));
|
||||
// 刷新节点组列表
|
||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
||||
const { data } = await getNodeGroupList({
|
||||
page: 1,
|
||||
size: 1000,
|
||||
});
|
||||
setAllNodeGroups(data.data?.list || []);
|
||||
ref.current?.refresh();
|
||||
setLoading(false);
|
||||
@@ -220,14 +229,20 @@ export default function NodeGroups() {
|
||||
}
|
||||
}}
|
||||
title={t("createNodeGroup", "Create Node Group")}
|
||||
trigger={
|
||||
<Button>
|
||||
{t("create", "Create")}
|
||||
</Button>
|
||||
}
|
||||
trigger={<Button>{t("create", "Create")}</Button>}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
request={async (params) => {
|
||||
const { data } = await getNodeGroupList({
|
||||
page: params.page || 1,
|
||||
size: params.size || 10,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
@@ -15,16 +16,15 @@ import {
|
||||
TableCell,
|
||||
TableRow,
|
||||
} from "@workspace/ui/components/table";
|
||||
import {
|
||||
getRecalculationStatus,
|
||||
getSubscribeGroupMapping,
|
||||
recalculateGroup,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
getRecalculationStatus,
|
||||
recalculateGroup,
|
||||
getSubscribeGroupMapping,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
|
||||
interface SubscribeGroupMapping {
|
||||
subscribe_name: string;
|
||||
@@ -51,7 +51,6 @@ export default function SubscribeModeTab() {
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
const loadStatus = async () => {
|
||||
setLoadingStatus(true);
|
||||
try {
|
||||
@@ -124,9 +123,14 @@ export default function SubscribeModeTab() {
|
||||
{/* Configuration Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("subscribeModeConfig", "Subscribe Mode Configuration")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("subscribeModeConfig", "Subscribe Mode Configuration")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t("subscribeModeDescription", "Group users by their purchased subscription plan")}
|
||||
{t(
|
||||
"subscribeModeDescription",
|
||||
"Group users by their purchased subscription plan"
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
@@ -134,7 +138,9 @@ export default function SubscribeModeTab() {
|
||||
{/* Subscribe Group Mapping Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("subscribeGroupMappingTitle", "套餐-节点组对应关系")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("subscribeGroupMappingTitle", "套餐-节点组对应关系")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{mappingLoading ? (
|
||||
@@ -147,16 +153,21 @@ export default function SubscribeModeTab() {
|
||||
{mappingData && mappingData.length > 0 ? (
|
||||
mappingData
|
||||
.filter(
|
||||
(item: SubscribeGroupMapping) => item.subscribe_name && item.node_group_name
|
||||
(item: SubscribeGroupMapping) =>
|
||||
item.subscribe_name && item.node_group_name
|
||||
)
|
||||
.map((item: SubscribeGroupMapping, index: number) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell>
|
||||
<span className="font-medium">{item.subscribe_name}</span>
|
||||
<span className="font-medium">
|
||||
{item.subscribe_name}
|
||||
</span>
|
||||
<span className="mx-2 text-muted-foreground">
|
||||
{t("arrow", "→")}
|
||||
</span>
|
||||
<Badge variant="outline">{item.node_group_name}</Badge>
|
||||
<Badge variant="outline">
|
||||
{item.node_group_name}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
@@ -176,7 +187,9 @@ export default function SubscribeModeTab() {
|
||||
{/* Recalculation Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("groupRecalculation", "Group Recalculation")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"groupRecalculationDescription",
|
||||
@@ -188,7 +201,7 @@ export default function SubscribeModeTab() {
|
||||
{/* Current Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
<span className="font-medium text-sm">
|
||||
{t("currentStatus", "Current Status")}
|
||||
</span>
|
||||
{loadingStatus ? (
|
||||
@@ -220,14 +233,20 @@ export default function SubscribeModeTab() {
|
||||
)}
|
||||
|
||||
{status?.state === "completed" && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"recalculationCompleted",
|
||||
"Recalculation completed successfully"
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status?.state === "failed" && (
|
||||
<div className="text-sm text-destructive">
|
||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
||||
<div className="text-destructive text-sm">
|
||||
{t(
|
||||
"recalculationFailed",
|
||||
"Recalculation failed. Please try again."
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -235,8 +254,8 @@ export default function SubscribeModeTab() {
|
||||
{/* Recalculate Button */}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleRecalculate}
|
||||
disabled={recalculating || status?.state === "running"}
|
||||
onClick={handleRecalculate}
|
||||
>
|
||||
{recalculating && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
@@ -9,17 +10,16 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@workspace/ui/components/card";
|
||||
import {
|
||||
getNodeGroupList,
|
||||
getRecalculationStatus,
|
||||
recalculateGroup,
|
||||
updateNodeGroup,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
getNodeGroupList,
|
||||
updateNodeGroup,
|
||||
getRecalculationStatus,
|
||||
recalculateGroup,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import TrafficRangeConfig from "./traffic-ranges-config";
|
||||
|
||||
export default function TrafficModeTab() {
|
||||
@@ -34,7 +34,11 @@ export default function TrafficModeTab() {
|
||||
} | null>(null);
|
||||
|
||||
// Fetch node groups
|
||||
const { data: nodeGroupsData, isLoading: isLoadingNodeGroups, refetch: refetchNodeGroups } = useQuery({
|
||||
const {
|
||||
data: nodeGroupsData,
|
||||
isLoading: isLoadingNodeGroups,
|
||||
refetch: refetchNodeGroups,
|
||||
} = useQuery({
|
||||
queryKey: ["nodeGroups"],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
||||
@@ -56,7 +60,10 @@ export default function TrafficModeTab() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleTrafficUpdate = async (nodeGroupId: number, fields: { min_traffic_gb?: number; max_traffic_gb?: number }) => {
|
||||
const handleTrafficUpdate = async (
|
||||
nodeGroupId: number,
|
||||
fields: { min_traffic_gb?: number; max_traffic_gb?: number }
|
||||
) => {
|
||||
try {
|
||||
await updateNodeGroup({
|
||||
id: nodeGroupId,
|
||||
@@ -116,7 +123,9 @@ export default function TrafficModeTab() {
|
||||
{/* Node Groups Traffic Configuration Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("trafficModeConfig", "Traffic Mode Configuration")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("trafficModeConfig", "Traffic Mode Configuration")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"trafficModeDescription",
|
||||
@@ -128,7 +137,7 @@ export default function TrafficModeTab() {
|
||||
{isLoadingNodeGroups ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
{t("loading", "Loading...")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -144,7 +153,9 @@ export default function TrafficModeTab() {
|
||||
{/* Recalculation Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
||||
<CardTitle>
|
||||
{t("groupRecalculation", "Group Recalculation")}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
"groupRecalculationDescription",
|
||||
@@ -156,7 +167,7 @@ export default function TrafficModeTab() {
|
||||
{/* Current Status */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">
|
||||
<span className="font-medium text-sm">
|
||||
{t("currentStatus", "Current Status")}
|
||||
</span>
|
||||
{loadingStatus ? (
|
||||
@@ -188,14 +199,20 @@ export default function TrafficModeTab() {
|
||||
)}
|
||||
|
||||
{status?.state === "completed" && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t(
|
||||
"recalculationCompleted",
|
||||
"Recalculation completed successfully"
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status?.state === "failed" && (
|
||||
<div className="text-sm text-destructive">
|
||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
||||
<div className="text-destructive text-sm">
|
||||
{t(
|
||||
"recalculationFailed",
|
||||
"Recalculation failed. Please try again."
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -203,8 +220,8 @@ export default function TrafficModeTab() {
|
||||
{/* Recalculate Button */}
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={handleRecalculate}
|
||||
disabled={recalculating || status?.state === "running"}
|
||||
onClick={handleRecalculate}
|
||||
>
|
||||
{recalculating && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface NodeGroup {
|
||||
@@ -15,12 +15,15 @@ interface NodeGroup {
|
||||
|
||||
interface TrafficRangeConfigProps {
|
||||
nodeGroups: NodeGroup[];
|
||||
onTrafficUpdate: (nodeGroupId: number, fields: { min_traffic_gb?: number; max_traffic_gb?: number }) => Promise<void>;
|
||||
onTrafficUpdate: (
|
||||
nodeGroupId: number,
|
||||
fields: { min_traffic_gb?: number; max_traffic_gb?: number }
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
interface UpdatingNode {
|
||||
nodeGroupId: number;
|
||||
field: 'min_traffic_gb' | 'max_traffic_gb';
|
||||
field: "min_traffic_gb" | "max_traffic_gb";
|
||||
}
|
||||
|
||||
interface NodeGroupTempValues {
|
||||
@@ -28,20 +31,30 @@ interface NodeGroupTempValues {
|
||||
max_traffic_gb?: number;
|
||||
}
|
||||
|
||||
export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: TrafficRangeConfigProps) {
|
||||
export default function TrafficRangeConfig({
|
||||
nodeGroups,
|
||||
onTrafficUpdate,
|
||||
}: TrafficRangeConfigProps) {
|
||||
const { t } = useTranslation("group");
|
||||
const [updatingNodes, setUpdatingNodes] = useState<UpdatingNode[]>([]);
|
||||
// 使用对象存储每个节点组的临时值
|
||||
const [temporaryValues, setTemporaryValues] = useState<Record<number, NodeGroupTempValues>>({});
|
||||
const [temporaryValues, setTemporaryValues] = useState<
|
||||
Record<number, NodeGroupTempValues>
|
||||
>({});
|
||||
|
||||
// Get the display value (temporary or actual)
|
||||
const getDisplayValue = (nodeGroupId: number, field: 'min_traffic_gb' | 'max_traffic_gb'): number => {
|
||||
const getDisplayValue = (
|
||||
nodeGroupId: number,
|
||||
field: "min_traffic_gb" | "max_traffic_gb"
|
||||
): number => {
|
||||
const temp = temporaryValues[nodeGroupId];
|
||||
if (temp && temp[field] !== undefined) {
|
||||
return temp[field]!;
|
||||
}
|
||||
const nodeGroup = nodeGroups.find(ng => ng.id === nodeGroupId);
|
||||
return field === 'min_traffic_gb' ? (nodeGroup?.min_traffic_gb ?? 0) : (nodeGroup?.max_traffic_gb ?? 0);
|
||||
const nodeGroup = nodeGroups.find((ng) => ng.id === nodeGroupId);
|
||||
return field === "min_traffic_gb"
|
||||
? (nodeGroup?.min_traffic_gb ?? 0)
|
||||
: (nodeGroup?.max_traffic_gb ?? 0);
|
||||
};
|
||||
|
||||
// Validate traffic ranges: no overlaps
|
||||
@@ -57,22 +70,34 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
|
||||
// Check if min >= max (both > 0)
|
||||
if (minTraffic > 0 && maxTraffic > 0 && minTraffic >= maxTraffic) {
|
||||
return { valid: false, error: t("minCannotExceedMax", "Minimum traffic cannot exceed maximum traffic") };
|
||||
return {
|
||||
valid: false,
|
||||
error: t(
|
||||
"minCannotExceedMax",
|
||||
"Minimum traffic cannot exceed maximum traffic"
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// Check for overlaps with other node groups
|
||||
const otherGroups = nodeGroups
|
||||
.filter(ng => ng.id !== nodeGroupId)
|
||||
.map(ng => {
|
||||
.filter((ng) => ng.id !== nodeGroupId)
|
||||
.map((ng) => {
|
||||
const temp = temporaryValues[ng.id];
|
||||
return {
|
||||
id: ng.id,
|
||||
name: ng.name,
|
||||
min: temp?.min_traffic_gb !== undefined ? temp.min_traffic_gb : (ng.min_traffic_gb ?? 0),
|
||||
max: temp?.max_traffic_gb !== undefined ? temp.max_traffic_gb : (ng.max_traffic_gb ?? 0),
|
||||
min:
|
||||
temp?.min_traffic_gb !== undefined
|
||||
? temp.min_traffic_gb
|
||||
: (ng.min_traffic_gb ?? 0),
|
||||
max:
|
||||
temp?.max_traffic_gb !== undefined
|
||||
? temp.max_traffic_gb
|
||||
: (ng.max_traffic_gb ?? 0),
|
||||
};
|
||||
})
|
||||
.filter(ng => !(ng.min === 0 && ng.max === 0)) // 跳过未配置流量区间的组
|
||||
.filter((ng) => !(ng.min === 0 && ng.max === 0)) // 跳过未配置流量区间的组
|
||||
.sort((a, b) => a.min - b.min);
|
||||
|
||||
for (const other of otherGroups) {
|
||||
@@ -85,7 +110,11 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
if (currentMax > other.min && otherMax > minTraffic) {
|
||||
return {
|
||||
valid: false,
|
||||
error: t("rangeOverlap", "Range overlaps with node group \"{{name}}\"", { name: other.name })
|
||||
error: t(
|
||||
"rangeOverlap",
|
||||
'Range overlaps with node group "{{name}}"',
|
||||
{ name: other.name }
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -94,31 +123,39 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
};
|
||||
|
||||
const handleTrafficBlur = async (nodeGroupId: number) => {
|
||||
const nodeGroup = nodeGroups.find(ng => ng.id === nodeGroupId);
|
||||
const nodeGroup = nodeGroups.find((ng) => ng.id === nodeGroupId);
|
||||
if (!nodeGroup) return;
|
||||
|
||||
const tempValues = temporaryValues[nodeGroupId];
|
||||
if (!tempValues) return;
|
||||
|
||||
// 获取当前的临时值或实际值
|
||||
const currentMin = tempValues.min_traffic_gb !== undefined
|
||||
? tempValues.min_traffic_gb
|
||||
: (nodeGroup.min_traffic_gb ?? 0);
|
||||
const currentMax = tempValues.max_traffic_gb !== undefined
|
||||
? tempValues.max_traffic_gb
|
||||
: (nodeGroup.max_traffic_gb ?? 0);
|
||||
const currentMin =
|
||||
tempValues.min_traffic_gb !== undefined
|
||||
? tempValues.min_traffic_gb
|
||||
: (nodeGroup.min_traffic_gb ?? 0);
|
||||
const currentMax =
|
||||
tempValues.max_traffic_gb !== undefined
|
||||
? tempValues.max_traffic_gb
|
||||
: (nodeGroup.max_traffic_gb ?? 0);
|
||||
|
||||
// 只要有一个字段被修改了就保存
|
||||
const hasMinChange = tempValues.min_traffic_gb !== undefined;
|
||||
const hasMaxChange = tempValues.max_traffic_gb !== undefined;
|
||||
if (!hasMinChange && !hasMaxChange) {
|
||||
if (!(hasMinChange || hasMaxChange)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证
|
||||
const validation = validateTrafficRange(nodeGroupId, currentMin, currentMax);
|
||||
const validation = validateTrafficRange(
|
||||
nodeGroupId,
|
||||
currentMin,
|
||||
currentMax
|
||||
);
|
||||
if (!validation.valid) {
|
||||
toast.error(validation.error || t("validationFailed", "Validation failed"));
|
||||
toast.error(
|
||||
validation.error || t("validationFailed", "Validation failed")
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -131,15 +168,24 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
|
||||
// 标记为更新中(只标记被修改的字段)
|
||||
if (hasMinChange) {
|
||||
setUpdatingNodes(prev => [...prev, { nodeGroupId, field: 'min_traffic_gb' }]);
|
||||
setUpdatingNodes((prev) => [
|
||||
...prev,
|
||||
{ nodeGroupId, field: "min_traffic_gb" },
|
||||
]);
|
||||
}
|
||||
if (hasMaxChange) {
|
||||
setUpdatingNodes(prev => [...prev, { nodeGroupId, field: 'max_traffic_gb' }]);
|
||||
setUpdatingNodes((prev) => [
|
||||
...prev,
|
||||
{ nodeGroupId, field: "max_traffic_gb" },
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
// 一次性传递两个字段
|
||||
const fieldsToUpdate: { min_traffic_gb?: number; max_traffic_gb?: number } = {};
|
||||
const fieldsToUpdate: {
|
||||
min_traffic_gb?: number;
|
||||
max_traffic_gb?: number;
|
||||
} = {};
|
||||
if (currentMin !== originalMin) {
|
||||
fieldsToUpdate.min_traffic_gb = currentMin;
|
||||
}
|
||||
@@ -152,40 +198,44 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
}
|
||||
} finally {
|
||||
// 移除更新状态
|
||||
setUpdatingNodes(prev => prev.filter(u => !(u.nodeGroupId === nodeGroupId)));
|
||||
setUpdatingNodes((prev) =>
|
||||
prev.filter((u) => !(u.nodeGroupId === nodeGroupId))
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const isUpdating = (nodeGroupId: number) => {
|
||||
return updatingNodes.some(u => u.nodeGroupId === nodeGroupId);
|
||||
};
|
||||
const isUpdating = (nodeGroupId: number) =>
|
||||
updatingNodes.some((u) => u.nodeGroupId === nodeGroupId);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-12 gap-2 text-sm font-medium text-muted-foreground">
|
||||
<div className="grid grid-cols-12 gap-2 font-medium text-muted-foreground text-sm">
|
||||
<div className="col-span-6">{t("nodeGroup", "Node Group")}</div>
|
||||
<div className="col-span-3">{t("minTrafficGB", "Min (GB)")}</div>
|
||||
<div className="col-span-3">{t("maxTrafficGB", "Max (GB)")}</div>
|
||||
</div>
|
||||
|
||||
{nodeGroups.map((nodeGroup) => (
|
||||
<div key={nodeGroup.id} className="grid grid-cols-12 gap-2 items-center">
|
||||
<div
|
||||
className="grid grid-cols-12 items-center gap-2"
|
||||
key={nodeGroup.id}
|
||||
>
|
||||
<div className="col-span-6">
|
||||
<div className="font-medium">{nodeGroup.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{t("id", "ID")}: {nodeGroup.id}</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{t("id", "ID")}: {nodeGroup.id}
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-span-3 relative">
|
||||
<div className="relative col-span-3">
|
||||
<Input
|
||||
type="number"
|
||||
disabled={isUpdating(nodeGroup.id)}
|
||||
min={0}
|
||||
step={1}
|
||||
placeholder="0"
|
||||
value={getDisplayValue(nodeGroup.id, "min_traffic_gb")}
|
||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||
onChange={(e) => {
|
||||
const newValue = parseFloat(e.target.value) || 0;
|
||||
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||
// 更新临时状态
|
||||
setTemporaryValues(prev => ({
|
||||
setTemporaryValues((prev) => ({
|
||||
...prev,
|
||||
[nodeGroup.id]: {
|
||||
...prev[nodeGroup.id],
|
||||
@@ -194,26 +244,26 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
},
|
||||
}));
|
||||
}}
|
||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||
disabled={isUpdating(nodeGroup.id)}
|
||||
placeholder="0"
|
||||
step={1}
|
||||
type="number"
|
||||
value={getDisplayValue(nodeGroup.id, "min_traffic_gb")}
|
||||
/>
|
||||
{isUpdating(nodeGroup.id) && (
|
||||
<div className="absolute right-2 top-1/2 -translate-y-1/2">
|
||||
<div className="-translate-y-1/2 absolute top-1/2 right-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-span-3 relative">
|
||||
<div className="relative col-span-3">
|
||||
<Input
|
||||
type="number"
|
||||
disabled={isUpdating(nodeGroup.id)}
|
||||
min={0}
|
||||
step={1}
|
||||
placeholder="0"
|
||||
value={getDisplayValue(nodeGroup.id, "max_traffic_gb")}
|
||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||
onChange={(e) => {
|
||||
const newValue = parseFloat(e.target.value) || 0;
|
||||
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||
// 更新临时状态
|
||||
setTemporaryValues(prev => ({
|
||||
setTemporaryValues((prev) => ({
|
||||
...prev,
|
||||
[nodeGroup.id]: {
|
||||
...prev[nodeGroup.id],
|
||||
@@ -222,11 +272,13 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
},
|
||||
}));
|
||||
}}
|
||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||
disabled={isUpdating(nodeGroup.id)}
|
||||
placeholder="0"
|
||||
step={1}
|
||||
type="number"
|
||||
value={getDisplayValue(nodeGroup.id, "max_traffic_gb")}
|
||||
/>
|
||||
{isUpdating(nodeGroup.id) && (
|
||||
<div className="absolute right-2 top-1/2 -translate-y-1/2">
|
||||
<div className="-translate-y-1/2 absolute top-1/2 right-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
@@ -235,7 +287,7 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded-md bg-muted p-4 text-sm text-muted-foreground">
|
||||
<div className="rounded-md bg-muted p-4 text-muted-foreground text-sm">
|
||||
<strong>{t("note", "Note")}:</strong>{" "}
|
||||
{t(
|
||||
"trafficRangesNote",
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import { getAdminInviteList } from "@workspace/ui/services/admin/invite";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import InviteManagement from ".";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (
|
||||
_key: string,
|
||||
fallback: string,
|
||||
options?: { count?: number }
|
||||
): string => {
|
||||
if (typeof options?.count === "number") {
|
||||
return `${options.count} days`;
|
||||
}
|
||||
return fallback;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/global", () => ({
|
||||
useGlobalStore: () => ({
|
||||
common: {
|
||||
currency: {
|
||||
currency_symbol: "$",
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/utils/common", () => ({
|
||||
formatDate: (timestamp: number) => `date-${timestamp}`,
|
||||
}));
|
||||
|
||||
vi.mock("@workspace/ui/services/admin/invite", () => ({
|
||||
getAdminInviteList: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedGetAdminInviteList = vi.mocked(getAdminInviteList);
|
||||
|
||||
function createInviteListResponse(
|
||||
data: API.GetAdminInviteListResponse
|
||||
): AxiosResponse<API.Response & { data?: API.GetAdminInviteListResponse }> {
|
||||
return {
|
||||
data: {
|
||||
code: 200,
|
||||
data,
|
||||
},
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {
|
||||
headers: {} as AxiosResponse["config"]["headers"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem("timezone", "UTC");
|
||||
});
|
||||
|
||||
describe("InviteManagement", () => {
|
||||
it("renders invite rows with status, purchase state, commission, and gift days", async () => {
|
||||
mockedGetAdminInviteList.mockResolvedValue(
|
||||
createInviteListResponse({
|
||||
total: 1,
|
||||
list: [
|
||||
{
|
||||
inviter_id: 10,
|
||||
inviter_identifier: "agent@example.com",
|
||||
invitee_id: 123,
|
||||
invitee_identifier: "user@example.com",
|
||||
invitee_avatar: "",
|
||||
invitee_enable: true,
|
||||
invited_at: 1_716_800_000,
|
||||
order_count: 3,
|
||||
has_purchased: true,
|
||||
inviter_commission: 1500,
|
||||
inviter_gift_days: 30,
|
||||
invitee_gift_days: 7,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
render(<InviteManagement />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockedGetAdminInviteList).toHaveBeenCalledWith({
|
||||
page: 1,
|
||||
size: 200,
|
||||
search: undefined,
|
||||
inviter_id: undefined,
|
||||
invitee_id: undefined,
|
||||
})
|
||||
);
|
||||
|
||||
expect(await screen.findByText("agent@example.com")).not.toBeNull();
|
||||
expect(screen.getByText("user@example.com")).not.toBeNull();
|
||||
expect(screen.getByText("Enabled")).not.toBeNull();
|
||||
expect(screen.getByText("Yes")).not.toBeNull();
|
||||
expect(screen.getByText("$15.00")).not.toBeNull();
|
||||
expect(screen.getByText("30 days")).not.toBeNull();
|
||||
expect(screen.getByText("7 days")).not.toBeNull();
|
||||
expect(screen.getByText("date-1716800000")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows the empty state when the API returns no rows", async () => {
|
||||
mockedGetAdminInviteList.mockResolvedValue(
|
||||
createInviteListResponse({
|
||||
total: 0,
|
||||
list: [],
|
||||
})
|
||||
);
|
||||
|
||||
render(<InviteManagement />);
|
||||
|
||||
expect(await screen.findByText("No invite records")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows a loading state while invites are being fetched", () => {
|
||||
let resolveRequest:
|
||||
| ((
|
||||
value: AxiosResponse<
|
||||
API.Response & { data?: API.GetAdminInviteListResponse }
|
||||
>
|
||||
) => void)
|
||||
| undefined;
|
||||
mockedGetAdminInviteList.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
render(<InviteManagement />);
|
||||
|
||||
expect(screen.getByRole("status", { name: "Loading data" })).not.toBeNull();
|
||||
expect(resolveRequest).toBeTypeOf("function");
|
||||
});
|
||||
|
||||
it("shows an error state when the request fails", async () => {
|
||||
mockedGetAdminInviteList.mockRejectedValue(new Error("network failed"));
|
||||
|
||||
render(<InviteManagement />);
|
||||
|
||||
await waitFor(() => expect(mockedGetAdminInviteList).toHaveBeenCalled());
|
||||
expect(await screen.findByText("Failed to load invites")).not.toBeNull();
|
||||
expect(screen.queryByText("No invite records")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
} from "@workspace/ui/components/alert";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
} from "@workspace/ui/components/avatar";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import Empty from "@workspace/ui/composed/empty";
|
||||
import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import { getAdminInviteList } from "@workspace/ui/services/admin/invite";
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Display } from "@/components/display";
|
||||
import { formatDate } from "@/utils/common";
|
||||
|
||||
type InviteFilters = {
|
||||
search?: string;
|
||||
inviter_id?: string;
|
||||
invitee_id?: string;
|
||||
};
|
||||
|
||||
function toOptionalNumber(value?: string) {
|
||||
if (!value) return;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function InviteUserCell({
|
||||
id,
|
||||
identifier,
|
||||
avatar,
|
||||
}: {
|
||||
id: number;
|
||||
identifier: string;
|
||||
avatar?: string;
|
||||
}) {
|
||||
const fallback = identifier?.charAt(0)?.toUpperCase() || "U";
|
||||
|
||||
return (
|
||||
<div className="flex min-w-48 items-center gap-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage alt={identifier || `#${id}`} src={avatar} />
|
||||
<AvatarFallback className="text-xs">{fallback}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-sm">#{id}</div>
|
||||
<div className="max-w-52 truncate text-muted-foreground text-xs">
|
||||
{identifier || "--"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InviteIdentifierCell({
|
||||
id,
|
||||
identifier,
|
||||
}: {
|
||||
id: number;
|
||||
identifier: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="min-w-44">
|
||||
<div className="font-medium text-sm">#{id}</div>
|
||||
<div className="max-w-52 truncate text-muted-foreground text-xs">
|
||||
{identifier || "--"}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function InviteManagement() {
|
||||
const { t } = useTranslation("invite");
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<ProTable<API.AdminInviteRelation, InviteFilters>
|
||||
action={ref}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "inviter_id",
|
||||
header: t("inviter", "Inviter"),
|
||||
cell: ({ row }) => (
|
||||
<InviteIdentifierCell
|
||||
id={row.original.inviter_id}
|
||||
identifier={row.original.inviter_identifier}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "invitee_id",
|
||||
header: t("invitee", "Invitee"),
|
||||
cell: ({ row }) => (
|
||||
<InviteUserCell
|
||||
avatar={row.original.invitee_avatar}
|
||||
id={row.original.invitee_id}
|
||||
identifier={row.original.invitee_identifier}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "invitee_enable",
|
||||
header: t("status", "Status"),
|
||||
cell: ({ row }) => (
|
||||
<Badge
|
||||
variant={row.original.invitee_enable ? "default" : "secondary"}
|
||||
>
|
||||
{row.original.invitee_enable
|
||||
? t("enabled", "Enabled")
|
||||
: t("disabled", "Disabled")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "invited_at",
|
||||
header: t("invitedAt", "Invited At"),
|
||||
cell: ({ row }) => formatDate(row.original.invited_at),
|
||||
},
|
||||
{
|
||||
accessorKey: "order_count",
|
||||
header: t("orderCount", "Orders"),
|
||||
},
|
||||
{
|
||||
accessorKey: "has_purchased",
|
||||
header: t("hasPurchased", "Purchased"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.has_purchased ? "default" : "outline"}>
|
||||
{row.original.has_purchased ? t("yes", "Yes") : t("no", "No")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "inviter_commission",
|
||||
header: t("commission", "Commission"),
|
||||
cell: ({ row }) => (
|
||||
<Display type="currency" value={row.original.inviter_commission} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "inviter_gift_days",
|
||||
header: t("inviterGiftDays", "Inviter Gift Days"),
|
||||
cell: ({ row }) =>
|
||||
t("days", "{{count}} days", {
|
||||
count: row.original.inviter_gift_days,
|
||||
}),
|
||||
},
|
||||
{
|
||||
accessorKey: "invitee_gift_days",
|
||||
header: t("inviteeGiftDays", "Invitee Gift Days"),
|
||||
cell: ({ row }) =>
|
||||
t("days", "{{count}} days", {
|
||||
count: row.original.invitee_gift_days,
|
||||
}),
|
||||
},
|
||||
]}
|
||||
empty={<Empty description={t("empty", "No invite records")} />}
|
||||
error={
|
||||
<Alert className="mx-auto max-w-md" variant="destructive">
|
||||
<CircleAlert aria-hidden="true" />
|
||||
<AlertTitle>
|
||||
{t("loadErrorTitle", "Failed to load invites")}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t("loadErrorDescription", "Refresh the table or try again later.")}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
}
|
||||
header={{ title: t("title", "Invite Management") }}
|
||||
params={[
|
||||
{
|
||||
key: "search",
|
||||
placeholder: t("searchPlaceholder", "Email or phone"),
|
||||
},
|
||||
{
|
||||
key: "inviter_id",
|
||||
placeholder: t("inviterId", "Inviter ID"),
|
||||
},
|
||||
{
|
||||
key: "invitee_id",
|
||||
placeholder: t("inviteeId", "Invitee ID"),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getAdminInviteList({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filters.search?.trim() || undefined,
|
||||
inviter_id: toOptionalNumber(filters.inviter_id),
|
||||
invitee_id: toOptionalNumber(filters.invitee_id),
|
||||
});
|
||||
|
||||
return {
|
||||
list:
|
||||
data.data?.list.map((item) => ({
|
||||
...item,
|
||||
id: `${item.inviter_id}-${item.invitee_id}-${item.invited_at}`,
|
||||
})) || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -81,7 +81,9 @@ export default function ResetSubscribeLogPage() {
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id ? Number((filter as any)?.user_subscribe_id) : undefined,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id
|
||||
? Number((filter as any)?.user_subscribe_id)
|
||||
: undefined,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
|
||||
@@ -93,7 +93,9 @@ export default function SubscribeTrafficLogPage() {
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id ? Number((filter as any)?.user_subscribe_id) : undefined,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id
|
||||
? Number((filter as any)?.user_subscribe_id)
|
||||
: undefined,
|
||||
});
|
||||
const list =
|
||||
((data?.data?.list || []) as API.UserSubscribeTrafficLog[]) || [];
|
||||
|
||||
@@ -26,7 +26,10 @@ export default function SubscribeLogPage() {
|
||||
user_subscribe_id: sp.user_subscribe_id || undefined,
|
||||
};
|
||||
return (
|
||||
<ProTable<API.SubscribeLog, { date?: string; user_id?: number; user_subscribe_id?: string }>
|
||||
<ProTable<
|
||||
API.SubscribeLog,
|
||||
{ date?: string; user_id?: number; user_subscribe_id?: string }
|
||||
>
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "user",
|
||||
@@ -94,7 +97,9 @@ export default function SubscribeLogPage() {
|
||||
size: pagination.size,
|
||||
date: (filter as any)?.date,
|
||||
user_id: (filter as any)?.user_id,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id ? Number((filter as any)?.user_subscribe_id) : undefined,
|
||||
user_subscribe_id: (filter as any)?.user_subscribe_id
|
||||
? Number((filter as any)?.user_subscribe_id)
|
||||
: undefined,
|
||||
});
|
||||
const list = (data?.data?.list || []) as any[];
|
||||
const total = Number(data?.data?.total || list.length);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
@@ -8,6 +9,10 @@ import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import {
|
||||
getGroupConfig,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import {
|
||||
createNode,
|
||||
deleteNode,
|
||||
@@ -16,13 +21,12 @@ import {
|
||||
toggleNodeStatus,
|
||||
updateNode,
|
||||
} from "@workspace/ui/services/admin/server";
|
||||
import { getGroupConfig, getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useNode } from "@/stores/node";
|
||||
import { useServer } from "@/stores/server";
|
||||
import NodeBatchSheet from "./node-batch-sheet";
|
||||
import NodeForm from "./node-form";
|
||||
|
||||
export default function Nodes() {
|
||||
@@ -52,7 +56,7 @@ export default function Nodes() {
|
||||
},
|
||||
});
|
||||
|
||||
const isGroupEnabled = groupConfigData?.enabled || false;
|
||||
const isGroupEnabled = groupConfigData?.enabled;
|
||||
|
||||
// Dynamic columns based on group feature status
|
||||
const columns = useMemo(() => {
|
||||
@@ -121,13 +125,13 @@ export default function Nodes() {
|
||||
id: "node_group_ids",
|
||||
header: t("nodeGroups", "Node Groups"),
|
||||
cell: ({ row }: { row: any }) => {
|
||||
const groupIds = row.original.node_group_ids as number[] || [];
|
||||
const groupIds = (row.original.node_group_ids as number[]) || [];
|
||||
|
||||
// Public node indicator (when node_group_ids is empty)
|
||||
if (groupIds.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<Badge className="text-xs" variant="secondary">
|
||||
{t("public", "Public")}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -151,7 +155,14 @@ export default function Nodes() {
|
||||
}
|
||||
|
||||
return baseColumns;
|
||||
}, [isGroupEnabled, nodeGroupsData, t, getServerName, getServerAddress, getProtocolPort]);
|
||||
}, [
|
||||
isGroupEnabled,
|
||||
nodeGroupsData,
|
||||
t,
|
||||
getServerName,
|
||||
getServerAddress,
|
||||
getProtocolPort,
|
||||
]);
|
||||
|
||||
return (
|
||||
<ProTable<API.Node, { search: string; node_group_id?: number }>
|
||||
@@ -168,7 +179,10 @@ export default function Nodes() {
|
||||
const body: API.UpdateNodeRequest = {
|
||||
...row,
|
||||
...values,
|
||||
node_group_ids: values.node_group_ids?.map((id: string | number) => Number(id)) || [],
|
||||
node_group_ids:
|
||||
values.node_group_ids?.map((id: string | number) =>
|
||||
Number(id)
|
||||
) || [],
|
||||
} as any;
|
||||
await updateNode(body);
|
||||
toast.success(t("updated", "Updated"));
|
||||
@@ -232,6 +246,15 @@ export default function Nodes() {
|
||||
],
|
||||
batchRender(rows) {
|
||||
return [
|
||||
<NodeBatchSheet
|
||||
key="batch-update"
|
||||
onSuccess={() => {
|
||||
ref.current?.refresh();
|
||||
fetchNodes();
|
||||
fetchTags();
|
||||
}}
|
||||
rows={rows}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
@@ -274,9 +297,10 @@ export default function Nodes() {
|
||||
port: Number(values.port!),
|
||||
tags: values.tags || [],
|
||||
};
|
||||
// Add node_group_ids if it exists
|
||||
if (values.node_group_ids) {
|
||||
body.node_group_ids = values.node_group_ids.map((id: string | number) => Number(id));
|
||||
body.node_group_ids = values.node_group_ids.map(
|
||||
(id: string | number) => Number(id)
|
||||
);
|
||||
}
|
||||
await createNode(body);
|
||||
toast.success(t("created", "Created"));
|
||||
@@ -290,8 +314,8 @@ export default function Nodes() {
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
title={t("drawerCreateTitle", "Create Node")}
|
||||
trigger={t("create", "Create")}
|
||||
title={t("drawerCreateTitle", "Create Landing Node")}
|
||||
trigger={t("create", "Create Landing Node")}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
@@ -372,7 +396,9 @@ export default function Nodes() {
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
search: filter?.search || undefined,
|
||||
node_group_id: filter?.node_group_id ? Number(filter.node_group_id) : undefined,
|
||||
node_group_id: filter?.node_group_id
|
||||
? Number(filter.node_group_id)
|
||||
: undefined,
|
||||
};
|
||||
|
||||
const { data } = await filterNodeList(filters);
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Checkbox } from "@workspace/ui/components/checkbox";
|
||||
import { Label } from "@workspace/ui/components/label";
|
||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import TagInput from "@workspace/ui/composed/tag-input";
|
||||
import {
|
||||
getGroupConfig,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { updateNode } from "@workspace/ui/services/admin/server";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useNode } from "@/stores/node";
|
||||
import { useServer } from "@/stores/server";
|
||||
|
||||
type FieldKey =
|
||||
| "name"
|
||||
| "enabled"
|
||||
| "tags"
|
||||
| "server_id"
|
||||
| "protocol"
|
||||
| "address"
|
||||
| "port"
|
||||
| "node_group_ids";
|
||||
|
||||
interface BatchPatch {
|
||||
name?: string;
|
||||
enabled?: boolean;
|
||||
tags?: string[];
|
||||
server_id?: number;
|
||||
protocol?: string;
|
||||
address?: string;
|
||||
port?: number;
|
||||
node_group_ids?: number[];
|
||||
}
|
||||
|
||||
export default function NodeBatchSheet({
|
||||
rows,
|
||||
onSuccess,
|
||||
}: {
|
||||
rows: API.Node[];
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("nodes");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// Which fields are active (will be applied)
|
||||
const [enabledFields, setEnabledFields] = useState<Set<FieldKey>>(new Set());
|
||||
|
||||
// Patch values
|
||||
const [patch, setPatch] = useState<BatchPatch>({
|
||||
name: "",
|
||||
enabled: true,
|
||||
tags: [],
|
||||
server_id: undefined,
|
||||
protocol: undefined,
|
||||
address: "",
|
||||
port: undefined,
|
||||
node_group_ids: [],
|
||||
});
|
||||
|
||||
const { servers, getAvailableProtocols } = useServer();
|
||||
const { tags: existingTags } = useNode();
|
||||
|
||||
const { data: nodeGroupsData } = useQuery({
|
||||
queryKey: ["nodeGroups"],
|
||||
queryFn: async () => {
|
||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
||||
return data.data?.list || [];
|
||||
},
|
||||
});
|
||||
|
||||
const { data: groupConfigData } = useQuery({
|
||||
queryKey: ["groupConfig"],
|
||||
queryFn: async () => {
|
||||
const { data } = await getGroupConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const isGroupEnabled = groupConfigData?.enabled;
|
||||
|
||||
const availableProtocols = getAvailableProtocols(patch.server_id);
|
||||
|
||||
function toggleField(key: FieldKey) {
|
||||
setEnabledFields((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) {
|
||||
next.delete(key);
|
||||
// When disabling server_id, also disable protocol (it depends on server selection)
|
||||
if (key === "server_id") next.delete("protocol");
|
||||
} else {
|
||||
next.add(key);
|
||||
// When enabling server_id, auto-enable protocol as it must be set together
|
||||
if (key === "server_id") next.add("protocol");
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function isEnabled(key: FieldKey) {
|
||||
return enabledFields.has(key);
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (rows.length === 0) return;
|
||||
if (enabledFields.size === 0) {
|
||||
toast.warning(
|
||||
t(
|
||||
"batch_no_fields_selected",
|
||||
"Please select at least one field to update"
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate enabled fields before submitting
|
||||
if (enabledFields.has("name") && !patch.name?.trim()) {
|
||||
toast.warning(t("batch_name_required", "Name cannot be empty"));
|
||||
return;
|
||||
}
|
||||
if (enabledFields.has("server_id") && !patch.server_id) {
|
||||
toast.warning(t("batch_server_required", "Please select a server"));
|
||||
return;
|
||||
}
|
||||
if (enabledFields.has("protocol") && !patch.protocol) {
|
||||
toast.warning(t("batch_protocol_required", "Please select a protocol"));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
enabledFields.has("port") &&
|
||||
(!patch.port || patch.port < 1 || patch.port > 65_535)
|
||||
) {
|
||||
toast.warning(
|
||||
t("batch_port_invalid", "Port must be between 1 and 65535")
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const activePatch: Partial<BatchPatch> = {};
|
||||
for (const key of enabledFields) {
|
||||
(activePatch as any)[key] = (patch as any)[key];
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const results = await Promise.allSettled(
|
||||
rows.map((row) => {
|
||||
const body: API.UpdateNodeRequest = {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
tags: row.tags,
|
||||
port: row.port,
|
||||
address: row.address,
|
||||
server_id: row.server_id,
|
||||
protocol: row.protocol,
|
||||
enabled: row.enabled,
|
||||
...activePatch,
|
||||
} as any;
|
||||
return updateNode(body);
|
||||
})
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failed = results.filter((r) => r.status === "rejected").length;
|
||||
|
||||
if (failed === 0) {
|
||||
toast.success(
|
||||
t("batch_updated", "Updated {{count}} nodes", { count: succeeded })
|
||||
);
|
||||
setOpen(false);
|
||||
setEnabledFields(new Set());
|
||||
onSuccess();
|
||||
} else if (succeeded > 0) {
|
||||
toast.warning(
|
||||
t("batch_partial", "{{succeeded}} updated, {{failed}} failed", {
|
||||
succeeded,
|
||||
failed,
|
||||
})
|
||||
);
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(t("batch_update_failed", "Batch update failed"));
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOpen() {
|
||||
setEnabledFields(new Set());
|
||||
setPatch({
|
||||
name: "",
|
||||
enabled: true,
|
||||
tags: [],
|
||||
server_id: undefined,
|
||||
protocol: undefined,
|
||||
address: "",
|
||||
port: undefined,
|
||||
node_group_ids: [],
|
||||
});
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<SheetTrigger asChild>
|
||||
<Button onClick={handleOpen} variant="outline">
|
||||
{t("batch_update", "Batch Update")}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className="w-[560px] max-w-full">
|
||||
<SheetHeader>
|
||||
<SheetTitle>
|
||||
{t("batch_update_title", "Batch Update ({{count}} nodes)", {
|
||||
count: rows.length,
|
||||
})}
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<ScrollArea className="h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6 pt-4">
|
||||
<p className="mb-4 text-muted-foreground text-sm">
|
||||
{t(
|
||||
"batch_update_desc",
|
||||
"Check the fields you want to overwrite. Unchecked fields will keep their original values."
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="space-y-5">
|
||||
{/* name */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("name")}
|
||||
id="batch-name"
|
||||
onCheckedChange={() => toggleField("name")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={isEnabled("name") ? "" : "text-muted-foreground"}
|
||||
htmlFor="batch-name"
|
||||
>
|
||||
{t("name", "Name")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("name") ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<EnhancedInput
|
||||
onValueChange={(v) =>
|
||||
setPatch((p) => ({ ...p, name: String(v ?? "") }))
|
||||
}
|
||||
value={patch.name ?? ""}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* enabled */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("enabled")}
|
||||
id="batch-enabled"
|
||||
onCheckedChange={() => toggleField("enabled")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("enabled") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-enabled"
|
||||
>
|
||||
{t("enabled", "Enabled")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("enabled") ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<Switch
|
||||
checked={!!patch.enabled}
|
||||
onCheckedChange={(v) =>
|
||||
setPatch((p) => ({ ...p, enabled: v }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* tags */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("tags")}
|
||||
id="batch-tags"
|
||||
onCheckedChange={() => toggleField("tags")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={isEnabled("tags") ? "" : "text-muted-foreground"}
|
||||
htmlFor="batch-tags"
|
||||
>
|
||||
{t("tags", "Tags")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("tags") ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<TagInput
|
||||
onChange={(v) => setPatch((p) => ({ ...p, tags: v }))}
|
||||
options={existingTags || []}
|
||||
placeholder={t(
|
||||
"tags_placeholder",
|
||||
"Use Enter or comma (,) to add"
|
||||
)}
|
||||
value={patch.tags || []}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* server_id */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("server_id")}
|
||||
id="batch-server"
|
||||
onCheckedChange={() => toggleField("server_id")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("server_id") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-server"
|
||||
>
|
||||
{t("server", "Server")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("server_id")
|
||||
? ""
|
||||
: "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<Combobox<number, false>
|
||||
onChange={(v) => {
|
||||
setPatch((p) => ({
|
||||
...p,
|
||||
server_id: v ?? undefined,
|
||||
protocol: undefined,
|
||||
}));
|
||||
}}
|
||||
options={servers.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name} (${(s.address as any) || ""})`,
|
||||
}))}
|
||||
placeholder={t("select_server", "Select server…")}
|
||||
value={patch.server_id}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* protocol */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("protocol")}
|
||||
id="batch-protocol"
|
||||
onCheckedChange={() => toggleField("protocol")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("protocol") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-protocol"
|
||||
>
|
||||
{t("protocol", "Protocol")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("protocol")
|
||||
? ""
|
||||
: "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<Combobox<string, false>
|
||||
onChange={(v) =>
|
||||
setPatch((p) => ({ ...p, protocol: v ?? undefined }))
|
||||
}
|
||||
options={availableProtocols.map((p) => ({
|
||||
value: p.protocol,
|
||||
label: `${p.protocol}${p.port ? ` (${p.port})` : ""}`,
|
||||
}))}
|
||||
placeholder={t("select_protocol", "Select protocol…")}
|
||||
value={patch.protocol}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* address */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("address")}
|
||||
id="batch-address"
|
||||
onCheckedChange={() => toggleField("address")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("address") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-address"
|
||||
>
|
||||
{t("address", "Address")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("address") ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<EnhancedInput
|
||||
onValueChange={(v) =>
|
||||
setPatch((p) => ({ ...p, address: String(v ?? "") }))
|
||||
}
|
||||
value={patch.address ?? ""}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* port */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("port")}
|
||||
id="batch-port"
|
||||
onCheckedChange={() => toggleField("port")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={isEnabled("port") ? "" : "text-muted-foreground"}
|
||||
htmlFor="batch-port"
|
||||
>
|
||||
{t("port", "Port")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("port") ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<EnhancedInput
|
||||
max={65_535}
|
||||
min={1}
|
||||
onValueChange={(v) =>
|
||||
setPatch((p) => ({
|
||||
...p,
|
||||
port: v ? Number(v) : undefined,
|
||||
}))
|
||||
}
|
||||
placeholder="1-65535"
|
||||
type="number"
|
||||
value={patch.port ?? ""}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* node_group_ids — only when group feature is enabled */}
|
||||
{isGroupEnabled && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("node_group_ids")}
|
||||
id="batch-groups"
|
||||
onCheckedChange={() => toggleField("node_group_ids")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("node_group_ids") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-groups"
|
||||
>
|
||||
{t("nodeGroups", "Node Groups")}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled("node_group_ids")
|
||||
? "grid grid-cols-2 gap-2"
|
||||
: "pointer-events-none grid grid-cols-2 gap-2 opacity-40"
|
||||
}
|
||||
>
|
||||
{nodeGroupsData?.map((g) => {
|
||||
const ids = patch.node_group_ids || [];
|
||||
const checked = ids.includes(g.id);
|
||||
return (
|
||||
<div className="flex items-center space-x-2" key={g.id}>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
id={`batch-group-${g.id}`}
|
||||
onCheckedChange={(c) => {
|
||||
setPatch((p) => {
|
||||
const current = p.node_group_ids || [];
|
||||
return {
|
||||
...p,
|
||||
node_group_ids: c
|
||||
? [...current, g.id]
|
||||
: current.filter((id) => id !== g.id),
|
||||
};
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<Label htmlFor={`batch-group-${g.id}`}>
|
||||
{g.name}
|
||||
</Label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<SheetFooter className="flex-row justify-end gap-2 pt-3">
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
{t("cancel", "Cancel")}
|
||||
</Button>
|
||||
<Button disabled={loading} onClick={handleSubmit}>
|
||||
{t("confirm", "Confirm")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Checkbox } from "@workspace/ui/components/checkbox";
|
||||
import {
|
||||
@@ -25,8 +26,10 @@ import {
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import TagInput from "@workspace/ui/composed/tag-input";
|
||||
import { getGroupConfig, getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
getGroupConfig,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
@@ -150,7 +153,7 @@ export default function NodeForm(props: {
|
||||
},
|
||||
});
|
||||
|
||||
const isGroupEnabled = groupConfigData?.enabled || false;
|
||||
const isGroupEnabled = groupConfigData?.enabled;
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
@@ -166,15 +169,21 @@ export default function NodeForm(props: {
|
||||
|
||||
// Copy only the values we need from initialValues
|
||||
if (initialValues.name) resetValues.name = initialValues.name;
|
||||
if (initialValues.server_id) resetValues.server_id = initialValues.server_id;
|
||||
if (initialValues.server_id)
|
||||
resetValues.server_id = initialValues.server_id;
|
||||
if (initialValues.protocol) resetValues.protocol = initialValues.protocol;
|
||||
if (initialValues.address) resetValues.address = initialValues.address;
|
||||
if (initialValues.port) resetValues.port = initialValues.port;
|
||||
if (initialValues.tags) resetValues.tags = initialValues.tags;
|
||||
|
||||
// Convert node_group_ids from number[] to string[], ensure it's always an array
|
||||
if (initialValues.node_group_ids && Array.isArray(initialValues.node_group_ids)) {
|
||||
resetValues.node_group_ids = initialValues.node_group_ids.map((id: string | number) => String(id));
|
||||
if (
|
||||
initialValues.node_group_ids &&
|
||||
Array.isArray(initialValues.node_group_ids)
|
||||
) {
|
||||
resetValues.node_group_ids = initialValues.node_group_ids.map(
|
||||
(id: string | number) => String(id)
|
||||
);
|
||||
} else {
|
||||
resetValues.node_group_ids = [];
|
||||
}
|
||||
@@ -449,23 +458,32 @@ export default function NodeForm(props: {
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{nodeGroupsData?.map((g) => (
|
||||
<div
|
||||
key={g.id}
|
||||
className="flex items-center space-x-2"
|
||||
key={g.id}
|
||||
>
|
||||
<Checkbox
|
||||
checked={field.value?.includes(String(g.id))}
|
||||
id={`node-group-${g.id}`}
|
||||
checked={field.value?.includes(String(g.id)) || false}
|
||||
onCheckedChange={(checked) => {
|
||||
// Ensure field.value is always an array
|
||||
const currentValue = Array.isArray(field.value) ? field.value : [];
|
||||
const currentValue = Array.isArray(
|
||||
field.value
|
||||
)
|
||||
? field.value
|
||||
: [];
|
||||
if (checked) {
|
||||
const newValue = [...currentValue, String(g.id)];
|
||||
const newValue = [
|
||||
...currentValue,
|
||||
String(g.id),
|
||||
];
|
||||
form.setValue(field.name, newValue, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
});
|
||||
} else {
|
||||
const newValue = currentValue.filter((v: string) => v !== String(g.id));
|
||||
const newValue = currentValue.filter(
|
||||
(v: string) => v !== String(g.id)
|
||||
);
|
||||
form.setValue(field.name, newValue, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
@@ -474,8 +492,8 @@ export default function NodeForm(props: {
|
||||
}}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`node-group-${g.id}`}
|
||||
className="cursor-pointer"
|
||||
htmlFor={`node-group-${g.id}`}
|
||||
>
|
||||
{g.name}
|
||||
</Label>
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useSearch } from "@tanstack/react-router";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@workspace/ui/components/alert-dialog";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
@@ -15,17 +28,33 @@ import { cn } from "@workspace/ui/lib/utils";
|
||||
import {
|
||||
activateOrder,
|
||||
getOrderList,
|
||||
refundOrder,
|
||||
updateOrderStatus,
|
||||
} from "@workspace/ui/services/admin/order";
|
||||
import { useRef } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Display } from "@/components/display";
|
||||
import { useGlobalStore } from "@/stores/global";
|
||||
import { useSubscribe } from "@/stores/subscribe";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import { UserDetail } from "../user/user-detail";
|
||||
|
||||
const REFUNDED_ORDER_STATUS = 6;
|
||||
|
||||
export default function Order() {
|
||||
const { t } = useTranslation("order");
|
||||
const sp = useSearch({ strict: false }) as Record<string, string | undefined>;
|
||||
const user = useGlobalStore((state) => state.user);
|
||||
const [confirmingOrderId, setConfirmingOrderId] = useState<number | null>(
|
||||
null
|
||||
);
|
||||
const initialFilters = {
|
||||
user_id: sp.user_id ? Number(sp.user_id) : undefined,
|
||||
search: sp.search || undefined,
|
||||
status: sp.status || undefined,
|
||||
subscribe_id: sp.subscribe_id || undefined,
|
||||
};
|
||||
|
||||
const statusOptions = [
|
||||
{
|
||||
@@ -45,6 +74,11 @@ export default function Order() {
|
||||
label: t("status.5", "Completed"),
|
||||
className: "bg-green-500",
|
||||
},
|
||||
{
|
||||
value: REFUNDED_ORDER_STATUS,
|
||||
label: t("status.6", "Refunded"),
|
||||
className: "bg-red-500",
|
||||
},
|
||||
];
|
||||
|
||||
const typeOptions = [
|
||||
@@ -57,10 +91,101 @@ export default function Order() {
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
|
||||
const { subscribes, getSubscribeName } = useSubscribe();
|
||||
const canRefundOrders = Boolean(user?.is_admin);
|
||||
|
||||
const refundMutation = useMutation({
|
||||
mutationFn: async (order: API.Order) => {
|
||||
await refundOrder({ id: order.id });
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t("refundSuccess", "Refund completed."));
|
||||
setConfirmingOrderId(null);
|
||||
ref.current?.refresh();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Refund order failed", error);
|
||||
setConfirmingOrderId(null);
|
||||
},
|
||||
});
|
||||
|
||||
const isRefundedOrder = (order: API.Order) =>
|
||||
order.status === REFUNDED_ORDER_STATUS ||
|
||||
order.status_name === t("status.6", "Refunded") ||
|
||||
order.status_name?.toLowerCase() === "refunded";
|
||||
|
||||
const canRefundOrder = (order: API.Order) =>
|
||||
canRefundOrders && !isRefundedOrder(order);
|
||||
|
||||
return (
|
||||
<ProTable<API.Order, any>
|
||||
action={ref}
|
||||
actions={{
|
||||
render: (order) => {
|
||||
if (!canRefundOrder(order)) return [];
|
||||
|
||||
const isPending =
|
||||
refundMutation.isPending && confirmingOrderId === order.id;
|
||||
|
||||
return [
|
||||
<AlertDialog
|
||||
key={`refund-${order.id}`}
|
||||
onOpenChange={(open) => {
|
||||
setConfirmingOrderId(open ? order.id : null);
|
||||
}}
|
||||
open={confirmingOrderId === order.id}
|
||||
>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button disabled={isPending} size="sm" variant="destructive">
|
||||
{isPending
|
||||
? t("refundSubmitting", "Refunding...")
|
||||
: t("refund", "Refund")}
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("refundConfirmTitle", "Confirm refund")}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
{t(
|
||||
"refundConfirmDescription",
|
||||
"This refund will immediately invalidate the user's subscription and deduct the related agent commission."
|
||||
)}
|
||||
</p>
|
||||
<p className="font-medium text-foreground">
|
||||
{t(
|
||||
"refundConfirmWarning",
|
||||
"This action cannot be repeated after the order is refunded."
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isPending}>
|
||||
{t("cancel", "Cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
disabled={isPending}
|
||||
onClick={async (event) => {
|
||||
event.preventDefault();
|
||||
if (isPending) return;
|
||||
await refundMutation.mutateAsync(order);
|
||||
}}
|
||||
>
|
||||
{isPending
|
||||
? t("refundSubmitting", "Refunding...")
|
||||
: t("confirmRefund", "Confirm refund")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "order_no",
|
||||
@@ -245,13 +370,19 @@ export default function Order() {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge>
|
||||
{option?.label || t(`status.${row.getValue("status")}`)}
|
||||
<Badge
|
||||
variant={isRefundedOrder(order) ? "destructive" : "default"}
|
||||
>
|
||||
{option?.label ||
|
||||
(order.status_name
|
||||
? t(`status.${row.getValue("status")}`, order.status_name)
|
||||
: t(`status.${row.getValue("status")}`))}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
initialFilters={initialFilters}
|
||||
params={[
|
||||
{
|
||||
key: "status",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
@@ -41,12 +42,14 @@ import { ArrayInput } from "@workspace/ui/composed/dynamic-inputs";
|
||||
import { JSONEditor } from "@workspace/ui/composed/editor/index";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
import {
|
||||
getGroupConfig,
|
||||
getNodeGroupList,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import {
|
||||
evaluateWithPrecision,
|
||||
unitConversion,
|
||||
} from "@workspace/ui/utils/unit-conversions";
|
||||
import { getGroupConfig, getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { CreditCard, Server, Settings } from "lucide-react";
|
||||
import { assign, shake } from "radash";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -112,6 +115,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
z.object({
|
||||
quantity: z.number(),
|
||||
discount: z.number(),
|
||||
map_apple: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
@@ -263,8 +267,13 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
}
|
||||
|
||||
// Convert node_group_ids from number[] to string[]
|
||||
if (initialValues?.node_group_ids && Array.isArray(initialValues.node_group_ids)) {
|
||||
processedValues.node_group_ids = (initialValues.node_group_ids as any[]).map((id) => String(id));
|
||||
if (
|
||||
initialValues?.node_group_ids &&
|
||||
Array.isArray(initialValues.node_group_ids)
|
||||
) {
|
||||
processedValues.node_group_ids = (
|
||||
initialValues.node_group_ids as any[]
|
||||
).map((id) => String(id));
|
||||
}
|
||||
|
||||
form?.reset(processedValues);
|
||||
@@ -290,7 +299,13 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
if (bool) setOpen(false);
|
||||
}
|
||||
|
||||
const { getAllAvailableTags, getNodesByTag, getNodesWithoutTags, getNodesWithoutGroups, nodes } = useNode();
|
||||
const {
|
||||
getAllAvailableTags,
|
||||
getNodesByTag,
|
||||
getNodesWithoutTags,
|
||||
getNodesWithoutGroups,
|
||||
nodes,
|
||||
} = useNode();
|
||||
|
||||
const tagGroups = getAllAvailableTags();
|
||||
|
||||
@@ -314,7 +329,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
},
|
||||
});
|
||||
|
||||
const isGroupEnabled = groupConfigData?.enabled || false;
|
||||
const isGroupEnabled = groupConfigData?.enabled;
|
||||
|
||||
const unit_time = form.watch("unit_time");
|
||||
const node_group_id = form.watch("node_group_id");
|
||||
@@ -332,7 +347,11 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
|
||||
// If node_group_id is empty or 0, automatically set it to the first item in node_group_ids
|
||||
useEffect(() => {
|
||||
if ((!node_group_id || node_group_id === "0") && node_group_ids && node_group_ids.length > 0) {
|
||||
if (
|
||||
(!node_group_id || node_group_id === "0") &&
|
||||
node_group_ids &&
|
||||
node_group_ids.length > 0
|
||||
) {
|
||||
form.setValue("node_group_id", node_group_ids[0]);
|
||||
}
|
||||
}, [node_group_ids, node_group_id, form]);
|
||||
@@ -475,12 +494,6 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
placeholder={t("form.noLimit")}
|
||||
type="number"
|
||||
{...field}
|
||||
formatInput={(value) =>
|
||||
unitConversion("bitsToMb", value)
|
||||
}
|
||||
formatOutput={(value) =>
|
||||
unitConversion("mbToBits", value)
|
||||
}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value);
|
||||
}}
|
||||
@@ -801,6 +814,11 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
value
|
||||
).toString(),
|
||||
},
|
||||
{
|
||||
name: "map_apple",
|
||||
type: "text",
|
||||
placeholder: t("form.appleProductId"),
|
||||
},
|
||||
]}
|
||||
onChange={(
|
||||
newValues: (API.SubscribeDiscount & {
|
||||
@@ -1030,11 +1048,16 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
const nodesWithTag = getNodesByTag(tag);
|
||||
|
||||
return (
|
||||
<AccordionItem key={tag} value={String(tag)}>
|
||||
<AccordionItem
|
||||
key={tag}
|
||||
value={String(tag)}
|
||||
>
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={value.includes(tagId as any)}
|
||||
checked={value.includes(
|
||||
tagId as any
|
||||
)}
|
||||
onCheckedChange={(checked) =>
|
||||
checked
|
||||
? form.setValue(field.name, [
|
||||
@@ -1098,7 +1121,10 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* When group feature is enabled, show nodes without groups */}
|
||||
{/* When group feature is disabled, show nodes without tags */}
|
||||
{(isGroupEnabled ? getNodesWithoutGroups() : getNodesWithoutTags()).map((item: API.Node) => {
|
||||
{(isGroupEnabled
|
||||
? getNodesWithoutGroups()
|
||||
: getNodesWithoutTags()
|
||||
).map((item: API.Node) => {
|
||||
const value = field.value || [];
|
||||
|
||||
return (
|
||||
@@ -1141,9 +1167,14 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{isGroupEnabled
|
||||
? t("form.nodesWithoutGroupsDescription", "Nodes without group assignment will be shown here (nodes that belong to groups are managed in the Node Groups section above)")
|
||||
: t("form.nodesDescription", "Select nodes for this subscription")
|
||||
}
|
||||
? t(
|
||||
"form.nodesWithoutGroupsDescription",
|
||||
"Nodes without group assignment will be shown here (nodes that belong to groups are managed in the Node Groups section above)"
|
||||
)
|
||||
: t(
|
||||
"form.nodesDescription",
|
||||
"Select nodes for this subscription"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -1154,70 +1185,325 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
{isGroupEnabled && (
|
||||
<>
|
||||
{/* When no default node group is set, show simple node group selection */}
|
||||
{!node_group_id ? (
|
||||
{node_group_id ? (
|
||||
<>
|
||||
{/* Default Node Group Selection - shown when default is set */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="node_group_id"
|
||||
render={({ field }) => {
|
||||
// Find the selected node group
|
||||
const selectedNodeGroup = nodeGroupsData?.find(
|
||||
(g) => String(g.id) === field.value
|
||||
);
|
||||
// Filter nodes that belong to this group
|
||||
const nodesInGroup = selectedNodeGroup
|
||||
? (nodes || []).filter((node) => {
|
||||
const nodeGroupIds =
|
||||
(node as any).node_group_ids || [];
|
||||
return nodeGroupIds.includes(
|
||||
selectedNodeGroup.id
|
||||
);
|
||||
})
|
||||
: [];
|
||||
|
||||
return (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"form.defaultNodeGroup",
|
||||
"Default Node Group"
|
||||
)}
|
||||
</FormLabel>
|
||||
<Card className="p-4">
|
||||
<FormControl>
|
||||
<Combobox
|
||||
onChange={(value) => {
|
||||
form.setValue(
|
||||
field.name,
|
||||
value || ""
|
||||
);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
label: t(
|
||||
"form.noDefaultNodeGroup",
|
||||
"No Default Node Group"
|
||||
),
|
||||
value: "",
|
||||
},
|
||||
...(nodeGroupsData?.map((g) => ({
|
||||
label: g.name,
|
||||
value: String(g.id),
|
||||
})) || []),
|
||||
]}
|
||||
placeholder={t(
|
||||
"form.selectDefaultNodeGroup",
|
||||
"Select a default node group..."
|
||||
)}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription className="mt-2">
|
||||
{t(
|
||||
"form.defaultNodeGroupDescription",
|
||||
"The default node group for this product."
|
||||
)}
|
||||
</FormDescription>
|
||||
{/* Show nodes in the selected default node group */}
|
||||
{nodesInGroup.length > 0 && (
|
||||
<>
|
||||
<div className="mt-3 mb-2 text-muted-foreground text-xs">
|
||||
{t(
|
||||
"form.nodesInGroup",
|
||||
"Nodes in this group:"
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{nodesInGroup.map((node) => (
|
||||
<div
|
||||
className="flex items-center justify-between rounded border bg-muted/30 p-2 text-sm"
|
||||
key={node.id}
|
||||
>
|
||||
<span className="flex-1 font-medium">
|
||||
{node.name}
|
||||
</span>
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
{node.address}:{node.port}
|
||||
</span>
|
||||
<span className="flex-1 text-right text-muted-foreground">
|
||||
{node.protocol}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Backup Node Groups Selection - filter out default node group */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="node_group_ids"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"form.backupNodeGroups",
|
||||
"Backup Node Groups"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="space-y-4">
|
||||
{nodeGroupsData
|
||||
?.filter(
|
||||
(g) => String(g.id) !== node_group_id
|
||||
)
|
||||
?.map((g) => {
|
||||
// Filter nodes that belong to this group
|
||||
const nodesInGroup = (
|
||||
nodes || []
|
||||
).filter((node) => {
|
||||
const nodeGroupIds =
|
||||
(node as any).node_group_ids ||
|
||||
[];
|
||||
return nodeGroupIds.includes(g.id);
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border p-4"
|
||||
key={g.id}
|
||||
>
|
||||
<div className="mb-3 flex items-center space-x-2">
|
||||
<Checkbox
|
||||
checked={field.value?.includes(
|
||||
String(g.id)
|
||||
)}
|
||||
id={`subscribe-backup-node-group-${g.id}`}
|
||||
onCheckedChange={(
|
||||
checked
|
||||
) => {
|
||||
const currentValue =
|
||||
field.value || [];
|
||||
if (checked) {
|
||||
form.setValue(
|
||||
field.name,
|
||||
[
|
||||
...currentValue,
|
||||
String(g.id),
|
||||
]
|
||||
);
|
||||
} else {
|
||||
form.setValue(
|
||||
field.name,
|
||||
currentValue.filter(
|
||||
(v: string) =>
|
||||
v !== String(g.id)
|
||||
)
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Label
|
||||
className="cursor-pointer font-medium"
|
||||
htmlFor={`subscribe-backup-node-group-${g.id}`}
|
||||
>
|
||||
{g.name}
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
({nodesInGroup.length}{" "}
|
||||
{t("form.nodes", "nodes")})
|
||||
</span>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* Show nodes in this group */}
|
||||
{nodesInGroup.length > 0 && (
|
||||
<div className="mt-3 ml-6">
|
||||
<div className="mb-2 text-muted-foreground text-xs">
|
||||
{t(
|
||||
"form.nodesInGroup",
|
||||
"Nodes in this group:"
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{nodesInGroup.map(
|
||||
(node) => (
|
||||
<div
|
||||
className="flex items-center justify-between rounded border bg-muted/30 p-2 text-sm"
|
||||
key={node.id}
|
||||
>
|
||||
<span className="flex-1 font-medium">
|
||||
{node.name}
|
||||
</span>
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
{node.address}:
|
||||
{node.port}
|
||||
</span>
|
||||
<span className="flex-1 text-right text-muted-foreground">
|
||||
{node.protocol}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"form.backupNodeGroupsDescription",
|
||||
"Select additional backup node groups."
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="node_group_ids"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.nodeGroups", "Node Groups")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("form.nodeGroups", "Node Groups")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="space-y-4">
|
||||
{nodeGroupsData?.map((g) => {
|
||||
// Filter nodes that belong to this group
|
||||
const nodesInGroup = (nodes || []).filter((node) => {
|
||||
const nodeGroupIds = (node as any).node_group_ids || [];
|
||||
return nodeGroupIds.includes(g.id);
|
||||
});
|
||||
const nodesInGroup = (nodes || []).filter(
|
||||
(node) => {
|
||||
const nodeGroupIds =
|
||||
(node as any).node_group_ids || [];
|
||||
return nodeGroupIds.includes(g.id);
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={g.id} className="border rounded-lg p-4">
|
||||
<div className="flex items-center space-x-2 mb-3">
|
||||
<div
|
||||
className="rounded-lg border p-4"
|
||||
key={g.id}
|
||||
>
|
||||
<div className="mb-3 flex items-center space-x-2">
|
||||
<Checkbox
|
||||
checked={field.value?.includes(
|
||||
String(g.id)
|
||||
)}
|
||||
id={`subscribe-node-group-${g.id}`}
|
||||
checked={field.value?.includes(String(g.id))}
|
||||
onCheckedChange={(checked) => {
|
||||
const currentValue = field.value || [];
|
||||
const currentDefaultGroupId = form.getValues("node_group_id");
|
||||
const currentValue =
|
||||
field.value || [];
|
||||
const currentDefaultGroupId =
|
||||
form.getValues(
|
||||
"node_group_id"
|
||||
);
|
||||
|
||||
if (checked) {
|
||||
const newValue = [...currentValue, String(g.id)];
|
||||
form.setValue(field.name, newValue);
|
||||
const newValue = [
|
||||
...currentValue,
|
||||
String(g.id),
|
||||
];
|
||||
form.setValue(
|
||||
field.name,
|
||||
newValue
|
||||
);
|
||||
|
||||
// If no default node group is set, set this one as default
|
||||
if (!currentDefaultGroupId) {
|
||||
form.setValue("node_group_id", String(g.id));
|
||||
form.setValue(
|
||||
"node_group_id",
|
||||
String(g.id)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
form.setValue(
|
||||
field.name,
|
||||
currentValue.filter((v: string) => v !== String(g.id))
|
||||
currentValue.filter(
|
||||
(v: string) =>
|
||||
v !== String(g.id)
|
||||
)
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`subscribe-node-group-${g.id}`}
|
||||
className="cursor-pointer font-medium"
|
||||
htmlFor={`subscribe-node-group-${g.id}`}
|
||||
>
|
||||
{g.name}
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
({nodesInGroup.length} {t("form.nodes", "nodes")})
|
||||
({nodesInGroup.length}{" "}
|
||||
{t("form.nodes", "nodes")})
|
||||
</span>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* Show nodes in this group */}
|
||||
{nodesInGroup.length > 0 && (
|
||||
<div className="ml-6 mt-3">
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
{t("form.nodesInGroup", "Nodes in this group:")}
|
||||
<div className="mt-3 ml-6">
|
||||
<div className="mb-2 text-muted-foreground text-xs">
|
||||
{t(
|
||||
"form.nodesInGroup",
|
||||
"Nodes in this group:"
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{nodesInGroup.map((node) => (
|
||||
<div
|
||||
className="flex items-center justify-between rounded border bg-muted/30 p-2 text-sm"
|
||||
key={node.id}
|
||||
className="flex items-center justify-between rounded border p-2 text-sm bg-muted/30"
|
||||
>
|
||||
<span className="flex-1 font-medium">
|
||||
{node.name}
|
||||
@@ -1248,169 +1534,6 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{/* Default Node Group Selection - shown when default is set */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="node_group_id"
|
||||
render={({ field }) => {
|
||||
// Find the selected node group
|
||||
const selectedNodeGroup = nodeGroupsData?.find((g) => String(g.id) === field.value);
|
||||
// Filter nodes that belong to this group
|
||||
const nodesInGroup = selectedNodeGroup ? (nodes || []).filter((node) => {
|
||||
const nodeGroupIds = (node as any).node_group_ids || [];
|
||||
return nodeGroupIds.includes(selectedNodeGroup.id);
|
||||
}) : [];
|
||||
|
||||
return (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.defaultNodeGroup", "Default Node Group")}</FormLabel>
|
||||
<Card className="p-4">
|
||||
<FormControl>
|
||||
<Combobox
|
||||
placeholder={t("form.selectDefaultNodeGroup", "Select a default node group...")}
|
||||
value={field.value}
|
||||
onChange={(value) => {
|
||||
form.setValue(field.name, value || "");
|
||||
}}
|
||||
options={[
|
||||
{ label: t("form.noDefaultNodeGroup", "No Default Node Group"), value: "" },
|
||||
...(nodeGroupsData?.map((g) => ({
|
||||
label: g.name,
|
||||
value: String(g.id),
|
||||
})) || []),
|
||||
]}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription className="mt-2">
|
||||
{t(
|
||||
"form.defaultNodeGroupDescription",
|
||||
"The default node group for this product."
|
||||
)}
|
||||
</FormDescription>
|
||||
{/* Show nodes in the selected default node group */}
|
||||
{nodesInGroup.length > 0 && (
|
||||
<>
|
||||
<div className="text-xs text-muted-foreground mb-2 mt-3">
|
||||
{t("form.nodesInGroup", "Nodes in this group:")}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{nodesInGroup.map((node) => (
|
||||
<div
|
||||
key={node.id}
|
||||
className="flex items-center justify-between rounded border p-2 text-sm bg-muted/30"
|
||||
>
|
||||
<span className="flex-1 font-medium">
|
||||
{node.name}
|
||||
</span>
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
{node.address}:{node.port}
|
||||
</span>
|
||||
<span className="flex-1 text-right text-muted-foreground">
|
||||
{node.protocol}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Backup Node Groups Selection - filter out default node group */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="node_group_ids"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.backupNodeGroups", "Backup Node Groups")}</FormLabel>
|
||||
<FormControl>
|
||||
<div className="space-y-4">
|
||||
{nodeGroupsData
|
||||
?.filter((g) => String(g.id) !== node_group_id)
|
||||
?.map((g) => {
|
||||
// Filter nodes that belong to this group
|
||||
const nodesInGroup = (nodes || []).filter((node) => {
|
||||
const nodeGroupIds = (node as any).node_group_ids || [];
|
||||
return nodeGroupIds.includes(g.id);
|
||||
});
|
||||
|
||||
return (
|
||||
<div key={g.id} className="border rounded-lg p-4">
|
||||
<div className="flex items-center space-x-2 mb-3">
|
||||
<Checkbox
|
||||
id={`subscribe-backup-node-group-${g.id}`}
|
||||
checked={field.value?.includes(String(g.id))}
|
||||
onCheckedChange={(checked) => {
|
||||
const currentValue = field.value || [];
|
||||
if (checked) {
|
||||
form.setValue(field.name, [...currentValue, String(g.id)]);
|
||||
} else {
|
||||
form.setValue(
|
||||
field.name,
|
||||
currentValue.filter((v: string) => v !== String(g.id))
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Label
|
||||
htmlFor={`subscribe-backup-node-group-${g.id}`}
|
||||
className="cursor-pointer font-medium"
|
||||
>
|
||||
{g.name}
|
||||
<span className="ml-2 text-muted-foreground text-sm">
|
||||
({nodesInGroup.length} {t("form.nodes", "nodes")})
|
||||
</span>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* Show nodes in this group */}
|
||||
{nodesInGroup.length > 0 && (
|
||||
<div className="ml-6 mt-3">
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
{t("form.nodesInGroup", "Nodes in this group:")}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
{nodesInGroup.map((node) => (
|
||||
<div
|
||||
key={node.id}
|
||||
className="flex items-center justify-between rounded border p-2 text-sm bg-muted/30"
|
||||
>
|
||||
<span className="flex-1 font-medium">
|
||||
{node.name}
|
||||
</span>
|
||||
<span className="flex-1 text-muted-foreground">
|
||||
{node.address}:{node.port}
|
||||
</span>
|
||||
<span className="flex-1 text-right text-muted-foreground">
|
||||
{node.protocol}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"form.backupNodeGroupsDescription",
|
||||
"Select additional backup node groups."
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
@@ -1425,68 +1548,121 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
||||
name="traffic_limit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.trafficLimitRules", "Traffic Limit Rules")}</FormLabel>
|
||||
<FormLabel>
|
||||
{t("form.trafficLimitRules", "Traffic Limit Rules")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<ArrayInput
|
||||
value={field.value && field.value.length > 0 ? field.value : [{ stat_type: "day" }]}
|
||||
onChange={field.onChange}
|
||||
fields={[
|
||||
{
|
||||
name: "stat_type",
|
||||
type: "select",
|
||||
placeholder: t("form.statType", "Statistics Type"),
|
||||
placeholder: t(
|
||||
"form.statType",
|
||||
"Statistics Type"
|
||||
),
|
||||
value: "day",
|
||||
options: [
|
||||
{ label: t("form.statTypeHour", "Hour"), value: "hour" },
|
||||
{ label: t("form.statTypeDay", "Day"), value: "day" },
|
||||
{
|
||||
label: t("form.statTypeHour", "Hour"),
|
||||
value: "hour",
|
||||
},
|
||||
{
|
||||
label: t("form.statTypeDay", "Day"),
|
||||
value: "day",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "stat_value",
|
||||
type: "number",
|
||||
placeholder: t("form.statValue", "Time Value"),
|
||||
placeholder: t(
|
||||
"form.statValue",
|
||||
"Time Value"
|
||||
),
|
||||
min: 1,
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === '.' || e.key === ',') {
|
||||
onKeyDown: (
|
||||
e: React.KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return isNaN(num) ? 0 : Math.floor(num);
|
||||
return String(
|
||||
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "traffic_usage",
|
||||
type: "number",
|
||||
placeholder: t("form.trafficUsage", "Traffic Usage (GB)"),
|
||||
placeholder: t(
|
||||
"form.trafficUsage",
|
||||
"Traffic Usage (GB)"
|
||||
),
|
||||
min: 0,
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === '.' || e.key === ',') {
|
||||
onKeyDown: (
|
||||
e: React.KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return isNaN(num) ? 0 : Math.floor(num);
|
||||
return String(
|
||||
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "speed_limit",
|
||||
type: "number",
|
||||
placeholder: t("form.speedLimitKb", "Speed Limit (kb)"),
|
||||
placeholder: t(
|
||||
"form.speedLimitMbps",
|
||||
"Speed Limit (Mbps)"
|
||||
),
|
||||
min: 0,
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === '.' || e.key === ',') {
|
||||
onKeyDown: (
|
||||
e: React.KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return isNaN(num) ? 0 : Math.floor(num);
|
||||
return String(
|
||||
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
onChange={(items: any[]) => {
|
||||
field.onChange(
|
||||
items.map((item) => ({
|
||||
...item,
|
||||
stat_value: Number(item.stat_value) || 0,
|
||||
traffic_usage:
|
||||
Number(item.traffic_usage) || 0,
|
||||
speed_limit: Number(item.speed_limit) || 0,
|
||||
}))
|
||||
);
|
||||
}}
|
||||
value={
|
||||
field.value && field.value.length > 0
|
||||
? field.value
|
||||
: [
|
||||
{
|
||||
stat_type: "day",
|
||||
stat_value: 1,
|
||||
traffic_usage: 0,
|
||||
speed_limit: 0,
|
||||
},
|
||||
]
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import { getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
import {
|
||||
batchDeleteSubscribe,
|
||||
createSubscribe,
|
||||
@@ -16,8 +18,6 @@ import {
|
||||
subscribeSort,
|
||||
updateSubscribe,
|
||||
} from "@workspace/ui/services/admin/subscribe";
|
||||
import { getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -46,15 +46,20 @@ export default function SubscribeTable() {
|
||||
const { data: groupConfigData } = useQuery({
|
||||
queryKey: ["groupConfig"],
|
||||
queryFn: async () => {
|
||||
const { data } = await (await import("@workspace/ui/services/admin/group")).getGroupConfig();
|
||||
const { data } = await (
|
||||
await import("@workspace/ui/services/admin/group")
|
||||
).getGroupConfig();
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const isGroupEnabled = groupConfigData?.enabled || false;
|
||||
const isGroupEnabled = groupConfigData?.enabled;
|
||||
|
||||
return (
|
||||
<ProTable<API.SubscribeItem, { group_id: number; query: string; node_group_id?: number }>
|
||||
<ProTable<
|
||||
API.SubscribeItem,
|
||||
{ group_id: number; query: string; node_group_id?: number }
|
||||
>
|
||||
action={ref}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
@@ -72,7 +77,9 @@ export default function SubscribeTable() {
|
||||
// Add node_group_ids if it exists in values
|
||||
const vals = values as any;
|
||||
if (vals.node_group_ids) {
|
||||
updateBody.node_group_ids = vals.node_group_ids.map((id: string | number) => Number(id));
|
||||
updateBody.node_group_ids = vals.node_group_ids.map(
|
||||
(id: string | number) => Number(id)
|
||||
);
|
||||
}
|
||||
await updateSubscribe(updateBody as API.UpdateSubscribeRequest);
|
||||
toast.success(t("updateSuccess"));
|
||||
@@ -241,10 +248,12 @@ export default function SubscribeTable() {
|
||||
header: t("inventory"),
|
||||
cell: ({ row }) => {
|
||||
const inventory = row.getValue("inventory") as number;
|
||||
return inventory === -1 ? (
|
||||
<Display type="number" unlimited value={0} />
|
||||
) : (
|
||||
<Display type="number" unlimited value={inventory} />
|
||||
return (
|
||||
<Display
|
||||
type="number"
|
||||
unlimited={inventory === -1}
|
||||
value={inventory === -1 ? 0 : inventory}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -281,7 +290,9 @@ export default function SubscribeTable() {
|
||||
header: t("defaultNodeGroup", "Default Node Group"),
|
||||
cell: ({ row }: { row: any }) => {
|
||||
const nodeGroupId = row.original.node_group_id;
|
||||
const nodeGroup = nodeGroupsData?.find((g) => g.id === nodeGroupId);
|
||||
const nodeGroup = nodeGroupsData?.find(
|
||||
(g) => g.id === nodeGroupId
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -310,7 +321,9 @@ export default function SubscribeTable() {
|
||||
// Add node_group_ids if it exists in values
|
||||
const vals = values as any;
|
||||
if (vals.node_group_ids) {
|
||||
createBody.node_group_ids = vals.node_group_ids.map((id: string | number) => Number(id));
|
||||
createBody.node_group_ids = vals.node_group_ids.map(
|
||||
(id: string | number) => Number(id)
|
||||
);
|
||||
}
|
||||
await createSubscribe(createBody);
|
||||
toast.success(t("createSuccess"));
|
||||
@@ -389,7 +402,9 @@ export default function SubscribeTable() {
|
||||
const params = {
|
||||
...pagination,
|
||||
...filters,
|
||||
node_group_id: filters?.node_group_id ? Number(filters.node_group_id) : undefined,
|
||||
node_group_id: filters?.node_group_id
|
||||
? Number(filters.node_group_id)
|
||||
: undefined,
|
||||
} as any;
|
||||
|
||||
const { data } = await getSubscribeList(params);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import { getPromoRuleList } from "@workspace/ui/services/admin/promo";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import PromoPage from ".";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback: string): string => fallback,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/stores/subscribe", () => ({
|
||||
useSubscribe: () => ({
|
||||
subscribes: [
|
||||
{
|
||||
id: 8,
|
||||
name: "Monthly Plan",
|
||||
unit_price: 1200,
|
||||
sold: 0,
|
||||
},
|
||||
],
|
||||
getSubscribeName: (id?: number) => (id === 8 ? "Monthly Plan" : "--"),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/utils/common", () => ({
|
||||
formatDate: (timestamp: number) => `date-${timestamp}`,
|
||||
}));
|
||||
|
||||
vi.mock("@workspace/ui/services/admin/promo", () => ({
|
||||
createPromoPrice: vi.fn(),
|
||||
createPromoRule: vi.fn(),
|
||||
deletePromoPrice: vi.fn(),
|
||||
deletePromoRule: vi.fn(),
|
||||
getPromoPriceList: vi.fn(),
|
||||
getPromoRuleList: vi.fn(),
|
||||
getPromoUsageList: vi.fn(),
|
||||
updatePromoRule: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedGetPromoRuleList = vi.mocked(getPromoRuleList);
|
||||
|
||||
function createRuleListResponse(
|
||||
data: API.GetPromoRuleListResponse
|
||||
): AxiosResponse<API.Response & { data?: API.GetPromoRuleListResponse }> {
|
||||
return {
|
||||
data: {
|
||||
code: 200,
|
||||
data,
|
||||
},
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {
|
||||
headers: {} as AxiosResponse["config"]["headers"],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem("timezone", "UTC");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("PromoPage", () => {
|
||||
it("renders promo rules with type, priority, status, and validity period", async () => {
|
||||
mockedGetPromoRuleList.mockResolvedValue(
|
||||
createRuleListResponse({
|
||||
total: 1,
|
||||
list: [
|
||||
{
|
||||
id: 1,
|
||||
name: "Return User Price",
|
||||
type: "inactive_user",
|
||||
params: { inactive_months: 3 },
|
||||
priority: 5,
|
||||
enabled: true,
|
||||
start_time: 1_716_800_000,
|
||||
end_time: 1_716_900_000,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
render(<PromoPage />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockedGetPromoRuleList).toHaveBeenCalledWith({
|
||||
page: 1,
|
||||
size: 200,
|
||||
search: undefined,
|
||||
type: undefined,
|
||||
enabled: undefined,
|
||||
})
|
||||
);
|
||||
expect(await screen.findByText("Return User Price")).not.toBeNull();
|
||||
expect(screen.getByText("inactive_user")).not.toBeNull();
|
||||
expect(screen.getByText("5")).not.toBeNull();
|
||||
expect(screen.getByText("date-1716800000")).not.toBeNull();
|
||||
expect(screen.getByText("date-1716900000")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows the empty state when there are no promo rules", async () => {
|
||||
mockedGetPromoRuleList.mockResolvedValue(
|
||||
createRuleListResponse({
|
||||
total: 0,
|
||||
list: [],
|
||||
})
|
||||
);
|
||||
|
||||
render(<PromoPage />);
|
||||
|
||||
expect(await screen.findByText("No promo rules")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows a loading state while promo rules are being fetched", () => {
|
||||
let resolveRequest:
|
||||
| ((
|
||||
value: AxiosResponse<
|
||||
API.Response & { data?: API.GetPromoRuleListResponse }
|
||||
>
|
||||
) => void)
|
||||
| undefined;
|
||||
mockedGetPromoRuleList.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
render(<PromoPage />);
|
||||
|
||||
expect(screen.getByRole("status", { name: "Loading data" })).not.toBeNull();
|
||||
expect(resolveRequest).toBeTypeOf("function");
|
||||
});
|
||||
|
||||
it("shows an error state when promo rules fail to load", async () => {
|
||||
mockedGetPromoRuleList.mockRejectedValue(new Error("network failed"));
|
||||
|
||||
render(<PromoPage />);
|
||||
|
||||
await waitFor(() => expect(mockedGetPromoRuleList).toHaveBeenCalled());
|
||||
expect(
|
||||
await screen.findByText("Failed to load promo rules")
|
||||
).not.toBeNull();
|
||||
expect(screen.queryByText("No promo rules")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,504 @@
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
} from "@workspace/ui/components/alert";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@workspace/ui/components/tabs";
|
||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||
import Empty from "@workspace/ui/composed/empty";
|
||||
import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import {
|
||||
createPromoPrice,
|
||||
createPromoRule,
|
||||
deletePromoPrice,
|
||||
deletePromoRule,
|
||||
getPromoPriceList,
|
||||
getPromoRuleList,
|
||||
getPromoUsageList,
|
||||
updatePromoRule,
|
||||
} from "@workspace/ui/services/admin/promo";
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useSubscribe } from "@/stores/subscribe";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import PriceForm from "./price-form";
|
||||
import RuleDetail from "./rule-detail";
|
||||
import RuleForm from "./rule-form";
|
||||
import { formatCurrency, parseOptionalNumber, promoRuleTypes } from "./utils";
|
||||
|
||||
type RuleFilters = {
|
||||
search?: string;
|
||||
type?: API.PromoRuleType;
|
||||
enabled?: string;
|
||||
};
|
||||
|
||||
type PriceFilters = {
|
||||
promo_rule_id?: string;
|
||||
subscribe_id?: string;
|
||||
};
|
||||
|
||||
type UsageFilters = PriceFilters & {
|
||||
user_id?: string;
|
||||
order_no?: string;
|
||||
};
|
||||
|
||||
function ErrorState({
|
||||
title,
|
||||
description,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
}) {
|
||||
return (
|
||||
<Alert className="mx-auto max-w-md" variant="destructive">
|
||||
<CircleAlert aria-hidden="true" />
|
||||
<AlertTitle>{title}</AlertTitle>
|
||||
<AlertDescription>{description}</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PromoPage() {
|
||||
const { t } = useTranslation("promo");
|
||||
const { subscribes, getSubscribeName } = useSubscribe();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [rules, setRules] = useState<API.PromoRule[]>([]);
|
||||
const [detailRule, setDetailRule] = useState<API.PromoRule>();
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const ruleRef = useRef<ProTableActions>(null);
|
||||
const priceRef = useRef<ProTableActions>(null);
|
||||
const usageRef = useRef<ProTableActions>(null);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tabs className="space-y-4" defaultValue="rules">
|
||||
<TabsList className="grid w-full grid-cols-3 md:w-fit">
|
||||
<TabsTrigger value="rules">{t("rules", "Rules")}</TabsTrigger>
|
||||
<TabsTrigger value="prices">{t("prices", "Prices")}</TabsTrigger>
|
||||
<TabsTrigger value="usage">{t("usage", "Usage")}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="rules">
|
||||
<ProTable<API.PromoRule, RuleFilters>
|
||||
action={ruleRef}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<Button
|
||||
key="detail"
|
||||
onClick={() => {
|
||||
setDetailRule(row);
|
||||
setDetailOpen(true);
|
||||
}}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{t("detail", "Detail")}
|
||||
</Button>,
|
||||
<RuleForm
|
||||
initialValues={row}
|
||||
key="edit"
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await updatePromoRule({ id: row.id }, values);
|
||||
toast.success(t("updateSuccess", "Update Success"));
|
||||
ruleRef.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
title={t("editRule", "Edit Rule")}
|
||||
trigger={t("edit", "Edit")}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
"deleteWarning",
|
||||
"Once deleted, data cannot be recovered. Please proceed with caution."
|
||||
)}
|
||||
key="delete"
|
||||
onConfirm={async () => {
|
||||
await deletePromoRule({ id: row.id });
|
||||
toast.success(t("deleteSuccess", "Delete Success"));
|
||||
ruleRef.current?.refresh();
|
||||
}}
|
||||
title={t("confirmDelete", "Are you sure you want to delete?")}
|
||||
trigger={
|
||||
<Button size="sm" variant="destructive">
|
||||
{t("delete", "Delete")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("name", "Name"),
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: t("type", "Type"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="outline">
|
||||
{t(`types.${row.original.type}`, row.original.type)}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "priority",
|
||||
header: t("priority", "Priority"),
|
||||
},
|
||||
{
|
||||
accessorKey: "enabled",
|
||||
header: t("enabled", "Enabled"),
|
||||
cell: ({ row }) => (
|
||||
<Switch
|
||||
defaultChecked={row.original.enabled}
|
||||
onCheckedChange={async (checked) => {
|
||||
await updatePromoRule(
|
||||
{ id: row.original.id },
|
||||
{ ...row.original, enabled: checked }
|
||||
);
|
||||
toast.success(t("updateSuccess", "Update Success"));
|
||||
ruleRef.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_time",
|
||||
header: t("startTime", "Start Time"),
|
||||
cell: ({ row }) =>
|
||||
row.original.start_time
|
||||
? formatDate(row.original.start_time)
|
||||
: "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "end_time",
|
||||
header: t("endTime", "End Time"),
|
||||
cell: ({ row }) =>
|
||||
row.original.end_time
|
||||
? formatDate(row.original.end_time)
|
||||
: "--",
|
||||
},
|
||||
]}
|
||||
empty={<Empty description={t("emptyRules", "No promo rules")} />}
|
||||
error={
|
||||
<ErrorState
|
||||
description={t(
|
||||
"loadErrorDescription",
|
||||
"Refresh the table or try again later."
|
||||
)}
|
||||
title={t("loadRulesError", "Failed to load promo rules")}
|
||||
/>
|
||||
}
|
||||
header={{
|
||||
toolbar: (
|
||||
<RuleForm
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createPromoRule(values);
|
||||
toast.success(t("createSuccess", "Create Success"));
|
||||
ruleRef.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
title={t("createRule", "Create Rule")}
|
||||
trigger={t("createRule", "Create Rule")}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
params={[
|
||||
{ key: "search", placeholder: t("searchRule", "Rule name") },
|
||||
{
|
||||
key: "type",
|
||||
placeholder: t("type", "Type"),
|
||||
options: promoRuleTypes.map((type) => ({
|
||||
label: t(`types.${type}`, type),
|
||||
value: type,
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: "enabled",
|
||||
placeholder: t("enabled", "Enabled"),
|
||||
options: [
|
||||
{ label: t("yes", "Yes"), value: "true" },
|
||||
{ label: t("no", "No"), value: "false" },
|
||||
],
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getPromoRuleList({
|
||||
...pagination,
|
||||
search: filters.search?.trim() || undefined,
|
||||
type: filters.type,
|
||||
enabled:
|
||||
filters.enabled === undefined || filters.enabled === ""
|
||||
? undefined
|
||||
: filters.enabled === "true",
|
||||
});
|
||||
const list = data.data?.list || [];
|
||||
setRules(list);
|
||||
return {
|
||||
list,
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="prices">
|
||||
<ProTable<API.PromoPrice, PriceFilters>
|
||||
action={priceRef}
|
||||
actions={{
|
||||
render: (row) => [
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
"deleteWarning",
|
||||
"Once deleted, data cannot be recovered. Please proceed with caution."
|
||||
)}
|
||||
key="delete"
|
||||
onConfirm={async () => {
|
||||
await deletePromoPrice({ id: row.id });
|
||||
toast.success(t("deleteSuccess", "Delete Success"));
|
||||
priceRef.current?.refresh();
|
||||
}}
|
||||
title={t("confirmDelete", "Are you sure you want to delete?")}
|
||||
trigger={
|
||||
<Button size="sm" variant="destructive">
|
||||
{t("delete", "Delete")}
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
],
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "promo_rule_id",
|
||||
header: t("rule", "Rule"),
|
||||
cell: ({ row }) =>
|
||||
row.original.promo_rule_id
|
||||
? rules.find(
|
||||
(rule) => rule.id === row.original.promo_rule_id
|
||||
)?.name || `#${row.original.promo_rule_id}`
|
||||
: "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "subscribe_id",
|
||||
header: t("subscribe", "Subscribe"),
|
||||
cell: ({ row }) =>
|
||||
row.original.subscribe_name ||
|
||||
getSubscribeName(row.original.subscribe_id),
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: t("quantity", "Quantity"),
|
||||
cell: ({ row }) => row.original.quantity || "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "unit_price",
|
||||
header: t("unitPrice", "Unit Price"),
|
||||
cell: ({ row }) => formatCurrency(row.original.unit_price),
|
||||
},
|
||||
{
|
||||
accessorKey: "promo_price",
|
||||
header: t("promoPrice", "Promo Price"),
|
||||
cell: ({ row }) => formatCurrency(row.original.promo_price),
|
||||
},
|
||||
]}
|
||||
empty={<Empty description={t("emptyPrices", "No promo prices")} />}
|
||||
error={
|
||||
<ErrorState
|
||||
description={t(
|
||||
"loadErrorDescription",
|
||||
"Refresh the table or try again later."
|
||||
)}
|
||||
title={t("loadPricesError", "Failed to load promo prices")}
|
||||
/>
|
||||
}
|
||||
header={{
|
||||
toolbar: (
|
||||
<PriceForm
|
||||
loading={loading}
|
||||
onSubmit={async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await createPromoPrice(values);
|
||||
toast.success(t("createSuccess", "Create Success"));
|
||||
priceRef.current?.refresh();
|
||||
setLoading(false);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
setLoading(false);
|
||||
return false;
|
||||
}
|
||||
}}
|
||||
rules={rules}
|
||||
subscribes={subscribes}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
params={[
|
||||
{
|
||||
key: "promo_rule_id",
|
||||
placeholder: t("rule", "Rule"),
|
||||
options: rules.map((rule) => ({
|
||||
label: rule.name,
|
||||
value: String(rule.id),
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: "subscribe_id",
|
||||
placeholder: t("subscribe", "Subscribe"),
|
||||
options: subscribes
|
||||
.filter((item) => typeof item.id === "number")
|
||||
.map((item) => ({
|
||||
label: item.name || `#${item.id}`,
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getPromoPriceList({
|
||||
...pagination,
|
||||
promo_rule_id: parseOptionalNumber(filters.promo_rule_id),
|
||||
subscribe_id: parseOptionalNumber(filters.subscribe_id),
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="usage">
|
||||
<ProTable<API.PromoUsage, UsageFilters>
|
||||
action={usageRef}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "promo_rule_id",
|
||||
header: t("rule", "Rule"),
|
||||
cell: ({ row }) =>
|
||||
row.original.rule_name ||
|
||||
rules.find((rule) => rule.id === row.original.promo_rule_id)
|
||||
?.name ||
|
||||
`#${row.original.promo_rule_id}`,
|
||||
},
|
||||
{
|
||||
accessorKey: "user_id",
|
||||
header: t("userId", "User ID"),
|
||||
cell: ({ row }) => `#${row.original.user_id}`,
|
||||
},
|
||||
{
|
||||
accessorKey: "subscribe_id",
|
||||
header: t("subscribe", "Subscribe"),
|
||||
cell: ({ row }) =>
|
||||
row.original.subscribe_name ||
|
||||
getSubscribeName(row.original.subscribe_id),
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: t("quantity", "Quantity"),
|
||||
cell: ({ row }) => row.original.quantity || "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "order_no",
|
||||
header: t("orderNo", "Order No."),
|
||||
},
|
||||
{
|
||||
accessorKey: "promo_price",
|
||||
header: t("promoPrice", "Promo Price"),
|
||||
cell: ({ row }) => formatCurrency(row.original.promo_price),
|
||||
},
|
||||
{
|
||||
accessorKey: "used_at",
|
||||
header: t("usedAt", "Used At"),
|
||||
cell: ({ row }) => formatDate(row.original.used_at),
|
||||
},
|
||||
]}
|
||||
empty={
|
||||
<Empty description={t("emptyUsage", "No promo usage records")} />
|
||||
}
|
||||
error={
|
||||
<ErrorState
|
||||
description={t(
|
||||
"loadErrorDescription",
|
||||
"Refresh the table or try again later."
|
||||
)}
|
||||
title={t("loadUsageError", "Failed to load promo usage")}
|
||||
/>
|
||||
}
|
||||
params={[
|
||||
{
|
||||
key: "promo_rule_id",
|
||||
placeholder: t("rule", "Rule"),
|
||||
options: rules.map((rule) => ({
|
||||
label: rule.name,
|
||||
value: String(rule.id),
|
||||
})),
|
||||
},
|
||||
{
|
||||
key: "subscribe_id",
|
||||
placeholder: t("subscribe", "Subscribe"),
|
||||
options: subscribes
|
||||
.filter((item) => typeof item.id === "number")
|
||||
.map((item) => ({
|
||||
label: item.name || `#${item.id}`,
|
||||
value: String(item.id),
|
||||
})),
|
||||
},
|
||||
{ key: "user_id", placeholder: t("userId", "User ID") },
|
||||
{ key: "order_no", placeholder: t("orderNo", "Order No.") },
|
||||
]}
|
||||
request={async (pagination, filters) => {
|
||||
const { data } = await getPromoUsageList({
|
||||
...pagination,
|
||||
promo_rule_id: parseOptionalNumber(filters.promo_rule_id),
|
||||
subscribe_id: parseOptionalNumber(filters.subscribe_id),
|
||||
user_id: parseOptionalNumber(filters.user_id),
|
||||
order_no: filters.order_no?.trim() || undefined,
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<RuleDetail
|
||||
onOpenChange={setDetailOpen}
|
||||
open={detailOpen}
|
||||
rule={detailRule}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import PriceForm from "./price-form";
|
||||
|
||||
globalThis.ResizeObserver = class ResizeObserver {
|
||||
observe() {
|
||||
return;
|
||||
}
|
||||
unobserve() {
|
||||
return;
|
||||
}
|
||||
disconnect() {
|
||||
return;
|
||||
}
|
||||
};
|
||||
Element.prototype.scrollIntoView = function scrollIntoView() {
|
||||
return;
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback: string): string => fallback,
|
||||
}),
|
||||
}));
|
||||
|
||||
const rules: API.PromoRule[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Campaign Rule",
|
||||
type: "campaign",
|
||||
params: {},
|
||||
priority: 1,
|
||||
enabled: true,
|
||||
},
|
||||
];
|
||||
|
||||
const subscribes: API.SubscribeItem[] = [
|
||||
{
|
||||
id: 8,
|
||||
name: "Monthly Plan",
|
||||
unit_price: 1200,
|
||||
unit_time: "Month",
|
||||
sold: 0,
|
||||
discount: [
|
||||
{
|
||||
quantity: 3,
|
||||
discount: 90,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const subscribesWithoutDiscounts: API.SubscribeItem[] = [
|
||||
{
|
||||
id: 8,
|
||||
name: "Monthly Plan",
|
||||
unit_price: 1200,
|
||||
unit_time: "Month",
|
||||
sold: 0,
|
||||
discount: [],
|
||||
},
|
||||
];
|
||||
|
||||
async function selectCombobox(index: number, option: string) {
|
||||
const combobox = screen.getAllByRole("combobox")[index];
|
||||
if (!combobox) throw new Error(`Combobox ${index} not found`);
|
||||
fireEvent.click(combobox);
|
||||
fireEvent.click(await screen.findByText(option));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("PriceForm", () => {
|
||||
it("submits promo price with promo_rule_id and selected quantity item", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(true);
|
||||
render(
|
||||
<PriceForm onSubmit={onSubmit} rules={rules} subscribes={subscribes} />
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Promo Price" }));
|
||||
await selectCombobox(0, "Campaign Rule");
|
||||
await selectCombobox(1, "Monthly Plan");
|
||||
await selectCombobox(2, "3 x Month");
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter price"), {
|
||||
target: { value: "20" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
promo_rule_id: 1,
|
||||
items: [{ subscribe_id: 8, quantity: 3, promo_price: 2000 }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks submit when subscribe has no discount quantities", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<PriceForm
|
||||
onSubmit={onSubmit}
|
||||
rules={rules}
|
||||
subscribes={subscribesWithoutDiscounts}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Promo Price" }));
|
||||
await selectCombobox(1, "Monthly Plan");
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
"This subscribe has no discount quantities and cannot be configured."
|
||||
)
|
||||
).not.toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Confirm" })).toHaveProperty(
|
||||
"disabled",
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the form open and shows an error when promo price reaches original price", async () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<PriceForm onSubmit={onSubmit} rules={rules} subscribes={subscribes} />
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Promo Price" }));
|
||||
await selectCombobox(0, "Campaign Rule");
|
||||
await selectCombobox(1, "Monthly Plan");
|
||||
await selectCombobox(2, "3 x Month");
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter price"), {
|
||||
target: { value: "36" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
|
||||
expect(
|
||||
await screen.findByText("Promo price must be lower than original price")
|
||||
).not.toBeNull();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@workspace/ui/components/form";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { unitConversion } from "@workspace/ui/utils/unit-conversions";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
formatCurrency,
|
||||
getSubscribeDiscounts,
|
||||
getSubscribeUnitPrice,
|
||||
} from "./utils";
|
||||
|
||||
const priceSchema = z.object({
|
||||
promo_rule_id: z.number().min(1),
|
||||
subscribe_id: z.number().min(1),
|
||||
quantity: z.number().min(1),
|
||||
promo_price: z.number().min(1),
|
||||
});
|
||||
|
||||
type PriceFormValues = z.infer<typeof priceSchema>;
|
||||
|
||||
interface PriceFormProps {
|
||||
loading?: boolean;
|
||||
rules: API.PromoRule[];
|
||||
subscribes: API.SubscribeItem[];
|
||||
onSubmit: (data: API.CreatePromoPriceRequest) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
export default function PriceForm({
|
||||
loading,
|
||||
rules,
|
||||
subscribes,
|
||||
onSubmit,
|
||||
}: PriceFormProps) {
|
||||
const { t } = useTranslation("promo");
|
||||
const [open, setOpen] = useState(false);
|
||||
const form = useForm<PriceFormValues>({
|
||||
resolver: zodResolver(priceSchema),
|
||||
defaultValues: {
|
||||
promo_rule_id: 0,
|
||||
subscribe_id: 0,
|
||||
quantity: 0,
|
||||
promo_price: 0,
|
||||
},
|
||||
});
|
||||
const subscribeId = form.watch("subscribe_id");
|
||||
const quantity = form.watch("quantity");
|
||||
const subscribe = subscribes.find((item) => item.id === subscribeId);
|
||||
const discounts = getSubscribeDiscounts(subscribe);
|
||||
const unitPrice = getSubscribeUnitPrice(subscribe);
|
||||
const originalPrice = unitPrice * quantity;
|
||||
const hasSelectedSubscribe = subscribeId > 0;
|
||||
const hasDiscounts = discounts.length > 0;
|
||||
|
||||
async function handleSubmit(values: PriceFormValues) {
|
||||
const maxPrice = unitPrice * values.quantity;
|
||||
if (maxPrice > 0 && values.promo_price >= maxPrice) {
|
||||
form.setError("promo_price", {
|
||||
message: t(
|
||||
"form.promoPriceLessThanOriginalPrice",
|
||||
"Promo price must be lower than original price"
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const success = await onSubmit({
|
||||
promo_rule_id: values.promo_rule_id,
|
||||
items: [
|
||||
{
|
||||
subscribe_id: values.subscribe_id,
|
||||
quantity: values.quantity,
|
||||
promo_price: values.promo_price,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (success) setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.reset({
|
||||
promo_rule_id: 0,
|
||||
subscribe_id: 0,
|
||||
quantity: 0,
|
||||
promo_price: 0,
|
||||
});
|
||||
setOpen(true);
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
{t("createPrice", "Create Promo Price")}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="w-[520px] max-w-full md:max-w-screen-md">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("createPrice", "Create Promo Price")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="space-y-4 px-6 pt-4"
|
||||
id="promo-price-form"
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="promo_rule_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("rule", "Rule")}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<number>
|
||||
onChange={field.onChange}
|
||||
options={rules.map((rule) => ({
|
||||
label: rule.name,
|
||||
value: rule.id,
|
||||
}))}
|
||||
placeholder={t("form.selectRule", "Select rule")}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="subscribe_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("subscribe", "Subscribe")}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<number>
|
||||
onChange={(value) => {
|
||||
field.onChange(value);
|
||||
form.setValue("quantity", 0, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
form.clearErrors(["quantity", "promo_price"]);
|
||||
}}
|
||||
options={subscribes
|
||||
.filter((item) => typeof item.id === "number")
|
||||
.map((item) => ({
|
||||
label: item.name || `#${item.id}`,
|
||||
value: item.id as number,
|
||||
}))}
|
||||
placeholder={t(
|
||||
"form.selectSubscribe",
|
||||
"Select subscribe"
|
||||
)}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="quantity"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("quantity", "Quantity")}</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox<number>
|
||||
onChange={field.onChange}
|
||||
options={discounts.map((item) => ({
|
||||
label: `${item.quantity} x ${t(
|
||||
subscribe?.unit_time || "Month",
|
||||
subscribe?.unit_time || "Month"
|
||||
)}`,
|
||||
value: item.quantity,
|
||||
}))}
|
||||
placeholder={t(
|
||||
"form.selectQuantity",
|
||||
"Select discount quantity"
|
||||
)}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
{hasSelectedSubscribe && !hasDiscounts && (
|
||||
<p className="text-destructive text-xs">
|
||||
{t(
|
||||
"form.noDiscounts",
|
||||
"This subscribe has no discount quantities and cannot be configured."
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="promo_price"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("promoPrice", "Promo Price")}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
formatInput={(value) =>
|
||||
unitConversion("centsToDollars", value)
|
||||
}
|
||||
formatOutput={(value) =>
|
||||
unitConversion("dollarsToCents", value)
|
||||
}
|
||||
min={0.01}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
placeholder={t("form.enterPromoPrice", "Enter price")}
|
||||
type="number"
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
{originalPrice > 0 && (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("originalPriceHint", "Original price")}:{" "}
|
||||
{formatCurrency(originalPrice)}
|
||||
</p>
|
||||
)}
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
<SheetFooter>
|
||||
<Button
|
||||
disabled={loading || (hasSelectedSubscribe && !hasDiscounts)}
|
||||
form="promo-price-form"
|
||||
type="submit"
|
||||
>
|
||||
{t("confirm", "Confirm")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableRow,
|
||||
} from "@workspace/ui/components/table";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDate } from "@/utils/common";
|
||||
|
||||
interface RuleDetailProps {
|
||||
open: boolean;
|
||||
rule?: API.PromoRule;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export default function RuleDetail({
|
||||
open,
|
||||
rule,
|
||||
onOpenChange,
|
||||
}: RuleDetailProps) {
|
||||
const { t } = useTranslation("promo");
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={onOpenChange} open={open}>
|
||||
<SheetContent className="w-[520px] max-w-full md:max-w-screen-md">
|
||||
<SheetHeader>
|
||||
<SheetTitle>
|
||||
{rule?.name || t("ruleDetail", "Rule Detail")}
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
{rule && (
|
||||
<div className="px-6 pt-4">
|
||||
<Table>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>{t("type", "Type")}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline">
|
||||
{t(`types.${rule.type}`, rule.type)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>{t("priority", "Priority")}</TableCell>
|
||||
<TableCell>{rule.priority}</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>{t("enabled", "Enabled")}</TableCell>
|
||||
<TableCell>
|
||||
{rule.enabled ? t("yes", "Yes") : t("no", "No")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>{t("params", "Params")}</TableCell>
|
||||
<TableCell>
|
||||
<code className="whitespace-pre-wrap rounded bg-muted px-2 py-1 text-xs">
|
||||
{JSON.stringify(rule.params || {}, null, 2)}
|
||||
</code>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>
|
||||
{t("validityPeriod", "Validity Period")}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{rule.start_time ? formatDate(rule.start_time) : "--"} -{" "}
|
||||
{rule.end_time ? formatDate(rule.end_time) : "--"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@workspace/ui/components/form";
|
||||
import {
|
||||
RadioGroup,
|
||||
RadioGroupItem,
|
||||
} from "@workspace/ui/components/radio-group";
|
||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { DatePicker } from "@workspace/ui/composed/date-picker";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import { promoRuleTypes } from "./utils";
|
||||
|
||||
const ruleSchema = z
|
||||
.object({
|
||||
name: z.string().min(1),
|
||||
type: z.enum(["new_user", "inactive_user", "campaign"]),
|
||||
inactive_months: z.number().optional(),
|
||||
window_hours: z.number().optional(),
|
||||
priority: z.number().min(0),
|
||||
enabled: z.boolean(),
|
||||
start_time: z.number().optional(),
|
||||
end_time: z.number().optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (
|
||||
data.start_time !== undefined &&
|
||||
data.end_time !== undefined &&
|
||||
data.start_time >= data.end_time
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "End time must be later than start time",
|
||||
path: ["end_time"],
|
||||
});
|
||||
}
|
||||
if (
|
||||
data.type === "inactive_user" &&
|
||||
(!data.inactive_months || data.inactive_months <= 0)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Inactive months must be greater than 0",
|
||||
path: ["inactive_months"],
|
||||
});
|
||||
}
|
||||
if (
|
||||
data.type === "new_user" &&
|
||||
(!data.window_hours || data.window_hours <= 0)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Window hours must be greater than 0",
|
||||
path: ["window_hours"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type RuleFormValues = z.infer<typeof ruleSchema>;
|
||||
|
||||
interface RuleFormProps {
|
||||
initialValues?: API.PromoRule;
|
||||
loading?: boolean;
|
||||
onSubmit: (data: API.CreatePromoRuleRequest) => Promise<boolean> | boolean;
|
||||
title: string;
|
||||
trigger: string;
|
||||
}
|
||||
|
||||
function toFormValues(rule?: API.PromoRule): RuleFormValues {
|
||||
return {
|
||||
name: rule?.name ?? "",
|
||||
type: rule?.type ?? "inactive_user",
|
||||
inactive_months: rule?.params?.inactive_months,
|
||||
window_hours: rule?.params?.window_hours,
|
||||
priority: rule?.priority ?? 0,
|
||||
enabled: rule?.enabled ?? false,
|
||||
start_time: rule?.start_time,
|
||||
end_time: rule?.end_time,
|
||||
};
|
||||
}
|
||||
|
||||
function toRequest(values: RuleFormValues): API.CreatePromoRuleRequest {
|
||||
const params: API.PromoRuleParams =
|
||||
values.type === "inactive_user"
|
||||
? { inactive_months: values.inactive_months }
|
||||
: values.type === "new_user"
|
||||
? { window_hours: values.window_hours }
|
||||
: {};
|
||||
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
type: values.type,
|
||||
params,
|
||||
priority: values.priority,
|
||||
enabled: values.enabled,
|
||||
start_time: values.start_time || undefined,
|
||||
end_time: values.end_time || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export default function RuleForm({
|
||||
initialValues,
|
||||
loading,
|
||||
onSubmit,
|
||||
title,
|
||||
trigger,
|
||||
}: RuleFormProps) {
|
||||
const { t } = useTranslation("promo");
|
||||
const [open, setOpen] = useState(false);
|
||||
const form = useForm<RuleFormValues>({
|
||||
resolver: zodResolver(ruleSchema),
|
||||
defaultValues: toFormValues(initialValues),
|
||||
});
|
||||
const type = form.watch("type");
|
||||
|
||||
useEffect(() => {
|
||||
form.reset(toFormValues(initialValues));
|
||||
}, [form, initialValues]);
|
||||
|
||||
async function handleSubmit(values: RuleFormValues) {
|
||||
const success = await onSubmit(toRequest(values));
|
||||
if (success) setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.reset(toFormValues(initialValues));
|
||||
setOpen(true);
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
{trigger}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="w-[520px] max-w-full md:max-w-screen-md">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{title}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className="h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]">
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="space-y-4 px-6 pt-4"
|
||||
id="promo-rule-form"
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.name", "Name")}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
placeholder={t("form.namePlaceholder", "Rule name")}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("form.type", "Rule Type")}</FormLabel>
|
||||
<FormControl>
|
||||
<RadioGroup
|
||||
className="grid gap-2 sm:grid-cols-3"
|
||||
onValueChange={(value) =>
|
||||
field.onChange(value as API.PromoRuleType)
|
||||
}
|
||||
value={field.value}
|
||||
>
|
||||
{promoRuleTypes.map((item) => (
|
||||
<FormItem
|
||||
className="flex items-center space-x-2 space-y-0"
|
||||
key={item}
|
||||
>
|
||||
<FormControl>
|
||||
<RadioGroupItem value={item} />
|
||||
</FormControl>
|
||||
<FormLabel className="font-normal">
|
||||
{t(`types.${item}`, item)}
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{type === "inactive_user" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="inactive_months"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("form.inactiveMonths", "Inactive Months")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={1}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
placeholder={t(
|
||||
"form.inactiveMonthsPlaceholder",
|
||||
"Months without purchase"
|
||||
)}
|
||||
type="number"
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{type === "new_user" && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="window_hours"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("form.windowHours", "Window Hours")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={1}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
placeholder={t(
|
||||
"form.windowHoursPlaceholder",
|
||||
"Hours after registration"
|
||||
)}
|
||||
type="number"
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="priority"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("priority", "Priority")}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
onValueChange={(value) => field.onChange(value)}
|
||||
placeholder="0"
|
||||
type="number"
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="start_time"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("startTime", "Start Time")}</FormLabel>
|
||||
<FormControl>
|
||||
<DatePicker
|
||||
onChange={(value) => field.onChange(value)}
|
||||
placeholder={t("form.selectStartTime", "Select time")}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="end_time"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("endTime", "End Time")}</FormLabel>
|
||||
<FormControl>
|
||||
<DatePicker
|
||||
onChange={(value) => field.onChange(value)}
|
||||
placeholder={t("form.selectEndTime", "Select time")}
|
||||
value={field.value}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center justify-between rounded-md border p-3">
|
||||
<div>
|
||||
<FormLabel>{t("enabled", "Enabled")}</FormLabel>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
<SheetFooter>
|
||||
<Button disabled={loading} form="promo-rule-form" type="submit">
|
||||
{t("confirm", "Confirm")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { unitConversion } from "@workspace/ui/utils/unit-conversions";
|
||||
|
||||
export const promoRuleTypes: API.PromoRuleType[] = [
|
||||
"inactive_user",
|
||||
"new_user",
|
||||
"campaign",
|
||||
];
|
||||
|
||||
export function formatCurrency(value?: number) {
|
||||
if (typeof value !== "number") return "--";
|
||||
return `$${unitConversion("centsToDollars", value)}`;
|
||||
}
|
||||
|
||||
export function parseOptionalNumber(value?: string) {
|
||||
if (!value) return;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
export function getSubscribeUnitPrice(subscribe?: API.SubscribeItem) {
|
||||
return typeof subscribe?.unit_price === "number" ? subscribe.unit_price : 0;
|
||||
}
|
||||
|
||||
export function getSubscribeDiscounts(subscribe?: API.SubscribeItem) {
|
||||
return (subscribe?.discount || []).filter(
|
||||
(item) => typeof item.quantity === "number" && item.quantity > 0
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { useNode } from "@/stores/node";
|
||||
import { useServer } from "@/stores/server";
|
||||
import DynamicMultiplier from "./dynamic-multiplier";
|
||||
import OnlineUsersCell from "./online-users-cell";
|
||||
import ServerBatchSheet from "./server-batch-sheet";
|
||||
import ServerConfig from "./server-config";
|
||||
import ServerForm from "./server-form";
|
||||
import ServerInstall from "./server-install";
|
||||
@@ -184,6 +185,14 @@ export default function Servers() {
|
||||
isServerReferencedByNodes(row.id)
|
||||
);
|
||||
return [
|
||||
<ServerBatchSheet
|
||||
key="batch-update"
|
||||
onSuccess={() => {
|
||||
ref.current?.refresh();
|
||||
fetchServers();
|
||||
}}
|
||||
rows={rows}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@workspace/ui/components/accordion";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Checkbox } from "@workspace/ui/components/checkbox";
|
||||
import { Form } from "@workspace/ui/components/form";
|
||||
import { Label } from "@workspace/ui/components/label";
|
||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { cn } from "@workspace/ui/lib/utils";
|
||||
import { updateServer } from "@workspace/ui/services/admin/server";
|
||||
import { useState } from "react";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
formSchema,
|
||||
getProtocolDefaultConfig,
|
||||
protocols as PROTOCOLS,
|
||||
useProtocolFields,
|
||||
} from "./form-schema";
|
||||
import { renderGroupCard } from "./server-form";
|
||||
|
||||
type SimpleFieldKey = "name" | "country" | "city" | "address";
|
||||
type FieldKey = SimpleFieldKey | "protocols";
|
||||
|
||||
interface SimplePatch {
|
||||
name: string;
|
||||
country: string;
|
||||
city: string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
export default function ServerBatchSheet({
|
||||
rows,
|
||||
onSuccess,
|
||||
}: {
|
||||
rows: API.Server[];
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation("servers");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [accordionValue, setAccordionValue] = useState<string>();
|
||||
|
||||
const [enabledFields, setEnabledFields] = useState<Set<FieldKey>>(new Set());
|
||||
const [patch, setPatch] = useState<SimplePatch>({
|
||||
name: "",
|
||||
country: "",
|
||||
city: "",
|
||||
address: "",
|
||||
});
|
||||
|
||||
const PROTOCOL_FIELDS = useProtocolFields();
|
||||
|
||||
const protocolForm = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
address: "",
|
||||
country: "",
|
||||
city: "",
|
||||
protocols: PROTOCOLS.map((type) => getProtocolDefaultConfig(type)),
|
||||
},
|
||||
});
|
||||
|
||||
const protocolsValues = useWatch({
|
||||
control: protocolForm.control,
|
||||
name: "protocols",
|
||||
});
|
||||
|
||||
function toggleField(key: FieldKey) {
|
||||
setEnabledFields((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function isEnabled(key: FieldKey) {
|
||||
return enabledFields.has(key);
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (rows.length === 0) return;
|
||||
if (enabledFields.size === 0) {
|
||||
toast.warning(
|
||||
t(
|
||||
"batch_no_fields_selected",
|
||||
"Please select at least one field to update"
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate enabled simple fields
|
||||
if (enabledFields.has("name") && !patch.name.trim()) {
|
||||
toast.warning(t("batch_name_required", "Name cannot be empty"));
|
||||
return;
|
||||
}
|
||||
if (enabledFields.has("address") && !patch.address.trim()) {
|
||||
toast.warning(t("batch_address_required", "Address cannot be empty"));
|
||||
return;
|
||||
}
|
||||
|
||||
const activePatch: Record<string, any> = {};
|
||||
for (const key of enabledFields) {
|
||||
if (key === "protocols") {
|
||||
const formValues = protocolForm.getValues();
|
||||
const filteredProtocols = (formValues.protocols || []).filter(
|
||||
(p: any) => {
|
||||
const port = Number(p?.port);
|
||||
return p && Number.isFinite(port) && port > 0 && port <= 65_535;
|
||||
}
|
||||
);
|
||||
activePatch.protocols = filteredProtocols;
|
||||
} else {
|
||||
activePatch[key] = patch[key];
|
||||
}
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const results = await Promise.allSettled(
|
||||
rows.map((row) => {
|
||||
const body: API.UpdateServerRequest = {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
country: row.country as string | undefined,
|
||||
city: row.city as string | undefined,
|
||||
address: row.address,
|
||||
sort: row.sort,
|
||||
protocols: row.protocols,
|
||||
...activePatch,
|
||||
};
|
||||
return updateServer(body);
|
||||
})
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "fulfilled").length;
|
||||
const failed = results.filter((r) => r.status === "rejected").length;
|
||||
|
||||
if (failed === 0) {
|
||||
toast.success(
|
||||
t("batch_updated", "Updated {{count}} servers", { count: succeeded })
|
||||
);
|
||||
setOpen(false);
|
||||
setEnabledFields(new Set());
|
||||
onSuccess();
|
||||
} else if (succeeded > 0) {
|
||||
toast.warning(
|
||||
t("batch_partial", "{{succeeded}} updated, {{failed}} failed", {
|
||||
succeeded,
|
||||
failed,
|
||||
})
|
||||
);
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(t("batch_update_failed", "Batch update failed"));
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOpen() {
|
||||
setEnabledFields(new Set());
|
||||
setPatch({ name: "", country: "", city: "", address: "" });
|
||||
protocolForm.reset({
|
||||
name: "",
|
||||
address: "",
|
||||
country: "",
|
||||
city: "",
|
||||
protocols: PROTOCOLS.map((type) => getProtocolDefaultConfig(type)),
|
||||
});
|
||||
setAccordionValue(undefined);
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
const simpleFields: Array<{
|
||||
key: SimpleFieldKey;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
}> = [
|
||||
{ key: "name", label: t("name", "Name") },
|
||||
{ key: "country", label: t("country", "Country") },
|
||||
{ key: "city", label: t("city", "City") },
|
||||
{
|
||||
key: "address",
|
||||
label: t("address", "Address"),
|
||||
placeholder: t("address_placeholder", "Server address"),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<SheetTrigger asChild>
|
||||
<Button onClick={handleOpen} variant="outline">
|
||||
{t("batch_update", "Batch Update")}
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
|
||||
<SheetContent className="w-[700px] max-w-full gap-0 md:max-w-3xl">
|
||||
<SheetHeader>
|
||||
<SheetTitle>
|
||||
{t("batch_update_title", "Batch Update ({{count}} servers)", {
|
||||
count: rows.length,
|
||||
})}
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<ScrollArea className="h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6 pt-4">
|
||||
<p className="mb-4 text-muted-foreground text-sm">
|
||||
{t(
|
||||
"batch_update_desc",
|
||||
"Check the fields you want to overwrite. Unchecked fields will keep their original values."
|
||||
)}
|
||||
</p>
|
||||
|
||||
<Form {...protocolForm}>
|
||||
<form className="space-y-5">
|
||||
{/* Simple text fields */}
|
||||
{simpleFields.map(({ key, label, placeholder }) => (
|
||||
<div className="flex items-start gap-3" key={key}>
|
||||
<Checkbox
|
||||
checked={isEnabled(key)}
|
||||
id={`batch-server-${key}`}
|
||||
onCheckedChange={() => toggleField(key)}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={isEnabled(key) ? "" : "text-muted-foreground"}
|
||||
htmlFor={`batch-server-${key}`}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
<div
|
||||
className={
|
||||
isEnabled(key) ? "" : "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<EnhancedInput
|
||||
onValueChange={(v) =>
|
||||
setPatch((p) => ({ ...p, [key]: String(v ?? "") }))
|
||||
}
|
||||
placeholder={placeholder}
|
||||
value={patch[key]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Protocol Configurations */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={isEnabled("protocols")}
|
||||
id="batch-server-protocols"
|
||||
onCheckedChange={() => toggleField("protocols")}
|
||||
/>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label
|
||||
className={
|
||||
isEnabled("protocols") ? "" : "text-muted-foreground"
|
||||
}
|
||||
htmlFor="batch-server-protocols"
|
||||
>
|
||||
{t("protocol_configurations", "Protocol Configurations")}
|
||||
</Label>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(
|
||||
"protocol_configurations_desc",
|
||||
"Enable and configure the required protocol types"
|
||||
)}
|
||||
</p>
|
||||
<div
|
||||
className={
|
||||
isEnabled("protocols")
|
||||
? ""
|
||||
: "pointer-events-none opacity-40"
|
||||
}
|
||||
>
|
||||
<Accordion
|
||||
className="w-full space-y-3"
|
||||
collapsible
|
||||
onValueChange={setAccordionValue}
|
||||
type="single"
|
||||
value={accordionValue}
|
||||
>
|
||||
{PROTOCOLS.map((type) => {
|
||||
const i = Math.max(0, PROTOCOLS.indexOf(type));
|
||||
const current = (protocolsValues?.[i] || {}) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
const isProtocolEnabled = current?.enable;
|
||||
const fields = PROTOCOL_FIELDS[type] || [];
|
||||
return (
|
||||
<AccordionItem
|
||||
className="mb-2 rounded-lg border"
|
||||
key={type}
|
||||
value={type}
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="font-medium capitalize">
|
||||
{type}
|
||||
</span>
|
||||
{current.transport && (
|
||||
<Badge
|
||||
className="text-xs"
|
||||
variant="secondary"
|
||||
>
|
||||
{current.transport.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
{current.security &&
|
||||
current.security !== "none" && (
|
||||
<Badge
|
||||
className="text-xs"
|
||||
variant="outline"
|
||||
>
|
||||
{current.security.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
{current.port && (
|
||||
<Badge className="text-xs">
|
||||
{current.port}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"text-xs",
|
||||
isProtocolEnabled
|
||||
? "text-green-500"
|
||||
: "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{isProtocolEnabled
|
||||
? t("enabled", "Enabled")
|
||||
: t("disabled", "Disabled")}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={!!isProtocolEnabled}
|
||||
className="mr-2"
|
||||
onCheckedChange={(checked) => {
|
||||
protocolForm.setValue(
|
||||
`protocols.${i}.enable` as any,
|
||||
checked
|
||||
);
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pt-0 pb-4">
|
||||
<div className="-mx-4 space-y-4 rounded-b-lg border-t px-4 pt-4">
|
||||
{renderGroupCard(
|
||||
t("basic", "Basic Configuration"),
|
||||
fields,
|
||||
"basic",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
{renderGroupCard(
|
||||
t("obfs", "Obfuscation"),
|
||||
fields,
|
||||
"obfs",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
{renderGroupCard(
|
||||
t("transport", "Transport"),
|
||||
fields,
|
||||
"transport",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
{renderGroupCard(
|
||||
t("security", "Security"),
|
||||
fields,
|
||||
"security",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
{renderGroupCard(
|
||||
t("reality", "Reality"),
|
||||
fields,
|
||||
"reality",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
{renderGroupCard(
|
||||
t("encryption", "Encryption"),
|
||||
fields,
|
||||
"encryption",
|
||||
protocolForm.control,
|
||||
protocolForm,
|
||||
i,
|
||||
current
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</ScrollArea>
|
||||
|
||||
<SheetFooter className="flex-row justify-end gap-2 pt-3">
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
{t("cancel", "Cancel")}
|
||||
</Button>
|
||||
<Button disabled={loading} onClick={handleSubmit}>
|
||||
{t("confirm", "Confirm")}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -184,7 +184,9 @@ function DynamicField({
|
||||
{...fieldProps}
|
||||
max={field.max}
|
||||
min={field.min}
|
||||
onValueChange={(v) => fieldProps.onChange(v)}
|
||||
onValueChange={(v) =>
|
||||
fieldProps.onChange(v === "" ? undefined : Number(v))
|
||||
}
|
||||
placeholder={field.placeholder}
|
||||
step={field.step || 1}
|
||||
suffix={field.suffix}
|
||||
@@ -308,7 +310,7 @@ function renderFieldsByGroup(
|
||||
);
|
||||
}
|
||||
|
||||
function renderGroupCard(
|
||||
export function renderGroupCard(
|
||||
title: string,
|
||||
fields: FieldConfig[],
|
||||
group: string,
|
||||
@@ -362,15 +364,52 @@ export default function ServerForm(props: {
|
||||
const { isProtocolUsedInNodes } = useNode();
|
||||
const PROTOCOL_FIELDS = useProtocolFields();
|
||||
|
||||
/**
|
||||
* mergeProtocol - 将后端返回的协议数据与前端默认配置安全合并。
|
||||
* 过滤掉空字符串 "",避免覆盖默认的枚举值(如 flow="none"),
|
||||
* 从而防止 Zod 枚举校验失败。
|
||||
* @param existingProtocol - 后端返回的协议对象(可能含空字符串)
|
||||
* @param defaultConfig - 前端定义的安全默认配置
|
||||
* @returns 合并后的协议对象
|
||||
*/
|
||||
function mergeProtocol(
|
||||
existingProtocol: Record<string, any> | undefined,
|
||||
defaultConfig: Record<string, any>
|
||||
) {
|
||||
if (!existingProtocol) return defaultConfig;
|
||||
const merged = { ...defaultConfig };
|
||||
for (const key in existingProtocol) {
|
||||
if (Object.hasOwn(existingProtocol, key)) {
|
||||
const val = existingProtocol[key];
|
||||
// 空字符串降级为默认值,避免 Zod 枚举校验错误
|
||||
if (val !== "") {
|
||||
merged[key] = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* buildSanitizedProtocols - 为所有协议类型构建安全的初始表单数据。
|
||||
* @param protocols - 后端返回的已有协议数组
|
||||
* @returns 清洗后的完整协议配置数组
|
||||
*/
|
||||
function buildSanitizedProtocols(protocols?: any[]) {
|
||||
return PROTOCOLS.map((type) => {
|
||||
const existing = protocols?.find((p) => p.type === type);
|
||||
return mergeProtocol(existing as any, getProtocolDefaultConfig(type));
|
||||
});
|
||||
}
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
address: "",
|
||||
country: "",
|
||||
city: "",
|
||||
protocols: [] as any[],
|
||||
...initialValues,
|
||||
name: initialValues?.name ?? "",
|
||||
address: initialValues?.address ?? "",
|
||||
country: initialValues?.country ?? "",
|
||||
city: initialValues?.city ?? "",
|
||||
protocols: buildSanitizedProtocols(initialValues?.protocols as any[]),
|
||||
},
|
||||
});
|
||||
const { control } = form;
|
||||
@@ -380,20 +419,11 @@ export default function ServerForm(props: {
|
||||
useEffect(() => {
|
||||
if (initialValues) {
|
||||
form.reset({
|
||||
name: "",
|
||||
address: "",
|
||||
country: "",
|
||||
city: "",
|
||||
...initialValues,
|
||||
protocols: PROTOCOLS.map((type) => {
|
||||
const existingProtocol = initialValues.protocols?.find(
|
||||
(p) => p.type === type
|
||||
);
|
||||
const defaultConfig = getProtocolDefaultConfig(type);
|
||||
return existingProtocol
|
||||
? { ...defaultConfig, ...existingProtocol }
|
||||
: defaultConfig;
|
||||
}),
|
||||
name: initialValues.name ?? "",
|
||||
address: initialValues.address ?? "",
|
||||
country: initialValues.country ?? "",
|
||||
city: initialValues.city ?? "",
|
||||
protocols: buildSanitizedProtocols(initialValues.protocols as any[]),
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
@@ -686,8 +716,22 @@ export default function ServerForm(props: {
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={form.handleSubmit(handleSubmit, (errors) => {
|
||||
const key = Object.keys(errors)[0] as keyof typeof errors;
|
||||
if (key) toast.error(String(errors[key]?.message));
|
||||
const getFirstErrorMessage = (
|
||||
errObj: any
|
||||
): string | undefined => {
|
||||
if (!errObj) return;
|
||||
if (errObj.message && typeof errObj.message === "string")
|
||||
return errObj.message;
|
||||
for (const k in errObj) {
|
||||
if (Object.hasOwn(errObj, k)) {
|
||||
const msg = getFirstErrorMessage(errObj[k]);
|
||||
if (msg) return msg;
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
const msg = getFirstErrorMessage(errors);
|
||||
if (msg) toast.error(msg);
|
||||
return false;
|
||||
})}
|
||||
>
|
||||
|
||||
@@ -27,10 +27,12 @@ type Props = {
|
||||
server: API.Server;
|
||||
};
|
||||
|
||||
const DEFAULT_API_HOST = "https://api.hifast.biz";
|
||||
|
||||
export default function ServerInstall({ server }: Props) {
|
||||
const { t } = useTranslation("servers");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [domain, setDomain] = useState("");
|
||||
const [domain, setDomain] = useState(DEFAULT_API_HOST);
|
||||
|
||||
const { data: cfgResp } = useQuery({
|
||||
queryKey: ["getNodeConfig"],
|
||||
@@ -43,8 +45,7 @@ export default function ServerInstall({ server }: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
const host = localStorage.getItem("API_HOST") ?? window.location.origin;
|
||||
setDomain(host);
|
||||
setDomain(DEFAULT_API_HOST);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
@@ -75,7 +76,6 @@ export default function ServerInstall({ server }: Props) {
|
||||
|
||||
const onDomainChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
|
||||
setDomain(e.target.value);
|
||||
localStorage.setItem("API_HOST", e.target.value);
|
||||
}, []);
|
||||
return (
|
||||
<Dialog onOpenChange={setOpen} open={open}>
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { Textarea } from "@workspace/ui/components/textarea";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
@@ -40,6 +41,8 @@ const registerSchema = z.object({
|
||||
trial_subscribe: z.number().optional(),
|
||||
trial_time: z.number().optional(),
|
||||
trial_time_unit: z.string().optional(),
|
||||
enable_trial_email_whitelist: z.boolean().optional(),
|
||||
trial_email_domain_whitelist: z.string().optional(),
|
||||
enable_ip_register_limit: z.boolean().optional(),
|
||||
ip_register_limit: z.number().optional(),
|
||||
ip_register_limit_duration: z.number().optional(),
|
||||
@@ -72,6 +75,8 @@ export default function RegisterConfig() {
|
||||
trial_subscribe: undefined,
|
||||
trial_time: 0,
|
||||
trial_time_unit: "day",
|
||||
enable_trial_email_whitelist: false,
|
||||
trial_email_domain_whitelist: "",
|
||||
enable_ip_register_limit: false,
|
||||
ip_register_limit: 1,
|
||||
ip_register_limit_duration: 1,
|
||||
@@ -331,114 +336,182 @@ export default function RegisterConfig() {
|
||||
/>
|
||||
|
||||
{form.watch("enable_trial") && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_time"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("register.trialConfig", "Trial Configuration")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-2">
|
||||
<EnhancedInput
|
||||
className="flex-1"
|
||||
min={0}
|
||||
onValueBlur={(value) =>
|
||||
field.onChange(Number(value))
|
||||
}
|
||||
placeholder={t(
|
||||
"register.inputPlaceholder",
|
||||
"Please enter"
|
||||
)}
|
||||
prefix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_subscribe"
|
||||
render={({ field }) => (
|
||||
<Combobox
|
||||
className="w-32 rounded-r-none bg-secondary"
|
||||
onChange={(value: number) => {
|
||||
if (value) {
|
||||
field.onChange(value);
|
||||
}
|
||||
}}
|
||||
options={subscribes?.map((item) => ({
|
||||
label: item.name!,
|
||||
value: item.id!,
|
||||
}))}
|
||||
placeholder={t(
|
||||
"register.selectPlaceholder",
|
||||
"Please select"
|
||||
)}
|
||||
value={field.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
suffix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_time_unit"
|
||||
render={({ field: unitField }) => (
|
||||
<Combobox
|
||||
className="w-32 rounded-l-none bg-secondary"
|
||||
onChange={(value: string) => {
|
||||
unitField.onChange(value);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
label: t("register.none", "None"),
|
||||
value: "None",
|
||||
},
|
||||
{
|
||||
label: t("register.year", "Year(s)"),
|
||||
value: "Year",
|
||||
},
|
||||
{
|
||||
label: t("register.month", "Month(s)"),
|
||||
value: "Month",
|
||||
},
|
||||
{
|
||||
label: t("register.day", "Day(s)"),
|
||||
value: "Day",
|
||||
},
|
||||
{
|
||||
label: t("register.hour", "Hour(s)"),
|
||||
value: "Hour",
|
||||
},
|
||||
{
|
||||
label: t(
|
||||
"register.minute",
|
||||
"Minute(s)"
|
||||
),
|
||||
value: "Minute",
|
||||
},
|
||||
]}
|
||||
placeholder={t(
|
||||
"register.selectPlaceholder",
|
||||
"Please select"
|
||||
)}
|
||||
value={unitField.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
type="number"
|
||||
value={field.value}
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_time"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("register.trialConfig", "Trial Configuration")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-2">
|
||||
<EnhancedInput
|
||||
className="flex-1"
|
||||
min={0}
|
||||
onValueBlur={(value) =>
|
||||
field.onChange(Number(value))
|
||||
}
|
||||
placeholder={t(
|
||||
"register.inputPlaceholder",
|
||||
"Please enter"
|
||||
)}
|
||||
prefix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_subscribe"
|
||||
render={({ field }) => (
|
||||
<Combobox
|
||||
className="w-32 rounded-r-none bg-secondary"
|
||||
onChange={(value: number) => {
|
||||
if (value) {
|
||||
field.onChange(value);
|
||||
}
|
||||
}}
|
||||
options={subscribes?.map((item) => ({
|
||||
label: item.name!,
|
||||
value: item.id!,
|
||||
}))}
|
||||
placeholder={t(
|
||||
"register.selectPlaceholder",
|
||||
"Please select"
|
||||
)}
|
||||
value={field.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
suffix={
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_time_unit"
|
||||
render={({ field: unitField }) => (
|
||||
<Combobox
|
||||
className="w-32 rounded-l-none bg-secondary"
|
||||
onChange={(value: string) => {
|
||||
unitField.onChange(value);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
label: t("register.none", "None"),
|
||||
value: "None",
|
||||
},
|
||||
{
|
||||
label: t("register.year", "Year(s)"),
|
||||
value: "Year",
|
||||
},
|
||||
{
|
||||
label: t(
|
||||
"register.month",
|
||||
"Month(s)"
|
||||
),
|
||||
value: "Month",
|
||||
},
|
||||
{
|
||||
label: t("register.day", "Day(s)"),
|
||||
value: "Day",
|
||||
},
|
||||
{
|
||||
label: t("register.hour", "Hour(s)"),
|
||||
value: "Hour",
|
||||
},
|
||||
{
|
||||
label: t(
|
||||
"register.minute",
|
||||
"Minute(s)"
|
||||
),
|
||||
value: "Minute",
|
||||
},
|
||||
]}
|
||||
placeholder={t(
|
||||
"register.selectPlaceholder",
|
||||
"Please select"
|
||||
)}
|
||||
value={unitField.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
type="number"
|
||||
value={field.value}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"register.trialConfigDescription",
|
||||
"Configure trial subscription, duration and time unit for new users upon registration"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enable_trial_email_whitelist"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"register.enableTrialEmailWhitelist",
|
||||
"Email Domain Whitelist"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
className="!mt-0 float-end"
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"register.trialConfigDescription",
|
||||
"Configure trial subscription, duration and time unit for new users upon registration"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"register.enableTrialEmailWhitelistDescription",
|
||||
"When enabled, trial subscription is only granted to emails with whitelisted domains"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{form.watch("enable_trial_email_whitelist") && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="trial_email_domain_whitelist"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t(
|
||||
"register.trialEmailDomainWhitelist",
|
||||
"Whitelisted Domains"
|
||||
)}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder={t(
|
||||
"register.trialEmailDomainWhitelistPlaceholder",
|
||||
"gmail.com,outlook.com,edu.cn"
|
||||
)}
|
||||
rows={3}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"register.trialEmailDomainWhitelistDescription",
|
||||
"Comma-separated list of allowed email domains for trial subscription"
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -158,7 +158,22 @@ export default function VerifyConfig() {
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="local">
|
||||
{t("verify.captchaTypeLocal", "Local Image Captcha")}
|
||||
{t(
|
||||
"verify.captchaTypeLocal",
|
||||
"Local Image Captcha"
|
||||
)}
|
||||
</SelectItem>
|
||||
<SelectItem value="slider">
|
||||
{t(
|
||||
"verify.captchaTypeSlider",
|
||||
"Local Slider Captcha"
|
||||
)}
|
||||
</SelectItem>
|
||||
<SelectItem value="slider">
|
||||
{t(
|
||||
"verify.captchaTypeSlider",
|
||||
"Local Slider Captcha"
|
||||
)}
|
||||
</SelectItem>
|
||||
<SelectItem value="turnstile">
|
||||
{t(
|
||||
|
||||
@@ -23,6 +23,10 @@ import {
|
||||
getTicketList,
|
||||
updateTicketStatus,
|
||||
} from "@workspace/ui/services/admin/ticket";
|
||||
import {
|
||||
getUserDetail,
|
||||
updateUserBasicInfo,
|
||||
} from "@workspace/ui/services/admin/user";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -42,6 +46,7 @@ export default function Page() {
|
||||
const [ticketId, setTicketId] = useState<any>(null);
|
||||
|
||||
const [message, setMessage] = useState("");
|
||||
const [loadingId, setLoadingId] = useState<any>(null);
|
||||
|
||||
const { data: ticket, refetch: refetchTicket } = useQuery({
|
||||
queryKey: ["getTicket", ticketId],
|
||||
@@ -74,45 +79,214 @@ export default function Page() {
|
||||
action={ref}
|
||||
actions={{
|
||||
render(row) {
|
||||
if (row.status !== 4) {
|
||||
if (row.status === 1) {
|
||||
return [
|
||||
<Button key="reply" onClick={() => setTicketId(row.id)}>
|
||||
{t("reply", "Reply")}
|
||||
</Button>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
"closeWarning",
|
||||
"Once closed, the ticket cannot be operated on. Please proceed with caution."
|
||||
)}
|
||||
description="您确定要取消此次打款吗?取消后系统将记录此操作并关闭工单。"
|
||||
key="cancel-payout"
|
||||
onConfirm={async () => {
|
||||
setLoadingId(row.id);
|
||||
try {
|
||||
await updateTicketStatus({
|
||||
id: row.id,
|
||||
status: 3,
|
||||
});
|
||||
toast.success("已取消打款并关闭工单");
|
||||
ref.current?.refresh();
|
||||
} catch (e) {
|
||||
console.error("Cancel payout failed", e);
|
||||
toast.error("取消打款失败");
|
||||
}
|
||||
setLoadingId(null);
|
||||
}}
|
||||
title="确认取消打款?"
|
||||
trigger={
|
||||
<Button
|
||||
className="mr-2"
|
||||
disabled={loadingId === row.id}
|
||||
variant="outline"
|
||||
>
|
||||
{loadingId === row.id && (
|
||||
<Icon
|
||||
className="mr-2 animate-spin"
|
||||
icon="lucide:loader-2"
|
||||
/>
|
||||
)}
|
||||
取消打款
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={
|
||||
<div className="flex flex-col gap-2">
|
||||
<p>
|
||||
请确保您已完成线下打款操作。点击确认后,系统将自动扣除用户对应的佣金并关闭此工单,此操作不可撤销。
|
||||
</p>
|
||||
<p className="font-bold text-rose-500 text-sm">
|
||||
※ USDT 提现需手续费 1 USDT
|
||||
</p>
|
||||
<p className="font-bold text-rose-500 text-sm">
|
||||
※ 支付宝/微信提现手续费 5%
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
key="colse"
|
||||
onConfirm={async () => {
|
||||
setLoadingId(row.id);
|
||||
try {
|
||||
const titleStr = row.title || "";
|
||||
const parts = titleStr.split("-");
|
||||
if (parts.length > 1) {
|
||||
const deductAmount = Number.parseFloat(
|
||||
parts?.[1] ?? "0"
|
||||
);
|
||||
if (!Number.isNaN(deductAmount)) {
|
||||
const res = await getUserDetail({ id: row.user_id });
|
||||
const user = res?.data?.data;
|
||||
if (user && typeof user.commission !== "undefined") {
|
||||
const deductAmountCent = deductAmount * 100;
|
||||
if (Number(user.commission) < deductAmountCent) {
|
||||
toast.error("用户佣金余额不足,无法完成打款扣费");
|
||||
setLoadingId(null);
|
||||
return;
|
||||
}
|
||||
const newCommission =
|
||||
Number(user.commission) - deductAmountCent;
|
||||
await updateUserBasicInfo({
|
||||
user_id: row.user_id,
|
||||
commission: newCommission,
|
||||
} as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Update commission failed", e);
|
||||
}
|
||||
|
||||
await updateTicketStatus({
|
||||
id: row.id,
|
||||
status: 4,
|
||||
});
|
||||
toast.success(t("closeSuccess", "Closed successfully"));
|
||||
ref.current?.refresh();
|
||||
setLoadingId(null);
|
||||
}}
|
||||
title={t("confirmClose", "Are you sure you want to close?")}
|
||||
title="确认已完成打款?"
|
||||
trigger={
|
||||
<Button variant="destructive">{t("close", "Close")}</Button>
|
||||
<Button
|
||||
disabled={loadingId === row.id}
|
||||
variant="destructive"
|
||||
>
|
||||
{loadingId === row.id && (
|
||||
<Icon
|
||||
className="mr-2 animate-spin"
|
||||
icon="lucide:loader-2"
|
||||
/>
|
||||
)}
|
||||
确认打款并结单
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description="检查佣金是否扣除,如已经扣除才可进行关闭,此操作不扣除佣金仅关闭工单。"
|
||||
key="cancel-payout-1"
|
||||
onConfirm={async () => {
|
||||
setLoadingId(row.id);
|
||||
try {
|
||||
await updateTicketStatus({
|
||||
id: row.id,
|
||||
status: 4,
|
||||
});
|
||||
toast.success("已关闭工单");
|
||||
ref.current?.refresh();
|
||||
} catch (e) {
|
||||
console.error("Cancel payout failed", e);
|
||||
toast.error("关闭工单失败");
|
||||
}
|
||||
setLoadingId(null);
|
||||
}}
|
||||
title="确认关闭订单?"
|
||||
trigger={
|
||||
<Button
|
||||
className="mr-2"
|
||||
disabled={loadingId === row.id}
|
||||
variant="secondary"
|
||||
>
|
||||
{loadingId === row.id && (
|
||||
<Icon
|
||||
className="mr-2 animate-spin"
|
||||
icon="lucide:loader-2"
|
||||
/>
|
||||
)}
|
||||
关闭
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
];
|
||||
}
|
||||
return [
|
||||
<Button key="check" onClick={() => setTicketId(row.id)} size="sm">
|
||||
{t("check", "Check")}
|
||||
</Button>,
|
||||
];
|
||||
return [];
|
||||
},
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: t("title", "Title"),
|
||||
id: "withdrawal_type",
|
||||
header: "提现类型",
|
||||
cell: ({ row }) => {
|
||||
const title = row.original.title || "";
|
||||
return title.split("-")[0] || title;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "withdrawal_amount",
|
||||
header: "提现金额",
|
||||
cell: ({ row }) => {
|
||||
const title = row.original.title || "";
|
||||
const parts = title.split("-");
|
||||
if (parts.length < 2) return "";
|
||||
return (
|
||||
<span className="font-bold text-rose-500">${parts[1]}</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "withdrawal_method",
|
||||
header: "提现方式",
|
||||
cell: ({ row }) => {
|
||||
const desc = row.original.description || "";
|
||||
return desc.split("-")[0] || "";
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "withdrawal_content",
|
||||
header: "提现内容",
|
||||
cell: ({ row }) => {
|
||||
const desc = row.original.description || "";
|
||||
const parts = desc.split("-");
|
||||
if (parts.length < 2) return "";
|
||||
const content = parts[1];
|
||||
if (content?.startsWith("data:image/")) {
|
||||
return (
|
||||
<img
|
||||
alt="withdrawal"
|
||||
className="h-10 w-10 cursor-zoom-in rounded border object-cover"
|
||||
height={40} // 这里的数值根据你的 UI 设计调整
|
||||
onClick={() => {
|
||||
const win = window.open();
|
||||
win?.document.write(`<img src="${content}" />`);
|
||||
}}
|
||||
src={content}
|
||||
width={40}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <span className="font-semibold">{content}</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "user_id",
|
||||
|
||||
@@ -261,6 +261,11 @@ export function FamilyDetailSheet({
|
||||
<Badge variant="outline">
|
||||
ID: {member.user_id}
|
||||
</Badge>
|
||||
{member.auth_type ? (
|
||||
<Badge className="uppercase">
|
||||
{member.auth_type}
|
||||
</Badge>
|
||||
) : null}
|
||||
{member.device_no ? (
|
||||
<Badge variant="outline">
|
||||
<span className="font-mono">
|
||||
@@ -268,7 +273,16 @@ export function FamilyDetailSheet({
|
||||
</span>
|
||||
</Badge>
|
||||
) : null}
|
||||
<span>{member.identifier}</span>
|
||||
{member.device_type ? (
|
||||
<Badge variant="secondary">
|
||||
{member.device_type}
|
||||
</Badge>
|
||||
) : null}
|
||||
<span>
|
||||
{member.auth_type === "device"
|
||||
? member.device_no || member.identifier
|
||||
: member.identifier}
|
||||
</span>
|
||||
<Badge>
|
||||
{getFamilyRoleLabel(t, member.role_name)}
|
||||
</Badge>
|
||||
|
||||
@@ -54,8 +54,19 @@ export default function FamilyManagement({
|
||||
{
|
||||
accessorKey: "owner_identifier",
|
||||
header: t("owner", "Owner"),
|
||||
cell: ({ row }) =>
|
||||
`${row.original.owner_identifier} (ID: ${row.original.owner_user_id})`,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1">
|
||||
{row.original.owner_auth_type ? (
|
||||
<Badge className="uppercase">
|
||||
{row.original.owner_auth_type}
|
||||
</Badge>
|
||||
) : null}
|
||||
<span>{row.original.owner_identifier}</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
(ID: {row.original.owner_user_id})
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link, useSearch } from "@tanstack/react-router";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@workspace/ui/components/dialog";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@workspace/ui/components/dropdown-menu";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@workspace/ui/components/select";
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@workspace/ui/components/popover";
|
||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
@@ -38,37 +34,48 @@ import {
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@workspace/ui/components/tabs";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@workspace/ui/components/tooltip";
|
||||
// import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||
import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import {
|
||||
// getUserGroupList,
|
||||
previewUserNodes,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import {
|
||||
createUser,
|
||||
deleteUser,
|
||||
// deleteUser,
|
||||
getUserDetail,
|
||||
getUserList,
|
||||
updateUserBasicInfo,
|
||||
} from "@workspace/ui/services/admin/user";
|
||||
import {
|
||||
// getUserGroupList,
|
||||
previewUserNodes,
|
||||
} from "@workspace/ui/services/admin/group";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { FilePenLine } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { Display } from "@/components/display";
|
||||
import { useSubscribe } from "@/stores/subscribe";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import FamilyManagement from "./family";
|
||||
import { RemarkForm } from "./remark-form";
|
||||
import { buildUserBasicInfoPayload } from "./user-basic-info-payload";
|
||||
import { UserDetail } from "./user-detail";
|
||||
import UserForm from "./user-form";
|
||||
import { UserIdentifier } from "./user-identifier";
|
||||
import { UserInviteStatsSheet } from "./user-invite-stats-sheet";
|
||||
import { AuthMethodsForm } from "./user-profile/auth-methods-form";
|
||||
import { BasicInfoForm } from "./user-profile/basic-info-form";
|
||||
import { NotifySettingsForm } from "./user-profile/notify-settings-form";
|
||||
import { UserSearchBar } from "./user-search-bar";
|
||||
import UserSubscription from "./user-subscription";
|
||||
|
||||
// import EditUserGroupDialog from "./edit-user-group-dialog";
|
||||
|
||||
export default function User() {
|
||||
@@ -84,11 +91,34 @@ export default function User() {
|
||||
value: sp.search || sp.user_id || "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
searchRef.current = {
|
||||
type: sp.user_id ? "user_id" : "email",
|
||||
value: sp.search || sp.user_id || "",
|
||||
};
|
||||
ref.current?.refresh();
|
||||
}, [sp.search, sp.user_id]);
|
||||
|
||||
const handleSearch = useCallback((type: string, value: string) => {
|
||||
searchRef.current = { type, value };
|
||||
ref.current?.refresh();
|
||||
}, []);
|
||||
|
||||
const buildSearchParams = () => {
|
||||
const { type, value } = searchRef.current;
|
||||
if (!value) return {};
|
||||
switch (type) {
|
||||
case "user_id":
|
||||
return { user_id: Number(value) };
|
||||
case "device":
|
||||
return { search: value };
|
||||
case "subscribe_id":
|
||||
return { subscribe_id: Number(value) };
|
||||
default:
|
||||
return { search: value };
|
||||
}
|
||||
};
|
||||
|
||||
// const { data: userGroupsData } = useQuery({
|
||||
// queryKey: ["userGroups"],
|
||||
// queryFn: async () => {
|
||||
@@ -122,8 +152,7 @@ export default function User() {
|
||||
onChanged={() => ref.current?.refresh()}
|
||||
userId={row.id}
|
||||
/>,
|
||||
<PreviewNodesDialog key="preview-nodes" userId={row.id} />,
|
||||
<ConfirmButton
|
||||
/* <ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description={t(
|
||||
@@ -140,50 +169,40 @@ export default function User() {
|
||||
trigger={
|
||||
<Button variant="destructive">{t("delete", "Delete")}</Button>
|
||||
}
|
||||
/>,
|
||||
/>,*/
|
||||
<DropdownMenu key="more" modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline">{t("more", "More")}</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<InviteStatsMenuItem userId={row.id} />
|
||||
<PreviewNodesMenuItem userId={row.id} />
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
search={{ user_id: String(row.id) }}
|
||||
to="/dashboard/order"
|
||||
>
|
||||
<Link search={{ user_id: row.id }} to="/dashboard/order">
|
||||
{t("orderList", "Order List")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
search={{ user_id: String(row.id) }}
|
||||
to="/dashboard/log/login"
|
||||
>
|
||||
<Link search={{ user_id: row.id }} to="/dashboard/log/login">
|
||||
{t("loginLogs", "Login Logs")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
search={{ user_id: String(row.id) }}
|
||||
to="/dashboard/log/balance"
|
||||
>
|
||||
<Link search={{ user_id: row.id }} to="/dashboard/log/balance">
|
||||
{t("balanceLogs", "Balance Logs")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
search={{ user_id: String(row.id) }}
|
||||
search={{ user_id: row.id }}
|
||||
to="/dashboard/log/commission"
|
||||
>
|
||||
{t("commissionLogs", "Commission Logs")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link
|
||||
search={{ user_id: String(row.id) }}
|
||||
to="/dashboard/log/gift"
|
||||
>
|
||||
<Link search={{ user_id: row.id }} to="/dashboard/log/gift">
|
||||
{t("giftLogs", "Gift Logs")}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
@@ -228,7 +247,7 @@ export default function User() {
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
},
|
||||
{
|
||||
/*{
|
||||
id: "deleted_at",
|
||||
accessorKey: "deleted_at",
|
||||
header: t("isDeleted", "Deleted"),
|
||||
@@ -240,31 +259,50 @@ export default function User() {
|
||||
<Badge variant="outline">{t("normal", "Normal")}</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
},*/
|
||||
{
|
||||
id: "auth_methods",
|
||||
accessorKey: "auth_methods",
|
||||
header: t("userName", "Username"),
|
||||
cell: ({ row }) => {
|
||||
const method = row.original.auth_methods?.[0];
|
||||
const identifier = method?.auth_identifier || "";
|
||||
const isDevice = method?.auth_type === "device";
|
||||
const deviceNo = (row.original.user_devices?.[0] as any)?.device_no;
|
||||
const display = isDevice ? deviceNo || identifier : identifier;
|
||||
return (
|
||||
<div>
|
||||
<Badge
|
||||
className="mr-1 uppercase"
|
||||
title={method?.verified ? t("verified", "Verified") : ""}
|
||||
>
|
||||
{method?.auth_type}
|
||||
</Badge>
|
||||
<span title={isDevice ? display : undefined}>{display}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
header: "设备码/邮箱",
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center">
|
||||
<UserIdentifier
|
||||
className="flex items-center"
|
||||
user={row.original}
|
||||
/>
|
||||
<Popover>
|
||||
<PopoverTrigger>
|
||||
<div className={"flex items-center"}>
|
||||
{row.original?.remark ? `(${row.original.remark})` : ""}
|
||||
<FilePenLine className={"ml-2 text-primary"} size={14} />
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className={"w-64"}>
|
||||
<RemarkForm
|
||||
initialRemark={row.original.remark}
|
||||
onSave={async (remark) => {
|
||||
const { data } = await getUserDetail({
|
||||
id: row.original.id,
|
||||
});
|
||||
const user = data.data;
|
||||
|
||||
if (!user) {
|
||||
throw new Error("User detail not found");
|
||||
}
|
||||
|
||||
await updateUserBasicInfo(
|
||||
buildUserBasicInfoPayload(user, remark)
|
||||
);
|
||||
toast.success(t("updateSuccess"));
|
||||
ref.current?.refresh();
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
/* {
|
||||
id: "balance",
|
||||
accessorKey: "balance",
|
||||
header: t("balance", "Balance"),
|
||||
@@ -279,7 +317,7 @@ export default function User() {
|
||||
cell: ({ row }) => (
|
||||
<Display type="currency" value={row.getValue("gift_amount")} />
|
||||
),
|
||||
},
|
||||
},*/
|
||||
{
|
||||
id: "commission",
|
||||
accessorKey: "commission",
|
||||
@@ -300,6 +338,48 @@ export default function User() {
|
||||
header: t("referer", "Referer"),
|
||||
cell: ({ row }) => <UserDetail id={row.original.referer_id} />,
|
||||
},
|
||||
{
|
||||
id: "last_login_time",
|
||||
accessorKey: "last_login_time",
|
||||
header: t("userStatus", "用户状态"),
|
||||
cell: ({ row }) => {
|
||||
const lastLoginTime = (
|
||||
row.original as API.User & {
|
||||
last_login_time?: number;
|
||||
}
|
||||
).last_login_time;
|
||||
const isOnline = Boolean(lastLoginTime);
|
||||
const dotClassName = isOnline ? "bg-green-500" : "bg-gray-400";
|
||||
const statusLabel = isOnline
|
||||
? t("active", "Active")
|
||||
: t("inactive", "Inactive");
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="inline-flex items-center gap-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`h-2.5 w-2.5 rounded-full ${dotClassName}`}
|
||||
/>
|
||||
<span className="sr-only">
|
||||
{isOnline
|
||||
? `${statusLabel}: ${formatDate(lastLoginTime)}`
|
||||
: statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{isOnline
|
||||
? formatDate(lastLoginTime)
|
||||
: t("neverLoggedIn", "Never logged in")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "created_at",
|
||||
accessorKey: "created_at",
|
||||
@@ -342,39 +422,10 @@ export default function User() {
|
||||
}}
|
||||
initialFilters={initialFilters}
|
||||
key={initialFilters.user_id}
|
||||
params={[
|
||||
{
|
||||
key: "subscribe_id",
|
||||
placeholder: t("subscription", "Subscription"),
|
||||
options: [
|
||||
{ label: t("all", "All"), value: "" },
|
||||
...(subscribes?.map((item) => ({
|
||||
label: item.name!,
|
||||
value: String(item.id!),
|
||||
})) || []),
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "search",
|
||||
placeholder: "Search",
|
||||
},
|
||||
{
|
||||
key: "user_id",
|
||||
placeholder: t("userId", "User ID"),
|
||||
},
|
||||
{
|
||||
key: "user_subscribe_id",
|
||||
placeholder: t("subscriptionId", "Subscription ID"),
|
||||
},
|
||||
{
|
||||
key: "short_code",
|
||||
placeholder: t("shortCode", "Short Code"),
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
request={async (pagination) => {
|
||||
const { data } = await getUserList({
|
||||
...pagination,
|
||||
...filter,
|
||||
...buildSearchParams(),
|
||||
});
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
@@ -497,6 +548,25 @@ function InviteStatsMenuItem({ userId }: { userId: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewNodesMenuItem({ userId }: { userId: number }) {
|
||||
const { t } = useTranslation("user");
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onSelect={(e) => {
|
||||
e.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
{t("previewNodes", "Preview Nodes")}
|
||||
</DropdownMenuItem>
|
||||
<PreviewNodesDialog onOpenChange={setOpen} open={open} userId={userId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DeviceGroupSheet({
|
||||
userId,
|
||||
onChanged,
|
||||
@@ -525,93 +595,16 @@ function DeviceGroupSheet({
|
||||
);
|
||||
}
|
||||
|
||||
function UserSearchBar({
|
||||
initialType,
|
||||
initialValue,
|
||||
onSearch,
|
||||
subscribes,
|
||||
function PreviewNodesDialog({
|
||||
userId,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
initialType: string;
|
||||
initialValue: string;
|
||||
onSearch: (type: string, value: string) => void;
|
||||
subscribes?: API.SubscribeItem[];
|
||||
userId: number;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation("user");
|
||||
const [searchType, setSearchType] = useState(initialType);
|
||||
const [searchValue, setSearchValue] = useState(initialValue);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
onValueChange={(v) => {
|
||||
setSearchType(v);
|
||||
setSearchValue("");
|
||||
}}
|
||||
value={searchType}
|
||||
>
|
||||
<SelectTrigger className="w-24">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="email">{t("email", "Email")}</SelectItem>
|
||||
<SelectItem value="device">{t("deviceSearch", "Device")}</SelectItem>
|
||||
<SelectItem value="user_id">{t("userId", "User ID")}</SelectItem>
|
||||
<SelectItem value="subscribe_id">
|
||||
{t("subscription", "Subscription")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{searchType === "subscribe_id" ? (
|
||||
<Combobox
|
||||
className="w-48"
|
||||
onChange={(value) => {
|
||||
setSearchValue(value);
|
||||
onSearch("subscribe_id", value);
|
||||
}}
|
||||
options={subscribes?.map((item) => ({
|
||||
label: item.name!,
|
||||
value: String(item.id!),
|
||||
}))}
|
||||
placeholder={t("subscription", "Subscription")}
|
||||
value={searchValue}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
className="w-48"
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === "Enter" && onSearch(searchType, searchValue)
|
||||
}
|
||||
placeholder={t("searchInputPlaceholder", "Enter search term")}
|
||||
value={searchValue}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => onSearch(searchType, searchValue)}
|
||||
variant="default"
|
||||
>
|
||||
{t("search", "Search")}
|
||||
</Button>
|
||||
{searchValue && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setSearchValue("");
|
||||
onSearch(searchType, "");
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
{t("resetSearch", "Reset")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PreviewNodesDialog({ userId }: { userId: number }) {
|
||||
const { t } = useTranslation("user");
|
||||
const [open, setOpen] = useState(false);
|
||||
const { data: previewData, isLoading } = useQuery({
|
||||
enabled: open,
|
||||
queryKey: ["previewUserNodes", userId],
|
||||
@@ -622,10 +615,7 @@ function PreviewNodesDialog({ userId }: { userId: number }) {
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={setOpen} open={open}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">{t("previewNodes", "Preview Nodes")}</Button>
|
||||
</DialogTrigger>
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
@@ -639,16 +629,19 @@ function PreviewNodesDialog({ userId }: { userId: number }) {
|
||||
) : previewData ? (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
<span className="font-medium text-muted-foreground text-sm">
|
||||
{t("availableNodes", "Available Nodes")}:
|
||||
</span>{" "}
|
||||
{previewData.node_groups?.reduce((sum, group) => sum + (group.nodes?.length || 0), 0) || 0}
|
||||
{previewData.node_groups?.reduce(
|
||||
(sum, group) => sum + (group.nodes?.length || 0),
|
||||
0
|
||||
) || 0}
|
||||
</div>
|
||||
{previewData.node_groups && previewData.node_groups.length > 0 ? (
|
||||
<div className="max-h-[400px] overflow-y-auto space-y-4">
|
||||
<div className="max-h-[400px] space-y-4 overflow-y-auto">
|
||||
{previewData.node_groups.map((group) => (
|
||||
<div key={group.id}>
|
||||
<h4 className="text-sm font-semibold mb-2">
|
||||
<h4 className="mb-2 font-semibold text-sm">
|
||||
{group.name ||
|
||||
(group.id === -1
|
||||
? t("subscriptionNodes", "Subscription Nodes")
|
||||
@@ -661,16 +654,22 @@ function PreviewNodesDialog({ userId }: { userId: number }) {
|
||||
<thead>
|
||||
<tr className="border-b">
|
||||
<th className="p-2 text-left font-medium">ID</th>
|
||||
<th className="p-2 text-left font-medium">{t("name", "Name")}</th>
|
||||
<th className="p-2 text-left font-medium">{t("address", "Address")}</th>
|
||||
<th className="p-2 text-left font-medium">
|
||||
{t("name", "Name")}
|
||||
</th>
|
||||
<th className="p-2 text-left font-medium">
|
||||
{t("address", "Address")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{group.nodes.map((node) => (
|
||||
<tr key={node.id} className="border-b">
|
||||
<tr className="border-b" key={node.id}>
|
||||
<td className="p-2">{node.id}</td>
|
||||
<td className="p-2">{node.name}</td>
|
||||
<td className="p-2">{node.address}:{node.port}</td>
|
||||
<td className="p-2">
|
||||
{node.address}:{node.port}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { Popover } from "@workspace/ui/components/popover";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { RemarkForm } from "./remark-form";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
function renderRemarkForm(props: Parameters<typeof RemarkForm>[0]) {
|
||||
return render(
|
||||
<Popover open>
|
||||
<RemarkForm {...props} />
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
describe("RemarkForm", () => {
|
||||
it("submits an intentionally cleared remark", async () => {
|
||||
const onSave = vi.fn<Parameters<typeof RemarkForm>[0]["onSave"]>();
|
||||
|
||||
renderRemarkForm({ initialRemark: "old remark", onSave });
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("在此输入备注..."), {
|
||||
target: { value: "" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "保存" }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledWith(""));
|
||||
});
|
||||
|
||||
it("shows loading and keeps the input disabled while saving", async () => {
|
||||
let resolveSave: (() => void) | undefined;
|
||||
const onSave = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveSave = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
renderRemarkForm({ initialRemark: "old remark", onSave });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "保存" }));
|
||||
|
||||
expect(
|
||||
screen.getByRole("button", { name: "保存中..." }).hasAttribute("disabled")
|
||||
).toBe(true);
|
||||
expect(
|
||||
screen.getByPlaceholderText("在此输入备注...").hasAttribute("disabled")
|
||||
).toBe(true);
|
||||
|
||||
resolveSave?.();
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole("button", { name: "保存" }).hasAttribute("disabled")
|
||||
).toBe(false)
|
||||
);
|
||||
});
|
||||
|
||||
it("shows an error state and preserves input after save failure", async () => {
|
||||
const onSave = vi.fn<Parameters<typeof RemarkForm>[0]["onSave"]>();
|
||||
onSave.mockRejectedValue(new Error("failed"));
|
||||
|
||||
renderRemarkForm({ initialRemark: "old remark", onSave });
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("在此输入备注..."), {
|
||||
target: { value: "kept remark" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "保存" }));
|
||||
|
||||
expect((await screen.findByRole("alert")).textContent).toBe(
|
||||
"备注保存失败,请重试"
|
||||
);
|
||||
expect(screen.getByDisplayValue("kept remark")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { PopoverClose } from "@workspace/ui/components/popover";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
interface RemarkFormProps {
|
||||
initialRemark?: string | null;
|
||||
onSave: (remark: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export function RemarkForm({ onSave, initialRemark }: RemarkFormProps) {
|
||||
const [remark, setRemark] = useState<string>(initialRemark ?? "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const closeRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setRemark(event.target.value);
|
||||
};
|
||||
|
||||
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setSaving(true);
|
||||
|
||||
try {
|
||||
await onSave(remark);
|
||||
closeRef.current?.click();
|
||||
} catch {
|
||||
setError("备注保存失败,请重试");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSave}>
|
||||
<div className="mb-2 font-semibold text-sm">备注</div>
|
||||
<Input
|
||||
aria-invalid={Boolean(error)}
|
||||
className="w-full"
|
||||
disabled={saving}
|
||||
onChange={handleInputChange}
|
||||
placeholder="在此输入备注..."
|
||||
type="text"
|
||||
value={remark}
|
||||
/>
|
||||
{error ? (
|
||||
<p className="mt-2 text-destructive text-sm" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Button
|
||||
className="mt-2"
|
||||
disabled={saving}
|
||||
size="sm"
|
||||
type="submit"
|
||||
variant="default"
|
||||
>
|
||||
{saving ? "保存中..." : "保存"}
|
||||
</Button>
|
||||
<PopoverClose asChild>
|
||||
<button className="sr-only" ref={closeRef} type="button">
|
||||
关闭
|
||||
</button>
|
||||
</PopoverClose>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildUserBasicInfoPayload } from "./user-basic-info-payload";
|
||||
|
||||
const user = {
|
||||
id: 37,
|
||||
avatar: "https://example.com/avatar.png",
|
||||
balance: 1200,
|
||||
commission: 300,
|
||||
referral_percentage: 10,
|
||||
only_first_purchase: true,
|
||||
gift_amount: 500,
|
||||
telegram: 123_456,
|
||||
refer_code: "INVITE37",
|
||||
referer_id: 7,
|
||||
enable: true,
|
||||
is_admin: false,
|
||||
enable_balance_notify: true,
|
||||
enable_login_notify: true,
|
||||
enable_subscribe_notify: false,
|
||||
enable_trade_notify: false,
|
||||
user_group_id: 2,
|
||||
group_locked: false,
|
||||
auth_methods: [],
|
||||
user_devices: [],
|
||||
remark: "old remark",
|
||||
rules: [],
|
||||
created_at: 1_700_000_000,
|
||||
updated_at: 1_700_000_100,
|
||||
} satisfies API.User;
|
||||
|
||||
describe("buildUserBasicInfoPayload", () => {
|
||||
it("keeps the full basic user fields when updating a remark", () => {
|
||||
expect(buildUserBasicInfoPayload(user, "new remark")).toEqual({
|
||||
user_id: 37,
|
||||
avatar: "https://example.com/avatar.png",
|
||||
balance: 1200,
|
||||
commission: 300,
|
||||
referral_percentage: 10,
|
||||
only_first_purchase: true,
|
||||
gift_amount: 500,
|
||||
telegram: 123_456,
|
||||
refer_code: "INVITE37",
|
||||
referer_id: 7,
|
||||
enable: true,
|
||||
is_admin: false,
|
||||
remark: "new remark",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an intentionally cleared remark", () => {
|
||||
expect(buildUserBasicInfoPayload(user, "").remark).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { UpdateUserBasicInfoBody } from "@workspace/ui/services/admin/user";
|
||||
|
||||
export type UserBasicInfoPayload = Omit<UpdateUserBasicInfoBody, "remark"> & {
|
||||
remark: string;
|
||||
};
|
||||
|
||||
export function buildUserBasicInfoPayload(
|
||||
user: API.User,
|
||||
remark: string
|
||||
): UserBasicInfoPayload {
|
||||
return {
|
||||
user_id: user.id,
|
||||
avatar: user.avatar,
|
||||
balance: user.balance,
|
||||
commission: user.commission,
|
||||
referral_percentage: user.referral_percentage,
|
||||
only_first_purchase: user.only_first_purchase,
|
||||
gift_amount: user.gift_amount,
|
||||
telegram: user.telegram,
|
||||
refer_code: user.refer_code,
|
||||
referer_id: user.referer_id,
|
||||
enable: user.enable,
|
||||
is_admin: user.is_admin ?? false,
|
||||
remark,
|
||||
};
|
||||
}
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
getUserDetail,
|
||||
getUserSubscribeById,
|
||||
} from "@workspace/ui/services/admin/user";
|
||||
import { shortenDeviceIdentifier } from "@workspace/ui/utils/device";
|
||||
import { formatBytes } from "@workspace/ui/utils/formatting";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Display } from "@/components/display";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import { UserIdentifier } from "./user-identifier";
|
||||
// import EditUserGroupDialog from "./edit-user-group-dialog";
|
||||
// import { getUserGroupList } from "@workspace/ui/services/admin/group";
|
||||
|
||||
@@ -103,7 +103,9 @@ export function UserSubscribeDetail({
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t("remainingTraffic")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{t("remainingTraffic")}
|
||||
</span>
|
||||
<span>
|
||||
{data
|
||||
? totalTraffic === 0
|
||||
@@ -228,21 +230,16 @@ export function UserDetail({ id }: { id: number }) {
|
||||
|
||||
if (!id) return "--";
|
||||
|
||||
const emailMethod = data?.auth_methods.find((m) => m.auth_type === "email");
|
||||
const firstMethod = data?.auth_methods[0];
|
||||
const rawIdentifier =
|
||||
emailMethod?.auth_identifier || firstMethod?.auth_identifier || "";
|
||||
const isDevice = !emailMethod && firstMethod?.auth_type === "device";
|
||||
const identifier = isDevice
|
||||
? shortenDeviceIdentifier(rawIdentifier)
|
||||
: rawIdentifier;
|
||||
|
||||
return (
|
||||
<HoverCard>
|
||||
<HoverCardTrigger asChild>
|
||||
<Button asChild className="p-0" variant="link">
|
||||
<Link search={{ user_id: id }} to="/dashboard/user">
|
||||
{identifier || t("loading", "Loading...")}
|
||||
{data ? (
|
||||
<UserIdentifier className="flex items-center" user={data} />
|
||||
) : (
|
||||
t("loading", "Loading...")
|
||||
)}
|
||||
</Link>
|
||||
</Button>
|
||||
</HoverCardTrigger>
|
||||
|
||||
@@ -59,8 +59,8 @@ export default function UserForm<T extends Record<string, any>>({
|
||||
referral_percentage: z.number().optional(),
|
||||
only_first_purchase: z.boolean().optional(),
|
||||
is_admin: z.boolean().optional(),
|
||||
balance: z.number().optional(),
|
||||
gift_amount: z.number().optional(),
|
||||
// balance: z.number().optional(),
|
||||
// gift_amount: z.number().optional(),
|
||||
commission: z.number().optional(),
|
||||
});
|
||||
const form = useForm({
|
||||
@@ -282,7 +282,7 @@ export default function UserForm<T extends Record<string, any>>({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
{/* <FormField
|
||||
control={form.control}
|
||||
name="balance"
|
||||
render={({ field }) => (
|
||||
@@ -309,8 +309,8 @@ export default function UserForm<T extends Record<string, any>>({
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
/> */}
|
||||
{/* <FormField
|
||||
control={form.control}
|
||||
name="gift_amount"
|
||||
render={({ field }) => (
|
||||
@@ -340,7 +340,7 @@ export default function UserForm<T extends Record<string, any>>({
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
/> */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="commission"
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { getUserIdentifierParts, UserIdentifier } from "./user-identifier";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
type DeviceWithOptionalNo = API.UserDevice & { device_no?: string };
|
||||
|
||||
describe("getUserIdentifierParts", () => {
|
||||
it("uses the device number and D label for device-auth users", () => {
|
||||
expect(
|
||||
getUserIdentifierParts({
|
||||
auth_methods: [
|
||||
{
|
||||
auth_type: "device",
|
||||
auth_identifier: "raw-device-id",
|
||||
verified: true,
|
||||
},
|
||||
],
|
||||
user_devices: [
|
||||
{
|
||||
id: 1,
|
||||
ip: "127.0.0.1",
|
||||
identifier: "device-id",
|
||||
user_agent:
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)",
|
||||
online: true,
|
||||
enabled: true,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
device_no: "DVC-001",
|
||||
} satisfies DeviceWithOptionalNo,
|
||||
],
|
||||
})
|
||||
).toMatchObject({
|
||||
authLabel: "(D)",
|
||||
identifier: "DVC-001",
|
||||
isDevice: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the raw identifier and E label for email-auth users", () => {
|
||||
expect(
|
||||
getUserIdentifierParts({
|
||||
auth_methods: [
|
||||
{
|
||||
auth_type: "email",
|
||||
auth_identifier: "user@example.com",
|
||||
verified: true,
|
||||
},
|
||||
],
|
||||
user_devices: [],
|
||||
})
|
||||
).toMatchObject({
|
||||
authLabel: "(E)",
|
||||
identifier: "user@example.com",
|
||||
isDevice: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("UserIdentifier", () => {
|
||||
it("renders the compact auth label and visible identifier", () => {
|
||||
render(
|
||||
<UserIdentifier
|
||||
user={{
|
||||
auth_methods: [
|
||||
{
|
||||
auth_type: "email",
|
||||
auth_identifier: "referrer@example.com",
|
||||
verified: true,
|
||||
},
|
||||
],
|
||||
user_devices: [],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("(E)")).not.toBeNull();
|
||||
expect(screen.getByText("referrer@example.com")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("renders an empty fallback when no identifier is available", () => {
|
||||
render(
|
||||
<UserIdentifier
|
||||
user={{
|
||||
auth_methods: [],
|
||||
user_devices: [],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("(E)")).not.toBeNull();
|
||||
expect(screen.getByText("--")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { parseDeviceType } from "@workspace/ui/utils/device";
|
||||
|
||||
type UserDeviceWithDeviceNo = API.UserDevice & {
|
||||
device_no?: string;
|
||||
};
|
||||
|
||||
type UserIdentifierUser = {
|
||||
auth_methods?: API.UserAuthMethod[];
|
||||
user_devices?: UserDeviceWithDeviceNo[];
|
||||
};
|
||||
|
||||
type UserIdentifierParts = {
|
||||
authLabel: "(D)" | "(E)";
|
||||
deviceBadge?: string;
|
||||
identifier: string;
|
||||
isDevice: boolean;
|
||||
};
|
||||
|
||||
export function getUserIdentifierParts(
|
||||
user?: UserIdentifierUser
|
||||
): UserIdentifierParts {
|
||||
const method = user?.auth_methods?.[0];
|
||||
const firstDevice = user?.user_devices?.[0] as
|
||||
| UserDeviceWithDeviceNo
|
||||
| undefined;
|
||||
const isDevice = method?.auth_type === "device";
|
||||
const rawIdentifier = method?.auth_identifier || "";
|
||||
const identifier = isDevice
|
||||
? firstDevice?.device_no || rawIdentifier
|
||||
: rawIdentifier;
|
||||
|
||||
return {
|
||||
authLabel: isDevice ? "(D)" : "(E)",
|
||||
deviceBadge: parseDeviceType(firstDevice?.user_agent || ""),
|
||||
identifier,
|
||||
isDevice,
|
||||
};
|
||||
}
|
||||
|
||||
export function UserIdentifier({
|
||||
className,
|
||||
user,
|
||||
}: {
|
||||
className?: string;
|
||||
user?: UserIdentifierUser;
|
||||
}) {
|
||||
const { authLabel, deviceBadge, identifier, isDevice } =
|
||||
getUserIdentifierParts(user);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{deviceBadge ? (
|
||||
<Badge className="mr-1" variant="secondary">
|
||||
{deviceBadge}
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="mr-1 font-mono text-xs uppercase">{authLabel}</span>
|
||||
<span title={isDevice ? identifier : undefined}>
|
||||
{identifier || "--"}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,7 @@ const notifySettingsSchema = z.object({
|
||||
enable_balance_notify: z.boolean(),
|
||||
enable_login_notify: z.boolean(),
|
||||
enable_subscribe_notify: z.boolean(),
|
||||
enable_trade_notify: z.boolean(),
|
||||
// enable_trade_notify: z.boolean(),
|
||||
});
|
||||
|
||||
type NotifySettingsValues = z.infer<typeof notifySettingsSchema>;
|
||||
@@ -44,13 +44,14 @@ export function NotifySettingsForm({
|
||||
enable_balance_notify: user.enable_balance_notify,
|
||||
enable_login_notify: user.enable_login_notify,
|
||||
enable_subscribe_notify: user.enable_subscribe_notify,
|
||||
enable_trade_notify: user.enable_trade_notify,
|
||||
// enable_trade_notify: user.enable_trade_notify,
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: NotifySettingsValues) {
|
||||
await updateUserNotifySetting({
|
||||
...data,
|
||||
enable_trade_notify: user.enable_trade_notify ?? false,
|
||||
user_id: user.id,
|
||||
});
|
||||
toast.success(t("updateSuccess", "Updated successfully"));
|
||||
@@ -126,7 +127,7 @@ export function NotifySettingsForm({
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
{/* <FormField
|
||||
control={form.control}
|
||||
name="enable_trade_notify"
|
||||
render={({ field }) => (
|
||||
@@ -142,7 +143,7 @@ export function NotifySettingsForm({
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
/> */}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { UserSearchBar } from "./user-search-bar";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback: string): string => fallback,
|
||||
}),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("UserSearchBar", () => {
|
||||
it("keeps the controls usable on a narrow mobile viewport", () => {
|
||||
Object.defineProperty(window, "innerWidth", {
|
||||
configurable: true,
|
||||
value: 390,
|
||||
});
|
||||
|
||||
render(
|
||||
<UserSearchBar
|
||||
initialType="email"
|
||||
initialValue=""
|
||||
onSearch={vi.fn()}
|
||||
subscribes={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("combobox")).not.toBeNull();
|
||||
expect(screen.getByRole("button", { name: "Search" })).not.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the typed happy-path value and triggers search", () => {
|
||||
const onSearch = vi.fn();
|
||||
|
||||
render(
|
||||
<UserSearchBar
|
||||
initialType="email"
|
||||
initialValue=""
|
||||
onSearch={onSearch}
|
||||
subscribes={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Enter search term"), {
|
||||
target: { value: "user@example.com" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Search" }));
|
||||
|
||||
expect(onSearch).toHaveBeenCalledWith("email", "user@example.com");
|
||||
expect(
|
||||
(screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
|
||||
.value
|
||||
).toBe("user@example.com");
|
||||
});
|
||||
|
||||
it("syncs to external search changes for precise referrer navigation", () => {
|
||||
const onSearch = vi.fn();
|
||||
const { rerender } = render(
|
||||
<UserSearchBar
|
||||
initialType="email"
|
||||
initialValue="old@example.com"
|
||||
onSearch={onSearch}
|
||||
subscribes={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(
|
||||
(screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
|
||||
.value
|
||||
).toBe("old@example.com");
|
||||
|
||||
rerender(
|
||||
<UserSearchBar
|
||||
initialType="user_id"
|
||||
initialValue="1024"
|
||||
onSearch={onSearch}
|
||||
subscribes={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(
|
||||
(screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
|
||||
.value
|
||||
).toBe("1024");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@workspace/ui/components/select";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export function UserSearchBar({
|
||||
initialType,
|
||||
initialValue,
|
||||
onSearch,
|
||||
subscribes,
|
||||
}: {
|
||||
initialType: string;
|
||||
initialValue: string;
|
||||
onSearch: (type: string, value: string) => void;
|
||||
subscribes?: API.SubscribeItem[];
|
||||
}) {
|
||||
const { t } = useTranslation("user");
|
||||
const [searchType, setSearchType] = useState(initialType);
|
||||
const [searchValue, setSearchValue] = useState(initialValue);
|
||||
|
||||
useEffect(() => {
|
||||
setSearchType(initialType);
|
||||
setSearchValue(initialValue);
|
||||
}, [initialType, initialValue]);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
onValueChange={(v) => {
|
||||
setSearchType(v);
|
||||
setSearchValue("");
|
||||
}}
|
||||
value={searchType}
|
||||
>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="email">设备码/邮箱</SelectItem>
|
||||
<SelectItem value="user_id">{t("userId", "User ID")}</SelectItem>
|
||||
<SelectItem value="subscribe_id">
|
||||
{t("subscription", "Subscription")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{searchType === "subscribe_id" ? (
|
||||
<Combobox
|
||||
className="w-48"
|
||||
onChange={(value) => {
|
||||
setSearchValue(value);
|
||||
onSearch("subscribe_id", value);
|
||||
}}
|
||||
options={subscribes?.map((item) => ({
|
||||
label: item.name!,
|
||||
value: String(item.id!),
|
||||
}))}
|
||||
placeholder={t("subscription", "Subscription")}
|
||||
value={searchValue}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Input
|
||||
className="w-48"
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === "Enter" && onSearch(searchType, searchValue)
|
||||
}
|
||||
placeholder={t("searchInputPlaceholder", "Enter search term")}
|
||||
value={searchValue}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => onSearch(searchType, searchValue)}
|
||||
variant="default"
|
||||
>
|
||||
{t("search", "Search")}
|
||||
</Button>
|
||||
{searchValue && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setSearchValue("");
|
||||
onSearch(searchType, "");
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
{t("resetSearch", "Reset")}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { Link, useNavigate } from "@tanstack/react-router";
|
||||
import { Alert, AlertDescription } from "@workspace/ui/components/alert";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
@@ -30,18 +30,40 @@ import { Display } from "@/components/display";
|
||||
import { useGlobalStore } from "@/stores/global";
|
||||
import { formatDate } from "@/utils/common";
|
||||
import { SubscriptionDetail } from "./subscription-detail";
|
||||
import { SubscriptionForm } from "./subscription-form";
|
||||
import {
|
||||
SubscriptionForm,
|
||||
type SubscriptionFormValues,
|
||||
} from "./subscription-form";
|
||||
|
||||
interface SharedInfo {
|
||||
ownerUserId: number;
|
||||
familyId: number;
|
||||
}
|
||||
|
||||
function toUserSubscribePayload(values: SubscriptionFormValues) {
|
||||
return {
|
||||
...values,
|
||||
expired_at: values.expired_at || 0,
|
||||
subscribe_id: values.subscribe_id || 0,
|
||||
traffic: values.traffic || 0,
|
||||
upload: values.upload || 0,
|
||||
download: values.download || 0,
|
||||
speed_limit: values.speed_limit || 0,
|
||||
device_limit: values.device_limit || 0,
|
||||
traffic_limit: values.traffic_limit || [],
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePlanSpeed(row: API.UserSubscribe) {
|
||||
return row.plan_speed_limit ?? row.subscribe?.speed_limit ?? 0;
|
||||
}
|
||||
|
||||
export default function UserSubscription({ userId }: { userId: number }) {
|
||||
const { t } = useTranslation("user");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
const [sharedInfo, setSharedInfo] = useState<SharedInfo | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const request = useCallback(
|
||||
async (pagination: { page: number; size: number }) => {
|
||||
@@ -116,19 +138,23 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
<span className="flex gap-2">
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link
|
||||
search={{ user_id: String(sharedInfo.ownerUserId) }}
|
||||
search={{ user_id: sharedInfo.ownerUserId }}
|
||||
to="/dashboard/family"
|
||||
>
|
||||
{t("viewDeviceGroup", "View Device Group")}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link
|
||||
search={{ user_id: String(sharedInfo.ownerUserId) }}
|
||||
to="/dashboard/user"
|
||||
>
|
||||
{t("viewOwner", "View Owner")}
|
||||
</Link>
|
||||
<Button
|
||||
onClick={() => {
|
||||
navigate({
|
||||
to: "/dashboard/user",
|
||||
search: { user_id: sharedInfo.ownerUserId },
|
||||
});
|
||||
}}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{t("viewOwner", "View Owner")}
|
||||
</Button>
|
||||
</span>
|
||||
</AlertDescription>
|
||||
@@ -161,7 +187,7 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
await updateUserSubscribe({
|
||||
user_id: Number(userId),
|
||||
user_subscribe_id: row.id,
|
||||
...values,
|
||||
...toUserSubscribePayload(values),
|
||||
});
|
||||
toast.success(t("updateSuccess", "Updated successfully"));
|
||||
ref.current?.refresh();
|
||||
@@ -280,7 +306,8 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
const upload = row.original.upload || 0;
|
||||
const download = row.original.download || 0;
|
||||
const totalTraffic = row.original.traffic || 0;
|
||||
const remainingTraffic = totalTraffic > 0 ? totalTraffic - upload - download : 0;
|
||||
const remainingTraffic =
|
||||
totalTraffic > 0 ? totalTraffic - upload - download : 0;
|
||||
return (
|
||||
<Display type="traffic" unlimited value={remainingTraffic} />
|
||||
);
|
||||
@@ -290,15 +317,50 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
accessorKey: "speed_limit",
|
||||
header: t("speedLimit", "Speed Limit"),
|
||||
cell: ({ row }) => {
|
||||
const speed = row.original?.subscribe?.speed_limit;
|
||||
return <Display type="trafficSpeed" value={speed} />;
|
||||
const userSpeed = row.original.speed_limit ?? 0;
|
||||
const effectiveSpeed = row.original.effective_speed ?? 0;
|
||||
const planSpeed = resolvePlanSpeed(row.original);
|
||||
const speed = effectiveSpeed || userSpeed || planSpeed;
|
||||
const source = row.original.is_throttled
|
||||
? t("effectiveSpeed", "Effective Speed")
|
||||
: userSpeed > 0
|
||||
? t("userOverride", "User Override")
|
||||
: t("subscriptionDefault", "Subscription Default");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Display type="trafficSpeed" value={speed} />
|
||||
{row.original.is_throttled && (
|
||||
<Badge variant="destructive">
|
||||
{t("throttled", "Throttled")}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{source}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{t("userOverride", "User Override")}:{" "}
|
||||
<span className="inline-block">
|
||||
<Display type="trafficSpeed" value={userSpeed} />
|
||||
</span>{" "}
|
||||
/ {t("subscriptionDefault", "Subscription Default")}:{" "}
|
||||
<span className="inline-block">
|
||||
<Display type="trafficSpeed" value={planSpeed} />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "device_limit",
|
||||
header: t("deviceLimit", "Device Limit"),
|
||||
cell: ({ row }) => {
|
||||
const limit = row.original?.subscribe?.device_limit;
|
||||
const limit =
|
||||
row.original.device_limit ||
|
||||
row.original?.subscribe?.device_limit;
|
||||
return <Display type="number" unlimited value={limit} />;
|
||||
},
|
||||
},
|
||||
@@ -323,6 +385,11 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
: t("permanent", "Permanent");
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "node_group_name",
|
||||
header: t("nodeGroup", "Node Group"),
|
||||
cell: ({ row }) => row.original.node_group_name || "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: t("createdAt", "Created At"),
|
||||
@@ -341,7 +408,7 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
||||
setLoading(true);
|
||||
await createUserSubscribe({
|
||||
user_id: Number(userId),
|
||||
...values,
|
||||
...toUserSubscribePayload(values),
|
||||
});
|
||||
toast.success(t("createSuccess", "Created successfully"));
|
||||
ref.current?.refresh();
|
||||
@@ -630,7 +697,7 @@ function RowMoreActions({
|
||||
"This action cannot be undone."
|
||||
)}
|
||||
onConfirm={async () => {
|
||||
await deleteUserSubscribe({ user_subscribe_id: String(row.id) });
|
||||
await deleteUserSubscribe({ user_subscribe_id: row.id });
|
||||
toast.success(t("deleteSuccess", "Deleted successfully"));
|
||||
refresh();
|
||||
}}
|
||||
|
||||
@@ -7,20 +7,214 @@ import {
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Skeleton } from "@workspace/ui/components/skeleton";
|
||||
import { Switch } from "@workspace/ui/components/switch";
|
||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||
import { ProTable } from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import {
|
||||
getUserSubscribeById,
|
||||
getUserSubscribeDevices,
|
||||
kickOfflineByUserDevice,
|
||||
} from "@workspace/ui/services/admin/user";
|
||||
import { deviceIdToHash } from "@workspace/ui/utils/device";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { AlertCircle, AlertTriangle, Gauge } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { IpLink } from "@/components/ip-link";
|
||||
import { formatDate } from "@/utils/common";
|
||||
|
||||
function SpeedLimitCard({ subscriptionId }: { subscriptionId: number }) {
|
||||
const { t } = useTranslation("user");
|
||||
const [detail, setDetail] = useState<API.UserSubscribeDetail | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let ignore = false;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsError(false);
|
||||
getUserSubscribeById({ id: subscriptionId })
|
||||
.then(({ data }) => {
|
||||
if (!ignore) setDetail(data.data || null);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!ignore) {
|
||||
setDetail(null);
|
||||
setIsError(true);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!ignore) setIsLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
ignore = true;
|
||||
};
|
||||
}, [subscriptionId]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mb-4 rounded-lg border bg-muted/30 p-3">
|
||||
<Skeleton className="mb-3 h-5 w-40" />
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Skeleton className="h-16" />
|
||||
<Skeleton className="h-16" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="mb-4 flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-destructive text-sm">
|
||||
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>
|
||||
{t("subscriptionDetailLoadFailed", "Failed to load speed settings.")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!detail) {
|
||||
return (
|
||||
<div className="mb-4 rounded-lg border bg-muted/30 p-3 text-muted-foreground text-sm">
|
||||
{t("subscriptionDetailEmpty", "No subscription details found.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (detail.status !== 1) return null;
|
||||
|
||||
const baseSpeed =
|
||||
detail.plan_speed_limit ?? detail.subscribe?.speed_limit ?? 0;
|
||||
const userSpeed = detail.speed_limit ?? 0;
|
||||
const effectiveSpeed = detail.effective_speed ?? 0;
|
||||
const isThrottled = detail.is_throttled;
|
||||
const rules = detail.user_traffic_limit || detail.traffic_limit || [];
|
||||
const hasLimitConfig =
|
||||
baseSpeed > 0 || userSpeed > 0 || effectiveSpeed > 0 || rules.length > 0;
|
||||
|
||||
if (!(hasLimitConfig || isThrottled)) {
|
||||
return (
|
||||
<div className="mb-4 rounded-lg border bg-muted/30 p-3 text-muted-foreground text-sm">
|
||||
{t("speedLimitEmpty", "No user-level speed limit rules configured.")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`mb-4 flex items-start gap-3 rounded-lg border p-3 text-sm ${
|
||||
isThrottled
|
||||
? "border-destructive/40 bg-destructive/5 text-destructive"
|
||||
: "border-border bg-muted/40 text-foreground"
|
||||
}`}
|
||||
>
|
||||
{isThrottled ? (
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
) : (
|
||||
<Gauge className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1 space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2 font-medium">
|
||||
{isThrottled ? (
|
||||
<>
|
||||
<span>{t("throttled", "Speed Throttled")}</span>
|
||||
<Badge className="text-xs" variant="destructive">
|
||||
{effectiveSpeed} Mbps
|
||||
</Badge>
|
||||
{baseSpeed > 0 && (
|
||||
<span className="text-muted-foreground text-xs line-through">
|
||||
{t("subscriptionDefault", "Subscription Default")}:{" "}
|
||||
{baseSpeed} Mbps
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-muted-foreground">
|
||||
{t("speedLimit", "Speed Limit")}
|
||||
</span>
|
||||
<Badge className="text-xs" variant="secondary">
|
||||
{effectiveSpeed > 0
|
||||
? `${effectiveSpeed} Mbps`
|
||||
: t("unlimited", "Unlimited")}
|
||||
</Badge>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<SpeedMetric
|
||||
label={t("subscriptionDefault", "Subscription Default")}
|
||||
value={baseSpeed}
|
||||
/>
|
||||
<SpeedMetric
|
||||
label={t("userOverride", "User Override")}
|
||||
value={userSpeed}
|
||||
/>
|
||||
<SpeedMetric
|
||||
label={t("effectiveSpeed", "Effective Speed")}
|
||||
value={effectiveSpeed}
|
||||
/>
|
||||
</div>
|
||||
{isThrottled && detail.throttle_rule && (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{detail.throttle_rule}
|
||||
</p>
|
||||
)}
|
||||
{isThrottled && detail.throttle_start && detail.throttle_end && (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{formatDate(detail.throttle_start)} ~{" "}
|
||||
{formatDate(detail.throttle_end)}
|
||||
</p>
|
||||
)}
|
||||
{rules.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium text-foreground text-xs">
|
||||
{t("trafficLimitRules", "Traffic Limit Rules")}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
{rules.map((rule, index) => (
|
||||
<div
|
||||
className="rounded-md border bg-background/60 px-3 py-2 text-muted-foreground text-xs"
|
||||
key={`${rule.stat_type}-${rule.stat_value}-${index}`}
|
||||
>
|
||||
{t("trafficLimitRuleSummary", {
|
||||
defaultValue:
|
||||
"{{traffic}} GB in {{value}} {{type}} -> {{speed}} Mbps",
|
||||
traffic: rule.traffic_usage,
|
||||
value: rule.stat_value,
|
||||
type:
|
||||
rule.stat_type === "hour"
|
||||
? t("hour", "Hour")
|
||||
: t("day", "Day"),
|
||||
speed: rule.speed_limit,
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SpeedMetric({ label, value }: { label: string; value: number }) {
|
||||
const { t } = useTranslation("user");
|
||||
|
||||
return (
|
||||
<div className="rounded-md border bg-background/60 p-2">
|
||||
<div className="text-muted-foreground text-xs">{label}</div>
|
||||
<div className="font-medium text-foreground">
|
||||
{value > 0 ? `${value} Mbps` : t("unlimited", "Unlimited")}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SubscriptionDetail({
|
||||
trigger,
|
||||
userId,
|
||||
@@ -44,6 +238,7 @@ export function SubscriptionDetail({
|
||||
<SheetTitle>{t("onlineDevices", "Online Devices")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="mt-4 max-h-[calc(100dvh-120px)] overflow-y-auto">
|
||||
{open && <SpeedLimitCard subscriptionId={subscriptionId} />}
|
||||
<ProTable<API.UserDevice, Record<string, unknown>>
|
||||
actions={{
|
||||
render: (row) => {
|
||||
@@ -78,12 +273,7 @@ export function SubscriptionDetail({
|
||||
accessorKey: "enabled",
|
||||
header: t("enable", "Enable"),
|
||||
cell: ({ row }) => (
|
||||
<Switch
|
||||
checked={row.getValue("enabled")}
|
||||
onChange={(checked) => {
|
||||
console.log("Switch:", checked);
|
||||
}}
|
||||
/>
|
||||
<Switch checked={row.getValue("enabled")} disabled />
|
||||
),
|
||||
},
|
||||
{ accessorKey: "id", header: "ID" },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
@@ -19,10 +20,11 @@ import {
|
||||
} from "@workspace/ui/components/sheet";
|
||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||
import { DatePicker } from "@workspace/ui/composed/date-picker";
|
||||
import { ArrayInput } from "@workspace/ui/composed/dynamic-inputs";
|
||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||
import { Icon } from "@workspace/ui/composed/icon";
|
||||
import { unitConversion } from "@workspace/ui/utils/unit-conversions";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { type KeyboardEvent, type ReactNode, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
@@ -33,18 +35,56 @@ interface Props {
|
||||
title: string;
|
||||
loading?: boolean;
|
||||
initialData?: API.UserSubscribe;
|
||||
onSubmit: (values: any) => Promise<boolean>;
|
||||
onSubmit: (values: SubscriptionFormValues) => Promise<boolean>;
|
||||
}
|
||||
|
||||
type SubscriptionTrafficLimitRule = API.UserSubscribeTrafficLimitRule;
|
||||
|
||||
function getUserTrafficLimitRules(
|
||||
data?: Pick<API.UserSubscribe, "traffic_limit" | "user_traffic_limit">
|
||||
) {
|
||||
return data?.user_traffic_limit || data?.traffic_limit || [];
|
||||
}
|
||||
|
||||
const defaultLimitRule: SubscriptionTrafficLimitRule = {
|
||||
stat_type: "day",
|
||||
stat_value: 1,
|
||||
traffic_usage: 0,
|
||||
speed_limit: 0,
|
||||
};
|
||||
|
||||
const formSchema = z.object({
|
||||
subscribe_id: z.number().optional(),
|
||||
traffic: z.number().optional(),
|
||||
speed_limit: z.number().optional(),
|
||||
device_limit: z.number().optional(),
|
||||
traffic: z.number().min(0).optional(),
|
||||
speed_limit: z.number().min(0).optional(),
|
||||
device_limit: z.number().min(0).optional(),
|
||||
expired_at: z.number().nullish().optional(),
|
||||
upload: z.number().optional(),
|
||||
download: z.number().optional(),
|
||||
upload: z.number().min(0).optional(),
|
||||
download: z.number().min(0).optional(),
|
||||
id: z.number().optional(),
|
||||
traffic_limit: z
|
||||
.array(
|
||||
z.object({
|
||||
stat_type: z.string(),
|
||||
stat_value: z.number().int().min(1),
|
||||
traffic_usage: z.number().min(0),
|
||||
speed_limit: z.number().min(0),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type SubscriptionFormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export type { SubscriptionFormValues };
|
||||
|
||||
const normalizeLimitRule = (
|
||||
item: SubscriptionTrafficLimitRule
|
||||
): SubscriptionTrafficLimitRule => ({
|
||||
stat_type: item.stat_type || "day",
|
||||
stat_value: Math.max(1, Math.floor(Number(item.stat_value) || 1)),
|
||||
traffic_usage: Math.max(0, Number(item.traffic_usage) || 0),
|
||||
speed_limit: Math.max(0, Number(item.speed_limit) || 0),
|
||||
});
|
||||
|
||||
export function SubscriptionForm({
|
||||
@@ -57,11 +97,14 @@ export function SubscriptionForm({
|
||||
const { t } = useTranslation("user");
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const form = useForm({
|
||||
const form = useForm<SubscriptionFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
subscribe_id: initialData?.subscribe_id || 0,
|
||||
traffic: initialData?.traffic || 0,
|
||||
speed_limit: initialData?.speed_limit || 0,
|
||||
device_limit: initialData?.device_limit || 0,
|
||||
traffic_limit: getUserTrafficLimitRules(initialData),
|
||||
upload: initialData?.upload || 0,
|
||||
download: initialData?.download || 0,
|
||||
expired_at: initialData?.expire_time || 0,
|
||||
@@ -69,7 +112,7 @@ export function SubscriptionForm({
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (values: any) => {
|
||||
const handleSubmit = async (values: SubscriptionFormValues) => {
|
||||
const success = await onSubmit(values);
|
||||
if (success) {
|
||||
setOpen(false);
|
||||
@@ -135,6 +178,7 @@ export function SubscriptionForm({
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
placeholder={t("unlimited", "Unlimited")}
|
||||
type="number"
|
||||
{...field}
|
||||
@@ -154,6 +198,56 @@ export function SubscriptionForm({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="speed_limit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("speedLimit", "Speed Limit")}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
placeholder={t("unlimited", "Unlimited")}
|
||||
type="number"
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value as number);
|
||||
}}
|
||||
suffix="Mbps"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"userSpeedLimitDescription",
|
||||
"Set to 0 to use the subscription default speed limit."
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="device_limit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{t("deviceLimit", "Device Limit")}</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
placeholder={t("unlimited", "Unlimited")}
|
||||
step={1}
|
||||
type="number"
|
||||
{...field}
|
||||
onValueChange={(value) => {
|
||||
form.setValue(field.name, value as number);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="upload"
|
||||
@@ -164,6 +258,7 @@ export function SubscriptionForm({
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
placeholder="0"
|
||||
type="number"
|
||||
{...field}
|
||||
@@ -193,6 +288,7 @@ export function SubscriptionForm({
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<EnhancedInput
|
||||
min={0}
|
||||
placeholder="0"
|
||||
type="number"
|
||||
{...field}
|
||||
@@ -212,6 +308,119 @@ export function SubscriptionForm({
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="traffic_limit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
{t("trafficLimitRules", "Traffic Limit Rules")}
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<ArrayInput<SubscriptionTrafficLimitRule>
|
||||
className="grid grid-cols-2 gap-3 lg:grid-cols-4"
|
||||
fields={[
|
||||
{
|
||||
name: "stat_type",
|
||||
type: "select",
|
||||
placeholder: t("statType", "Statistics Type"),
|
||||
value: "day",
|
||||
options: [
|
||||
{
|
||||
label: t("statTypeHour", "Hour"),
|
||||
value: "hour",
|
||||
},
|
||||
{
|
||||
label: t("statTypeDay", "Day"),
|
||||
value: "day",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "stat_value",
|
||||
type: "number",
|
||||
placeholder: t("statValue", "Time Value"),
|
||||
min: 1,
|
||||
step: 1,
|
||||
onKeyDown: (
|
||||
e: KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return String(
|
||||
Number.isNaN(num) ? 1 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "traffic_usage",
|
||||
type: "number",
|
||||
placeholder: t(
|
||||
"trafficUsage",
|
||||
"Traffic Usage (GB)"
|
||||
),
|
||||
min: 0,
|
||||
onKeyDown: (
|
||||
e: KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return String(
|
||||
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "speed_limit",
|
||||
type: "number",
|
||||
placeholder: t(
|
||||
"speedLimitMbps",
|
||||
"Speed Limit (Mbps)"
|
||||
),
|
||||
min: 0,
|
||||
onKeyDown: (
|
||||
e: KeyboardEvent<HTMLInputElement>
|
||||
) => {
|
||||
if (e.key === "." || e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
formatOutput: (value: string | number) => {
|
||||
const num = Number(value);
|
||||
return String(
|
||||
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
onChange={(items) => {
|
||||
field.onChange(items.map(normalizeLimitRule));
|
||||
}}
|
||||
value={
|
||||
field.value && field.value.length > 0
|
||||
? field.value
|
||||
: [defaultLimitRule]
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{t(
|
||||
"trafficLimitDescription",
|
||||
"Limit speed when usage reaches the configured amount in the selected time window."
|
||||
)}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expired_at"
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { Button } from "@workspace/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@workspace/ui/components/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@workspace/ui/components/form";
|
||||
import { Textarea } from "@workspace/ui/components/textarea";
|
||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||
import {
|
||||
ProTable,
|
||||
type ProTableActions,
|
||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||
import {
|
||||
approveWithdrawal,
|
||||
getWithdrawalList,
|
||||
rejectWithdrawal,
|
||||
} from "@workspace/ui/services/admin/withdrawal";
|
||||
import { useRef, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
import { Display } from "@/components/display";
|
||||
import { UserDetail } from "@/sections/user/user-detail";
|
||||
import { formatDate } from "@/utils/common";
|
||||
|
||||
const WITHDRAWAL_METHOD_MAP: Record<number, string> = {
|
||||
0: "其他",
|
||||
1: "支付宝",
|
||||
2: "微信",
|
||||
3: "USDT(TRC20)",
|
||||
};
|
||||
|
||||
const rejectSchema = z.object({
|
||||
reason: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2, "请填写拒绝原因")
|
||||
.max(500, "拒绝原因不能超过 500 个字符"),
|
||||
});
|
||||
|
||||
function QrCodeCell({ url }: { url?: string }) {
|
||||
const [zoomOpen, setZoomOpen] = useState(false);
|
||||
if (!url) return <span>--</span>;
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
className="block overflow-hidden rounded border"
|
||||
onClick={() => setZoomOpen(true)}
|
||||
type="button"
|
||||
>
|
||||
<img
|
||||
alt="收款码"
|
||||
className="h-12 w-12 cursor-zoom-in object-cover"
|
||||
height={48}
|
||||
src={url}
|
||||
width={48}
|
||||
/>
|
||||
</button>
|
||||
{zoomOpen && (
|
||||
<Dialog onOpenChange={setZoomOpen} open={zoomOpen}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<img
|
||||
alt="收款码"
|
||||
className="w-full"
|
||||
height={320}
|
||||
src={url}
|
||||
width={320}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function WithdrawalPage() {
|
||||
const { t } = useTranslation("user");
|
||||
const ref = useRef<ProTableActions>(null);
|
||||
const [rejectOpen, setRejectOpen] = useState(false);
|
||||
const [currentRow, setCurrentRow] = useState<API.AdminWithdrawalLog | null>(
|
||||
null
|
||||
);
|
||||
const form = useForm<z.infer<typeof rejectSchema>>({
|
||||
resolver: zodResolver(rejectSchema),
|
||||
defaultValues: {
|
||||
reason: "",
|
||||
},
|
||||
});
|
||||
|
||||
const approveMutation = useMutation({
|
||||
mutationFn: async (withdrawalId: number) =>
|
||||
approveWithdrawal({ withdrawal_id: withdrawalId }),
|
||||
onSuccess: () => {
|
||||
toast.success("提现申请已通过");
|
||||
ref.current?.refresh();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Approve withdrawal failed", error);
|
||||
toast.error("提现通过失败");
|
||||
},
|
||||
});
|
||||
|
||||
const rejectMutation = useMutation({
|
||||
mutationFn: async (values: { withdrawal_id: number; reason: string }) =>
|
||||
rejectWithdrawal(values),
|
||||
onSuccess: () => {
|
||||
toast.success("提现申请已拒绝");
|
||||
setRejectOpen(false);
|
||||
setCurrentRow(null);
|
||||
form.reset({ reason: "" });
|
||||
ref.current?.refresh();
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Reject withdrawal failed", error);
|
||||
toast.error("提现拒绝失败");
|
||||
},
|
||||
});
|
||||
|
||||
const statusOptions = [
|
||||
{ value: "0", label: "审核中" },
|
||||
{ value: "1", label: "已通过" },
|
||||
{ value: "2", label: "已拒绝" },
|
||||
{ value: "3", label: "已取消" },
|
||||
];
|
||||
|
||||
const methodOptions = [
|
||||
{ value: "1", label: "支付宝" },
|
||||
{ value: "2", label: "微信" },
|
||||
{ value: "3", label: "USDT(TRC20)" },
|
||||
{ value: "0", label: "其他" },
|
||||
];
|
||||
|
||||
const statusMap: Record<number, { label: string; className: string }> = {
|
||||
0: {
|
||||
label: "审核中",
|
||||
className: "bg-amber-100 text-amber-700 border-amber-200",
|
||||
},
|
||||
1: {
|
||||
label: "已通过",
|
||||
className: "bg-emerald-100 text-emerald-700 border-emerald-200",
|
||||
},
|
||||
2: {
|
||||
label: "已拒绝",
|
||||
className: "bg-rose-100 text-rose-700 border-rose-200",
|
||||
},
|
||||
3: {
|
||||
label: "已取消",
|
||||
className: "bg-gray-100 text-gray-500 border-gray-200",
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ProTable<
|
||||
API.AdminWithdrawalLog,
|
||||
{ status?: string; user_id?: string; method?: string }
|
||||
>
|
||||
action={ref}
|
||||
actions={{
|
||||
render: (row) => {
|
||||
if (row.status !== 0) return [];
|
||||
|
||||
return [
|
||||
<ConfirmButton
|
||||
cancelText={t("cancel", "Cancel")}
|
||||
confirmText={t("confirm", "Confirm")}
|
||||
description="确认后将标记该提现为已通过,请确保线下打款流程已完成。"
|
||||
key="approve"
|
||||
onConfirm={async () => {
|
||||
await approveMutation.mutateAsync(row.id);
|
||||
}}
|
||||
title="确认通过提现吗?"
|
||||
trigger={
|
||||
<Button
|
||||
disabled={approveMutation.isPending}
|
||||
size="sm"
|
||||
variant="default"
|
||||
>
|
||||
通过
|
||||
</Button>
|
||||
}
|
||||
/>,
|
||||
<Button
|
||||
key="reject"
|
||||
onClick={() => {
|
||||
setCurrentRow(row);
|
||||
setRejectOpen(true);
|
||||
}}
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
>
|
||||
拒绝
|
||||
</Button>,
|
||||
];
|
||||
},
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: "ID",
|
||||
},
|
||||
{
|
||||
accessorKey: "user_id",
|
||||
header: t("user", "User"),
|
||||
cell: ({ row }) => <UserDetail id={row.original.user_id} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "amount",
|
||||
header: "提现金额",
|
||||
cell: ({ row }) => (
|
||||
<Display type="currency" value={row.original.amount} />
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "method",
|
||||
header: "收款方式",
|
||||
cell: ({ row }) =>
|
||||
WITHDRAWAL_METHOD_MAP[row.original.method] ?? "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "account",
|
||||
header: "收款账号",
|
||||
cell: ({ row }) => (
|
||||
<div className="max-w-[200px] break-all text-sm">
|
||||
{row.original.account || "--"}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "qr_code_url",
|
||||
header: "收款码",
|
||||
cell: ({ row }) => <QrCodeCell url={row.original.qr_code_url} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "content",
|
||||
header: "备注",
|
||||
cell: ({ row }) => (
|
||||
<div className="max-w-[200px] break-all text-sm">
|
||||
{row.original.content || "--"}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: "状态",
|
||||
cell: ({ row }) => {
|
||||
const status = statusMap[row.original.status] ?? {
|
||||
label: `未知 (${row.original.status})`,
|
||||
className: "",
|
||||
};
|
||||
return (
|
||||
<Badge className={status.className} variant="outline">
|
||||
{status.label}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "reason",
|
||||
header: "拒绝原因",
|
||||
cell: ({ row }) => row.original.reason || "--",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: "申请时间",
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
{
|
||||
accessorKey: "updated_at",
|
||||
header: "更新时间",
|
||||
cell: ({ row }) => formatDate(row.original.updated_at),
|
||||
},
|
||||
]}
|
||||
header={{ title: "提现管理" }}
|
||||
params={[
|
||||
{
|
||||
key: "status",
|
||||
options: statusOptions,
|
||||
placeholder: "状态",
|
||||
},
|
||||
{
|
||||
key: "method",
|
||||
options: methodOptions,
|
||||
placeholder: "收款方式",
|
||||
},
|
||||
{
|
||||
key: "user_id",
|
||||
placeholder: "用户 ID",
|
||||
},
|
||||
]}
|
||||
request={async (pagination, filter) => {
|
||||
const { data } = await getWithdrawalList({
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
status: filter.status ? Number(filter.status) : undefined,
|
||||
method: filter.method ? Number(filter.method) : undefined,
|
||||
user_id: filter.user_id ? Number(filter.user_id) : undefined,
|
||||
});
|
||||
|
||||
return {
|
||||
list: data.data?.list || [],
|
||||
total: data.data?.total || 0,
|
||||
};
|
||||
}}
|
||||
/>
|
||||
|
||||
<Dialog
|
||||
onOpenChange={(open) => {
|
||||
setRejectOpen(open);
|
||||
if (!open) {
|
||||
setCurrentRow(null);
|
||||
form.reset({ reason: "" });
|
||||
}
|
||||
}}
|
||||
open={rejectOpen}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>拒绝提现申请</DialogTitle>
|
||||
<DialogDescription>
|
||||
为用户填写本次拒绝原因,提交后该记录会更新为已拒绝。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={form.handleSubmit(async (values) => {
|
||||
if (!currentRow) return;
|
||||
await rejectMutation.mutateAsync({
|
||||
withdrawal_id: currentRow.id,
|
||||
reason: values.reason.trim(),
|
||||
});
|
||||
})}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="reason"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>拒绝原因</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="请输入拒绝原因,用户端会看到这条说明"
|
||||
rows={5}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={() => setRejectOpen(false)}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
{t("cancel", "Cancel")}
|
||||
</Button>
|
||||
<Button disabled={rejectMutation.isPending} type="submit">
|
||||
{rejectMutation.isPending ? "提交中..." : "确认拒绝"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -29,13 +29,10 @@ export function formatDate(date?: Date | number, showTime = true) {
|
||||
// Unix timestamps (seconds): 10 digits e.g. 1771936457
|
||||
// JavaScript timestamps (milliseconds): 13 digits
|
||||
let dateValue = date;
|
||||
if (typeof date === "number") {
|
||||
if (date < 10000000000) {
|
||||
dateValue = date * 1000;
|
||||
}
|
||||
if (typeof date === "number" && date < 10_000_000_000) {
|
||||
dateValue = date * 1000;
|
||||
}
|
||||
|
||||
|
||||
const timeZone = localStorage.getItem("timezone") || "UTC";
|
||||
return intlFormat(dateValue, {
|
||||
year: "numeric",
|
||||
|
||||
@@ -1,11 +1,37 @@
|
||||
{
|
||||
"accountInfo": "Payout Details",
|
||||
"accountPlaceholder": "Enter bank card, Alipay, USDT wallet, or other payout details",
|
||||
"accountRequired": "Payout details are required",
|
||||
"accountTooLong": "Payout details must be 200 characters or fewer",
|
||||
"amountInvalid": "Enter a valid amount",
|
||||
"amountPositive": "Withdrawal amount must be greater than 0",
|
||||
"applyTime": "Applied At",
|
||||
"applyWithdraw": "Request Withdrawal",
|
||||
"cancel": "Cancel",
|
||||
"commissionInfo": "Commission Info",
|
||||
"commissionRate": "Commission Rate",
|
||||
"copyInviteLink": "Copy Invite Link",
|
||||
"copySuccess": "Copy Success",
|
||||
"currentCommission": "Current Commission",
|
||||
"inviteCode": "Invite Code",
|
||||
"inviteRecords": "Invite Records",
|
||||
"noReason": "None",
|
||||
"rejectReason": "Reject Reason",
|
||||
"registrationTime": "Registration Time",
|
||||
"submitWithdraw": "Submit Request",
|
||||
"submitting": "Submitting...",
|
||||
"totalCommission": "Total Commission",
|
||||
"userIdentifier": "User Identifier"
|
||||
"unknownStatus": "Unknown Status",
|
||||
"userIdentifier": "User Identifier",
|
||||
"withdrawAmount": "Withdrawal Amount",
|
||||
"withdrawAmountPlaceholder": "Enter the withdrawal amount in dollars",
|
||||
"withdrawDescription": "Submit the withdrawal amount and payout details, then wait for review.",
|
||||
"withdrawError": "Failed to submit withdrawal request",
|
||||
"withdrawRecords": "Withdrawal Records",
|
||||
"withdrawStatus": {
|
||||
"approved": "Approved",
|
||||
"pending": "Pending Review",
|
||||
"rejected": "Rejected"
|
||||
},
|
||||
"withdrawSuccess": "Withdrawal request submitted"
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user