Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 82bd00e06d | |||
| 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
|
||||||
|
}
|
||||||
@@ -34,3 +34,4 @@ npm-debug.log*
|
|||||||
# Misc
|
# Misc
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*.pem
|
*.pem
|
||||||
|
.mcp.json
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# API base URL
|
# API base URL
|
||||||
VITE_API_BASE_URL=
|
VITE_API_BASE_URL=https://tapi.hifast.biz
|
||||||
# API prefix path
|
# API prefix path
|
||||||
VITE_API_PREFIX=
|
VITE_API_PREFIX=
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -4,7 +4,21 @@
|
|||||||
"noImage": "No Image",
|
"noImage": "No Image",
|
||||||
"placeholder": "Enter captcha code...",
|
"placeholder": "Enter captcha code...",
|
||||||
"refresh": "Refresh captcha",
|
"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": {
|
"check": {
|
||||||
"description": "Verify your identity",
|
"description": "Verify your identity",
|
||||||
|
|||||||
@@ -15,7 +15,7 @@
|
|||||||
"pending": "Pending",
|
"pending": "Pending",
|
||||||
"pendingTickets": "Pending Tickets",
|
"pendingTickets": "Pending Tickets",
|
||||||
"register": "Register",
|
"register": "Register",
|
||||||
"repurchase": "Repurchase",
|
"repurchase": "Renewal",
|
||||||
"revenueTitle": "Revenue Statistics",
|
"revenueTitle": "Revenue Statistics",
|
||||||
"selectTypePlaceholder": "Select Type",
|
"selectTypePlaceholder": "Select Type",
|
||||||
"today": "Today",
|
"today": "Today",
|
||||||
|
|||||||
@@ -34,5 +34,6 @@
|
|||||||
"Traffic Details": "Traffic Details",
|
"Traffic Details": "Traffic Details",
|
||||||
"Device Group": "Device Group",
|
"Device Group": "Device Group",
|
||||||
"User Management": "User Management",
|
"User Management": "User Management",
|
||||||
"Users & Support": "Users & Support"
|
"Users & Support": "Users & Support",
|
||||||
|
"Withdrawal Management": "Withdrawal Management"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,11 @@
|
|||||||
"confirmDeleteTitle": "Delete this node?",
|
"confirmDeleteTitle": "Delete this node?",
|
||||||
"copied": "Copied",
|
"copied": "Copied",
|
||||||
"copy": "Copy",
|
"copy": "Copy",
|
||||||
"create": "Create",
|
"create": "Create Landing Node",
|
||||||
"created": "Created",
|
"created": "Created",
|
||||||
"delete": "Delete",
|
"delete": "Delete",
|
||||||
"deleted": "Deleted",
|
"deleted": "Deleted",
|
||||||
"drawerCreateTitle": "Create Node",
|
"drawerCreateTitle": "Create Landing Node",
|
||||||
"drawerEditTitle": "Edit Node",
|
"drawerEditTitle": "Edit Node",
|
||||||
"edit": "Edit",
|
"edit": "Edit",
|
||||||
"enabled": "Enabled",
|
"enabled": "Enabled",
|
||||||
|
|||||||
@@ -1,17 +1,25 @@
|
|||||||
{
|
{
|
||||||
"amount": "Amount",
|
"amount": "Amount",
|
||||||
"couponDiscount": "Coupon Discount",
|
"couponDiscount": "Coupon Discount",
|
||||||
|
"confirmRefund": "Confirm refund",
|
||||||
"discount": "Discount Amount",
|
"discount": "Discount Amount",
|
||||||
"feeAmount": "Fee Amount",
|
"feeAmount": "Fee Amount",
|
||||||
"method": "Payment Method",
|
"method": "Payment Method",
|
||||||
"orderNumber": "Order Number",
|
"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": {
|
"status": {
|
||||||
"0": "Status",
|
"0": "Status",
|
||||||
"1": "Pending",
|
"1": "Pending",
|
||||||
"2": "Paid",
|
"2": "Paid",
|
||||||
"3": "Cancelled",
|
"3": "Cancelled",
|
||||||
"4": "Closed",
|
"4": "Closed",
|
||||||
"5": "Completed"
|
"5": "Completed",
|
||||||
|
"6": "Refunded"
|
||||||
},
|
},
|
||||||
"subscribe": "Subscribe",
|
"subscribe": "Subscribe",
|
||||||
"subscribePrice": "Subscription Price",
|
"subscribePrice": "Subscription Price",
|
||||||
|
|||||||
@@ -32,6 +32,7 @@
|
|||||||
"discount_price": "Discount Price",
|
"discount_price": "Discount Price",
|
||||||
"discountDescription": "Set discount based on unit price",
|
"discountDescription": "Set discount based on unit price",
|
||||||
"discountPercent": "Discount Percentage",
|
"discountPercent": "Discount Percentage",
|
||||||
|
"appleProductId": "Apple Product ID",
|
||||||
"Hour": "Hour",
|
"Hour": "Hour",
|
||||||
"inventory": "Subscription Limit",
|
"inventory": "Subscription Limit",
|
||||||
"language": "Language",
|
"language": "Language",
|
||||||
|
|||||||
@@ -126,9 +126,10 @@
|
|||||||
"userSecuritySettings": "User & Security",
|
"userSecuritySettings": "User & Security",
|
||||||
"verify": {
|
"verify": {
|
||||||
"captchaType": "Captcha Type",
|
"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",
|
"captchaTypeLocal": "Local Image Captcha",
|
||||||
"captchaTypePlaceholder": "Select captcha type",
|
"captchaTypePlaceholder": "Select captcha type",
|
||||||
|
"captchaTypeSlider": "Local Slider Captcha",
|
||||||
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
||||||
"description": "Configure captcha type and verification settings",
|
"description": "Configure captcha type and verification settings",
|
||||||
"enableAdminLoginCaptcha": "Enable Admin Authentication Captcha",
|
"enableAdminLoginCaptcha": "Enable Admin Authentication Captcha",
|
||||||
|
|||||||
@@ -4,7 +4,21 @@
|
|||||||
"noImage": "无图片",
|
"noImage": "无图片",
|
||||||
"placeholder": "请输入验证码...",
|
"placeholder": "请输入验证码...",
|
||||||
"refresh": "刷新验证码",
|
"refresh": "刷新验证码",
|
||||||
"required": "请输入验证码"
|
"required": "请输入验证码",
|
||||||
|
"sliderRequired": "请完成滑块验证",
|
||||||
|
"slider": {
|
||||||
|
"clickToVerify": "点击进行验证",
|
||||||
|
"fail": "请重试",
|
||||||
|
"hint": "拖动拼图块到对应位置",
|
||||||
|
"success": "验证成功",
|
||||||
|
"title": "安全验证"
|
||||||
|
},
|
||||||
|
"turnstile": {
|
||||||
|
"cancel": "取消",
|
||||||
|
"clickToVerify": "点击进行验证",
|
||||||
|
"success": "验证成功",
|
||||||
|
"title": "安全验证"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"check": {
|
"check": {
|
||||||
"description": "验证您的身份",
|
"description": "验证您的身份",
|
||||||
|
|||||||
@@ -198,4 +198,3 @@
|
|||||||
"nodeGroupUsedBySubscribe": "该节点组已被订阅商品设置为默认节点组,不能设为过期节点组",
|
"nodeGroupUsedBySubscribe": "该节点组已被订阅商品设置为默认节点组,不能设为过期节点组",
|
||||||
"expiredGroupForCalculationDescription": "过期专用节点组不能参与分组计算"
|
"expiredGroupForCalculationDescription": "过期专用节点组不能参与分组计算"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,5 +34,6 @@
|
|||||||
"Traffic Details": "流量详情",
|
"Traffic Details": "流量详情",
|
||||||
"Device Group": "设备组",
|
"Device Group": "设备组",
|
||||||
"User Management": "用户管理",
|
"User Management": "用户管理",
|
||||||
"Users & Support": "用户与支持"
|
"Users & Support": "用户与支持",
|
||||||
|
"Withdrawal Management": "提现管理"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,11 +7,11 @@
|
|||||||
"confirmDeleteTitle": "删除此节点?",
|
"confirmDeleteTitle": "删除此节点?",
|
||||||
"copied": "已复制",
|
"copied": "已复制",
|
||||||
"copy": "复制",
|
"copy": "复制",
|
||||||
"create": "创建",
|
"create": "创建落地节点",
|
||||||
"created": "已创建",
|
"created": "已创建",
|
||||||
"delete": "删除",
|
"delete": "删除",
|
||||||
"deleted": "已删除",
|
"deleted": "已删除",
|
||||||
"drawerCreateTitle": "创建节点",
|
"drawerCreateTitle": "创建落地节点",
|
||||||
"drawerEditTitle": "编辑节点",
|
"drawerEditTitle": "编辑节点",
|
||||||
"edit": "编辑",
|
"edit": "编辑",
|
||||||
"enabled": "已启用",
|
"enabled": "已启用",
|
||||||
|
|||||||
@@ -1,17 +1,25 @@
|
|||||||
{
|
{
|
||||||
"amount": "金额",
|
"amount": "金额",
|
||||||
"couponDiscount": "优惠券折扣",
|
"couponDiscount": "优惠券折扣",
|
||||||
|
"confirmRefund": "确认退费",
|
||||||
"discount": "折扣金额",
|
"discount": "折扣金额",
|
||||||
"feeAmount": "手续费",
|
"feeAmount": "手续费",
|
||||||
"method": "支付方式",
|
"method": "支付方式",
|
||||||
"orderNumber": "订单编号",
|
"orderNumber": "订单编号",
|
||||||
|
"refund": "退费",
|
||||||
|
"refundConfirmDescription": "该退费操作会使用户订阅立即失效,并扣减关联代理佣金。",
|
||||||
|
"refundConfirmTitle": "确认退费",
|
||||||
|
"refundConfirmWarning": "订单退费后不可再次重复执行,请谨慎操作。",
|
||||||
|
"refundSubmitting": "退费中...",
|
||||||
|
"refundSuccess": "退费成功。",
|
||||||
"status": {
|
"status": {
|
||||||
"0": "状态",
|
"0": "状态",
|
||||||
"1": "待支付",
|
"1": "待支付",
|
||||||
"2": "已支付",
|
"2": "已支付",
|
||||||
"3": "已取消",
|
"3": "已取消",
|
||||||
"4": "已关闭",
|
"4": "已关闭",
|
||||||
"5": "已完成"
|
"5": "已完成",
|
||||||
|
"6": "已退费"
|
||||||
},
|
},
|
||||||
"subscribe": "订阅",
|
"subscribe": "订阅",
|
||||||
"subscribePrice": "订阅价格",
|
"subscribePrice": "订阅价格",
|
||||||
|
|||||||
@@ -32,6 +32,7 @@
|
|||||||
"discount_price": "折扣价格",
|
"discount_price": "折扣价格",
|
||||||
"discountDescription": "根据单价设置折扣",
|
"discountDescription": "根据单价设置折扣",
|
||||||
"discountPercent": "折扣百分比",
|
"discountPercent": "折扣百分比",
|
||||||
|
"appleProductId": "苹果商品ID",
|
||||||
"Hour": "小时",
|
"Hour": "小时",
|
||||||
"inventory": "订阅库存",
|
"inventory": "订阅库存",
|
||||||
"language": "语言",
|
"language": "语言",
|
||||||
|
|||||||
@@ -126,9 +126,10 @@
|
|||||||
"userSecuritySettings": "用户与安全",
|
"userSecuritySettings": "用户与安全",
|
||||||
"verify": {
|
"verify": {
|
||||||
"captchaType": "验证码类型",
|
"captchaType": "验证码类型",
|
||||||
"captchaTypeDescription": "选择本地图形验证码(离线)或 Cloudflare Turnstile",
|
"captchaTypeDescription": "选择本地图形验证码、本地滑块验证码(均可离线)或 Cloudflare Turnstile",
|
||||||
"captchaTypeLocal": "本地图形验证码",
|
"captchaTypeLocal": "本地图形验证码",
|
||||||
"captchaTypePlaceholder": "选择验证码类型",
|
"captchaTypePlaceholder": "选择验证码类型",
|
||||||
|
"captchaTypeSlider": "本地滑块验证码",
|
||||||
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
"captchaTypeTurnstile": "Cloudflare Turnstile",
|
||||||
"description": "配置验证码类型和验证设置",
|
"description": "配置验证码类型和验证设置",
|
||||||
"enableAdminLoginCaptcha": "启用管理端认证验证码",
|
"enableAdminLoginCaptcha": "启用管理端认证验证码",
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"0": "状态",
|
"0": "状态",
|
||||||
"1": "待跟进",
|
"1": "待跟进",
|
||||||
"2": "待回复",
|
"2": "待回复",
|
||||||
"3": "已解决",
|
"3": "已取消",
|
||||||
"4": "已关闭"
|
"4": "已关闭"
|
||||||
},
|
},
|
||||||
"ticketList": "工单列表",
|
"ticketList": "工单列表",
|
||||||
|
|||||||
@@ -34,7 +34,6 @@
|
|||||||
"deleteDescription": "此操作无法撤销。",
|
"deleteDescription": "此操作无法撤销。",
|
||||||
"deleteSubscriptionDescription": "此操作无法撤销。",
|
"deleteSubscriptionDescription": "此操作无法撤销。",
|
||||||
"deleteSuccess": "删除成功",
|
"deleteSuccess": "删除成功",
|
||||||
"isDeleted": "状态",
|
|
||||||
"deviceGroup": "设备组",
|
"deviceGroup": "设备组",
|
||||||
"deviceLimit": "IP限制",
|
"deviceLimit": "IP限制",
|
||||||
"deviceNo": "设备编号",
|
"deviceNo": "设备编号",
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export function Display<T extends number | undefined | null>({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (type === "trafficSpeed") {
|
if (type === "trafficSpeed") {
|
||||||
return value ? `${formatBytes(value).replace("B", "b")}ps` : "0";
|
return value ? `${value} Mbps` : "0";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === "number") {
|
if (type === "number") {
|
||||||
|
|||||||
@@ -93,6 +93,11 @@ export function useNavs() {
|
|||||||
url: "/dashboard/user",
|
url: "/dashboard/user",
|
||||||
icon: "flat-color-icons:conference-call",
|
icon: "flat-color-icons:conference-call",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: t("Withdrawal Management", "Withdrawal Management"),
|
||||||
|
url: "/dashboard/withdrawal",
|
||||||
|
icon: "flat-color-icons:money-transfer",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: t("Device Group", "Device Group"),
|
title: t("Device Group", "Device Group"),
|
||||||
url: "/dashboard/family",
|
url: "/dashboard/family",
|
||||||
|
|||||||
@@ -15,8 +15,14 @@ import { Route as rootRouteImport } from './routes/__root'
|
|||||||
const DashboardRouteLazyRouteImport = createFileRoute('/dashboard')()
|
const DashboardRouteLazyRouteImport = createFileRoute('/dashboard')()
|
||||||
const IndexLazyRouteImport = createFileRoute('/')()
|
const IndexLazyRouteImport = createFileRoute('/')()
|
||||||
const DashboardIndexLazyRouteImport = createFileRoute('/dashboard/')()
|
const DashboardIndexLazyRouteImport = createFileRoute('/dashboard/')()
|
||||||
|
const DashboardWithdrawalLazyRouteImport = createFileRoute(
|
||||||
|
'/dashboard/withdrawal',
|
||||||
|
)()
|
||||||
const DashboardServersLazyRouteImport = createFileRoute('/dashboard/servers')()
|
const DashboardServersLazyRouteImport = createFileRoute('/dashboard/servers')()
|
||||||
const DashboardNodesLazyRouteImport = createFileRoute('/dashboard/nodes')()
|
const DashboardNodesLazyRouteImport = createFileRoute('/dashboard/nodes')()
|
||||||
|
const DashboardWithdrawalIndexLazyRouteImport = createFileRoute(
|
||||||
|
'/dashboard/withdrawal/',
|
||||||
|
)()
|
||||||
const DashboardUserIndexLazyRouteImport = createFileRoute('/dashboard/user/')()
|
const DashboardUserIndexLazyRouteImport = createFileRoute('/dashboard/user/')()
|
||||||
const DashboardTicketIndexLazyRouteImport =
|
const DashboardTicketIndexLazyRouteImport =
|
||||||
createFileRoute('/dashboard/ticket/')()
|
createFileRoute('/dashboard/ticket/')()
|
||||||
@@ -109,6 +115,13 @@ const DashboardIndexLazyRoute = DashboardIndexLazyRouteImport.update({
|
|||||||
} as any).lazy(() =>
|
} as any).lazy(() =>
|
||||||
import('./routes/dashboard/index.lazy').then((d) => d.Route),
|
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({
|
const DashboardServersLazyRoute = DashboardServersLazyRouteImport.update({
|
||||||
id: '/servers',
|
id: '/servers',
|
||||||
path: '/servers',
|
path: '/servers',
|
||||||
@@ -123,6 +136,14 @@ const DashboardNodesLazyRoute = DashboardNodesLazyRouteImport.update({
|
|||||||
} as any).lazy(() =>
|
} as any).lazy(() =>
|
||||||
import('./routes/dashboard/nodes.lazy').then((d) => d.Route),
|
import('./routes/dashboard/nodes.lazy').then((d) => d.Route),
|
||||||
)
|
)
|
||||||
|
const DashboardWithdrawalIndexLazyRoute =
|
||||||
|
DashboardWithdrawalIndexLazyRouteImport.update({
|
||||||
|
id: '/withdrawal/',
|
||||||
|
path: '/withdrawal/',
|
||||||
|
getParentRoute: () => DashboardRouteLazyRoute,
|
||||||
|
} as any).lazy(() =>
|
||||||
|
import('./routes/dashboard/withdrawal/index.lazy').then((d) => d.Route),
|
||||||
|
)
|
||||||
const DashboardUserIndexLazyRoute = DashboardUserIndexLazyRouteImport.update({
|
const DashboardUserIndexLazyRoute = DashboardUserIndexLazyRouteImport.update({
|
||||||
id: '/user/',
|
id: '/user/',
|
||||||
path: '/user/',
|
path: '/user/',
|
||||||
@@ -346,6 +367,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
||||||
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
||||||
'/dashboard/servers': typeof DashboardServersLazyRoute
|
'/dashboard/servers': typeof DashboardServersLazyRoute
|
||||||
|
'/dashboard/withdrawal': typeof DashboardWithdrawalLazyRoute
|
||||||
'/dashboard/': typeof DashboardIndexLazyRoute
|
'/dashboard/': typeof DashboardIndexLazyRoute
|
||||||
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
||||||
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
||||||
@@ -375,11 +397,13 @@ export interface FileRoutesByFullPath {
|
|||||||
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
||||||
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
||||||
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
||||||
|
'/dashboard/withdrawal': typeof DashboardWithdrawalIndexLazyRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/': typeof IndexLazyRoute
|
'/': typeof IndexLazyRoute
|
||||||
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
||||||
'/dashboard/servers': typeof DashboardServersLazyRoute
|
'/dashboard/servers': typeof DashboardServersLazyRoute
|
||||||
|
'/dashboard/withdrawal': typeof DashboardWithdrawalLazyRoute
|
||||||
'/dashboard': typeof DashboardIndexLazyRoute
|
'/dashboard': typeof DashboardIndexLazyRoute
|
||||||
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
||||||
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
||||||
@@ -409,6 +433,7 @@ export interface FileRoutesByTo {
|
|||||||
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
'/dashboard/system': typeof DashboardSystemIndexLazyRoute
|
||||||
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
'/dashboard/ticket': typeof DashboardTicketIndexLazyRoute
|
||||||
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
'/dashboard/user': typeof DashboardUserIndexLazyRoute
|
||||||
|
'/dashboard/withdrawal': typeof DashboardWithdrawalIndexLazyRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
@@ -416,6 +441,7 @@ export interface FileRoutesById {
|
|||||||
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
'/dashboard': typeof DashboardRouteLazyRouteWithChildren
|
||||||
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
'/dashboard/nodes': typeof DashboardNodesLazyRoute
|
||||||
'/dashboard/servers': typeof DashboardServersLazyRoute
|
'/dashboard/servers': typeof DashboardServersLazyRoute
|
||||||
|
'/dashboard/withdrawal': typeof DashboardWithdrawalLazyRoute
|
||||||
'/dashboard/': typeof DashboardIndexLazyRoute
|
'/dashboard/': typeof DashboardIndexLazyRoute
|
||||||
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
'/dashboard/log/balance': typeof DashboardLogBalanceLazyRoute
|
||||||
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
'/dashboard/log/commission': typeof DashboardLogCommissionLazyRoute
|
||||||
@@ -445,6 +471,7 @@ export interface FileRoutesById {
|
|||||||
'/dashboard/system/': typeof DashboardSystemIndexLazyRoute
|
'/dashboard/system/': typeof DashboardSystemIndexLazyRoute
|
||||||
'/dashboard/ticket/': typeof DashboardTicketIndexLazyRoute
|
'/dashboard/ticket/': typeof DashboardTicketIndexLazyRoute
|
||||||
'/dashboard/user/': typeof DashboardUserIndexLazyRoute
|
'/dashboard/user/': typeof DashboardUserIndexLazyRoute
|
||||||
|
'/dashboard/withdrawal/': typeof DashboardWithdrawalIndexLazyRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
@@ -453,6 +480,7 @@ export interface FileRouteTypes {
|
|||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/dashboard/nodes'
|
| '/dashboard/nodes'
|
||||||
| '/dashboard/servers'
|
| '/dashboard/servers'
|
||||||
|
| '/dashboard/withdrawal'
|
||||||
| '/dashboard/'
|
| '/dashboard/'
|
||||||
| '/dashboard/log/balance'
|
| '/dashboard/log/balance'
|
||||||
| '/dashboard/log/commission'
|
| '/dashboard/log/commission'
|
||||||
@@ -482,11 +510,13 @@ export interface FileRouteTypes {
|
|||||||
| '/dashboard/system'
|
| '/dashboard/system'
|
||||||
| '/dashboard/ticket'
|
| '/dashboard/ticket'
|
||||||
| '/dashboard/user'
|
| '/dashboard/user'
|
||||||
|
| '/dashboard/withdrawal'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
| '/'
|
| '/'
|
||||||
| '/dashboard/nodes'
|
| '/dashboard/nodes'
|
||||||
| '/dashboard/servers'
|
| '/dashboard/servers'
|
||||||
|
| '/dashboard/withdrawal'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/dashboard/log/balance'
|
| '/dashboard/log/balance'
|
||||||
| '/dashboard/log/commission'
|
| '/dashboard/log/commission'
|
||||||
@@ -516,12 +546,14 @@ export interface FileRouteTypes {
|
|||||||
| '/dashboard/system'
|
| '/dashboard/system'
|
||||||
| '/dashboard/ticket'
|
| '/dashboard/ticket'
|
||||||
| '/dashboard/user'
|
| '/dashboard/user'
|
||||||
|
| '/dashboard/withdrawal'
|
||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/'
|
| '/'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/dashboard/nodes'
|
| '/dashboard/nodes'
|
||||||
| '/dashboard/servers'
|
| '/dashboard/servers'
|
||||||
|
| '/dashboard/withdrawal'
|
||||||
| '/dashboard/'
|
| '/dashboard/'
|
||||||
| '/dashboard/log/balance'
|
| '/dashboard/log/balance'
|
||||||
| '/dashboard/log/commission'
|
| '/dashboard/log/commission'
|
||||||
@@ -551,6 +583,7 @@ export interface FileRouteTypes {
|
|||||||
| '/dashboard/system/'
|
| '/dashboard/system/'
|
||||||
| '/dashboard/ticket/'
|
| '/dashboard/ticket/'
|
||||||
| '/dashboard/user/'
|
| '/dashboard/user/'
|
||||||
|
| '/dashboard/withdrawal/'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
@@ -581,6 +614,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof DashboardIndexLazyRouteImport
|
preLoaderRoute: typeof DashboardIndexLazyRouteImport
|
||||||
parentRoute: typeof DashboardRouteLazyRoute
|
parentRoute: typeof DashboardRouteLazyRoute
|
||||||
}
|
}
|
||||||
|
'/dashboard/withdrawal': {
|
||||||
|
id: '/dashboard/withdrawal'
|
||||||
|
path: '/withdrawal'
|
||||||
|
fullPath: '/dashboard/withdrawal'
|
||||||
|
preLoaderRoute: typeof DashboardWithdrawalLazyRouteImport
|
||||||
|
parentRoute: typeof DashboardRouteLazyRoute
|
||||||
|
}
|
||||||
'/dashboard/servers': {
|
'/dashboard/servers': {
|
||||||
id: '/dashboard/servers'
|
id: '/dashboard/servers'
|
||||||
path: '/servers'
|
path: '/servers'
|
||||||
@@ -595,6 +635,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof DashboardNodesLazyRouteImport
|
preLoaderRoute: typeof DashboardNodesLazyRouteImport
|
||||||
parentRoute: typeof DashboardRouteLazyRoute
|
parentRoute: typeof DashboardRouteLazyRoute
|
||||||
}
|
}
|
||||||
|
'/dashboard/withdrawal/': {
|
||||||
|
id: '/dashboard/withdrawal/'
|
||||||
|
path: '/withdrawal'
|
||||||
|
fullPath: '/dashboard/withdrawal'
|
||||||
|
preLoaderRoute: typeof DashboardWithdrawalIndexLazyRouteImport
|
||||||
|
parentRoute: typeof DashboardRouteLazyRoute
|
||||||
|
}
|
||||||
'/dashboard/user/': {
|
'/dashboard/user/': {
|
||||||
id: '/dashboard/user/'
|
id: '/dashboard/user/'
|
||||||
path: '/user'
|
path: '/user'
|
||||||
@@ -797,6 +844,7 @@ declare module '@tanstack/react-router' {
|
|||||||
interface DashboardRouteLazyRouteChildren {
|
interface DashboardRouteLazyRouteChildren {
|
||||||
DashboardNodesLazyRoute: typeof DashboardNodesLazyRoute
|
DashboardNodesLazyRoute: typeof DashboardNodesLazyRoute
|
||||||
DashboardServersLazyRoute: typeof DashboardServersLazyRoute
|
DashboardServersLazyRoute: typeof DashboardServersLazyRoute
|
||||||
|
DashboardWithdrawalLazyRoute: typeof DashboardWithdrawalLazyRoute
|
||||||
DashboardIndexLazyRoute: typeof DashboardIndexLazyRoute
|
DashboardIndexLazyRoute: typeof DashboardIndexLazyRoute
|
||||||
DashboardLogBalanceLazyRoute: typeof DashboardLogBalanceLazyRoute
|
DashboardLogBalanceLazyRoute: typeof DashboardLogBalanceLazyRoute
|
||||||
DashboardLogCommissionLazyRoute: typeof DashboardLogCommissionLazyRoute
|
DashboardLogCommissionLazyRoute: typeof DashboardLogCommissionLazyRoute
|
||||||
@@ -826,11 +874,13 @@ interface DashboardRouteLazyRouteChildren {
|
|||||||
DashboardSystemIndexLazyRoute: typeof DashboardSystemIndexLazyRoute
|
DashboardSystemIndexLazyRoute: typeof DashboardSystemIndexLazyRoute
|
||||||
DashboardTicketIndexLazyRoute: typeof DashboardTicketIndexLazyRoute
|
DashboardTicketIndexLazyRoute: typeof DashboardTicketIndexLazyRoute
|
||||||
DashboardUserIndexLazyRoute: typeof DashboardUserIndexLazyRoute
|
DashboardUserIndexLazyRoute: typeof DashboardUserIndexLazyRoute
|
||||||
|
DashboardWithdrawalIndexLazyRoute: typeof DashboardWithdrawalIndexLazyRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
const DashboardRouteLazyRouteChildren: DashboardRouteLazyRouteChildren = {
|
const DashboardRouteLazyRouteChildren: DashboardRouteLazyRouteChildren = {
|
||||||
DashboardNodesLazyRoute: DashboardNodesLazyRoute,
|
DashboardNodesLazyRoute: DashboardNodesLazyRoute,
|
||||||
DashboardServersLazyRoute: DashboardServersLazyRoute,
|
DashboardServersLazyRoute: DashboardServersLazyRoute,
|
||||||
|
DashboardWithdrawalLazyRoute: DashboardWithdrawalLazyRoute,
|
||||||
DashboardIndexLazyRoute: DashboardIndexLazyRoute,
|
DashboardIndexLazyRoute: DashboardIndexLazyRoute,
|
||||||
DashboardLogBalanceLazyRoute: DashboardLogBalanceLazyRoute,
|
DashboardLogBalanceLazyRoute: DashboardLogBalanceLazyRoute,
|
||||||
DashboardLogCommissionLazyRoute: DashboardLogCommissionLazyRoute,
|
DashboardLogCommissionLazyRoute: DashboardLogCommissionLazyRoute,
|
||||||
@@ -860,6 +910,7 @@ const DashboardRouteLazyRouteChildren: DashboardRouteLazyRouteChildren = {
|
|||||||
DashboardSystemIndexLazyRoute: DashboardSystemIndexLazyRoute,
|
DashboardSystemIndexLazyRoute: DashboardSystemIndexLazyRoute,
|
||||||
DashboardTicketIndexLazyRoute: DashboardTicketIndexLazyRoute,
|
DashboardTicketIndexLazyRoute: DashboardTicketIndexLazyRoute,
|
||||||
DashboardUserIndexLazyRoute: DashboardUserIndexLazyRoute,
|
DashboardUserIndexLazyRoute: DashboardUserIndexLazyRoute,
|
||||||
|
DashboardWithdrawalIndexLazyRoute: DashboardWithdrawalIndexLazyRoute,
|
||||||
}
|
}
|
||||||
|
|
||||||
const DashboardRouteLazyRouteWithChildren =
|
const DashboardRouteLazyRouteWithChildren =
|
||||||
|
|||||||
@@ -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 { useNavigate } from "@tanstack/react-router";
|
||||||
import {
|
import {
|
||||||
resetPassword,
|
adminLogin,
|
||||||
userLogin,
|
adminResetPassword,
|
||||||
userRegister,
|
} from "@workspace/ui/services/admin/auth";
|
||||||
} from "@workspace/ui/services/common/auth";
|
import { userRegister } from "@workspace/ui/services/common/auth";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { useState, useTransition } from "react";
|
import { useState, useTransition } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -42,7 +42,7 @@ export default function EmailAuthForm() {
|
|||||||
try {
|
try {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case "login": {
|
case "login": {
|
||||||
const login = await userLogin(params);
|
const login = await adminLogin(params);
|
||||||
toast.success(t("login.success", "Login successful!"));
|
toast.success(t("login.success", "Login successful!"));
|
||||||
onLogin(login.data.data?.token);
|
onLogin(login.data.data?.token);
|
||||||
break;
|
break;
|
||||||
@@ -54,7 +54,7 @@ export default function EmailAuthForm() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "reset":
|
case "reset":
|
||||||
await resetPassword(params);
|
await adminResetPassword(params);
|
||||||
toast.success(t("reset.success", "Password reset successful!"));
|
toast.success(t("reset.success", "Password reset successful!"));
|
||||||
setType("login");
|
setType("login");
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
|
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
||||||
|
|
||||||
export default function LoginForm({
|
export default function LoginForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -38,6 +39,7 @@ export default function LoginForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_admin_login_captcha;
|
const captchaEnabled = verify.enable_admin_login_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -53,14 +55,26 @@ export default function LoginForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().optional(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -71,6 +85,7 @@ export default function LoginForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -143,8 +158,8 @@ export default function LoginForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("login.title", "Login")}
|
{t("login.title", "Login")}
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
import SendCode from "../send-code";
|
|
||||||
import CloudFlareTurnstile, { type TurnstileRef } from "../turnstile";
|
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
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({
|
export default function ResetForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -40,6 +41,7 @@ export default function ResetForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -56,14 +58,26 @@ export default function ResetForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().nullish(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -74,6 +88,7 @@ export default function ResetForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -173,8 +188,8 @@ export default function ResetForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("reset.title", "Reset Password")}
|
{t("reset.title", "Reset Password")}
|
||||||
|
|||||||
@@ -2,7 +2,13 @@ import { Button } from "@workspace/ui/components/button";
|
|||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
import { Icon } from "@workspace/ui/composed/icon";
|
import { Icon } from "@workspace/ui/composed/icon";
|
||||||
import { adminGenerateCaptcha } from "@workspace/ui/services/admin/auth";
|
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";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
export interface LocalCaptchaRef {
|
export interface LocalCaptchaRef {
|
||||||
@@ -15,80 +21,85 @@ interface LocalCaptchaProps {
|
|||||||
onCaptchaIdChange?: (id: string) => void;
|
onCaptchaIdChange?: (id: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const LocalCaptcha = forwardRef<LocalCaptchaRef, LocalCaptchaProps>(
|
const LocalCaptcha = ({
|
||||||
({ value, onChange, onCaptchaIdChange }, ref) => {
|
value,
|
||||||
const { t } = useTranslation("auth");
|
onChange,
|
||||||
const [captchaImage, setCaptchaImage] = useState("");
|
onCaptchaIdChange,
|
||||||
const [loading, setLoading] = useState(false);
|
ref,
|
||||||
|
}: LocalCaptchaProps & { ref?: RefObject<LocalCaptchaRef | null> }) => {
|
||||||
|
const { t } = useTranslation("auth");
|
||||||
|
const [captchaImage, setCaptchaImage] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
const fetchCaptcha = async () => {
|
const fetchCaptcha = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await adminGenerateCaptcha();
|
const res = await adminGenerateCaptcha();
|
||||||
const captchaData = res.data?.data;
|
const captchaData = res.data?.data;
|
||||||
if (captchaData) {
|
if (captchaData) {
|
||||||
setCaptchaImage(captchaData.image);
|
setCaptchaImage(captchaData.image);
|
||||||
onCaptchaIdChange?.(captchaData.id);
|
onCaptchaIdChange?.(captchaData.id);
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to generate captcha:", error);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
} catch (error) {
|
||||||
|
console.error("Failed to generate captcha:", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
fetchCaptcha();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useImperativeHandle(ref, () => ({
|
||||||
|
reset: () => {
|
||||||
|
onChange?.("");
|
||||||
fetchCaptcha();
|
fetchCaptcha();
|
||||||
}, []);
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
return (
|
||||||
reset: () => {
|
<div className="flex gap-2">
|
||||||
onChange?.("");
|
<Input
|
||||||
fetchCaptcha();
|
className="flex-1"
|
||||||
},
|
onChange={(e) => onChange?.(e.target.value)}
|
||||||
}));
|
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
||||||
|
value={value || ""}
|
||||||
return (
|
/>
|
||||||
<div className="flex gap-2">
|
<div className="relative h-10 w-32 flex-shrink-0">
|
||||||
<Input
|
{loading ? (
|
||||||
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
<div className="flex h-full items-center justify-center bg-muted">
|
||||||
value={value || ""}
|
<Icon className="animate-spin" icon="mdi:loading" />
|
||||||
onChange={(e) => onChange?.(e.target.value)}
|
</div>
|
||||||
className="flex-1"
|
) : captchaImage ? (
|
||||||
/>
|
<img
|
||||||
<div className="relative h-10 w-32 flex-shrink-0">
|
alt="captcha"
|
||||||
{loading ? (
|
className="h-full w-full cursor-pointer object-contain"
|
||||||
<div className="flex h-full items-center justify-center bg-muted">
|
height={40}
|
||||||
<Icon className="animate-spin" icon="mdi:loading" />
|
onClick={fetchCaptcha}
|
||||||
</div>
|
src={captchaImage}
|
||||||
) : captchaImage ? (
|
title={t("captcha.clickToRefresh", "Click to refresh")}
|
||||||
<img
|
width={120}
|
||||||
src={captchaImage}
|
/>
|
||||||
alt="captcha"
|
) : (
|
||||||
className="h-full w-full cursor-pointer object-contain"
|
<div className="flex h-full items-center justify-center bg-muted text-muted-foreground text-xs">
|
||||||
onClick={fetchCaptcha}
|
{t("captcha.noImage", "No Image")}
|
||||||
title={t("captcha.clickToRefresh", "Click to refresh")}
|
</div>
|
||||||
/>
|
)}
|
||||||
) : (
|
|
||||||
<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>
|
|
||||||
</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";
|
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 { 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 { useTranslation } from "react-i18next";
|
||||||
import Turnstile, { useTurnstile } from "react-turnstile";
|
import Turnstile, { useTurnstile } from "react-turnstile";
|
||||||
|
|
||||||
@@ -23,43 +36,119 @@ const CloudFlareTurnstile = function CloudFlareTurnstile({
|
|||||||
const { common } = useGlobalStore();
|
const { common } = useGlobalStore();
|
||||||
const { verify } = common;
|
const { verify } = common;
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const { i18n } = useTranslation();
|
const { i18n, t } = useTranslation("auth");
|
||||||
const locale = i18n.language;
|
const locale = i18n.language;
|
||||||
const turnstile = useTurnstile();
|
const turnstile = useTurnstile();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [verified, setVerified] = useState(false);
|
||||||
|
|
||||||
useImperativeHandle(
|
useImperativeHandle(
|
||||||
ref,
|
ref,
|
||||||
() => ({
|
() => ({
|
||||||
reset: () => turnstile.reset(),
|
reset: () => {
|
||||||
|
setVerified(false);
|
||||||
|
onChange("");
|
||||||
|
turnstile.reset();
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
[turnstile]
|
[turnstile, onChange]
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (value === "") {
|
if (value === "") {
|
||||||
|
setVerified(false);
|
||||||
turnstile.reset();
|
turnstile.reset();
|
||||||
}
|
}
|
||||||
}, [turnstile, value]);
|
}, [turnstile, value]);
|
||||||
|
|
||||||
|
const handleOpen = () => {
|
||||||
|
if (verified) return;
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!verify.turnstile_site_key) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
verify.turnstile_site_key && (
|
<>
|
||||||
<Turnstile
|
{/* Trigger button */}
|
||||||
fixedSize
|
<button
|
||||||
id={id}
|
className={`relative flex w-full items-center gap-3 rounded-md border px-4 py-3 text-sm transition-colors ${
|
||||||
language={locale.toLowerCase()}
|
verified
|
||||||
onExpire={() => {
|
? "border-green-400 bg-green-50 text-green-700 dark:bg-green-950/30"
|
||||||
onChange();
|
: "border-input bg-background hover:bg-muted"
|
||||||
turnstile.reset();
|
}`}
|
||||||
|
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={() => {
|
open={open}
|
||||||
onChange();
|
>
|
||||||
turnstile.reset();
|
<DialogContent className="flex w-auto flex-col items-center gap-4 p-6">
|
||||||
}}
|
<DialogHeader>
|
||||||
onVerify={(token) => onChange(token)}
|
<DialogTitle>
|
||||||
sitekey={verify.turnstile_site_key}
|
{t("captcha.turnstile.title", "Security Verification")}
|
||||||
theme={resolvedTheme as "light" | "dark"}
|
</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>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -11,17 +12,16 @@ import {
|
|||||||
} from "@workspace/ui/components/card";
|
} from "@workspace/ui/components/card";
|
||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
import { Label } from "@workspace/ui/components/label";
|
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 {
|
import {
|
||||||
getGroupConfig,
|
getGroupConfig,
|
||||||
getNodeGroupList,
|
getNodeGroupList,
|
||||||
getRecalculationStatus,
|
getRecalculationStatus,
|
||||||
recalculateGroup,
|
recalculateGroup,
|
||||||
} from "@workspace/ui/services/admin/group";
|
} 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() {
|
export default function AverageModeTab() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
@@ -147,7 +147,9 @@ export default function AverageModeTab() {
|
|||||||
{/* Configuration Card */}
|
{/* Configuration Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("averageModeConfig", "Average Mode Configuration")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("averageModeConfig", "Average Mode Configuration")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"averageModeDescription",
|
"averageModeDescription",
|
||||||
@@ -162,15 +164,18 @@ export default function AverageModeTab() {
|
|||||||
{t("availableNodeGroups", "Available Node Groups")}
|
{t("availableNodeGroups", "Available Node Groups")}
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="node_group_count"
|
|
||||||
type="number"
|
|
||||||
min={1}
|
|
||||||
value={averageConfig.node_group_count}
|
|
||||||
readOnly
|
|
||||||
className="bg-muted"
|
className="bg-muted"
|
||||||
|
id="node_group_count"
|
||||||
|
min={1}
|
||||||
|
readOnly
|
||||||
|
type="number"
|
||||||
|
value={averageConfig.node_group_count}
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-muted-foreground text-xs">
|
||||||
{t("nodeGroupCountAutoCalculated", "Auto-calculated from actual node groups")}
|
{t(
|
||||||
|
"nodeGroupCountAutoCalculated",
|
||||||
|
"Auto-calculated from actual node groups"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -180,7 +185,9 @@ export default function AverageModeTab() {
|
|||||||
{/* Recalculation Card */}
|
{/* Recalculation Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("groupRecalculation", "Group Recalculation")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"groupRecalculationDescription",
|
"groupRecalculationDescription",
|
||||||
@@ -192,7 +199,7 @@ export default function AverageModeTab() {
|
|||||||
{/* Current Status */}
|
{/* Current Status */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium">
|
<span className="font-medium text-sm">
|
||||||
{t("currentStatus", "Current Status")}
|
{t("currentStatus", "Current Status")}
|
||||||
</span>
|
</span>
|
||||||
{loadingStatus ? (
|
{loadingStatus ? (
|
||||||
@@ -224,14 +231,20 @@ export default function AverageModeTab() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "completed" && (
|
{status?.state === "completed" && (
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
{t(
|
||||||
|
"recalculationCompleted",
|
||||||
|
"Recalculation completed successfully"
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "failed" && (
|
{status?.state === "failed" && (
|
||||||
<div className="text-sm text-destructive">
|
<div className="text-destructive text-sm">
|
||||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
{t(
|
||||||
|
"recalculationFailed",
|
||||||
|
"Recalculation failed. Please try again."
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -239,8 +252,8 @@ export default function AverageModeTab() {
|
|||||||
{/* Recalculate Button */}
|
{/* Recalculate Button */}
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleRecalculate}
|
|
||||||
disabled={recalculating || status?.state === "running"}
|
disabled={recalculating || status?.state === "running"}
|
||||||
|
onClick={handleRecalculate}
|
||||||
>
|
>
|
||||||
{recalculating && (
|
{recalculating && (
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -18,12 +19,14 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@workspace/ui/components/select";
|
} from "@workspace/ui/components/select";
|
||||||
|
import {
|
||||||
|
bindNodeGroups,
|
||||||
|
getNodeGroupList,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { getNodeGroupList, bindNodeGroups } from "@workspace/ui/services/admin/group";
|
|
||||||
|
|
||||||
interface BindNodeGroupsDialogProps {
|
interface BindNodeGroupsDialogProps {
|
||||||
userGroupIds: number[];
|
userGroupIds: number[];
|
||||||
@@ -41,7 +44,9 @@ export default function BindNodeGroupsDialog({
|
|||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [selectedNodeGroupId, setSelectedNodeGroupId] = useState<number | undefined>();
|
const [selectedNodeGroupId, setSelectedNodeGroupId] = useState<
|
||||||
|
number | undefined
|
||||||
|
>();
|
||||||
|
|
||||||
const { data: nodeGroupsData, isLoading } = useQuery({
|
const { data: nodeGroupsData, isLoading } = useQuery({
|
||||||
queryKey: ["nodeGroups"],
|
queryKey: ["nodeGroups"],
|
||||||
@@ -78,10 +83,10 @@ export default function BindNodeGroupsDialog({
|
|||||||
} as API.BindNodeGroupsRequest);
|
} as API.BindNodeGroupsRequest);
|
||||||
|
|
||||||
toast.success(
|
toast.success(
|
||||||
t("bindSuccess", "Successfully bound {{userGroupCount}} user groups to node group").replace(
|
t(
|
||||||
/{{userGroupCount}}/g,
|
"bindSuccess",
|
||||||
String(userGroupIds.length)
|
"Successfully bound {{userGroupCount}} user groups to node group"
|
||||||
)
|
).replace(/{{userGroupCount}}/g, String(userGroupIds.length))
|
||||||
);
|
);
|
||||||
|
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
@@ -101,12 +106,15 @@ export default function BindNodeGroupsDialog({
|
|||||||
: userGroupNames.join(", ");
|
: userGroupNames.join(", ");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={(newOpen) => {
|
<Dialog
|
||||||
setOpen(newOpen);
|
onOpenChange={(newOpen) => {
|
||||||
onOpenChange?.(newOpen);
|
setOpen(newOpen);
|
||||||
}}>
|
onOpenChange?.(newOpen);
|
||||||
|
}}
|
||||||
|
open={open}
|
||||||
|
>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button variant="outline" size="sm">
|
<Button size="sm" variant="outline">
|
||||||
{t("bindNodeGroup", "Bind Node Group")}
|
{t("bindNodeGroup", "Bind Node Group")}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -129,18 +137,25 @@ export default function BindNodeGroupsDialog({
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-2">
|
<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
|
<Select
|
||||||
|
onValueChange={(val) =>
|
||||||
|
setSelectedNodeGroupId(Number.parseInt(val, 10) || undefined)
|
||||||
|
}
|
||||||
value={selectedNodeGroupId?.toString() || ""}
|
value={selectedNodeGroupId?.toString() || ""}
|
||||||
onValueChange={(val) => setSelectedNodeGroupId(parseInt(val) || undefined)}
|
|
||||||
>
|
>
|
||||||
<SelectTrigger id="node-group" className="w-full">
|
<SelectTrigger className="w-full" id="node-group">
|
||||||
<SelectValue placeholder={t("selectNodeGroupPlaceholder", "Select a node group...")} />
|
<SelectValue
|
||||||
|
placeholder={t(
|
||||||
|
"selectNodeGroupPlaceholder",
|
||||||
|
"Select a node group..."
|
||||||
|
)}
|
||||||
|
/>
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="0">
|
<SelectItem value="0">{t("unbound", "Unbound")}</SelectItem>
|
||||||
{t("unbound", "Unbound")}
|
|
||||||
</SelectItem>
|
|
||||||
{nodeGroupsData?.map((nodeGroup) => (
|
{nodeGroupsData?.map((nodeGroup) => (
|
||||||
<SelectItem key={nodeGroup.id} value={String(nodeGroup.id)}>
|
<SelectItem key={nodeGroup.id} value={String(nodeGroup.id)}>
|
||||||
{nodeGroup.name}
|
{nodeGroup.name}
|
||||||
@@ -154,16 +169,19 @@ export default function BindNodeGroupsDialog({
|
|||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
disabled={saving}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
onOpenChange?.(false);
|
onOpenChange?.(false);
|
||||||
}}
|
}}
|
||||||
disabled={saving}
|
variant="outline"
|
||||||
>
|
>
|
||||||
{t("cancel", "Cancel")}
|
{t("cancel", "Cancel")}
|
||||||
</Button>
|
</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" />}
|
{saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||||
{t("confirm", "Confirm")}
|
{t("confirm", "Confirm")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -22,11 +23,14 @@ import {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "@workspace/ui/components/table";
|
} from "@workspace/ui/components/table";
|
||||||
|
import {
|
||||||
|
getGroupHistory,
|
||||||
|
getGroupHistoryDetail,
|
||||||
|
getNodeGroupList,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
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() {
|
export default function CurrentGroupResults() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
@@ -37,7 +41,8 @@ export default function CurrentGroupResults() {
|
|||||||
|
|
||||||
// User list dialog state
|
// User list dialog state
|
||||||
const [userListOpen, setUserListOpen] = useState(false);
|
const [userListOpen, setUserListOpen] = useState(false);
|
||||||
const [selectedNodeGroupName, setSelectedNodeGroupName] = useState<string>("");
|
const [selectedNodeGroupName, setSelectedNodeGroupName] =
|
||||||
|
useState<string>("");
|
||||||
const [userList, setUserList] = useState<any[]>([]);
|
const [userList, setUserList] = useState<any[]>([]);
|
||||||
const [userListLoading, setUserListLoading] = useState(false);
|
const [userListLoading, setUserListLoading] = useState(false);
|
||||||
const [userListTotal, setUserListTotal] = useState(0);
|
const [userListTotal, setUserListTotal] = useState(0);
|
||||||
@@ -94,7 +99,10 @@ export default function CurrentGroupResults() {
|
|||||||
loadData();
|
loadData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleShowUserList = async (nodeGroupId: number, nodeGroupName: string) => {
|
const handleShowUserList = async (
|
||||||
|
nodeGroupId: number,
|
||||||
|
nodeGroupName: string
|
||||||
|
) => {
|
||||||
setSelectedNodeGroupName(nodeGroupName);
|
setSelectedNodeGroupName(nodeGroupName);
|
||||||
setUserListOpen(true);
|
setUserListOpen(true);
|
||||||
setUserListLoading(true);
|
setUserListLoading(true);
|
||||||
@@ -132,10 +140,10 @@ export default function CurrentGroupResults() {
|
|||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("currentGroupingResult", "Current Grouping Result")}</CardTitle>
|
<CardTitle>
|
||||||
<CardDescription>
|
{t("currentGroupingResult", "Current Grouping Result")}
|
||||||
{t("loading", "Loading...")}
|
</CardTitle>
|
||||||
</CardDescription>
|
<CardDescription>{t("loading", "Loading...")}</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
@@ -144,110 +152,144 @@ export default function CurrentGroupResults() {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Latest Result Card */}
|
{/* Latest Result Card */}
|
||||||
{!latestResult ? (
|
{latestResult ? (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("currentGroupingResult", "Current Grouping Result")}</CardTitle>
|
<CardTitle>
|
||||||
</CardHeader>
|
{t("currentGroupingResult", "Current Grouping Result")}
|
||||||
<CardContent>
|
</CardTitle>
|
||||||
<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>
|
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t("latestGroupingCalculation", "Latest grouping calculation details")}
|
{t(
|
||||||
|
"latestGroupingCalculation",
|
||||||
|
"Latest grouping calculation details"
|
||||||
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
{/* Calculation Info */}
|
{/* Calculation Info */}
|
||||||
<div className="space-y-2">
|
<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 className="grid grid-cols-2 gap-4 rounded-lg bg-muted/50 p-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-xs text-muted-foreground">{t("groupMode", "Group Mode")}</div>
|
<div className="text-muted-foreground text-xs">
|
||||||
<div className="font-medium">
|
{t("groupMode", "Group Mode")}
|
||||||
{(latestResult.GroupMode || latestResult.group_mode) === "average"
|
</div>
|
||||||
? t("averageMode", "Average Mode")
|
<div className="font-medium">
|
||||||
: (latestResult.GroupMode || latestResult.group_mode) === "subscribe"
|
{(latestResult.GroupMode || latestResult.group_mode) ===
|
||||||
? t("subscribeMode", "Subscribe Mode")
|
"average"
|
||||||
: t("trafficMode", "Traffic Mode")}
|
? 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>
|
||||||
<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>
|
</div>
|
||||||
|
|
||||||
{/* Grouping Details */}
|
{/* Grouping Details */}
|
||||||
<div className="space-y-2">
|
<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="grid grid-cols-3 gap-4 rounded-lg bg-muted/50 p-4">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">
|
<div className="font-bold text-2xl">
|
||||||
{latestDetails.reduce((sum: number, d: any) => sum + (d.UserCount || d.user_count || 0), 0)}
|
{latestDetails.reduce(
|
||||||
|
(sum: number, d: any) =>
|
||||||
|
sum + (d.UserCount || d.user_count || 0),
|
||||||
|
0
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalUsers", "Total Users")}
|
{t("totalUsers", "Total Users")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">
|
<div className="font-bold text-2xl">
|
||||||
{latestDetails.reduce((sum: number, d: any) => sum + (d.NodeCount || d.node_count || 0), 0)}
|
{latestDetails.reduce(
|
||||||
|
(sum: number, d: any) =>
|
||||||
|
sum + (d.NodeCount || d.node_count || 0),
|
||||||
|
0
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalNodes", "Total Nodes")}
|
{t("totalNodes", "Total Nodes")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">{latestDetails.length}</div>
|
<div className="font-bold text-2xl">
|
||||||
<div className="text-xs text-muted-foreground">
|
{latestDetails.length}
|
||||||
|
</div>
|
||||||
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalNodeGroups", "Total Node Groups")}
|
{t("totalNodeGroups", "Total Node Groups")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -257,7 +299,7 @@ export default function CurrentGroupResults() {
|
|||||||
{detailsLoading ? (
|
{detailsLoading ? (
|
||||||
<div className="flex items-center justify-center py-8">
|
<div className="flex items-center justify-center py-8">
|
||||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
<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...")}
|
{t("loading", "Loading...")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -281,26 +323,41 @@ export default function CurrentGroupResults() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{latestDetails.map((detail: any, index: number) => {
|
{latestDetails.map((detail: any, index: number) => {
|
||||||
const nodeGroupId = detail.NodeGroupId || detail.node_group_id;
|
const nodeGroupId =
|
||||||
const nodeGroup = nodeGroups?.find((ng) => ng.id === nodeGroupId);
|
detail.NodeGroupId || detail.node_group_id;
|
||||||
const nodeGroupName = nodeGroup?.name || `${t("idPrefix", "#")}${nodeGroupId}`;
|
const nodeGroup = nodeGroups?.find(
|
||||||
const userCount = detail.UserCount || detail.user_count || 0;
|
(ng) => ng.id === nodeGroupId
|
||||||
|
);
|
||||||
|
const nodeGroupName =
|
||||||
|
nodeGroup?.name ||
|
||||||
|
`${t("idPrefix", "#")}${nodeGroupId}`;
|
||||||
|
const userCount =
|
||||||
|
detail.UserCount || detail.user_count || 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr key={index}>
|
<tr key={index}>
|
||||||
<td className="border-b px-4 py-2">
|
<td className="border-b px-4 py-2">
|
||||||
<div>
|
<div>
|
||||||
<div className="font-medium">{nodeGroupName}</div>
|
<div className="font-medium">
|
||||||
<div className="text-xs text-muted-foreground">{t("id", "ID")}: {nodeGroupId}</div>
|
{nodeGroupName}
|
||||||
|
</div>
|
||||||
|
<div className="text-muted-foreground text-xs">
|
||||||
|
{t("id", "ID")}: {nodeGroupId}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="border-b px-4 py-2 text-right">
|
<td className="border-b px-4 py-2 text-right">
|
||||||
<button
|
<button
|
||||||
className={`font-semibold hover:underline ${
|
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}
|
disabled={userCount === 0}
|
||||||
|
onClick={() =>
|
||||||
|
handleShowUserList(nodeGroupId, nodeGroupName)
|
||||||
|
}
|
||||||
|
type="button"
|
||||||
>
|
>
|
||||||
{userCount}
|
{userCount}
|
||||||
</button>
|
</button>
|
||||||
@@ -316,17 +373,30 @@ export default function CurrentGroupResults() {
|
|||||||
</div>
|
</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")}
|
{t("noDetails", "No details available")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</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 */}
|
{/* User List Dialog */}
|
||||||
<Dialog open={userListOpen} onOpenChange={setUserListOpen}>
|
<Dialog onOpenChange={setUserListOpen} open={userListOpen}>
|
||||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>
|
<DialogTitle>
|
||||||
{selectedNodeGroupName} - {t("userList", "User List")}
|
{selectedNodeGroupName} - {t("userList", "User List")}
|
||||||
@@ -339,7 +409,7 @@ export default function CurrentGroupResults() {
|
|||||||
{userListLoading ? (
|
{userListLoading ? (
|
||||||
<div className="flex items-center justify-center py-8">
|
<div className="flex items-center justify-center py-8">
|
||||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
<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...")}
|
{t("loading", "Loading...")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -355,15 +425,13 @@ export default function CurrentGroupResults() {
|
|||||||
{userList.map((user) => (
|
{userList.map((user) => (
|
||||||
<TableRow key={user.id}>
|
<TableRow key={user.id}>
|
||||||
<TableCell className="font-medium">{user.id}</TableCell>
|
<TableCell className="font-medium">{user.id}</TableCell>
|
||||||
<TableCell>
|
<TableCell>{user.email || "-"}</TableCell>
|
||||||
{user.email || "-"}
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</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")}
|
{t("noUsers", "No users found")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,22 +1,5 @@
|
|||||||
"use client";
|
"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 {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@@ -28,6 +11,23 @@ import {
|
|||||||
AlertDialogTitle,
|
AlertDialogTitle,
|
||||||
AlertDialogTrigger,
|
AlertDialogTrigger,
|
||||||
} from "@workspace/ui/components/alert-dialog";
|
} 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() {
|
export default function GroupConfig() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
@@ -47,8 +47,11 @@ export default function GroupConfig() {
|
|||||||
const { data } = await getGroupConfig();
|
const { data } = await getGroupConfig();
|
||||||
if (data.data) {
|
if (data.data) {
|
||||||
setConfig({
|
setConfig({
|
||||||
enabled: data.data.enabled || false,
|
enabled: data.data.enabled,
|
||||||
mode: (data.data.mode || "average") as "average" | "subscribe" | "traffic",
|
mode: (data.data.mode || "average") as
|
||||||
|
| "average"
|
||||||
|
| "subscribe"
|
||||||
|
| "traffic",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} 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);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const payload: any = {
|
const payload: any = {
|
||||||
@@ -101,7 +106,9 @@ export default function GroupConfig() {
|
|||||||
setResetting(true);
|
setResetting(true);
|
||||||
try {
|
try {
|
||||||
await resetGroups({ confirm: true });
|
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);
|
setShowResetDialog(false);
|
||||||
// Reload config after reset
|
// Reload config after reset
|
||||||
await loadConfig();
|
await loadConfig();
|
||||||
@@ -129,10 +136,10 @@ export default function GroupConfig() {
|
|||||||
{/* Enable/Disable */}
|
{/* Enable/Disable */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="enabled" className="font-medium">
|
<label className="font-medium" htmlFor="enabled">
|
||||||
{t("enableGrouping", "Enable Grouping")}
|
{t("enableGrouping", "Enable Grouping")}
|
||||||
</label>
|
</label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{t(
|
{t(
|
||||||
"enableGroupingDescription",
|
"enableGroupingDescription",
|
||||||
"When enabled, users will only see nodes from their assigned group"
|
"When enabled, users will only see nodes from their assigned group"
|
||||||
@@ -140,36 +147,36 @@ export default function GroupConfig() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
id="enabled"
|
|
||||||
type="checkbox"
|
|
||||||
checked={config.enabled}
|
checked={config.enabled}
|
||||||
onChange={(e) => handleUpdateEnabled(e.target.checked)}
|
|
||||||
disabled={saving}
|
|
||||||
className="h-4 w-4"
|
className="h-4 w-4"
|
||||||
|
disabled={saving}
|
||||||
|
id="enabled"
|
||||||
|
onChange={(e) => handleUpdateEnabled(e.target.checked)}
|
||||||
|
type="checkbox"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mode Selection */}
|
{/* Mode Selection */}
|
||||||
{config.enabled && (
|
{config.enabled && (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="font-medium">
|
<p className="font-medium">
|
||||||
{t("groupingMode", "Grouping Mode")}
|
{t("groupingMode", "Grouping Mode")}
|
||||||
</label>
|
</p>
|
||||||
<div className="grid grid-cols-3 gap-4">
|
<div className="grid grid-cols-3 gap-4">
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={() => handleUpdateMode("average")}
|
|
||||||
disabled={saving}
|
|
||||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||||
config.mode === "average"
|
config.mode === "average"
|
||||||
? "border-primary bg-primary/10"
|
? "border-primary bg-primary/10"
|
||||||
: "border-border hover:bg-muted"
|
: "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">
|
<div className="font-medium">
|
||||||
{t("averageMode", "Average Mode")}
|
{t("averageMode", "Average Mode")}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t(
|
{t(
|
||||||
"averageModeDescription",
|
"averageModeDescription",
|
||||||
"Distribute users evenly across groups"
|
"Distribute users evenly across groups"
|
||||||
@@ -178,19 +185,19 @@ export default function GroupConfig() {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={() => handleUpdateMode("subscribe")}
|
|
||||||
disabled={saving}
|
|
||||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||||
config.mode === "subscribe"
|
config.mode === "subscribe"
|
||||||
? "border-primary bg-primary/10"
|
? "border-primary bg-primary/10"
|
||||||
: "border-border hover:bg-muted"
|
: "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">
|
<div className="font-medium">
|
||||||
{t("subscribeMode", "Subscribe Mode")}
|
{t("subscribeMode", "Subscribe Mode")}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t(
|
{t(
|
||||||
"subscribeModeDescription",
|
"subscribeModeDescription",
|
||||||
"Group users by their subscription plan"
|
"Group users by their subscription plan"
|
||||||
@@ -199,19 +206,19 @@ export default function GroupConfig() {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={() => handleUpdateMode("traffic")}
|
|
||||||
disabled={saving}
|
|
||||||
className={`rounded-lg border p-4 text-left transition-colors ${
|
className={`rounded-lg border p-4 text-left transition-colors ${
|
||||||
config.mode === "traffic"
|
config.mode === "traffic"
|
||||||
? "border-primary bg-primary/10"
|
? "border-primary bg-primary/10"
|
||||||
: "border-border hover:bg-muted"
|
: "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">
|
<div className="font-medium">
|
||||||
{t("trafficMode", "Traffic Mode")}
|
{t("trafficMode", "Traffic Mode")}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t(
|
{t(
|
||||||
"trafficModeDescription",
|
"trafficModeDescription",
|
||||||
"Group users by their traffic usage"
|
"Group users by their traffic usage"
|
||||||
@@ -223,8 +230,11 @@ export default function GroupConfig() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Reset Button */}
|
{/* Reset Button */}
|
||||||
<div className="flex justify-end pt-4 border-t">
|
<div className="flex justify-end border-t pt-4">
|
||||||
<AlertDialog open={showResetDialog} onOpenChange={setShowResetDialog}>
|
<AlertDialog
|
||||||
|
onOpenChange={setShowResetDialog}
|
||||||
|
open={showResetDialog}
|
||||||
|
>
|
||||||
<AlertDialogTrigger asChild>
|
<AlertDialogTrigger asChild>
|
||||||
<Button variant="destructive">
|
<Button variant="destructive">
|
||||||
{t("resetGroups", "Reset All Groups")}
|
{t("resetGroups", "Reset All Groups")}
|
||||||
@@ -243,14 +253,14 @@ export default function GroupConfig() {
|
|||||||
</AlertDialogDescription>
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>
|
<AlertDialogCancel>{t("cancel", "Cancel")}</AlertDialogCancel>
|
||||||
{t("cancel", "Cancel")}
|
|
||||||
</AlertDialogCancel>
|
|
||||||
<AlertDialogAction
|
<AlertDialogAction
|
||||||
onClick={handleResetGroups}
|
|
||||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
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")}
|
{t("confirm", "Confirm")}
|
||||||
</AlertDialogAction>
|
</AlertDialogAction>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -33,24 +34,27 @@ import {
|
|||||||
getGroupHistoryDetail,
|
getGroupHistoryDetail,
|
||||||
getNodeGroupList,
|
getNodeGroupList,
|
||||||
} from "@workspace/ui/services/admin/group";
|
} from "@workspace/ui/services/admin/group";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
import { useRef, useState } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { formatDate } from "@/utils/common";
|
import { formatDate } from "@/utils/common";
|
||||||
import { Loader2 } from "lucide-react";
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export default function GroupHistory() {
|
export default function GroupHistory() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
const ref = useRef<ProTableActions>(null);
|
const ref = useRef<ProTableActions>(null);
|
||||||
const [detailOpen, setDetailOpen] = useState(false);
|
const [detailOpen, setDetailOpen] = useState(false);
|
||||||
const [detailLoading, setDetailLoading] = 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 [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
|
// User list dialog state
|
||||||
const [userListOpen, setUserListOpen] = useState(false);
|
const [userListOpen, setUserListOpen] = useState(false);
|
||||||
const [selectedNodeGroupName, setSelectedNodeGroupName] = useState<string>("");
|
const [selectedNodeGroupName, setSelectedNodeGroupName] =
|
||||||
|
useState<string>("");
|
||||||
const [userList, setUserList] = useState<any[]>([]);
|
const [userList, setUserList] = useState<any[]>([]);
|
||||||
const [userListTotal, setUserListTotal] = useState(0);
|
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);
|
setSelectedNodeGroupName(nodeGroupName);
|
||||||
setUserListOpen(true);
|
setUserListOpen(true);
|
||||||
|
|
||||||
@@ -166,23 +173,30 @@ export default function GroupHistory() {
|
|||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("groupHistory", "Group Calculation History")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("groupHistory", "Group Calculation History")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t("groupHistoryDescription", "View group recalculation history and results")}
|
{t(
|
||||||
|
"groupHistoryDescription",
|
||||||
|
"View group recalculation history and results"
|
||||||
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ProTable<API.GroupHistory, API.GetGroupHistoryRequest>
|
<ProTable<API.GroupHistory, API.GetGroupHistoryRequest>
|
||||||
action={ref}
|
action={ref}
|
||||||
request={async (params) => {
|
actions={{
|
||||||
const { data } = await getGroupHistory({
|
render: (row: any) => [
|
||||||
page: params.page || 1,
|
<Button
|
||||||
size: params.size || 10,
|
key="detail"
|
||||||
});
|
onClick={() => handleViewDetail(row)}
|
||||||
return {
|
size="sm"
|
||||||
list: data.data?.list || [],
|
variant="outline"
|
||||||
total: data.data?.total || 0,
|
>
|
||||||
};
|
{t("viewDetail", "View Detail")}
|
||||||
|
</Button>,
|
||||||
|
],
|
||||||
}}
|
}}
|
||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
@@ -191,7 +205,8 @@ export default function GroupHistory() {
|
|||||||
header: t("id", "ID"),
|
header: t("id", "ID"),
|
||||||
cell: ({ row }: { row: any }) => (
|
cell: ({ row }: { row: any }) => (
|
||||||
<span className="text-muted-foreground">
|
<span className="text-muted-foreground">
|
||||||
{t("idPrefix", "#")}{row.getValue("id")}
|
{t("idPrefix", "#")}
|
||||||
|
{row.getValue("id")}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -220,7 +235,9 @@ export default function GroupHistory() {
|
|||||||
accessorKey: "total_users",
|
accessorKey: "total_users",
|
||||||
header: t("totalUsers", "Total Users"),
|
header: t("totalUsers", "Total Users"),
|
||||||
cell: ({ row }: { row: any }) => (
|
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;
|
const record = row.original;
|
||||||
return (
|
return (
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("successCount", "Success")}: {record.success_count}
|
{t("successCount", "Success")}: {record.success_count}{" "}
|
||||||
{" "}{t("separator", "/")}{" "}
|
{t("separator", "/")} {t("failedCount", "Failed")}:{" "}
|
||||||
{t("failedCount", "Failed")}: {record.failed_count}
|
{record.failed_count}
|
||||||
</div>
|
</div>
|
||||||
{record.error_log && (
|
{record.error_log && (
|
||||||
<Badge variant="destructive">
|
<Badge variant="destructive">
|
||||||
@@ -254,31 +271,30 @@ export default function GroupHistory() {
|
|||||||
id: "created_at",
|
id: "created_at",
|
||||||
accessorKey: "created_at",
|
accessorKey: "created_at",
|
||||||
header: t("createdAt", "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={{
|
header={{
|
||||||
title: t("groupHistory", "Group Calculation History"),
|
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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Detail Dialog */}
|
{/* Detail Dialog */}
|
||||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
<Dialog onOpenChange={setDetailOpen} open={detailOpen}>
|
||||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>
|
<DialogTitle>
|
||||||
{t("groupHistoryDetail", "Group Calculation Detail")}
|
{t("groupHistoryDetail", "Group Calculation Detail")}
|
||||||
@@ -292,7 +308,7 @@ export default function GroupHistory() {
|
|||||||
<>
|
<>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("groupMode", "Group Mode")}
|
{t("groupMode", "Group Mode")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">
|
<div className="font-medium">
|
||||||
@@ -300,7 +316,7 @@ export default function GroupHistory() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("triggerType", "Trigger Type")}
|
{t("triggerType", "Trigger Type")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">
|
<div className="font-medium">
|
||||||
@@ -308,24 +324,27 @@ export default function GroupHistory() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("totalUsers", "Total Users")}
|
{t("totalUsers", "Total Users")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">{selectedHistory.total_users}</div>
|
<div className="font-medium">
|
||||||
|
{selectedHistory.total_users}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("result", "Result")}
|
{t("result", "Result")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">
|
<div className="font-medium">
|
||||||
{t("successCount", "Success")}: {selectedHistory.success_count}
|
{t("successCount", "Success")}:{" "}
|
||||||
{" "}{t("separator", "/")}{" "}
|
{selectedHistory.success_count} {t("separator", "/")}{" "}
|
||||||
{t("failedCount", "Failed")}: {selectedHistory.failed_count}
|
{t("failedCount", "Failed")}:{" "}
|
||||||
|
{selectedHistory.failed_count}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{selectedHistory.start_time && (
|
{selectedHistory.start_time && (
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("startTime", "Start Time")}
|
{t("startTime", "Start Time")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">
|
<div className="font-medium">
|
||||||
@@ -335,7 +354,7 @@ export default function GroupHistory() {
|
|||||||
)}
|
)}
|
||||||
{selectedHistory.end_time && (
|
{selectedHistory.end_time && (
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("endTime", "End Time")}
|
{t("endTime", "End Time")}
|
||||||
</div>
|
</div>
|
||||||
<div className="font-medium">
|
<div className="font-medium">
|
||||||
@@ -347,10 +366,10 @@ export default function GroupHistory() {
|
|||||||
|
|
||||||
{selectedHistory.error_log && (
|
{selectedHistory.error_log && (
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("errorMessage", "Error Message")}
|
{t("errorMessage", "Error Message")}
|
||||||
</div>
|
</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}
|
{selectedHistory.error_log}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -359,13 +378,13 @@ export default function GroupHistory() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-2 text-sm font-medium">
|
<div className="mb-2 font-medium text-sm">
|
||||||
{t("groupDetails", "Group Details")}
|
{t("groupDetails", "Group Details")}
|
||||||
</div>
|
</div>
|
||||||
{detailLoading ? (
|
{detailLoading ? (
|
||||||
<div className="flex items-center justify-center py-8">
|
<div className="flex items-center justify-center py-8">
|
||||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
<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...")}
|
{t("loading", "Loading...")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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="mb-4 grid grid-cols-3 gap-4 rounded-lg bg-muted/50 p-4">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">
|
<div className="font-bold text-2xl">
|
||||||
{details.reduce((sum: number, d: any) => sum + (d.UserCount || d.user_count || 0), 0)}
|
{details.reduce(
|
||||||
|
(sum: number, d: any) =>
|
||||||
|
sum + (d.UserCount || d.user_count || 0),
|
||||||
|
0
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalUsers", "Total Users")}
|
{t("totalUsers", "Total Users")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">
|
<div className="font-bold text-2xl">
|
||||||
{details.reduce((sum: number, d: any) => sum + (d.NodeCount || d.node_count || 0), 0)}
|
{details.reduce(
|
||||||
|
(sum: number, d: any) =>
|
||||||
|
sum + (d.NodeCount || d.node_count || 0),
|
||||||
|
0
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalNodes", "Total Nodes")}
|
{t("totalNodes", "Total Nodes")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-2xl font-bold">{details.length}</div>
|
<div className="font-bold text-2xl">{details.length}</div>
|
||||||
<div className="text-xs text-muted-foreground">
|
<div className="text-muted-foreground text-xs">
|
||||||
{t("totalNodeGroups", "Total Node Groups")}
|
{t("totalNodeGroups", "Total Node Groups")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -415,22 +442,39 @@ export default function GroupHistory() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{details.map((detail: any, index: number) => {
|
{details.map((detail: any, index: number) => {
|
||||||
const nodeGroupId = detail.NodeGroupId || detail.node_group_id;
|
const nodeGroupId =
|
||||||
const nodeGroupName = nodeGroupMap.get(nodeGroupId) || `${t("idPrefix", "#")}${nodeGroupId}`;
|
detail.NodeGroupId || detail.node_group_id;
|
||||||
|
const nodeGroupName =
|
||||||
|
nodeGroupMap.get(nodeGroupId) ||
|
||||||
|
`${t("idPrefix", "#")}${nodeGroupId}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr key={index}>
|
<tr key={index}>
|
||||||
<td className="border-b px-4 py-2">
|
<td className="border-b px-4 py-2">
|
||||||
<div>
|
<div>
|
||||||
<div className="font-medium">{nodeGroupName}</div>
|
<div className="font-medium">
|
||||||
<div className="text-xs text-muted-foreground">{t("id", "ID")}: {nodeGroupId}</div>
|
{nodeGroupName}
|
||||||
|
</div>
|
||||||
|
<div className="text-muted-foreground text-xs">
|
||||||
|
{t("id", "ID")}: {nodeGroupId}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="border-b px-4 py-2 text-right">
|
<td className="border-b px-4 py-2 text-right">
|
||||||
<button
|
<button
|
||||||
className="font-semibold hover:underline cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
className="cursor-pointer font-semibold hover:underline disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
onClick={() => handleShowUserList(nodeGroupId, nodeGroupName)}
|
disabled={
|
||||||
disabled={(detail.UserCount || detail.user_count || 0) === 0}
|
(detail.UserCount ||
|
||||||
|
detail.user_count ||
|
||||||
|
0) === 0
|
||||||
|
}
|
||||||
|
onClick={() =>
|
||||||
|
handleShowUserList(
|
||||||
|
nodeGroupId,
|
||||||
|
nodeGroupName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
type="button"
|
||||||
>
|
>
|
||||||
{detail.UserCount || detail.user_count || 0}
|
{detail.UserCount || detail.user_count || 0}
|
||||||
</button>
|
</button>
|
||||||
@@ -446,7 +490,7 @@ export default function GroupHistory() {
|
|||||||
</div>
|
</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")}
|
{t("noDetails", "No details available")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -456,8 +500,8 @@ export default function GroupHistory() {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
{/* User List Dialog */}
|
{/* User List Dialog */}
|
||||||
<Dialog open={userListOpen} onOpenChange={setUserListOpen}>
|
<Dialog onOpenChange={setUserListOpen} open={userListOpen}>
|
||||||
<DialogContent className="sm:max-w-[700px] max-h-[80vh] overflow-y-auto">
|
<DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-[700px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>
|
<DialogTitle>
|
||||||
{selectedNodeGroupName} - {t("userList", "User List")}
|
{selectedNodeGroupName} - {t("userList", "User List")}
|
||||||
@@ -479,15 +523,13 @@ export default function GroupHistory() {
|
|||||||
{userList.map((user) => (
|
{userList.map((user) => (
|
||||||
<TableRow key={user.id}>
|
<TableRow key={user.id}>
|
||||||
<TableCell className="font-medium">{user.id}</TableCell>
|
<TableCell className="font-medium">{user.id}</TableCell>
|
||||||
<TableCell>
|
<TableCell>{user.email || "-"}</TableCell>
|
||||||
{user.email || "-"}
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</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")}
|
{t("noUsers", "No users found")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import {
|
|||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@workspace/ui/components/card";
|
} 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 {
|
import {
|
||||||
getRecalculationStatus,
|
getRecalculationStatus,
|
||||||
recalculateGroup,
|
recalculateGroup,
|
||||||
} from "@workspace/ui/services/admin/group";
|
} 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() {
|
export default function GroupRecalculate() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
@@ -54,7 +54,9 @@ export default function GroupRecalculate() {
|
|||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [status?.state]);
|
}, [status?.state]);
|
||||||
|
|
||||||
const handleRecalculate = async (mode: "average" | "subscribe" | "traffic") => {
|
const handleRecalculate = async (
|
||||||
|
mode: "average" | "subscribe" | "traffic"
|
||||||
|
) => {
|
||||||
setRecalculating(mode);
|
setRecalculating(mode);
|
||||||
try {
|
try {
|
||||||
await recalculateGroup({ mode });
|
await recalculateGroup({ mode });
|
||||||
@@ -98,7 +100,9 @@ export default function GroupRecalculate() {
|
|||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("groupRecalculation", "Group Recalculation")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"groupRecalculationDescription",
|
"groupRecalculationDescription",
|
||||||
@@ -110,7 +114,7 @@ export default function GroupRecalculate() {
|
|||||||
{/* Current Status */}
|
{/* Current Status */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium">
|
<span className="font-medium text-sm">
|
||||||
{t("currentStatus", "Current Status")}
|
{t("currentStatus", "Current Status")}
|
||||||
</span>
|
</span>
|
||||||
{loadingStatus ? (
|
{loadingStatus ? (
|
||||||
@@ -142,14 +146,20 @@ export default function GroupRecalculate() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "completed" && (
|
{status?.state === "completed" && (
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
{t(
|
||||||
|
"recalculationCompleted",
|
||||||
|
"Recalculation completed successfully"
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "failed" && (
|
{status?.state === "failed" && (
|
||||||
<div className="text-sm text-destructive">
|
<div className="text-destructive text-sm">
|
||||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
{t(
|
||||||
|
"recalculationFailed",
|
||||||
|
"Recalculation failed. Please try again."
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -163,9 +173,11 @@ export default function GroupRecalculate() {
|
|||||||
{t("averageMode", "Average Mode")}
|
{t("averageMode", "Average Mode")}
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => handleRecalculate("average")}
|
|
||||||
disabled={recalculating === "average" || status?.state === "running"}
|
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
disabled={
|
||||||
|
recalculating === "average" || status?.state === "running"
|
||||||
|
}
|
||||||
|
onClick={() => handleRecalculate("average")}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
{recalculating === "average" && (
|
{recalculating === "average" && (
|
||||||
@@ -181,9 +193,11 @@ export default function GroupRecalculate() {
|
|||||||
{t("subscribeMode", "Subscribe Mode")}
|
{t("subscribeMode", "Subscribe Mode")}
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => handleRecalculate("subscribe")}
|
|
||||||
disabled={recalculating === "subscribe" || status?.state === "running"}
|
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
disabled={
|
||||||
|
recalculating === "subscribe" || status?.state === "running"
|
||||||
|
}
|
||||||
|
onClick={() => handleRecalculate("subscribe")}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
{recalculating === "subscribe" && (
|
{recalculating === "subscribe" && (
|
||||||
@@ -199,9 +213,11 @@ export default function GroupRecalculate() {
|
|||||||
{t("trafficMode", "Traffic Mode")}
|
{t("trafficMode", "Traffic Mode")}
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => handleRecalculate("traffic")}
|
|
||||||
disabled={recalculating === "traffic" || status?.state === "running"}
|
|
||||||
className="w-full"
|
className="w-full"
|
||||||
|
disabled={
|
||||||
|
recalculating === "traffic" || status?.state === "running"
|
||||||
|
}
|
||||||
|
onClick={() => handleRecalculate("traffic")}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
{recalculating === "traffic" && (
|
{recalculating === "traffic" && (
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
"use client";
|
"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 { 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 UserGroups from "./user-groups";
|
||||||
import NodeGroups from "./node-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 SubscribeModeTab from "./subscribe-mode-tab";
|
||||||
import TrafficModeTab from "./traffic-mode-tab";
|
import TrafficModeTab from "./traffic-mode-tab";
|
||||||
import CurrentGroupResults from "./current-group-results";
|
|
||||||
|
|
||||||
export default function Group() {
|
export default function Group() {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
@@ -22,9 +27,7 @@ export default function Group() {
|
|||||||
|
|
||||||
<Tabs defaultValue="config">
|
<Tabs defaultValue="config">
|
||||||
<TabsList className="flex flex-wrap gap-2">
|
<TabsList className="flex flex-wrap gap-2">
|
||||||
<TabsTrigger value="config">
|
<TabsTrigger value="config">{t("config", "Config")}</TabsTrigger>
|
||||||
{t("config", "Config")}
|
|
||||||
</TabsTrigger>
|
|
||||||
{/* <TabsTrigger value="user">
|
{/* <TabsTrigger value="user">
|
||||||
{t("userGroups", "User Groups")}
|
{t("userGroups", "User Groups")}
|
||||||
</TabsTrigger> */}
|
</TabsTrigger> */}
|
||||||
@@ -43,12 +46,10 @@ export default function Group() {
|
|||||||
<TabsTrigger value="results">
|
<TabsTrigger value="results">
|
||||||
{t("currentGroupingResult", "Current Grouping Result")}
|
{t("currentGroupingResult", "Current Grouping Result")}
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="history">
|
<TabsTrigger value="history">{t("history", "History")}</TabsTrigger>
|
||||||
{t("history", "History")}
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<TabsContent value="config" className="mt-4">
|
<TabsContent className="mt-4" value="config">
|
||||||
<GroupConfig />
|
<GroupConfig />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
@@ -56,27 +57,27 @@ export default function Group() {
|
|||||||
<UserGroups />
|
<UserGroups />
|
||||||
</TabsContent> */}
|
</TabsContent> */}
|
||||||
|
|
||||||
<TabsContent value="node" className="mt-4">
|
<TabsContent className="mt-4" value="node">
|
||||||
<NodeGroups />
|
<NodeGroups />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="average" className="mt-4">
|
<TabsContent className="mt-4" value="average">
|
||||||
<AverageModeTab />
|
<AverageModeTab />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="subscribe" className="mt-4">
|
<TabsContent className="mt-4" value="subscribe">
|
||||||
<SubscribeModeTab />
|
<SubscribeModeTab />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="traffic" className="mt-4">
|
<TabsContent className="mt-4" value="traffic">
|
||||||
<TrafficModeTab />
|
<TrafficModeTab />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="results" className="mt-4">
|
<TabsContent className="mt-4" value="results">
|
||||||
<CurrentGroupResults />
|
<CurrentGroupResults />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="history" className="mt-4">
|
<TabsContent className="mt-4" value="history">
|
||||||
<GroupHistory />
|
<GroupHistory />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ import {
|
|||||||
} from "@workspace/ui/components/dialog";
|
} from "@workspace/ui/components/dialog";
|
||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
import { Label } from "@workspace/ui/components/label";
|
import { Label } from "@workspace/ui/components/label";
|
||||||
import { Textarea } from "@workspace/ui/components/textarea";
|
|
||||||
import { Switch } from "@workspace/ui/components/switch";
|
import { Switch } from "@workspace/ui/components/switch";
|
||||||
|
import { Textarea } from "@workspace/ui/components/textarea";
|
||||||
import { AlertCircle, Loader2 } from "lucide-react";
|
import { AlertCircle, Loader2 } from "lucide-react";
|
||||||
import { forwardRef, useEffect, useState } from "react";
|
import { type RefObject, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
interface NodeGroupFormProps {
|
interface NodeGroupFormProps {
|
||||||
@@ -26,10 +26,16 @@ interface NodeGroupFormProps {
|
|||||||
trigger: React.ReactNode;
|
trigger: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const NodeGroupForm = forwardRef<
|
const NodeGroupForm = ({
|
||||||
HTMLButtonElement,
|
initialValues,
|
||||||
NodeGroupFormProps
|
allNodeGroups = [],
|
||||||
>(({ initialValues, allNodeGroups = [], currentGroupId, loading, onSubmit, title, trigger }, ref) => {
|
currentGroupId,
|
||||||
|
loading,
|
||||||
|
onSubmit,
|
||||||
|
title,
|
||||||
|
trigger,
|
||||||
|
ref,
|
||||||
|
}: NodeGroupFormProps & { ref?: RefObject<HTMLButtonElement | null> }) => {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
@@ -82,7 +88,10 @@ const NodeGroupForm = forwardRef<
|
|||||||
}, [initialValues, open]);
|
}, [initialValues, open]);
|
||||||
|
|
||||||
// 检测流量区间冲突
|
// 检测流量区间冲突
|
||||||
const checkTrafficRangeConflict = (minTraffic: number, maxTraffic: number): string => {
|
const checkTrafficRangeConflict = (
|
||||||
|
minTraffic: number,
|
||||||
|
maxTraffic: number
|
||||||
|
): string => {
|
||||||
// 如果 min=0 且 max=0,表示不参与流量分组,跳过所有验证
|
// 如果 min=0 且 max=0,表示不参与流量分组,跳过所有验证
|
||||||
if (minTraffic === 0 && maxTraffic === 0) {
|
if (minTraffic === 0 && maxTraffic === 0) {
|
||||||
return "";
|
return "";
|
||||||
@@ -111,12 +120,14 @@ const NodeGroupForm = forwardRef<
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 处理现有节点组 max=0 的情况
|
// 处理现有节点组 max=0 的情况
|
||||||
const actualExistingMax = existingMax === 0 ? Number.MAX_VALUE : existingMax;
|
const actualExistingMax =
|
||||||
|
existingMax === 0 ? Number.MAX_VALUE : existingMax;
|
||||||
|
|
||||||
// 检测区间重叠
|
// 检测区间重叠
|
||||||
// 两个区间 [min1, max1] 和 [min2, max2] 重叠的条件:
|
// 两个区间 [min1, max1] 和 [min2, max2] 重叠的条件:
|
||||||
// max1 > min2 && max2 > min1
|
// max1 > min2 && max2 > min1
|
||||||
const hasOverlap = actualMax > existingMin && actualExistingMax > minTraffic;
|
const hasOverlap =
|
||||||
|
actualMax > existingMin && actualExistingMax > minTraffic;
|
||||||
|
|
||||||
if (hasOverlap) {
|
if (hasOverlap) {
|
||||||
return t("rangeConflict", {
|
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) {
|
if (!isExpiredGroup) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
@@ -142,21 +155,29 @@ const NodeGroupForm = forwardRef<
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (existingExpiredGroup) {
|
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) {
|
if (currentGroupId) {
|
||||||
try {
|
try {
|
||||||
const { getSubscribeList } = await import("@workspace/ui/services/admin/subscribe");
|
const { getSubscribeList } = await import(
|
||||||
|
"@workspace/ui/services/admin/subscribe"
|
||||||
|
);
|
||||||
const { data } = await getSubscribeList({
|
const { data } = await getSubscribeList({
|
||||||
page: 1,
|
page: 1,
|
||||||
size: 1,
|
size: 1,
|
||||||
node_group_id: currentGroupId
|
node_group_id: currentGroupId,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data.data && data.data.total > 0) {
|
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) {
|
} catch (error) {
|
||||||
console.error("Failed to check subscribe usage:", error);
|
console.error("Failed to check subscribe usage:", error);
|
||||||
@@ -178,7 +199,9 @@ const NodeGroupForm = forwardRef<
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
// 检测过期节点组冲突
|
// 检测过期节点组冲突
|
||||||
const expiredGroupConflict = await checkExpiredGroupConflict(values.is_expired_group);
|
const expiredGroupConflict = await checkExpiredGroupConflict(
|
||||||
|
values.is_expired_group
|
||||||
|
);
|
||||||
if (expiredGroupConflict) {
|
if (expiredGroupConflict) {
|
||||||
setConflictError(expiredGroupConflict);
|
setConflictError(expiredGroupConflict);
|
||||||
return;
|
return;
|
||||||
@@ -186,7 +209,10 @@ const NodeGroupForm = forwardRef<
|
|||||||
|
|
||||||
// 仅在非过期节点组时检测流量区间冲突
|
// 仅在非过期节点组时检测流量区间冲突
|
||||||
if (!values.is_expired_group) {
|
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) {
|
if (conflict) {
|
||||||
setConflictError(conflict);
|
setConflictError(conflict);
|
||||||
return;
|
return;
|
||||||
@@ -215,7 +241,7 @@ const NodeGroupForm = forwardRef<
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog onOpenChange={setOpen} open={open}>
|
||||||
<DialogTrigger asChild ref={ref}>
|
<DialogTrigger asChild ref={ref}>
|
||||||
{trigger}
|
{trigger}
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
@@ -226,19 +252,15 @@ const NodeGroupForm = forwardRef<
|
|||||||
{t("nodeGroupFormDescription", "Configure node group settings")}
|
{t("nodeGroupFormDescription", "Configure node group settings")}
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form className="space-y-4" onSubmit={handleSubmit}>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="name">
|
<Label htmlFor="name">{t("name", "Name")} *</Label>
|
||||||
{t("name", "Name")} *
|
|
||||||
</Label>
|
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
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")}
|
placeholder={t("namePlaceholder", "Enter name")}
|
||||||
required
|
required
|
||||||
|
value={values.name}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -248,12 +270,12 @@ const NodeGroupForm = forwardRef<
|
|||||||
</Label>
|
</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
id="description"
|
id="description"
|
||||||
value={values.description}
|
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setValues({ ...values, description: e.target.value })
|
setValues({ ...values, description: e.target.value })
|
||||||
}
|
}
|
||||||
placeholder={t("descriptionPlaceholder", "Enter description")}
|
placeholder={t("descriptionPlaceholder", "Enter description")}
|
||||||
rows={3}
|
rows={3}
|
||||||
|
value={values.description}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -261,12 +283,15 @@ const NodeGroupForm = forwardRef<
|
|||||||
<Label htmlFor="sort">{t("sort", "Sort Order")}</Label>
|
<Label htmlFor="sort">{t("sort", "Sort Order")}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="sort"
|
id="sort"
|
||||||
|
min={0}
|
||||||
|
onChange={(e) =>
|
||||||
|
setValues({
|
||||||
|
...values,
|
||||||
|
sort: Number.parseInt(e.target.value, 10) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
type="number"
|
type="number"
|
||||||
value={values.sort}
|
value={values.sort}
|
||||||
onChange={(e) =>
|
|
||||||
setValues({ ...values, sort: parseInt(e.target.value) || 0 })
|
|
||||||
}
|
|
||||||
min={0}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -275,16 +300,22 @@ const NodeGroupForm = forwardRef<
|
|||||||
<Label htmlFor="for_calculation">
|
<Label htmlFor="for_calculation">
|
||||||
{t("forCalculation", "For Calculation")}
|
{t("forCalculation", "For Calculation")}
|
||||||
</Label>
|
</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{values.is_expired_group
|
{values.is_expired_group
|
||||||
? t("expiredGroupForCalculationDescription", "Expired-only node groups cannot participate in group calculation")
|
? t(
|
||||||
: t("forCalculationDescription", "Whether this node group participates in grouping calculation")}
|
"expiredGroupForCalculationDescription",
|
||||||
|
"Expired-only node groups cannot participate in group calculation"
|
||||||
|
)
|
||||||
|
: t(
|
||||||
|
"forCalculationDescription",
|
||||||
|
"Whether this node group participates in grouping calculation"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Switch
|
<Switch
|
||||||
id="for_calculation"
|
|
||||||
checked={values.for_calculation}
|
checked={values.for_calculation}
|
||||||
disabled={values.is_expired_group}
|
disabled={values.is_expired_group}
|
||||||
|
id="for_calculation"
|
||||||
onCheckedChange={(checked) =>
|
onCheckedChange={(checked) =>
|
||||||
setValues({ ...values, for_calculation: checked })
|
setValues({ ...values, for_calculation: checked })
|
||||||
}
|
}
|
||||||
@@ -298,13 +329,16 @@ const NodeGroupForm = forwardRef<
|
|||||||
<Label htmlFor="is_expired_group">
|
<Label htmlFor="is_expired_group">
|
||||||
{t("isExpiredGroup", "Expired Node Group")}
|
{t("isExpiredGroup", "Expired Node Group")}
|
||||||
</Label>
|
</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{t("isExpiredGroupDescription", "Allow expired users to use limited nodes")}
|
{t(
|
||||||
|
"isExpiredGroupDescription",
|
||||||
|
"Allow expired users to use limited nodes"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Switch
|
<Switch
|
||||||
id="is_expired_group"
|
|
||||||
checked={values.is_expired_group}
|
checked={values.is_expired_group}
|
||||||
|
id="is_expired_group"
|
||||||
onCheckedChange={async (checked) => {
|
onCheckedChange={async (checked) => {
|
||||||
setValues({
|
setValues({
|
||||||
...values,
|
...values,
|
||||||
@@ -327,50 +361,70 @@ const NodeGroupForm = forwardRef<
|
|||||||
<Label htmlFor="expired_days_limit">
|
<Label htmlFor="expired_days_limit">
|
||||||
{t("expiredDaysLimit", "Expired Days Limit")}
|
{t("expiredDaysLimit", "Expired Days Limit")}
|
||||||
</Label>
|
</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{t("expiredDaysLimitDescription", "Number of days after expiration that users can still access nodes")}
|
{t(
|
||||||
|
"expiredDaysLimitDescription",
|
||||||
|
"Number of days after expiration that users can still access nodes"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
<Input
|
<Input
|
||||||
id="expired_days_limit"
|
id="expired_days_limit"
|
||||||
type="number"
|
|
||||||
min={1}
|
min={1}
|
||||||
value={values.expired_days_limit}
|
|
||||||
onChange={(e) =>
|
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>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="max_traffic_gb_expired">
|
<Label htmlFor="max_traffic_gb_expired">
|
||||||
{t("maxTrafficGBExpired", "Max Traffic for Expired Users (GB)")}
|
{t(
|
||||||
|
"maxTrafficGBExpired",
|
||||||
|
"Max Traffic for Expired Users (GB)"
|
||||||
|
)}
|
||||||
</Label>
|
</Label>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{t("maxTrafficGBExpiredDescription", "Maximum traffic allowed for expired users (0 = unlimited)")}
|
{t(
|
||||||
|
"maxTrafficGBExpiredDescription",
|
||||||
|
"Maximum traffic allowed for expired users (0 = unlimited)"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
<Input
|
<Input
|
||||||
id="max_traffic_gb_expired"
|
id="max_traffic_gb_expired"
|
||||||
type="number"
|
|
||||||
min={0}
|
min={0}
|
||||||
value={values.max_traffic_gb_expired}
|
|
||||||
onChange={(e) =>
|
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>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="speed_limit">
|
<Label htmlFor="speed_limit">
|
||||||
{t("speedLimit", "Speed Limit (KB/s)")}
|
{t("speedLimit", "Speed Limit (Mbps)")}
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="speed_limit"
|
id="speed_limit"
|
||||||
type="number"
|
|
||||||
min={0}
|
min={0}
|
||||||
value={values.speed_limit}
|
|
||||||
onChange={(e) =>
|
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>
|
</div>
|
||||||
</>
|
</>
|
||||||
@@ -381,48 +435,61 @@ const NodeGroupForm = forwardRef<
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<Label>{t("trafficRangeGB", "Traffic Range (GB)")}</Label>
|
<Label>{t("trafficRangeGB", "Traffic Range (GB)")}</Label>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-muted-foreground text-sm">
|
||||||
{t("trafficRangeDescription", "Users with traffic >= Min and < Max will be assigned to this node group")}
|
{t(
|
||||||
|
"trafficRangeDescription",
|
||||||
|
"Users with traffic >= Min and < Max will be assigned to this node group"
|
||||||
|
)}
|
||||||
</p>
|
</p>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<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
|
<Input
|
||||||
id="min_traffic_gb"
|
id="min_traffic_gb"
|
||||||
type="number"
|
|
||||||
min={0}
|
min={0}
|
||||||
step={1}
|
|
||||||
value={values.min_traffic_gb}
|
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const newValue = parseFloat(e.target.value) || 0;
|
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||||
setValues({ ...values, min_traffic_gb: newValue });
|
setValues({ ...values, min_traffic_gb: newValue });
|
||||||
// 实时检测冲突
|
// 实时检测冲突
|
||||||
const conflict = checkTrafficRangeConflict(newValue, values.max_traffic_gb);
|
const conflict = checkTrafficRangeConflict(
|
||||||
|
newValue,
|
||||||
|
values.max_traffic_gb
|
||||||
|
);
|
||||||
setConflictError(conflict);
|
setConflictError(conflict);
|
||||||
}}
|
}}
|
||||||
|
step={1}
|
||||||
|
type="number"
|
||||||
|
value={values.min_traffic_gb}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<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
|
<Input
|
||||||
id="max_traffic_gb"
|
id="max_traffic_gb"
|
||||||
type="number"
|
|
||||||
min={0}
|
min={0}
|
||||||
step={1}
|
|
||||||
value={values.max_traffic_gb}
|
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const newValue = parseFloat(e.target.value) || 0;
|
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||||
setValues({ ...values, max_traffic_gb: newValue });
|
setValues({ ...values, max_traffic_gb: newValue });
|
||||||
// 实时检测冲突
|
// 实时检测冲突
|
||||||
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, newValue);
|
const conflict = checkTrafficRangeConflict(
|
||||||
|
values.min_traffic_gb,
|
||||||
|
newValue
|
||||||
|
);
|
||||||
setConflictError(conflict);
|
setConflictError(conflict);
|
||||||
}}
|
}}
|
||||||
|
step={1}
|
||||||
|
type="number"
|
||||||
|
value={values.max_traffic_gb}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/* 显示冲突错误 */}
|
{/* 显示冲突错误 */}
|
||||||
{conflictError && (
|
{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" />
|
<AlertCircle className="h-4 w-4 flex-shrink-0" />
|
||||||
<span>{conflictError}</span>
|
<span>{conflictError}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -432,17 +499,17 @@ const NodeGroupForm = forwardRef<
|
|||||||
|
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={() => setOpen(false)}
|
|
||||||
className="rounded-md border px-4 py-2 text-sm"
|
className="rounded-md border px-4 py-2 text-sm"
|
||||||
disabled={submitting || loading}
|
disabled={submitting || loading}
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
type="button"
|
||||||
>
|
>
|
||||||
{t("cancel", "Cancel")}
|
{t("cancel", "Cancel")}
|
||||||
</button>
|
</button>
|
||||||
<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}
|
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" />}
|
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
{t("save", "Save")}
|
{t("save", "Save")}
|
||||||
@@ -452,7 +519,7 @@ const NodeGroupForm = forwardRef<
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
});
|
};
|
||||||
|
|
||||||
NodeGroupForm.displayName = "NodeGroupForm";
|
NodeGroupForm.displayName = "NodeGroupForm";
|
||||||
|
|
||||||
|
|||||||
@@ -50,28 +50,91 @@ export default function NodeGroups() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("nodeGroups", "Node Groups")}</CardTitle>
|
<CardTitle>{t("nodeGroups", "Node Groups")}</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t("nodeGroupsDescription", "Manage node groups for user access control")}
|
{t(
|
||||||
|
"nodeGroupsDescription",
|
||||||
|
"Manage node groups for user access control"
|
||||||
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ProTable<API.NodeGroup, API.GetNodeGroupListRequest>
|
<ProTable<API.NodeGroup, API.GetNodeGroupListRequest>
|
||||||
action={ref}
|
action={ref}
|
||||||
request={async (params) => {
|
actions={{
|
||||||
const { data } = await getNodeGroupList({
|
render: (row: any) => [
|
||||||
page: params.page || 1,
|
<NodeGroupForm
|
||||||
size: params.size || 10,
|
allNodeGroups={allNodeGroups}
|
||||||
});
|
currentGroupId={row.id}
|
||||||
return {
|
initialValues={row}
|
||||||
list: data.data?.list || [],
|
key={`edit-${row.id}`}
|
||||||
total: data.data?.total || 0,
|
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={[
|
columns={[
|
||||||
{
|
{
|
||||||
id: "id",
|
id: "id",
|
||||||
accessorKey: "id",
|
accessorKey: "id",
|
||||||
header: t("id", "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",
|
id: "name",
|
||||||
@@ -95,7 +158,8 @@ export default function NodeGroups() {
|
|||||||
id: "description",
|
id: "description",
|
||||||
accessorKey: "description",
|
accessorKey: "description",
|
||||||
header: t("description", "Description"),
|
header: t("description", "Description"),
|
||||||
cell: ({ row }: { row: any }) => row.getValue("description") || "--",
|
cell: ({ row }: { row: any }) =>
|
||||||
|
row.getValue("description") || "--",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "for_calculation",
|
id: "for_calculation",
|
||||||
@@ -134,82 +198,27 @@ export default function NodeGroups() {
|
|||||||
header: t("sort", "Sort"),
|
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={{
|
header={{
|
||||||
title: t("nodeGroups", "Node Groups"),
|
title: t("nodeGroups", "Node Groups"),
|
||||||
toolbar: (
|
toolbar: (
|
||||||
<NodeGroupForm
|
<NodeGroupForm
|
||||||
key="create"
|
|
||||||
initialValues={undefined}
|
|
||||||
allNodeGroups={allNodeGroups}
|
allNodeGroups={allNodeGroups}
|
||||||
currentGroupId={undefined}
|
currentGroupId={undefined}
|
||||||
|
initialValues={undefined}
|
||||||
|
key="create"
|
||||||
loading={loading}
|
loading={loading}
|
||||||
onSubmit={async (values) => {
|
onSubmit={async (values) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
await createNodeGroup(values as API.CreateNodeGroupRequest);
|
await createNodeGroup(
|
||||||
|
values as API.CreateNodeGroupRequest
|
||||||
|
);
|
||||||
toast.success(t("created", "Created successfully"));
|
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 || []);
|
setAllNodeGroups(data.data?.list || []);
|
||||||
ref.current?.refresh();
|
ref.current?.refresh();
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -220,14 +229,20 @@ export default function NodeGroups() {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
title={t("createNodeGroup", "Create Node Group")}
|
title={t("createNodeGroup", "Create Node Group")}
|
||||||
trigger={
|
trigger={<Button>{t("create", "Create")}</Button>}
|
||||||
<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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -15,16 +16,15 @@ import {
|
|||||||
TableCell,
|
TableCell,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "@workspace/ui/components/table";
|
} from "@workspace/ui/components/table";
|
||||||
|
import {
|
||||||
|
getRecalculationStatus,
|
||||||
|
getSubscribeGroupMapping,
|
||||||
|
recalculateGroup,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import {
|
|
||||||
getRecalculationStatus,
|
|
||||||
recalculateGroup,
|
|
||||||
getSubscribeGroupMapping,
|
|
||||||
} from "@workspace/ui/services/admin/group";
|
|
||||||
|
|
||||||
interface SubscribeGroupMapping {
|
interface SubscribeGroupMapping {
|
||||||
subscribe_name: string;
|
subscribe_name: string;
|
||||||
@@ -51,7 +51,6 @@ export default function SubscribeModeTab() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const loadStatus = async () => {
|
const loadStatus = async () => {
|
||||||
setLoadingStatus(true);
|
setLoadingStatus(true);
|
||||||
try {
|
try {
|
||||||
@@ -124,9 +123,14 @@ export default function SubscribeModeTab() {
|
|||||||
{/* Configuration Card */}
|
{/* Configuration Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("subscribeModeConfig", "Subscribe Mode Configuration")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("subscribeModeConfig", "Subscribe Mode Configuration")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t("subscribeModeDescription", "Group users by their purchased subscription plan")}
|
{t(
|
||||||
|
"subscribeModeDescription",
|
||||||
|
"Group users by their purchased subscription plan"
|
||||||
|
)}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -134,7 +138,9 @@ export default function SubscribeModeTab() {
|
|||||||
{/* Subscribe Group Mapping Card */}
|
{/* Subscribe Group Mapping Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("subscribeGroupMappingTitle", "套餐-节点组对应关系")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("subscribeGroupMappingTitle", "套餐-节点组对应关系")}
|
||||||
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{mappingLoading ? (
|
{mappingLoading ? (
|
||||||
@@ -147,16 +153,21 @@ export default function SubscribeModeTab() {
|
|||||||
{mappingData && mappingData.length > 0 ? (
|
{mappingData && mappingData.length > 0 ? (
|
||||||
mappingData
|
mappingData
|
||||||
.filter(
|
.filter(
|
||||||
(item: SubscribeGroupMapping) => item.subscribe_name && item.node_group_name
|
(item: SubscribeGroupMapping) =>
|
||||||
|
item.subscribe_name && item.node_group_name
|
||||||
)
|
)
|
||||||
.map((item: SubscribeGroupMapping, index: number) => (
|
.map((item: SubscribeGroupMapping, index: number) => (
|
||||||
<TableRow key={index}>
|
<TableRow key={index}>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<span className="font-medium">{item.subscribe_name}</span>
|
<span className="font-medium">
|
||||||
|
{item.subscribe_name}
|
||||||
|
</span>
|
||||||
<span className="mx-2 text-muted-foreground">
|
<span className="mx-2 text-muted-foreground">
|
||||||
{t("arrow", "→")}
|
{t("arrow", "→")}
|
||||||
</span>
|
</span>
|
||||||
<Badge variant="outline">{item.node_group_name}</Badge>
|
<Badge variant="outline">
|
||||||
|
{item.node_group_name}
|
||||||
|
</Badge>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
@@ -176,7 +187,9 @@ export default function SubscribeModeTab() {
|
|||||||
{/* Recalculation Card */}
|
{/* Recalculation Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("groupRecalculation", "Group Recalculation")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"groupRecalculationDescription",
|
"groupRecalculationDescription",
|
||||||
@@ -188,7 +201,7 @@ export default function SubscribeModeTab() {
|
|||||||
{/* Current Status */}
|
{/* Current Status */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium">
|
<span className="font-medium text-sm">
|
||||||
{t("currentStatus", "Current Status")}
|
{t("currentStatus", "Current Status")}
|
||||||
</span>
|
</span>
|
||||||
{loadingStatus ? (
|
{loadingStatus ? (
|
||||||
@@ -220,14 +233,20 @@ export default function SubscribeModeTab() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "completed" && (
|
{status?.state === "completed" && (
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
{t(
|
||||||
|
"recalculationCompleted",
|
||||||
|
"Recalculation completed successfully"
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "failed" && (
|
{status?.state === "failed" && (
|
||||||
<div className="text-sm text-destructive">
|
<div className="text-destructive text-sm">
|
||||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
{t(
|
||||||
|
"recalculationFailed",
|
||||||
|
"Recalculation failed. Please try again."
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -235,8 +254,8 @@ export default function SubscribeModeTab() {
|
|||||||
{/* Recalculate Button */}
|
{/* Recalculate Button */}
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleRecalculate}
|
|
||||||
disabled={recalculating || status?.state === "running"}
|
disabled={recalculating || status?.state === "running"}
|
||||||
|
onClick={handleRecalculate}
|
||||||
>
|
>
|
||||||
{recalculating && (
|
{recalculating && (
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -9,17 +10,16 @@ import {
|
|||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@workspace/ui/components/card";
|
} from "@workspace/ui/components/card";
|
||||||
|
import {
|
||||||
|
getNodeGroupList,
|
||||||
|
getRecalculationStatus,
|
||||||
|
recalculateGroup,
|
||||||
|
updateNodeGroup,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
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";
|
import TrafficRangeConfig from "./traffic-ranges-config";
|
||||||
|
|
||||||
export default function TrafficModeTab() {
|
export default function TrafficModeTab() {
|
||||||
@@ -34,7 +34,11 @@ export default function TrafficModeTab() {
|
|||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
// Fetch node groups
|
// Fetch node groups
|
||||||
const { data: nodeGroupsData, isLoading: isLoadingNodeGroups, refetch: refetchNodeGroups } = useQuery({
|
const {
|
||||||
|
data: nodeGroupsData,
|
||||||
|
isLoading: isLoadingNodeGroups,
|
||||||
|
refetch: refetchNodeGroups,
|
||||||
|
} = useQuery({
|
||||||
queryKey: ["nodeGroups"],
|
queryKey: ["nodeGroups"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
|
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 {
|
try {
|
||||||
await updateNodeGroup({
|
await updateNodeGroup({
|
||||||
id: nodeGroupId,
|
id: nodeGroupId,
|
||||||
@@ -116,7 +123,9 @@ export default function TrafficModeTab() {
|
|||||||
{/* Node Groups Traffic Configuration Card */}
|
{/* Node Groups Traffic Configuration Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("trafficModeConfig", "Traffic Mode Configuration")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("trafficModeConfig", "Traffic Mode Configuration")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"trafficModeDescription",
|
"trafficModeDescription",
|
||||||
@@ -128,7 +137,7 @@ export default function TrafficModeTab() {
|
|||||||
{isLoadingNodeGroups ? (
|
{isLoadingNodeGroups ? (
|
||||||
<div className="flex items-center justify-center py-8">
|
<div className="flex items-center justify-center py-8">
|
||||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
<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...")}
|
{t("loading", "Loading...")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -144,7 +153,9 @@ export default function TrafficModeTab() {
|
|||||||
{/* Recalculation Card */}
|
{/* Recalculation Card */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>{t("groupRecalculation", "Group Recalculation")}</CardTitle>
|
<CardTitle>
|
||||||
|
{t("groupRecalculation", "Group Recalculation")}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
{t(
|
{t(
|
||||||
"groupRecalculationDescription",
|
"groupRecalculationDescription",
|
||||||
@@ -156,7 +167,7 @@ export default function TrafficModeTab() {
|
|||||||
{/* Current Status */}
|
{/* Current Status */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-medium">
|
<span className="font-medium text-sm">
|
||||||
{t("currentStatus", "Current Status")}
|
{t("currentStatus", "Current Status")}
|
||||||
</span>
|
</span>
|
||||||
{loadingStatus ? (
|
{loadingStatus ? (
|
||||||
@@ -188,14 +199,20 @@ export default function TrafficModeTab() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "completed" && (
|
{status?.state === "completed" && (
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-muted-foreground text-sm">
|
||||||
{t("recalculationCompleted", "Recalculation completed successfully")}
|
{t(
|
||||||
|
"recalculationCompleted",
|
||||||
|
"Recalculation completed successfully"
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{status?.state === "failed" && (
|
{status?.state === "failed" && (
|
||||||
<div className="text-sm text-destructive">
|
<div className="text-destructive text-sm">
|
||||||
{t("recalculationFailed", "Recalculation failed. Please try again.")}
|
{t(
|
||||||
|
"recalculationFailed",
|
||||||
|
"Recalculation failed. Please try again."
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -203,8 +220,8 @@ export default function TrafficModeTab() {
|
|||||||
{/* Recalculate Button */}
|
{/* Recalculate Button */}
|
||||||
<div className="flex justify-end">
|
<div className="flex justify-end">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleRecalculate}
|
|
||||||
disabled={recalculating || status?.state === "running"}
|
disabled={recalculating || status?.state === "running"}
|
||||||
|
onClick={handleRecalculate}
|
||||||
>
|
>
|
||||||
{recalculating && (
|
{recalculating && (
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
interface NodeGroup {
|
interface NodeGroup {
|
||||||
@@ -15,12 +15,15 @@ interface NodeGroup {
|
|||||||
|
|
||||||
interface TrafficRangeConfigProps {
|
interface TrafficRangeConfigProps {
|
||||||
nodeGroups: NodeGroup[];
|
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 {
|
interface UpdatingNode {
|
||||||
nodeGroupId: number;
|
nodeGroupId: number;
|
||||||
field: 'min_traffic_gb' | 'max_traffic_gb';
|
field: "min_traffic_gb" | "max_traffic_gb";
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NodeGroupTempValues {
|
interface NodeGroupTempValues {
|
||||||
@@ -28,20 +31,30 @@ interface NodeGroupTempValues {
|
|||||||
max_traffic_gb?: number;
|
max_traffic_gb?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: TrafficRangeConfigProps) {
|
export default function TrafficRangeConfig({
|
||||||
|
nodeGroups,
|
||||||
|
onTrafficUpdate,
|
||||||
|
}: TrafficRangeConfigProps) {
|
||||||
const { t } = useTranslation("group");
|
const { t } = useTranslation("group");
|
||||||
const [updatingNodes, setUpdatingNodes] = useState<UpdatingNode[]>([]);
|
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)
|
// 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];
|
const temp = temporaryValues[nodeGroupId];
|
||||||
if (temp && temp[field] !== undefined) {
|
if (temp && temp[field] !== undefined) {
|
||||||
return temp[field]!;
|
return temp[field]!;
|
||||||
}
|
}
|
||||||
const nodeGroup = nodeGroups.find(ng => ng.id === nodeGroupId);
|
const nodeGroup = nodeGroups.find((ng) => ng.id === nodeGroupId);
|
||||||
return field === 'min_traffic_gb' ? (nodeGroup?.min_traffic_gb ?? 0) : (nodeGroup?.max_traffic_gb ?? 0);
|
return field === "min_traffic_gb"
|
||||||
|
? (nodeGroup?.min_traffic_gb ?? 0)
|
||||||
|
: (nodeGroup?.max_traffic_gb ?? 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validate traffic ranges: no overlaps
|
// Validate traffic ranges: no overlaps
|
||||||
@@ -57,22 +70,34 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
|
|
||||||
// Check if min >= max (both > 0)
|
// Check if min >= max (both > 0)
|
||||||
if (minTraffic > 0 && maxTraffic > 0 && minTraffic >= maxTraffic) {
|
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
|
// Check for overlaps with other node groups
|
||||||
const otherGroups = nodeGroups
|
const otherGroups = nodeGroups
|
||||||
.filter(ng => ng.id !== nodeGroupId)
|
.filter((ng) => ng.id !== nodeGroupId)
|
||||||
.map(ng => {
|
.map((ng) => {
|
||||||
const temp = temporaryValues[ng.id];
|
const temp = temporaryValues[ng.id];
|
||||||
return {
|
return {
|
||||||
id: ng.id,
|
id: ng.id,
|
||||||
name: ng.name,
|
name: ng.name,
|
||||||
min: temp?.min_traffic_gb !== undefined ? temp.min_traffic_gb : (ng.min_traffic_gb ?? 0),
|
min:
|
||||||
max: temp?.max_traffic_gb !== undefined ? temp.max_traffic_gb : (ng.max_traffic_gb ?? 0),
|
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);
|
.sort((a, b) => a.min - b.min);
|
||||||
|
|
||||||
for (const other of otherGroups) {
|
for (const other of otherGroups) {
|
||||||
@@ -85,7 +110,11 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
if (currentMax > other.min && otherMax > minTraffic) {
|
if (currentMax > other.min && otherMax > minTraffic) {
|
||||||
return {
|
return {
|
||||||
valid: false,
|
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 handleTrafficBlur = async (nodeGroupId: number) => {
|
||||||
const nodeGroup = nodeGroups.find(ng => ng.id === nodeGroupId);
|
const nodeGroup = nodeGroups.find((ng) => ng.id === nodeGroupId);
|
||||||
if (!nodeGroup) return;
|
if (!nodeGroup) return;
|
||||||
|
|
||||||
const tempValues = temporaryValues[nodeGroupId];
|
const tempValues = temporaryValues[nodeGroupId];
|
||||||
if (!tempValues) return;
|
if (!tempValues) return;
|
||||||
|
|
||||||
// 获取当前的临时值或实际值
|
// 获取当前的临时值或实际值
|
||||||
const currentMin = tempValues.min_traffic_gb !== undefined
|
const currentMin =
|
||||||
? tempValues.min_traffic_gb
|
tempValues.min_traffic_gb !== undefined
|
||||||
: (nodeGroup.min_traffic_gb ?? 0);
|
? tempValues.min_traffic_gb
|
||||||
const currentMax = tempValues.max_traffic_gb !== undefined
|
: (nodeGroup.min_traffic_gb ?? 0);
|
||||||
? tempValues.max_traffic_gb
|
const currentMax =
|
||||||
: (nodeGroup.max_traffic_gb ?? 0);
|
tempValues.max_traffic_gb !== undefined
|
||||||
|
? tempValues.max_traffic_gb
|
||||||
|
: (nodeGroup.max_traffic_gb ?? 0);
|
||||||
|
|
||||||
// 只要有一个字段被修改了就保存
|
// 只要有一个字段被修改了就保存
|
||||||
const hasMinChange = tempValues.min_traffic_gb !== undefined;
|
const hasMinChange = tempValues.min_traffic_gb !== undefined;
|
||||||
const hasMaxChange = tempValues.max_traffic_gb !== undefined;
|
const hasMaxChange = tempValues.max_traffic_gb !== undefined;
|
||||||
if (!hasMinChange && !hasMaxChange) {
|
if (!(hasMinChange || hasMaxChange)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证
|
// 验证
|
||||||
const validation = validateTrafficRange(nodeGroupId, currentMin, currentMax);
|
const validation = validateTrafficRange(
|
||||||
|
nodeGroupId,
|
||||||
|
currentMin,
|
||||||
|
currentMax
|
||||||
|
);
|
||||||
if (!validation.valid) {
|
if (!validation.valid) {
|
||||||
toast.error(validation.error || t("validationFailed", "Validation failed"));
|
toast.error(
|
||||||
|
validation.error || t("validationFailed", "Validation failed")
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,15 +168,24 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
|
|
||||||
// 标记为更新中(只标记被修改的字段)
|
// 标记为更新中(只标记被修改的字段)
|
||||||
if (hasMinChange) {
|
if (hasMinChange) {
|
||||||
setUpdatingNodes(prev => [...prev, { nodeGroupId, field: 'min_traffic_gb' }]);
|
setUpdatingNodes((prev) => [
|
||||||
|
...prev,
|
||||||
|
{ nodeGroupId, field: "min_traffic_gb" },
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
if (hasMaxChange) {
|
if (hasMaxChange) {
|
||||||
setUpdatingNodes(prev => [...prev, { nodeGroupId, field: 'max_traffic_gb' }]);
|
setUpdatingNodes((prev) => [
|
||||||
|
...prev,
|
||||||
|
{ nodeGroupId, field: "max_traffic_gb" },
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 一次性传递两个字段
|
// 一次性传递两个字段
|
||||||
const fieldsToUpdate: { min_traffic_gb?: number; max_traffic_gb?: number } = {};
|
const fieldsToUpdate: {
|
||||||
|
min_traffic_gb?: number;
|
||||||
|
max_traffic_gb?: number;
|
||||||
|
} = {};
|
||||||
if (currentMin !== originalMin) {
|
if (currentMin !== originalMin) {
|
||||||
fieldsToUpdate.min_traffic_gb = currentMin;
|
fieldsToUpdate.min_traffic_gb = currentMin;
|
||||||
}
|
}
|
||||||
@@ -152,40 +198,44 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// 移除更新状态
|
// 移除更新状态
|
||||||
setUpdatingNodes(prev => prev.filter(u => !(u.nodeGroupId === nodeGroupId)));
|
setUpdatingNodes((prev) =>
|
||||||
|
prev.filter((u) => !(u.nodeGroupId === nodeGroupId))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const isUpdating = (nodeGroupId: number) => {
|
const isUpdating = (nodeGroupId: number) =>
|
||||||
return updatingNodes.some(u => u.nodeGroupId === nodeGroupId);
|
updatingNodes.some((u) => u.nodeGroupId === nodeGroupId);
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="space-y-2">
|
<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-6">{t("nodeGroup", "Node Group")}</div>
|
||||||
<div className="col-span-3">{t("minTrafficGB", "Min (GB)")}</div>
|
<div className="col-span-3">{t("minTrafficGB", "Min (GB)")}</div>
|
||||||
<div className="col-span-3">{t("maxTrafficGB", "Max (GB)")}</div>
|
<div className="col-span-3">{t("maxTrafficGB", "Max (GB)")}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{nodeGroups.map((nodeGroup) => (
|
{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="col-span-6">
|
||||||
<div className="font-medium">{nodeGroup.name}</div>
|
<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>
|
||||||
<div className="col-span-3 relative">
|
<div className="relative col-span-3">
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
disabled={isUpdating(nodeGroup.id)}
|
||||||
min={0}
|
min={0}
|
||||||
step={1}
|
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||||
placeholder="0"
|
|
||||||
value={getDisplayValue(nodeGroup.id, "min_traffic_gb")}
|
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const newValue = parseFloat(e.target.value) || 0;
|
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||||
// 更新临时状态
|
// 更新临时状态
|
||||||
setTemporaryValues(prev => ({
|
setTemporaryValues((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
[nodeGroup.id]: {
|
[nodeGroup.id]: {
|
||||||
...prev[nodeGroup.id],
|
...prev[nodeGroup.id],
|
||||||
@@ -194,26 +244,26 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
}}
|
}}
|
||||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
placeholder="0"
|
||||||
disabled={isUpdating(nodeGroup.id)}
|
step={1}
|
||||||
|
type="number"
|
||||||
|
value={getDisplayValue(nodeGroup.id, "min_traffic_gb")}
|
||||||
/>
|
/>
|
||||||
{isUpdating(nodeGroup.id) && (
|
{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" />
|
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="col-span-3 relative">
|
<div className="relative col-span-3">
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
disabled={isUpdating(nodeGroup.id)}
|
||||||
min={0}
|
min={0}
|
||||||
step={1}
|
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
||||||
placeholder="0"
|
|
||||||
value={getDisplayValue(nodeGroup.id, "max_traffic_gb")}
|
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const newValue = parseFloat(e.target.value) || 0;
|
const newValue = Number.parseFloat(e.target.value) || 0;
|
||||||
// 更新临时状态
|
// 更新临时状态
|
||||||
setTemporaryValues(prev => ({
|
setTemporaryValues((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
[nodeGroup.id]: {
|
[nodeGroup.id]: {
|
||||||
...prev[nodeGroup.id],
|
...prev[nodeGroup.id],
|
||||||
@@ -222,11 +272,13 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
}}
|
}}
|
||||||
onBlur={() => handleTrafficBlur(nodeGroup.id)}
|
placeholder="0"
|
||||||
disabled={isUpdating(nodeGroup.id)}
|
step={1}
|
||||||
|
type="number"
|
||||||
|
value={getDisplayValue(nodeGroup.id, "max_traffic_gb")}
|
||||||
/>
|
/>
|
||||||
{isUpdating(nodeGroup.id) && (
|
{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" />
|
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -235,7 +287,7 @@ export default function TrafficRangeConfig({ nodeGroups, onTrafficUpdate }: Traf
|
|||||||
))}
|
))}
|
||||||
</div>
|
</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>{" "}
|
<strong>{t("note", "Note")}:</strong>{" "}
|
||||||
{t(
|
{t(
|
||||||
"trafficRangesNote",
|
"trafficRangesNote",
|
||||||
|
|||||||
@@ -81,7 +81,9 @@ export default function ResetSubscribeLogPage() {
|
|||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
size: pagination.size,
|
size: pagination.size,
|
||||||
date: (filter as any)?.date,
|
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 list = (data?.data?.list || []) as any[];
|
||||||
const total = Number(data?.data?.total || list.length);
|
const total = Number(data?.data?.total || list.length);
|
||||||
|
|||||||
@@ -93,7 +93,9 @@ export default function SubscribeTrafficLogPage() {
|
|||||||
size: pagination.size,
|
size: pagination.size,
|
||||||
date: (filter as any)?.date,
|
date: (filter as any)?.date,
|
||||||
user_id: (filter as any)?.user_id,
|
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 =
|
const list =
|
||||||
((data?.data?.list || []) as API.UserSubscribeTrafficLog[]) || [];
|
((data?.data?.list || []) as API.UserSubscribeTrafficLog[]) || [];
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ export default function SubscribeLogPage() {
|
|||||||
user_subscribe_id: sp.user_subscribe_id || undefined,
|
user_subscribe_id: sp.user_subscribe_id || undefined,
|
||||||
};
|
};
|
||||||
return (
|
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={[
|
columns={[
|
||||||
{
|
{
|
||||||
accessorKey: "user",
|
accessorKey: "user",
|
||||||
@@ -94,7 +97,9 @@ export default function SubscribeLogPage() {
|
|||||||
size: pagination.size,
|
size: pagination.size,
|
||||||
date: (filter as any)?.date,
|
date: (filter as any)?.date,
|
||||||
user_id: (filter as any)?.user_id,
|
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 list = (data?.data?.list || []) as any[];
|
||||||
const total = Number(data?.data?.total || list.length);
|
const total = Number(data?.data?.total || list.length);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import { Switch } from "@workspace/ui/components/switch";
|
import { Switch } from "@workspace/ui/components/switch";
|
||||||
@@ -8,6 +9,10 @@ import {
|
|||||||
ProTable,
|
ProTable,
|
||||||
type ProTableActions,
|
type ProTableActions,
|
||||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||||
|
import {
|
||||||
|
getGroupConfig,
|
||||||
|
getNodeGroupList,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import {
|
import {
|
||||||
createNode,
|
createNode,
|
||||||
deleteNode,
|
deleteNode,
|
||||||
@@ -16,13 +21,12 @@ import {
|
|||||||
toggleNodeStatus,
|
toggleNodeStatus,
|
||||||
updateNode,
|
updateNode,
|
||||||
} from "@workspace/ui/services/admin/server";
|
} 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 { useMemo, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useNode } from "@/stores/node";
|
import { useNode } from "@/stores/node";
|
||||||
import { useServer } from "@/stores/server";
|
import { useServer } from "@/stores/server";
|
||||||
|
import NodeBatchSheet from "./node-batch-sheet";
|
||||||
import NodeForm from "./node-form";
|
import NodeForm from "./node-form";
|
||||||
|
|
||||||
export default function Nodes() {
|
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
|
// Dynamic columns based on group feature status
|
||||||
const columns = useMemo(() => {
|
const columns = useMemo(() => {
|
||||||
@@ -121,13 +125,13 @@ export default function Nodes() {
|
|||||||
id: "node_group_ids",
|
id: "node_group_ids",
|
||||||
header: t("nodeGroups", "Node Groups"),
|
header: t("nodeGroups", "Node Groups"),
|
||||||
cell: ({ row }: { row: any }) => {
|
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)
|
// Public node indicator (when node_group_ids is empty)
|
||||||
if (groupIds.length === 0) {
|
if (groupIds.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Badge variant="secondary" className="text-xs">
|
<Badge className="text-xs" variant="secondary">
|
||||||
{t("public", "Public")}
|
{t("public", "Public")}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -151,7 +155,14 @@ export default function Nodes() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return baseColumns;
|
return baseColumns;
|
||||||
}, [isGroupEnabled, nodeGroupsData, t, getServerName, getServerAddress, getProtocolPort]);
|
}, [
|
||||||
|
isGroupEnabled,
|
||||||
|
nodeGroupsData,
|
||||||
|
t,
|
||||||
|
getServerName,
|
||||||
|
getServerAddress,
|
||||||
|
getProtocolPort,
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ProTable<API.Node, { search: string; node_group_id?: number }>
|
<ProTable<API.Node, { search: string; node_group_id?: number }>
|
||||||
@@ -168,7 +179,10 @@ export default function Nodes() {
|
|||||||
const body: API.UpdateNodeRequest = {
|
const body: API.UpdateNodeRequest = {
|
||||||
...row,
|
...row,
|
||||||
...values,
|
...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;
|
} as any;
|
||||||
await updateNode(body);
|
await updateNode(body);
|
||||||
toast.success(t("updated", "Updated"));
|
toast.success(t("updated", "Updated"));
|
||||||
@@ -232,6 +246,15 @@ export default function Nodes() {
|
|||||||
],
|
],
|
||||||
batchRender(rows) {
|
batchRender(rows) {
|
||||||
return [
|
return [
|
||||||
|
<NodeBatchSheet
|
||||||
|
key="batch-update"
|
||||||
|
onSuccess={() => {
|
||||||
|
ref.current?.refresh();
|
||||||
|
fetchNodes();
|
||||||
|
fetchTags();
|
||||||
|
}}
|
||||||
|
rows={rows}
|
||||||
|
/>,
|
||||||
<ConfirmButton
|
<ConfirmButton
|
||||||
cancelText={t("cancel", "Cancel")}
|
cancelText={t("cancel", "Cancel")}
|
||||||
confirmText={t("confirm", "Confirm")}
|
confirmText={t("confirm", "Confirm")}
|
||||||
@@ -274,9 +297,10 @@ export default function Nodes() {
|
|||||||
port: Number(values.port!),
|
port: Number(values.port!),
|
||||||
tags: values.tags || [],
|
tags: values.tags || [],
|
||||||
};
|
};
|
||||||
// Add node_group_ids if it exists
|
|
||||||
if (values.node_group_ids) {
|
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);
|
await createNode(body);
|
||||||
toast.success(t("created", "Created"));
|
toast.success(t("created", "Created"));
|
||||||
@@ -290,8 +314,8 @@ export default function Nodes() {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
title={t("drawerCreateTitle", "Create Node")}
|
title={t("drawerCreateTitle", "Create Landing Node")}
|
||||||
trigger={t("create", "Create")}
|
trigger={t("create", "Create Landing Node")}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
}}
|
}}
|
||||||
@@ -372,7 +396,9 @@ export default function Nodes() {
|
|||||||
page: pagination.page,
|
page: pagination.page,
|
||||||
size: pagination.size,
|
size: pagination.size,
|
||||||
search: filter?.search || undefined,
|
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);
|
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";
|
"use client";
|
||||||
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import { Checkbox } from "@workspace/ui/components/checkbox";
|
import { Checkbox } from "@workspace/ui/components/checkbox";
|
||||||
import {
|
import {
|
||||||
@@ -25,8 +26,10 @@ import {
|
|||||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||||
import TagInput from "@workspace/ui/composed/tag-input";
|
import TagInput from "@workspace/ui/composed/tag-input";
|
||||||
import { getGroupConfig, getNodeGroupList } from "@workspace/ui/services/admin/group";
|
import {
|
||||||
import { useQuery } from "@tanstack/react-query";
|
getGroupConfig,
|
||||||
|
getNodeGroupList,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import type { TFunction } from "i18next";
|
import type { TFunction } from "i18next";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
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(() => {
|
useEffect(() => {
|
||||||
if (initialValues) {
|
if (initialValues) {
|
||||||
@@ -166,15 +169,21 @@ export default function NodeForm(props: {
|
|||||||
|
|
||||||
// Copy only the values we need from initialValues
|
// Copy only the values we need from initialValues
|
||||||
if (initialValues.name) resetValues.name = initialValues.name;
|
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.protocol) resetValues.protocol = initialValues.protocol;
|
||||||
if (initialValues.address) resetValues.address = initialValues.address;
|
if (initialValues.address) resetValues.address = initialValues.address;
|
||||||
if (initialValues.port) resetValues.port = initialValues.port;
|
if (initialValues.port) resetValues.port = initialValues.port;
|
||||||
if (initialValues.tags) resetValues.tags = initialValues.tags;
|
if (initialValues.tags) resetValues.tags = initialValues.tags;
|
||||||
|
|
||||||
// Convert node_group_ids from number[] to string[], ensure it's always an array
|
// 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)) {
|
if (
|
||||||
resetValues.node_group_ids = initialValues.node_group_ids.map((id: string | number) => String(id));
|
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 {
|
} else {
|
||||||
resetValues.node_group_ids = [];
|
resetValues.node_group_ids = [];
|
||||||
}
|
}
|
||||||
@@ -449,23 +458,32 @@ export default function NodeForm(props: {
|
|||||||
<div className="grid grid-cols-2 gap-2">
|
<div className="grid grid-cols-2 gap-2">
|
||||||
{nodeGroupsData?.map((g) => (
|
{nodeGroupsData?.map((g) => (
|
||||||
<div
|
<div
|
||||||
key={g.id}
|
|
||||||
className="flex items-center space-x-2"
|
className="flex items-center space-x-2"
|
||||||
|
key={g.id}
|
||||||
>
|
>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
|
checked={field.value?.includes(String(g.id))}
|
||||||
id={`node-group-${g.id}`}
|
id={`node-group-${g.id}`}
|
||||||
checked={field.value?.includes(String(g.id)) || false}
|
|
||||||
onCheckedChange={(checked) => {
|
onCheckedChange={(checked) => {
|
||||||
// Ensure field.value is always an array
|
// 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) {
|
if (checked) {
|
||||||
const newValue = [...currentValue, String(g.id)];
|
const newValue = [
|
||||||
|
...currentValue,
|
||||||
|
String(g.id),
|
||||||
|
];
|
||||||
form.setValue(field.name, newValue, {
|
form.setValue(field.name, newValue, {
|
||||||
shouldValidate: true,
|
shouldValidate: true,
|
||||||
shouldDirty: true,
|
shouldDirty: true,
|
||||||
});
|
});
|
||||||
} else {
|
} 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, {
|
form.setValue(field.name, newValue, {
|
||||||
shouldValidate: true,
|
shouldValidate: true,
|
||||||
shouldDirty: true,
|
shouldDirty: true,
|
||||||
@@ -474,8 +492,8 @@ export default function NodeForm(props: {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Label
|
<Label
|
||||||
htmlFor={`node-group-${g.id}`}
|
|
||||||
className="cursor-pointer"
|
className="cursor-pointer"
|
||||||
|
htmlFor={`node-group-${g.id}`}
|
||||||
>
|
>
|
||||||
{g.name}
|
{g.name}
|
||||||
</Label>
|
</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 { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -15,17 +28,33 @@ import { cn } from "@workspace/ui/lib/utils";
|
|||||||
import {
|
import {
|
||||||
activateOrder,
|
activateOrder,
|
||||||
getOrderList,
|
getOrderList,
|
||||||
|
refundOrder,
|
||||||
updateOrderStatus,
|
updateOrderStatus,
|
||||||
} from "@workspace/ui/services/admin/order";
|
} from "@workspace/ui/services/admin/order";
|
||||||
import { useRef } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { toast } from "sonner";
|
||||||
import { Display } from "@/components/display";
|
import { Display } from "@/components/display";
|
||||||
|
import { useGlobalStore } from "@/stores/global";
|
||||||
import { useSubscribe } from "@/stores/subscribe";
|
import { useSubscribe } from "@/stores/subscribe";
|
||||||
import { formatDate } from "@/utils/common";
|
import { formatDate } from "@/utils/common";
|
||||||
import { UserDetail } from "../user/user-detail";
|
import { UserDetail } from "../user/user-detail";
|
||||||
|
|
||||||
|
const REFUNDED_ORDER_STATUS = 6;
|
||||||
|
|
||||||
export default function Order() {
|
export default function Order() {
|
||||||
const { t } = useTranslation("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 = [
|
const statusOptions = [
|
||||||
{
|
{
|
||||||
@@ -45,6 +74,11 @@ export default function Order() {
|
|||||||
label: t("status.5", "Completed"),
|
label: t("status.5", "Completed"),
|
||||||
className: "bg-green-500",
|
className: "bg-green-500",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
value: REFUNDED_ORDER_STATUS,
|
||||||
|
label: t("status.6", "Refunded"),
|
||||||
|
className: "bg-red-500",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const typeOptions = [
|
const typeOptions = [
|
||||||
@@ -57,10 +91,101 @@ export default function Order() {
|
|||||||
const ref = useRef<ProTableActions>(null);
|
const ref = useRef<ProTableActions>(null);
|
||||||
|
|
||||||
const { subscribes, getSubscribeName } = useSubscribe();
|
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 (
|
return (
|
||||||
<ProTable<API.Order, any>
|
<ProTable<API.Order, any>
|
||||||
action={ref}
|
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={[
|
columns={[
|
||||||
{
|
{
|
||||||
accessorKey: "order_no",
|
accessorKey: "order_no",
|
||||||
@@ -245,13 +370,19 @@ export default function Order() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Badge>
|
<Badge
|
||||||
{option?.label || t(`status.${row.getValue("status")}`)}
|
variant={isRefundedOrder(order) ? "destructive" : "default"}
|
||||||
|
>
|
||||||
|
{option?.label ||
|
||||||
|
(order.status_name
|
||||||
|
? t(`status.${row.getValue("status")}`, order.status_name)
|
||||||
|
: t(`status.${row.getValue("status")}`))}
|
||||||
</Badge>
|
</Badge>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
|
initialFilters={initialFilters}
|
||||||
params={[
|
params={[
|
||||||
{
|
{
|
||||||
key: "status",
|
key: "status",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Accordion,
|
Accordion,
|
||||||
AccordionContent,
|
AccordionContent,
|
||||||
@@ -41,12 +42,14 @@ import { ArrayInput } from "@workspace/ui/composed/dynamic-inputs";
|
|||||||
import { JSONEditor } from "@workspace/ui/composed/editor/index";
|
import { JSONEditor } from "@workspace/ui/composed/editor/index";
|
||||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||||
import { Icon } from "@workspace/ui/composed/icon";
|
import { Icon } from "@workspace/ui/composed/icon";
|
||||||
|
import {
|
||||||
|
getGroupConfig,
|
||||||
|
getNodeGroupList,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import {
|
import {
|
||||||
evaluateWithPrecision,
|
evaluateWithPrecision,
|
||||||
unitConversion,
|
unitConversion,
|
||||||
} from "@workspace/ui/utils/unit-conversions";
|
} 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 { CreditCard, Server, Settings } from "lucide-react";
|
||||||
import { assign, shake } from "radash";
|
import { assign, shake } from "radash";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
@@ -112,6 +115,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
z.object({
|
z.object({
|
||||||
quantity: z.number(),
|
quantity: z.number(),
|
||||||
discount: z.number(),
|
discount: z.number(),
|
||||||
|
map_apple: z.string().optional(),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.optional(),
|
.optional(),
|
||||||
@@ -263,8 +267,13 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convert node_group_ids from number[] to string[]
|
// Convert node_group_ids from number[] to string[]
|
||||||
if (initialValues?.node_group_ids && Array.isArray(initialValues.node_group_ids)) {
|
if (
|
||||||
processedValues.node_group_ids = (initialValues.node_group_ids as any[]).map((id) => String(id));
|
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);
|
form?.reset(processedValues);
|
||||||
@@ -290,7 +299,13 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
if (bool) setOpen(false);
|
if (bool) setOpen(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { getAllAvailableTags, getNodesByTag, getNodesWithoutTags, getNodesWithoutGroups, nodes } = useNode();
|
const {
|
||||||
|
getAllAvailableTags,
|
||||||
|
getNodesByTag,
|
||||||
|
getNodesWithoutTags,
|
||||||
|
getNodesWithoutGroups,
|
||||||
|
nodes,
|
||||||
|
} = useNode();
|
||||||
|
|
||||||
const tagGroups = getAllAvailableTags();
|
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 unit_time = form.watch("unit_time");
|
||||||
const node_group_id = form.watch("node_group_id");
|
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
|
// If node_group_id is empty or 0, automatically set it to the first item in node_group_ids
|
||||||
useEffect(() => {
|
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]);
|
form.setValue("node_group_id", node_group_ids[0]);
|
||||||
}
|
}
|
||||||
}, [node_group_ids, node_group_id, form]);
|
}, [node_group_ids, node_group_id, form]);
|
||||||
@@ -475,12 +494,6 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
placeholder={t("form.noLimit")}
|
placeholder={t("form.noLimit")}
|
||||||
type="number"
|
type="number"
|
||||||
{...field}
|
{...field}
|
||||||
formatInput={(value) =>
|
|
||||||
unitConversion("bitsToMb", value)
|
|
||||||
}
|
|
||||||
formatOutput={(value) =>
|
|
||||||
unitConversion("mbToBits", value)
|
|
||||||
}
|
|
||||||
onValueChange={(value) => {
|
onValueChange={(value) => {
|
||||||
form.setValue(field.name, value);
|
form.setValue(field.name, value);
|
||||||
}}
|
}}
|
||||||
@@ -801,6 +814,11 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
value
|
value
|
||||||
).toString(),
|
).toString(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "map_apple",
|
||||||
|
type: "text",
|
||||||
|
placeholder: t("form.appleProductId"),
|
||||||
|
},
|
||||||
]}
|
]}
|
||||||
onChange={(
|
onChange={(
|
||||||
newValues: (API.SubscribeDiscount & {
|
newValues: (API.SubscribeDiscount & {
|
||||||
@@ -1030,11 +1048,16 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
const nodesWithTag = getNodesByTag(tag);
|
const nodesWithTag = getNodesByTag(tag);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AccordionItem key={tag} value={String(tag)}>
|
<AccordionItem
|
||||||
|
key={tag}
|
||||||
|
value={String(tag)}
|
||||||
|
>
|
||||||
<AccordionTrigger>
|
<AccordionTrigger>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={value.includes(tagId as any)}
|
checked={value.includes(
|
||||||
|
tagId as any
|
||||||
|
)}
|
||||||
onCheckedChange={(checked) =>
|
onCheckedChange={(checked) =>
|
||||||
checked
|
checked
|
||||||
? form.setValue(field.name, [
|
? form.setValue(field.name, [
|
||||||
@@ -1098,7 +1121,10 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
{/* When group feature is enabled, show nodes without groups */}
|
{/* When group feature is enabled, show nodes without groups */}
|
||||||
{/* When group feature is disabled, show nodes without tags */}
|
{/* 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 || [];
|
const value = field.value || [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -1141,9 +1167,14 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
<FormDescription>
|
<FormDescription>
|
||||||
{isGroupEnabled
|
{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(
|
||||||
: t("form.nodesDescription", "Select nodes for this subscription")
|
"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>
|
</FormDescription>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
@@ -1154,70 +1185,325 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
{isGroupEnabled && (
|
{isGroupEnabled && (
|
||||||
<>
|
<>
|
||||||
{/* When no default node group is set, show simple node group selection */}
|
{/* 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
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="node_group_ids"
|
name="node_group_ids"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>{t("form.nodeGroups", "Node Groups")}</FormLabel>
|
<FormLabel>
|
||||||
|
{t("form.nodeGroups", "Node Groups")}
|
||||||
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{nodeGroupsData?.map((g) => {
|
{nodeGroupsData?.map((g) => {
|
||||||
// Filter nodes that belong to this group
|
// Filter nodes that belong to this group
|
||||||
const nodesInGroup = (nodes || []).filter((node) => {
|
const nodesInGroup = (nodes || []).filter(
|
||||||
const nodeGroupIds = (node as any).node_group_ids || [];
|
(node) => {
|
||||||
return nodeGroupIds.includes(g.id);
|
const nodeGroupIds =
|
||||||
});
|
(node as any).node_group_ids || [];
|
||||||
|
return nodeGroupIds.includes(g.id);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={g.id} className="border rounded-lg p-4">
|
<div
|
||||||
<div className="flex items-center space-x-2 mb-3">
|
className="rounded-lg border p-4"
|
||||||
|
key={g.id}
|
||||||
|
>
|
||||||
|
<div className="mb-3 flex items-center space-x-2">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
|
checked={field.value?.includes(
|
||||||
|
String(g.id)
|
||||||
|
)}
|
||||||
id={`subscribe-node-group-${g.id}`}
|
id={`subscribe-node-group-${g.id}`}
|
||||||
checked={field.value?.includes(String(g.id))}
|
|
||||||
onCheckedChange={(checked) => {
|
onCheckedChange={(checked) => {
|
||||||
const currentValue = field.value || [];
|
const currentValue =
|
||||||
const currentDefaultGroupId = form.getValues("node_group_id");
|
field.value || [];
|
||||||
|
const currentDefaultGroupId =
|
||||||
|
form.getValues(
|
||||||
|
"node_group_id"
|
||||||
|
);
|
||||||
|
|
||||||
if (checked) {
|
if (checked) {
|
||||||
const newValue = [...currentValue, String(g.id)];
|
const newValue = [
|
||||||
form.setValue(field.name, newValue);
|
...currentValue,
|
||||||
|
String(g.id),
|
||||||
|
];
|
||||||
|
form.setValue(
|
||||||
|
field.name,
|
||||||
|
newValue
|
||||||
|
);
|
||||||
|
|
||||||
// If no default node group is set, set this one as default
|
// If no default node group is set, set this one as default
|
||||||
if (!currentDefaultGroupId) {
|
if (!currentDefaultGroupId) {
|
||||||
form.setValue("node_group_id", String(g.id));
|
form.setValue(
|
||||||
|
"node_group_id",
|
||||||
|
String(g.id)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
form.setValue(
|
form.setValue(
|
||||||
field.name,
|
field.name,
|
||||||
currentValue.filter((v: string) => v !== String(g.id))
|
currentValue.filter(
|
||||||
|
(v: string) =>
|
||||||
|
v !== String(g.id)
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Label
|
<Label
|
||||||
htmlFor={`subscribe-node-group-${g.id}`}
|
|
||||||
className="cursor-pointer font-medium"
|
className="cursor-pointer font-medium"
|
||||||
|
htmlFor={`subscribe-node-group-${g.id}`}
|
||||||
>
|
>
|
||||||
{g.name}
|
{g.name}
|
||||||
<span className="ml-2 text-muted-foreground text-sm">
|
<span className="ml-2 text-muted-foreground text-sm">
|
||||||
({nodesInGroup.length} {t("form.nodes", "nodes")})
|
({nodesInGroup.length}{" "}
|
||||||
|
{t("form.nodes", "nodes")})
|
||||||
</span>
|
</span>
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Show nodes in this group */}
|
{/* Show nodes in this group */}
|
||||||
{nodesInGroup.length > 0 && (
|
{nodesInGroup.length > 0 && (
|
||||||
<div className="ml-6 mt-3">
|
<div className="mt-3 ml-6">
|
||||||
<div className="text-xs text-muted-foreground mb-2">
|
<div className="mb-2 text-muted-foreground text-xs">
|
||||||
{t("form.nodesInGroup", "Nodes in this group:")}
|
{t(
|
||||||
|
"form.nodesInGroup",
|
||||||
|
"Nodes in this group:"
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 gap-2">
|
<div className="grid grid-cols-1 gap-2">
|
||||||
{nodesInGroup.map((node) => (
|
{nodesInGroup.map((node) => (
|
||||||
<div
|
<div
|
||||||
|
className="flex items-center justify-between rounded border bg-muted/30 p-2 text-sm"
|
||||||
key={node.id}
|
key={node.id}
|
||||||
className="flex items-center justify-between rounded border p-2 text-sm bg-muted/30"
|
|
||||||
>
|
>
|
||||||
<span className="flex-1 font-medium">
|
<span className="flex-1 font-medium">
|
||||||
{node.name}
|
{node.name}
|
||||||
@@ -1248,169 +1534,6 @@ export default function SubscribeForm<T extends Record<string, any>>({
|
|||||||
</FormItem>
|
</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"
|
name="traffic_limit"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>{t("form.trafficLimitRules", "Traffic Limit Rules")}</FormLabel>
|
<FormLabel>
|
||||||
|
{t("form.trafficLimitRules", "Traffic Limit Rules")}
|
||||||
|
</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<ArrayInput
|
<ArrayInput
|
||||||
value={field.value && field.value.length > 0 ? field.value : [{ stat_type: "day" }]}
|
|
||||||
onChange={field.onChange}
|
|
||||||
fields={[
|
fields={[
|
||||||
{
|
{
|
||||||
name: "stat_type",
|
name: "stat_type",
|
||||||
type: "select",
|
type: "select",
|
||||||
placeholder: t("form.statType", "Statistics Type"),
|
placeholder: t(
|
||||||
|
"form.statType",
|
||||||
|
"Statistics Type"
|
||||||
|
),
|
||||||
value: "day",
|
value: "day",
|
||||||
options: [
|
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",
|
name: "stat_value",
|
||||||
type: "number",
|
type: "number",
|
||||||
placeholder: t("form.statValue", "Time Value"),
|
placeholder: t(
|
||||||
|
"form.statValue",
|
||||||
|
"Time Value"
|
||||||
|
),
|
||||||
min: 1,
|
min: 1,
|
||||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
onKeyDown: (
|
||||||
if (e.key === '.' || e.key === ',') {
|
e: React.KeyboardEvent<HTMLInputElement>
|
||||||
|
) => {
|
||||||
|
if (e.key === "." || e.key === ",") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
formatOutput: (value: string | number) => {
|
formatOutput: (value: string | number) => {
|
||||||
const num = Number(value);
|
const num = Number(value);
|
||||||
return isNaN(num) ? 0 : Math.floor(num);
|
return String(
|
||||||
|
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "traffic_usage",
|
name: "traffic_usage",
|
||||||
type: "number",
|
type: "number",
|
||||||
placeholder: t("form.trafficUsage", "Traffic Usage (GB)"),
|
placeholder: t(
|
||||||
|
"form.trafficUsage",
|
||||||
|
"Traffic Usage (GB)"
|
||||||
|
),
|
||||||
min: 0,
|
min: 0,
|
||||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
onKeyDown: (
|
||||||
if (e.key === '.' || e.key === ',') {
|
e: React.KeyboardEvent<HTMLInputElement>
|
||||||
|
) => {
|
||||||
|
if (e.key === "." || e.key === ",") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
formatOutput: (value: string | number) => {
|
formatOutput: (value: string | number) => {
|
||||||
const num = Number(value);
|
const num = Number(value);
|
||||||
return isNaN(num) ? 0 : Math.floor(num);
|
return String(
|
||||||
|
Number.isNaN(num) ? 0 : Math.floor(num)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "speed_limit",
|
name: "speed_limit",
|
||||||
type: "number",
|
type: "number",
|
||||||
placeholder: t("form.speedLimitKb", "Speed Limit (kb)"),
|
placeholder: t(
|
||||||
|
"form.speedLimitMbps",
|
||||||
|
"Speed Limit (Mbps)"
|
||||||
|
),
|
||||||
min: 0,
|
min: 0,
|
||||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
onKeyDown: (
|
||||||
if (e.key === '.' || e.key === ',') {
|
e: React.KeyboardEvent<HTMLInputElement>
|
||||||
|
) => {
|
||||||
|
if (e.key === "." || e.key === ",") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
formatOutput: (value: string | number) => {
|
formatOutput: (value: string | number) => {
|
||||||
const num = Number(value);
|
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>
|
</FormControl>
|
||||||
<FormDescription>
|
<FormDescription>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import { Switch } from "@workspace/ui/components/switch";
|
import { Switch } from "@workspace/ui/components/switch";
|
||||||
@@ -8,6 +9,7 @@ import {
|
|||||||
ProTable,
|
ProTable,
|
||||||
type ProTableActions,
|
type ProTableActions,
|
||||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||||
|
import { getNodeGroupList } from "@workspace/ui/services/admin/group";
|
||||||
import {
|
import {
|
||||||
batchDeleteSubscribe,
|
batchDeleteSubscribe,
|
||||||
createSubscribe,
|
createSubscribe,
|
||||||
@@ -16,8 +18,6 @@ import {
|
|||||||
subscribeSort,
|
subscribeSort,
|
||||||
updateSubscribe,
|
updateSubscribe,
|
||||||
} from "@workspace/ui/services/admin/subscribe";
|
} 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 { useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -46,15 +46,20 @@ export default function SubscribeTable() {
|
|||||||
const { data: groupConfigData } = useQuery({
|
const { data: groupConfigData } = useQuery({
|
||||||
queryKey: ["groupConfig"],
|
queryKey: ["groupConfig"],
|
||||||
queryFn: async () => {
|
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;
|
return data.data;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const isGroupEnabled = groupConfigData?.enabled || false;
|
const isGroupEnabled = groupConfigData?.enabled;
|
||||||
|
|
||||||
return (
|
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}
|
action={ref}
|
||||||
actions={{
|
actions={{
|
||||||
render: (row) => [
|
render: (row) => [
|
||||||
@@ -72,7 +77,9 @@ export default function SubscribeTable() {
|
|||||||
// Add node_group_ids if it exists in values
|
// Add node_group_ids if it exists in values
|
||||||
const vals = values as any;
|
const vals = values as any;
|
||||||
if (vals.node_group_ids) {
|
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);
|
await updateSubscribe(updateBody as API.UpdateSubscribeRequest);
|
||||||
toast.success(t("updateSuccess"));
|
toast.success(t("updateSuccess"));
|
||||||
@@ -241,10 +248,12 @@ export default function SubscribeTable() {
|
|||||||
header: t("inventory"),
|
header: t("inventory"),
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const inventory = row.getValue("inventory") as number;
|
const inventory = row.getValue("inventory") as number;
|
||||||
return inventory === -1 ? (
|
return (
|
||||||
<Display type="number" unlimited value={0} />
|
<Display
|
||||||
) : (
|
type="number"
|
||||||
<Display type="number" unlimited value={inventory} />
|
unlimited={inventory === -1}
|
||||||
|
value={inventory === -1 ? 0 : inventory}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -281,7 +290,9 @@ export default function SubscribeTable() {
|
|||||||
header: t("defaultNodeGroup", "Default Node Group"),
|
header: t("defaultNodeGroup", "Default Node Group"),
|
||||||
cell: ({ row }: { row: any }) => {
|
cell: ({ row }: { row: any }) => {
|
||||||
const nodeGroupId = row.original.node_group_id;
|
const nodeGroupId = row.original.node_group_id;
|
||||||
const nodeGroup = nodeGroupsData?.find((g) => g.id === nodeGroupId);
|
const nodeGroup = nodeGroupsData?.find(
|
||||||
|
(g) => g.id === nodeGroupId
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -310,7 +321,9 @@ export default function SubscribeTable() {
|
|||||||
// Add node_group_ids if it exists in values
|
// Add node_group_ids if it exists in values
|
||||||
const vals = values as any;
|
const vals = values as any;
|
||||||
if (vals.node_group_ids) {
|
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);
|
await createSubscribe(createBody);
|
||||||
toast.success(t("createSuccess"));
|
toast.success(t("createSuccess"));
|
||||||
@@ -389,7 +402,9 @@ export default function SubscribeTable() {
|
|||||||
const params = {
|
const params = {
|
||||||
...pagination,
|
...pagination,
|
||||||
...filters,
|
...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;
|
} as any;
|
||||||
|
|
||||||
const { data } = await getSubscribeList(params);
|
const { data } = await getSubscribeList(params);
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { useNode } from "@/stores/node";
|
|||||||
import { useServer } from "@/stores/server";
|
import { useServer } from "@/stores/server";
|
||||||
import DynamicMultiplier from "./dynamic-multiplier";
|
import DynamicMultiplier from "./dynamic-multiplier";
|
||||||
import OnlineUsersCell from "./online-users-cell";
|
import OnlineUsersCell from "./online-users-cell";
|
||||||
|
import ServerBatchSheet from "./server-batch-sheet";
|
||||||
import ServerConfig from "./server-config";
|
import ServerConfig from "./server-config";
|
||||||
import ServerForm from "./server-form";
|
import ServerForm from "./server-form";
|
||||||
import ServerInstall from "./server-install";
|
import ServerInstall from "./server-install";
|
||||||
@@ -184,6 +185,14 @@ export default function Servers() {
|
|||||||
isServerReferencedByNodes(row.id)
|
isServerReferencedByNodes(row.id)
|
||||||
);
|
);
|
||||||
return [
|
return [
|
||||||
|
<ServerBatchSheet
|
||||||
|
key="batch-update"
|
||||||
|
onSuccess={() => {
|
||||||
|
ref.current?.refresh();
|
||||||
|
fetchServers();
|
||||||
|
}}
|
||||||
|
rows={rows}
|
||||||
|
/>,
|
||||||
<ConfirmButton
|
<ConfirmButton
|
||||||
cancelText={t("cancel", "Cancel")}
|
cancelText={t("cancel", "Cancel")}
|
||||||
confirmText={t("confirm", "Confirm")}
|
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}
|
{...fieldProps}
|
||||||
max={field.max}
|
max={field.max}
|
||||||
min={field.min}
|
min={field.min}
|
||||||
onValueChange={(v) => fieldProps.onChange(v)}
|
onValueChange={(v) =>
|
||||||
|
fieldProps.onChange(v === "" ? undefined : Number(v))
|
||||||
|
}
|
||||||
placeholder={field.placeholder}
|
placeholder={field.placeholder}
|
||||||
step={field.step || 1}
|
step={field.step || 1}
|
||||||
suffix={field.suffix}
|
suffix={field.suffix}
|
||||||
@@ -308,7 +310,7 @@ function renderFieldsByGroup(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderGroupCard(
|
export function renderGroupCard(
|
||||||
title: string,
|
title: string,
|
||||||
fields: FieldConfig[],
|
fields: FieldConfig[],
|
||||||
group: string,
|
group: string,
|
||||||
@@ -362,15 +364,52 @@ export default function ServerForm(props: {
|
|||||||
const { isProtocolUsedInNodes } = useNode();
|
const { isProtocolUsedInNodes } = useNode();
|
||||||
const PROTOCOL_FIELDS = useProtocolFields();
|
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({
|
const form = useForm({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
name: "",
|
name: initialValues?.name ?? "",
|
||||||
address: "",
|
address: initialValues?.address ?? "",
|
||||||
country: "",
|
country: initialValues?.country ?? "",
|
||||||
city: "",
|
city: initialValues?.city ?? "",
|
||||||
protocols: [] as any[],
|
protocols: buildSanitizedProtocols(initialValues?.protocols as any[]),
|
||||||
...initialValues,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const { control } = form;
|
const { control } = form;
|
||||||
@@ -380,20 +419,11 @@ export default function ServerForm(props: {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialValues) {
|
if (initialValues) {
|
||||||
form.reset({
|
form.reset({
|
||||||
name: "",
|
name: initialValues.name ?? "",
|
||||||
address: "",
|
address: initialValues.address ?? "",
|
||||||
country: "",
|
country: initialValues.country ?? "",
|
||||||
city: "",
|
city: initialValues.city ?? "",
|
||||||
...initialValues,
|
protocols: buildSanitizedProtocols(initialValues.protocols as any[]),
|
||||||
protocols: PROTOCOLS.map((type) => {
|
|
||||||
const existingProtocol = initialValues.protocols?.find(
|
|
||||||
(p) => p.type === type
|
|
||||||
);
|
|
||||||
const defaultConfig = getProtocolDefaultConfig(type);
|
|
||||||
return existingProtocol
|
|
||||||
? { ...defaultConfig, ...existingProtocol }
|
|
||||||
: defaultConfig;
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
@@ -686,8 +716,22 @@ export default function ServerForm(props: {
|
|||||||
<Button
|
<Button
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
onClick={form.handleSubmit(handleSubmit, (errors) => {
|
onClick={form.handleSubmit(handleSubmit, (errors) => {
|
||||||
const key = Object.keys(errors)[0] as keyof typeof errors;
|
const getFirstErrorMessage = (
|
||||||
if (key) toast.error(String(errors[key]?.message));
|
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;
|
return false;
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -27,10 +27,12 @@ type Props = {
|
|||||||
server: API.Server;
|
server: API.Server;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const DEFAULT_API_HOST = "https://api.hifast.biz";
|
||||||
|
|
||||||
export default function ServerInstall({ server }: Props) {
|
export default function ServerInstall({ server }: Props) {
|
||||||
const { t } = useTranslation("servers");
|
const { t } = useTranslation("servers");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [domain, setDomain] = useState("");
|
const [domain, setDomain] = useState(DEFAULT_API_HOST);
|
||||||
|
|
||||||
const { data: cfgResp } = useQuery({
|
const { data: cfgResp } = useQuery({
|
||||||
queryKey: ["getNodeConfig"],
|
queryKey: ["getNodeConfig"],
|
||||||
@@ -43,8 +45,7 @@ export default function ServerInstall({ server }: Props) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
const host = localStorage.getItem("API_HOST") ?? window.location.origin;
|
setDomain(DEFAULT_API_HOST);
|
||||||
setDomain(host);
|
|
||||||
}
|
}
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
@@ -75,7 +76,6 @@ export default function ServerInstall({ server }: Props) {
|
|||||||
|
|
||||||
const onDomainChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
|
const onDomainChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
|
||||||
setDomain(e.target.value);
|
setDomain(e.target.value);
|
||||||
localStorage.setItem("API_HOST", e.target.value);
|
|
||||||
}, []);
|
}, []);
|
||||||
return (
|
return (
|
||||||
<Dialog onOpenChange={setOpen} open={open}>
|
<Dialog onOpenChange={setOpen} open={open}>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
SheetTrigger,
|
SheetTrigger,
|
||||||
} from "@workspace/ui/components/sheet";
|
} from "@workspace/ui/components/sheet";
|
||||||
import { Switch } from "@workspace/ui/components/switch";
|
import { Switch } from "@workspace/ui/components/switch";
|
||||||
|
import { Textarea } from "@workspace/ui/components/textarea";
|
||||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||||
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
import { EnhancedInput } from "@workspace/ui/composed/enhanced-input";
|
||||||
import { Icon } from "@workspace/ui/composed/icon";
|
import { Icon } from "@workspace/ui/composed/icon";
|
||||||
@@ -40,6 +41,8 @@ const registerSchema = z.object({
|
|||||||
trial_subscribe: z.number().optional(),
|
trial_subscribe: z.number().optional(),
|
||||||
trial_time: z.number().optional(),
|
trial_time: z.number().optional(),
|
||||||
trial_time_unit: z.string().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(),
|
enable_ip_register_limit: z.boolean().optional(),
|
||||||
ip_register_limit: z.number().optional(),
|
ip_register_limit: z.number().optional(),
|
||||||
ip_register_limit_duration: z.number().optional(),
|
ip_register_limit_duration: z.number().optional(),
|
||||||
@@ -72,6 +75,8 @@ export default function RegisterConfig() {
|
|||||||
trial_subscribe: undefined,
|
trial_subscribe: undefined,
|
||||||
trial_time: 0,
|
trial_time: 0,
|
||||||
trial_time_unit: "day",
|
trial_time_unit: "day",
|
||||||
|
enable_trial_email_whitelist: false,
|
||||||
|
trial_email_domain_whitelist: "",
|
||||||
enable_ip_register_limit: false,
|
enable_ip_register_limit: false,
|
||||||
ip_register_limit: 1,
|
ip_register_limit: 1,
|
||||||
ip_register_limit_duration: 1,
|
ip_register_limit_duration: 1,
|
||||||
@@ -331,114 +336,182 @@ export default function RegisterConfig() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{form.watch("enable_trial") && (
|
{form.watch("enable_trial") && (
|
||||||
<FormField
|
<>
|
||||||
control={form.control}
|
<FormField
|
||||||
name="trial_time"
|
control={form.control}
|
||||||
render={({ field }) => (
|
name="trial_time"
|
||||||
<FormItem>
|
render={({ field }) => (
|
||||||
<FormLabel>
|
<FormItem>
|
||||||
{t("register.trialConfig", "Trial Configuration")}
|
<FormLabel>
|
||||||
</FormLabel>
|
{t("register.trialConfig", "Trial Configuration")}
|
||||||
<FormControl>
|
</FormLabel>
|
||||||
<div className="flex gap-2">
|
<FormControl>
|
||||||
<EnhancedInput
|
<div className="flex gap-2">
|
||||||
className="flex-1"
|
<EnhancedInput
|
||||||
min={0}
|
className="flex-1"
|
||||||
onValueBlur={(value) =>
|
min={0}
|
||||||
field.onChange(Number(value))
|
onValueBlur={(value) =>
|
||||||
}
|
field.onChange(Number(value))
|
||||||
placeholder={t(
|
}
|
||||||
"register.inputPlaceholder",
|
placeholder={t(
|
||||||
"Please enter"
|
"register.inputPlaceholder",
|
||||||
)}
|
"Please enter"
|
||||||
prefix={
|
)}
|
||||||
<FormField
|
prefix={
|
||||||
control={form.control}
|
<FormField
|
||||||
name="trial_subscribe"
|
control={form.control}
|
||||||
render={({ field }) => (
|
name="trial_subscribe"
|
||||||
<Combobox
|
render={({ field }) => (
|
||||||
className="w-32 rounded-r-none bg-secondary"
|
<Combobox
|
||||||
onChange={(value: number) => {
|
className="w-32 rounded-r-none bg-secondary"
|
||||||
if (value) {
|
onChange={(value: number) => {
|
||||||
field.onChange(value);
|
if (value) {
|
||||||
}
|
field.onChange(value);
|
||||||
}}
|
}
|
||||||
options={subscribes?.map((item) => ({
|
}}
|
||||||
label: item.name!,
|
options={subscribes?.map((item) => ({
|
||||||
value: item.id!,
|
label: item.name!,
|
||||||
}))}
|
value: item.id!,
|
||||||
placeholder={t(
|
}))}
|
||||||
"register.selectPlaceholder",
|
placeholder={t(
|
||||||
"Please select"
|
"register.selectPlaceholder",
|
||||||
)}
|
"Please select"
|
||||||
value={field.value}
|
)}
|
||||||
/>
|
value={field.value}
|
||||||
)}
|
/>
|
||||||
/>
|
)}
|
||||||
}
|
/>
|
||||||
suffix={
|
}
|
||||||
<FormField
|
suffix={
|
||||||
control={form.control}
|
<FormField
|
||||||
name="trial_time_unit"
|
control={form.control}
|
||||||
render={({ field: unitField }) => (
|
name="trial_time_unit"
|
||||||
<Combobox
|
render={({ field: unitField }) => (
|
||||||
className="w-32 rounded-l-none bg-secondary"
|
<Combobox
|
||||||
onChange={(value: string) => {
|
className="w-32 rounded-l-none bg-secondary"
|
||||||
unitField.onChange(value);
|
onChange={(value: string) => {
|
||||||
}}
|
unitField.onChange(value);
|
||||||
options={[
|
}}
|
||||||
{
|
options={[
|
||||||
label: t("register.none", "None"),
|
{
|
||||||
value: "None",
|
label: t("register.none", "None"),
|
||||||
},
|
value: "None",
|
||||||
{
|
},
|
||||||
label: t("register.year", "Year(s)"),
|
{
|
||||||
value: "Year",
|
label: t("register.year", "Year(s)"),
|
||||||
},
|
value: "Year",
|
||||||
{
|
},
|
||||||
label: t("register.month", "Month(s)"),
|
{
|
||||||
value: "Month",
|
label: t(
|
||||||
},
|
"register.month",
|
||||||
{
|
"Month(s)"
|
||||||
label: t("register.day", "Day(s)"),
|
),
|
||||||
value: "Day",
|
value: "Month",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t("register.hour", "Hour(s)"),
|
label: t("register.day", "Day(s)"),
|
||||||
value: "Hour",
|
value: "Day",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t(
|
label: t("register.hour", "Hour(s)"),
|
||||||
"register.minute",
|
value: "Hour",
|
||||||
"Minute(s)"
|
},
|
||||||
),
|
{
|
||||||
value: "Minute",
|
label: t(
|
||||||
},
|
"register.minute",
|
||||||
]}
|
"Minute(s)"
|
||||||
placeholder={t(
|
),
|
||||||
"register.selectPlaceholder",
|
value: "Minute",
|
||||||
"Please select"
|
},
|
||||||
)}
|
]}
|
||||||
value={unitField.value}
|
placeholder={t(
|
||||||
/>
|
"register.selectPlaceholder",
|
||||||
)}
|
"Please select"
|
||||||
/>
|
)}
|
||||||
}
|
value={unitField.value}
|
||||||
type="number"
|
/>
|
||||||
value={field.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>
|
||||||
</FormControl>
|
<FormDescription>
|
||||||
<FormDescription>
|
{t(
|
||||||
{t(
|
"register.enableTrialEmailWhitelistDescription",
|
||||||
"register.trialConfigDescription",
|
"When enabled, trial subscription is only granted to emails with whitelisted domains"
|
||||||
"Configure trial subscription, duration and time unit for new users upon registration"
|
)}
|
||||||
)}
|
</FormDescription>
|
||||||
</FormDescription>
|
<FormMessage />
|
||||||
<FormMessage />
|
</FormItem>
|
||||||
</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>
|
||||||
</Form>
|
</Form>
|
||||||
|
|||||||
@@ -158,7 +158,22 @@ export default function VerifyConfig() {
|
|||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="local">
|
<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>
|
||||||
<SelectItem value="turnstile">
|
<SelectItem value="turnstile">
|
||||||
{t(
|
{t(
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ import {
|
|||||||
getTicketList,
|
getTicketList,
|
||||||
updateTicketStatus,
|
updateTicketStatus,
|
||||||
} from "@workspace/ui/services/admin/ticket";
|
} from "@workspace/ui/services/admin/ticket";
|
||||||
|
import {
|
||||||
|
getUserDetail,
|
||||||
|
updateUserBasicInfo,
|
||||||
|
} from "@workspace/ui/services/admin/user";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -42,6 +46,7 @@ export default function Page() {
|
|||||||
const [ticketId, setTicketId] = useState<any>(null);
|
const [ticketId, setTicketId] = useState<any>(null);
|
||||||
|
|
||||||
const [message, setMessage] = useState("");
|
const [message, setMessage] = useState("");
|
||||||
|
const [loadingId, setLoadingId] = useState<any>(null);
|
||||||
|
|
||||||
const { data: ticket, refetch: refetchTicket } = useQuery({
|
const { data: ticket, refetch: refetchTicket } = useQuery({
|
||||||
queryKey: ["getTicket", ticketId],
|
queryKey: ["getTicket", ticketId],
|
||||||
@@ -74,45 +79,214 @@ export default function Page() {
|
|||||||
action={ref}
|
action={ref}
|
||||||
actions={{
|
actions={{
|
||||||
render(row) {
|
render(row) {
|
||||||
if (row.status !== 4) {
|
if (row.status === 1) {
|
||||||
return [
|
return [
|
||||||
<Button key="reply" onClick={() => setTicketId(row.id)}>
|
|
||||||
{t("reply", "Reply")}
|
|
||||||
</Button>,
|
|
||||||
<ConfirmButton
|
<ConfirmButton
|
||||||
cancelText={t("cancel", "Cancel")}
|
cancelText={t("cancel", "Cancel")}
|
||||||
confirmText={t("confirm", "Confirm")}
|
confirmText={t("confirm", "Confirm")}
|
||||||
description={t(
|
description="您确定要取消此次打款吗?取消后系统将记录此操作并关闭工单。"
|
||||||
"closeWarning",
|
key="cancel-payout"
|
||||||
"Once closed, the ticket cannot be operated on. Please proceed with caution."
|
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"
|
key="colse"
|
||||||
onConfirm={async () => {
|
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({
|
await updateTicketStatus({
|
||||||
id: row.id,
|
id: row.id,
|
||||||
status: 4,
|
status: 4,
|
||||||
});
|
});
|
||||||
toast.success(t("closeSuccess", "Closed successfully"));
|
toast.success(t("closeSuccess", "Closed successfully"));
|
||||||
ref.current?.refresh();
|
ref.current?.refresh();
|
||||||
|
setLoadingId(null);
|
||||||
}}
|
}}
|
||||||
title={t("confirmClose", "Are you sure you want to close?")}
|
title="确认已完成打款?"
|
||||||
trigger={
|
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 [
|
return [];
|
||||||
<Button key="check" onClick={() => setTicketId(row.id)} size="sm">
|
|
||||||
{t("check", "Check")}
|
|
||||||
</Button>,
|
|
||||||
];
|
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
accessorKey: "title",
|
id: "withdrawal_type",
|
||||||
header: t("title", "Title"),
|
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",
|
accessorKey: "user_id",
|
||||||
|
|||||||
@@ -261,6 +261,11 @@ export function FamilyDetailSheet({
|
|||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
ID: {member.user_id}
|
ID: {member.user_id}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
{member.auth_type ? (
|
||||||
|
<Badge className="uppercase">
|
||||||
|
{member.auth_type}
|
||||||
|
</Badge>
|
||||||
|
) : null}
|
||||||
{member.device_no ? (
|
{member.device_no ? (
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
<span className="font-mono">
|
<span className="font-mono">
|
||||||
@@ -268,7 +273,16 @@ export function FamilyDetailSheet({
|
|||||||
</span>
|
</span>
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : 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>
|
<Badge>
|
||||||
{getFamilyRoleLabel(t, member.role_name)}
|
{getFamilyRoleLabel(t, member.role_name)}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
|||||||
@@ -54,8 +54,19 @@ export default function FamilyManagement({
|
|||||||
{
|
{
|
||||||
accessorKey: "owner_identifier",
|
accessorKey: "owner_identifier",
|
||||||
header: t("owner", "Owner"),
|
header: t("owner", "Owner"),
|
||||||
cell: ({ row }) =>
|
cell: ({ row }) => (
|
||||||
`${row.original.owner_identifier} (ID: ${row.original.owner_user_id})`,
|
<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",
|
accessorKey: "status",
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@workspace/ui/components/dropdown-menu";
|
} from "@workspace/ui/components/dropdown-menu";
|
||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@workspace/ui/components/popover";
|
||||||
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
import { ScrollArea } from "@workspace/ui/components/scroll-area";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -39,22 +44,24 @@ import {
|
|||||||
TabsTrigger,
|
TabsTrigger,
|
||||||
} from "@workspace/ui/components/tabs";
|
} from "@workspace/ui/components/tabs";
|
||||||
import { Combobox } from "@workspace/ui/composed/combobox";
|
import { Combobox } from "@workspace/ui/composed/combobox";
|
||||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
// import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||||
import {
|
import {
|
||||||
ProTable,
|
ProTable,
|
||||||
type ProTableActions,
|
type ProTableActions,
|
||||||
} from "@workspace/ui/composed/pro-table/pro-table";
|
} from "@workspace/ui/composed/pro-table/pro-table";
|
||||||
|
import {
|
||||||
|
// getUserGroupList,
|
||||||
|
previewUserNodes,
|
||||||
|
} from "@workspace/ui/services/admin/group";
|
||||||
import {
|
import {
|
||||||
createUser,
|
createUser,
|
||||||
deleteUser,
|
// deleteUser,
|
||||||
getUserDetail,
|
getUserDetail,
|
||||||
getUserList,
|
getUserList,
|
||||||
updateUserBasicInfo,
|
updateUserBasicInfo,
|
||||||
} from "@workspace/ui/services/admin/user";
|
} from "@workspace/ui/services/admin/user";
|
||||||
import {
|
import { parseDeviceType } from "@workspace/ui/utils/device";
|
||||||
// getUserGroupList,
|
import { FilePenLine } from "lucide-react";
|
||||||
previewUserNodes,
|
|
||||||
} from "@workspace/ui/services/admin/group";
|
|
||||||
import { useCallback, useRef, useState } from "react";
|
import { useCallback, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@@ -62,6 +69,8 @@ import { Display } from "@/components/display";
|
|||||||
import { useSubscribe } from "@/stores/subscribe";
|
import { useSubscribe } from "@/stores/subscribe";
|
||||||
import { formatDate } from "@/utils/common";
|
import { formatDate } from "@/utils/common";
|
||||||
import FamilyManagement from "./family";
|
import FamilyManagement from "./family";
|
||||||
|
import { RemarkForm } from "./remark-form";
|
||||||
|
import { buildUserBasicInfoPayload } from "./user-basic-info-payload";
|
||||||
import { UserDetail } from "./user-detail";
|
import { UserDetail } from "./user-detail";
|
||||||
import UserForm from "./user-form";
|
import UserForm from "./user-form";
|
||||||
import { UserInviteStatsSheet } from "./user-invite-stats-sheet";
|
import { UserInviteStatsSheet } from "./user-invite-stats-sheet";
|
||||||
@@ -69,8 +78,13 @@ import { AuthMethodsForm } from "./user-profile/auth-methods-form";
|
|||||||
import { BasicInfoForm } from "./user-profile/basic-info-form";
|
import { BasicInfoForm } from "./user-profile/basic-info-form";
|
||||||
import { NotifySettingsForm } from "./user-profile/notify-settings-form";
|
import { NotifySettingsForm } from "./user-profile/notify-settings-form";
|
||||||
import UserSubscription from "./user-subscription";
|
import UserSubscription from "./user-subscription";
|
||||||
|
|
||||||
// import EditUserGroupDialog from "./edit-user-group-dialog";
|
// import EditUserGroupDialog from "./edit-user-group-dialog";
|
||||||
|
|
||||||
|
type UserDeviceWithDeviceNo = API.UserDevice & {
|
||||||
|
device_no?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export default function User() {
|
export default function User() {
|
||||||
const { t } = useTranslation("user");
|
const { t } = useTranslation("user");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
@@ -89,6 +103,21 @@ export default function User() {
|
|||||||
ref.current?.refresh();
|
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({
|
// const { data: userGroupsData } = useQuery({
|
||||||
// queryKey: ["userGroups"],
|
// queryKey: ["userGroups"],
|
||||||
// queryFn: async () => {
|
// queryFn: async () => {
|
||||||
@@ -123,7 +152,7 @@ export default function User() {
|
|||||||
userId={row.id}
|
userId={row.id}
|
||||||
/>,
|
/>,
|
||||||
<PreviewNodesDialog key="preview-nodes" userId={row.id} />,
|
<PreviewNodesDialog key="preview-nodes" userId={row.id} />,
|
||||||
<ConfirmButton
|
/* <ConfirmButton
|
||||||
cancelText={t("cancel", "Cancel")}
|
cancelText={t("cancel", "Cancel")}
|
||||||
confirmText={t("confirm", "Confirm")}
|
confirmText={t("confirm", "Confirm")}
|
||||||
description={t(
|
description={t(
|
||||||
@@ -140,7 +169,7 @@ export default function User() {
|
|||||||
trigger={
|
trigger={
|
||||||
<Button variant="destructive">{t("delete", "Delete")}</Button>
|
<Button variant="destructive">{t("delete", "Delete")}</Button>
|
||||||
}
|
}
|
||||||
/>,
|
/>,*/
|
||||||
<DropdownMenu key="more" modal={false}>
|
<DropdownMenu key="more" modal={false}>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="outline">{t("more", "More")}</Button>
|
<Button variant="outline">{t("more", "More")}</Button>
|
||||||
@@ -148,42 +177,30 @@ export default function User() {
|
|||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<InviteStatsMenuItem userId={row.id} />
|
<InviteStatsMenuItem userId={row.id} />
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link search={{ user_id: row.id }} to="/dashboard/order">
|
||||||
search={{ user_id: String(row.id) }}
|
|
||||||
to="/dashboard/order"
|
|
||||||
>
|
|
||||||
{t("orderList", "Order List")}
|
{t("orderList", "Order List")}
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link search={{ user_id: row.id }} to="/dashboard/log/login">
|
||||||
search={{ user_id: String(row.id) }}
|
|
||||||
to="/dashboard/log/login"
|
|
||||||
>
|
|
||||||
{t("loginLogs", "Login Logs")}
|
{t("loginLogs", "Login Logs")}
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link search={{ user_id: row.id }} to="/dashboard/log/balance">
|
||||||
search={{ user_id: String(row.id) }}
|
|
||||||
to="/dashboard/log/balance"
|
|
||||||
>
|
|
||||||
{t("balanceLogs", "Balance Logs")}
|
{t("balanceLogs", "Balance Logs")}
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link
|
||||||
search={{ user_id: String(row.id) }}
|
search={{ user_id: row.id }}
|
||||||
to="/dashboard/log/commission"
|
to="/dashboard/log/commission"
|
||||||
>
|
>
|
||||||
{t("commissionLogs", "Commission Logs")}
|
{t("commissionLogs", "Commission Logs")}
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild>
|
<DropdownMenuItem asChild>
|
||||||
<Link
|
<Link search={{ user_id: row.id }} to="/dashboard/log/gift">
|
||||||
search={{ user_id: String(row.id) }}
|
|
||||||
to="/dashboard/log/gift"
|
|
||||||
>
|
|
||||||
{t("giftLogs", "Gift Logs")}
|
{t("giftLogs", "Gift Logs")}
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@@ -228,7 +245,7 @@ export default function User() {
|
|||||||
accessorKey: "id",
|
accessorKey: "id",
|
||||||
header: "ID",
|
header: "ID",
|
||||||
},
|
},
|
||||||
{
|
/*{
|
||||||
id: "deleted_at",
|
id: "deleted_at",
|
||||||
accessorKey: "deleted_at",
|
accessorKey: "deleted_at",
|
||||||
header: t("isDeleted", "Deleted"),
|
header: t("isDeleted", "Deleted"),
|
||||||
@@ -240,31 +257,69 @@ export default function User() {
|
|||||||
<Badge variant="outline">{t("normal", "Normal")}</Badge>
|
<Badge variant="outline">{t("normal", "Normal")}</Badge>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},*/
|
||||||
{
|
{
|
||||||
id: "auth_methods",
|
id: "auth_methods",
|
||||||
accessorKey: "auth_methods",
|
accessorKey: "auth_methods",
|
||||||
header: t("userName", "Username"),
|
header: "设备码/邮箱",
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const method = row.original.auth_methods?.[0];
|
const method = row.original.auth_methods?.[0];
|
||||||
const identifier = method?.auth_identifier || "";
|
const identifier = method?.auth_identifier || "";
|
||||||
const isDevice = method?.auth_type === "device";
|
const isDevice = method?.auth_type === "device";
|
||||||
const deviceNo = (row.original.user_devices?.[0] as any)?.device_no;
|
const firstDevice = row.original.user_devices?.[0] as
|
||||||
|
| UserDeviceWithDeviceNo
|
||||||
|
| undefined;
|
||||||
|
const deviceNo = firstDevice?.device_no;
|
||||||
|
const deviceType = parseDeviceType(firstDevice?.user_agent || "");
|
||||||
const display = isDevice ? deviceNo || identifier : identifier;
|
const display = isDevice ? deviceNo || identifier : identifier;
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="flex items-center">
|
||||||
<Badge
|
{/* <Badge
|
||||||
className="mr-1 uppercase"
|
className="mr-1 uppercase"
|
||||||
title={method?.verified ? t("verified", "Verified") : ""}
|
title={method?.verified ? t("verified", "Verified") : ""}
|
||||||
>
|
>
|
||||||
{method?.auth_type}
|
{method?.auth_type}
|
||||||
</Badge>
|
</Badge>*/}
|
||||||
|
{deviceType && (
|
||||||
|
<Badge className="mr-1" variant="secondary">
|
||||||
|
{deviceType}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
<span title={isDevice ? display : undefined}>{display}</span>
|
<span title={isDevice ? display : undefined}>{display}</span>
|
||||||
|
<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>
|
</div>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
/* {
|
||||||
id: "balance",
|
id: "balance",
|
||||||
accessorKey: "balance",
|
accessorKey: "balance",
|
||||||
header: t("balance", "Balance"),
|
header: t("balance", "Balance"),
|
||||||
@@ -279,7 +334,7 @@ export default function User() {
|
|||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<Display type="currency" value={row.getValue("gift_amount")} />
|
<Display type="currency" value={row.getValue("gift_amount")} />
|
||||||
),
|
),
|
||||||
},
|
},*/
|
||||||
{
|
{
|
||||||
id: "commission",
|
id: "commission",
|
||||||
accessorKey: "commission",
|
accessorKey: "commission",
|
||||||
@@ -342,39 +397,10 @@ export default function User() {
|
|||||||
}}
|
}}
|
||||||
initialFilters={initialFilters}
|
initialFilters={initialFilters}
|
||||||
key={initialFilters.user_id}
|
key={initialFilters.user_id}
|
||||||
params={[
|
request={async (pagination) => {
|
||||||
{
|
|
||||||
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) => {
|
|
||||||
const { data } = await getUserList({
|
const { data } = await getUserList({
|
||||||
...pagination,
|
...pagination,
|
||||||
...filter,
|
...buildSearchParams(),
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
list: data.data?.list || [],
|
list: data.data?.list || [],
|
||||||
@@ -549,12 +575,11 @@ function UserSearchBar({
|
|||||||
}}
|
}}
|
||||||
value={searchType}
|
value={searchType}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-24">
|
<SelectTrigger className="w-48">
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="email">{t("email", "Email")}</SelectItem>
|
<SelectItem value="email">设备码/邮箱</SelectItem>
|
||||||
<SelectItem value="device">{t("deviceSearch", "Device")}</SelectItem>
|
|
||||||
<SelectItem value="user_id">{t("userId", "User ID")}</SelectItem>
|
<SelectItem value="user_id">{t("userId", "User ID")}</SelectItem>
|
||||||
<SelectItem value="subscribe_id">
|
<SelectItem value="subscribe_id">
|
||||||
{t("subscription", "Subscription")}
|
{t("subscription", "Subscription")}
|
||||||
@@ -639,16 +664,19 @@ function PreviewNodesDialog({ userId }: { userId: number }) {
|
|||||||
) : previewData ? (
|
) : previewData ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
<span className="font-medium text-muted-foreground text-sm">
|
||||||
{t("availableNodes", "Available Nodes")}:
|
{t("availableNodes", "Available Nodes")}:
|
||||||
</span>{" "}
|
</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>
|
</div>
|
||||||
{previewData.node_groups && previewData.node_groups.length > 0 ? (
|
{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) => (
|
{previewData.node_groups.map((group) => (
|
||||||
<div key={group.id}>
|
<div key={group.id}>
|
||||||
<h4 className="text-sm font-semibold mb-2">
|
<h4 className="mb-2 font-semibold text-sm">
|
||||||
{group.name ||
|
{group.name ||
|
||||||
(group.id === -1
|
(group.id === -1
|
||||||
? t("subscriptionNodes", "Subscription Nodes")
|
? t("subscriptionNodes", "Subscription Nodes")
|
||||||
@@ -661,16 +689,22 @@ function PreviewNodesDialog({ userId }: { userId: number }) {
|
|||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b">
|
<tr className="border-b">
|
||||||
<th className="p-2 text-left font-medium">ID</th>
|
<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">
|
||||||
<th className="p-2 text-left font-medium">{t("address", "Address")}</th>
|
{t("name", "Name")}
|
||||||
|
</th>
|
||||||
|
<th className="p-2 text-left font-medium">
|
||||||
|
{t("address", "Address")}
|
||||||
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{group.nodes.map((node) => (
|
{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.id}</td>
|
||||||
<td className="p-2">{node.name}</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>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</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,7 +12,6 @@ import {
|
|||||||
getUserDetail,
|
getUserDetail,
|
||||||
getUserSubscribeById,
|
getUserSubscribeById,
|
||||||
} from "@workspace/ui/services/admin/user";
|
} from "@workspace/ui/services/admin/user";
|
||||||
import { shortenDeviceIdentifier } from "@workspace/ui/utils/device";
|
|
||||||
import { formatBytes } from "@workspace/ui/utils/formatting";
|
import { formatBytes } from "@workspace/ui/utils/formatting";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Display } from "@/components/display";
|
import { Display } from "@/components/display";
|
||||||
@@ -103,7 +102,9 @@ export function UserSubscribeDetail({
|
|||||||
</span>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
<li className="flex items-center justify-between">
|
<li className="flex items-center justify-between">
|
||||||
<span className="text-muted-foreground">{t("remainingTraffic")}</span>
|
<span className="text-muted-foreground">
|
||||||
|
{t("remainingTraffic")}
|
||||||
|
</span>
|
||||||
<span>
|
<span>
|
||||||
{data
|
{data
|
||||||
? totalTraffic === 0
|
? totalTraffic === 0
|
||||||
@@ -228,21 +229,29 @@ export function UserDetail({ id }: { id: number }) {
|
|||||||
|
|
||||||
if (!id) return "--";
|
if (!id) return "--";
|
||||||
|
|
||||||
const emailMethod = data?.auth_methods.find((m) => m.auth_type === "email");
|
|
||||||
const firstMethod = data?.auth_methods[0];
|
const firstMethod = data?.auth_methods[0];
|
||||||
const rawIdentifier =
|
const isDevice = firstMethod?.auth_type === "device";
|
||||||
emailMethod?.auth_identifier || firstMethod?.auth_identifier || "";
|
const deviceNo = (data as any)?.user_devices?.[0]?.device_no;
|
||||||
const isDevice = !emailMethod && firstMethod?.auth_type === "device";
|
const rawIdentifier = firstMethod?.auth_identifier || "";
|
||||||
const identifier = isDevice
|
const identifier = isDevice ? deviceNo || rawIdentifier : rawIdentifier;
|
||||||
? shortenDeviceIdentifier(rawIdentifier)
|
|
||||||
: rawIdentifier;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HoverCard>
|
<HoverCard>
|
||||||
<HoverCardTrigger asChild>
|
<HoverCardTrigger asChild>
|
||||||
<Button asChild className="p-0" variant="link">
|
<Button asChild className="p-0" variant="link">
|
||||||
<Link search={{ user_id: id }} to="/dashboard/user">
|
<Link search={{ user_id: id }} to="/dashboard/user">
|
||||||
{identifier || t("loading", "Loading...")}
|
{data ? (
|
||||||
|
<>
|
||||||
|
{firstMethod && (
|
||||||
|
<span className="mr-1 inline-flex items-center rounded border px-1 py-0.5 font-mono text-xs uppercase">
|
||||||
|
{firstMethod.auth_type}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{identifier}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
t("loading", "Loading...")
|
||||||
|
)}
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</HoverCardTrigger>
|
</HoverCardTrigger>
|
||||||
|
|||||||
@@ -59,8 +59,8 @@ export default function UserForm<T extends Record<string, any>>({
|
|||||||
referral_percentage: z.number().optional(),
|
referral_percentage: z.number().optional(),
|
||||||
only_first_purchase: z.boolean().optional(),
|
only_first_purchase: z.boolean().optional(),
|
||||||
is_admin: z.boolean().optional(),
|
is_admin: z.boolean().optional(),
|
||||||
balance: z.number().optional(),
|
// balance: z.number().optional(),
|
||||||
gift_amount: z.number().optional(),
|
// gift_amount: z.number().optional(),
|
||||||
commission: z.number().optional(),
|
commission: z.number().optional(),
|
||||||
});
|
});
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
@@ -282,7 +282,7 @@ export default function UserForm<T extends Record<string, any>>({
|
|||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<FormField
|
{/* <FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="balance"
|
name="balance"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
@@ -309,8 +309,8 @@ export default function UserForm<T extends Record<string, any>>({
|
|||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/> */}
|
||||||
<FormField
|
{/* <FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="gift_amount"
|
name="gift_amount"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
@@ -340,7 +340,7 @@ export default function UserForm<T extends Record<string, any>>({
|
|||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/> */}
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="commission"
|
name="commission"
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ const notifySettingsSchema = z.object({
|
|||||||
enable_balance_notify: z.boolean(),
|
enable_balance_notify: z.boolean(),
|
||||||
enable_login_notify: z.boolean(),
|
enable_login_notify: z.boolean(),
|
||||||
enable_subscribe_notify: z.boolean(),
|
enable_subscribe_notify: z.boolean(),
|
||||||
enable_trade_notify: z.boolean(),
|
// enable_trade_notify: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type NotifySettingsValues = z.infer<typeof notifySettingsSchema>;
|
type NotifySettingsValues = z.infer<typeof notifySettingsSchema>;
|
||||||
@@ -44,13 +44,14 @@ export function NotifySettingsForm({
|
|||||||
enable_balance_notify: user.enable_balance_notify,
|
enable_balance_notify: user.enable_balance_notify,
|
||||||
enable_login_notify: user.enable_login_notify,
|
enable_login_notify: user.enable_login_notify,
|
||||||
enable_subscribe_notify: user.enable_subscribe_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) {
|
async function onSubmit(data: NotifySettingsValues) {
|
||||||
await updateUserNotifySetting({
|
await updateUserNotifySetting({
|
||||||
...data,
|
...data,
|
||||||
|
enable_trade_notify: user.enable_trade_notify ?? false,
|
||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
});
|
});
|
||||||
toast.success(t("updateSuccess", "Updated successfully"));
|
toast.success(t("updateSuccess", "Updated successfully"));
|
||||||
@@ -126,7 +127,7 @@ export function NotifySettingsForm({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<FormField
|
{/* <FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="enable_trade_notify"
|
name="enable_trade_notify"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
@@ -142,7 +143,7 @@ export function NotifySettingsForm({
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/> */}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -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 { Alert, AlertDescription } from "@workspace/ui/components/alert";
|
||||||
import { Badge } from "@workspace/ui/components/badge";
|
import { Badge } from "@workspace/ui/components/badge";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
@@ -42,6 +42,7 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const ref = useRef<ProTableActions>(null);
|
const ref = useRef<ProTableActions>(null);
|
||||||
const [sharedInfo, setSharedInfo] = useState<SharedInfo | null>(null);
|
const [sharedInfo, setSharedInfo] = useState<SharedInfo | null>(null);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const request = useCallback(
|
const request = useCallback(
|
||||||
async (pagination: { page: number; size: number }) => {
|
async (pagination: { page: number; size: number }) => {
|
||||||
@@ -116,19 +117,23 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
|||||||
<span className="flex gap-2">
|
<span className="flex gap-2">
|
||||||
<Button asChild size="sm" variant="outline">
|
<Button asChild size="sm" variant="outline">
|
||||||
<Link
|
<Link
|
||||||
search={{ user_id: String(sharedInfo.ownerUserId) }}
|
search={{ user_id: sharedInfo.ownerUserId }}
|
||||||
to="/dashboard/family"
|
to="/dashboard/family"
|
||||||
>
|
>
|
||||||
{t("viewDeviceGroup", "View Device Group")}
|
{t("viewDeviceGroup", "View Device Group")}
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
<Button asChild size="sm" variant="outline">
|
<Button
|
||||||
<Link
|
onClick={() => {
|
||||||
search={{ user_id: String(sharedInfo.ownerUserId) }}
|
navigate({
|
||||||
to="/dashboard/user"
|
to: "/dashboard/user",
|
||||||
>
|
search: { user_id: sharedInfo.ownerUserId },
|
||||||
{t("viewOwner", "View Owner")}
|
});
|
||||||
</Link>
|
}}
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
{t("viewOwner", "View Owner")}
|
||||||
</Button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
</AlertDescription>
|
</AlertDescription>
|
||||||
@@ -280,7 +285,8 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
|||||||
const upload = row.original.upload || 0;
|
const upload = row.original.upload || 0;
|
||||||
const download = row.original.download || 0;
|
const download = row.original.download || 0;
|
||||||
const totalTraffic = row.original.traffic || 0;
|
const totalTraffic = row.original.traffic || 0;
|
||||||
const remainingTraffic = totalTraffic > 0 ? totalTraffic - upload - download : 0;
|
const remainingTraffic =
|
||||||
|
totalTraffic > 0 ? totalTraffic - upload - download : 0;
|
||||||
return (
|
return (
|
||||||
<Display type="traffic" unlimited value={remainingTraffic} />
|
<Display type="traffic" unlimited value={remainingTraffic} />
|
||||||
);
|
);
|
||||||
@@ -323,6 +329,11 @@ export default function UserSubscription({ userId }: { userId: number }) {
|
|||||||
: t("permanent", "Permanent");
|
: t("permanent", "Permanent");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "node_group_name",
|
||||||
|
header: t("nodeGroup", "Node Group"),
|
||||||
|
cell: ({ row }) => row.original.node_group_name || "-",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "created_at",
|
accessorKey: "created_at",
|
||||||
header: t("createdAt", "Created At"),
|
header: t("createdAt", "Created At"),
|
||||||
@@ -630,7 +641,7 @@ function RowMoreActions({
|
|||||||
"This action cannot be undone."
|
"This action cannot be undone."
|
||||||
)}
|
)}
|
||||||
onConfirm={async () => {
|
onConfirm={async () => {
|
||||||
await deleteUserSubscribe({ user_subscribe_id: String(row.id) });
|
await deleteUserSubscribe({ user_subscribe_id: row.id });
|
||||||
toast.success(t("deleteSuccess", "Deleted successfully"));
|
toast.success(t("deleteSuccess", "Deleted successfully"));
|
||||||
refresh();
|
refresh();
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -11,16 +11,92 @@ import { Switch } from "@workspace/ui/components/switch";
|
|||||||
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
import { ConfirmButton } from "@workspace/ui/composed/confirm-button";
|
||||||
import { ProTable } from "@workspace/ui/composed/pro-table/pro-table";
|
import { ProTable } from "@workspace/ui/composed/pro-table/pro-table";
|
||||||
import {
|
import {
|
||||||
|
getUserSubscribeById,
|
||||||
getUserSubscribeDevices,
|
getUserSubscribeDevices,
|
||||||
kickOfflineByUserDevice,
|
kickOfflineByUserDevice,
|
||||||
} from "@workspace/ui/services/admin/user";
|
} from "@workspace/ui/services/admin/user";
|
||||||
import { deviceIdToHash } from "@workspace/ui/utils/device";
|
import { deviceIdToHash } from "@workspace/ui/utils/device";
|
||||||
import { type ReactNode, useState } from "react";
|
import { AlertTriangle, Gauge } from "lucide-react";
|
||||||
|
import { type ReactNode, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { IpLink } from "@/components/ip-link";
|
import { IpLink } from "@/components/ip-link";
|
||||||
import { formatDate } from "@/utils/common";
|
import { formatDate } from "@/utils/common";
|
||||||
|
|
||||||
|
function SpeedLimitCard({ subscriptionId }: { subscriptionId: number }) {
|
||||||
|
const { t } = useTranslation("user");
|
||||||
|
const [detail, setDetail] = useState<API.UserSubscribeDetail | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getUserSubscribeById({ id: subscriptionId }).then(({ data }) => {
|
||||||
|
if (data.data) setDetail(data.data);
|
||||||
|
});
|
||||||
|
}, [subscriptionId]);
|
||||||
|
|
||||||
|
if (!detail || detail.status !== 1) return null;
|
||||||
|
|
||||||
|
const baseSpeed = detail.subscribe?.speed_limit ?? 0;
|
||||||
|
const effectiveSpeed = detail.effective_speed ?? 0;
|
||||||
|
const isThrottled = detail.is_throttled;
|
||||||
|
|
||||||
|
if (baseSpeed === 0 && !isThrottled) return null;
|
||||||
|
|
||||||
|
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="space-y-1">
|
||||||
|
<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">
|
||||||
|
{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>
|
||||||
|
{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>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function SubscriptionDetail({
|
export function SubscriptionDetail({
|
||||||
trigger,
|
trigger,
|
||||||
userId,
|
userId,
|
||||||
@@ -44,6 +120,7 @@ export function SubscriptionDetail({
|
|||||||
<SheetTitle>{t("onlineDevices", "Online Devices")}</SheetTitle>
|
<SheetTitle>{t("onlineDevices", "Online Devices")}</SheetTitle>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
<div className="mt-4 max-h-[calc(100dvh-120px)] overflow-y-auto">
|
<div className="mt-4 max-h-[calc(100dvh-120px)] overflow-y-auto">
|
||||||
|
{open && <SpeedLimitCard subscriptionId={subscriptionId} />}
|
||||||
<ProTable<API.UserDevice, Record<string, unknown>>
|
<ProTable<API.UserDevice, Record<string, unknown>>
|
||||||
actions={{
|
actions={{
|
||||||
render: (row) => {
|
render: (row) => {
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
"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 rejectSchema = z.object({
|
||||||
|
reason: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(2, "请填写拒绝原因")
|
||||||
|
.max(500, "拒绝原因不能超过 500 个字符"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default function WithdrawalPage() {
|
||||||
|
const { t } = useTranslation("user");
|
||||||
|
const ref = useRef<ProTableActions>(null);
|
||||||
|
const [rejectOpen, setRejectOpen] = useState(false);
|
||||||
|
const [currentRow, setCurrentRow] = useState<API.WithdrawalLog | 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: "已拒绝" },
|
||||||
|
];
|
||||||
|
|
||||||
|
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",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ProTable<API.WithdrawalLog, { status?: string; user_id?: 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: "content",
|
||||||
|
header: "收款信息",
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="max-w-[360px] 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: "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,
|
||||||
|
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
|
// Unix timestamps (seconds): 10 digits e.g. 1771936457
|
||||||
// JavaScript timestamps (milliseconds): 13 digits
|
// JavaScript timestamps (milliseconds): 13 digits
|
||||||
let dateValue = date;
|
let dateValue = date;
|
||||||
if (typeof date === "number") {
|
if (typeof date === "number" && date < 10_000_000_000) {
|
||||||
if (date < 10000000000) {
|
dateValue = date * 1000;
|
||||||
dateValue = date * 1000;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const timeZone = localStorage.getItem("timezone") || "UTC";
|
const timeZone = localStorage.getItem("timezone") || "UTC";
|
||||||
return intlFormat(dateValue, {
|
return intlFormat(dateValue, {
|
||||||
year: "numeric",
|
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",
|
"commissionInfo": "Commission Info",
|
||||||
"commissionRate": "Commission Rate",
|
"commissionRate": "Commission Rate",
|
||||||
"copyInviteLink": "Copy Invite Link",
|
"copyInviteLink": "Copy Invite Link",
|
||||||
"copySuccess": "Copy Success",
|
"copySuccess": "Copy Success",
|
||||||
|
"currentCommission": "Current Commission",
|
||||||
"inviteCode": "Invite Code",
|
"inviteCode": "Invite Code",
|
||||||
"inviteRecords": "Invite Records",
|
"inviteRecords": "Invite Records",
|
||||||
|
"noReason": "None",
|
||||||
|
"rejectReason": "Reject Reason",
|
||||||
"registrationTime": "Registration Time",
|
"registrationTime": "Registration Time",
|
||||||
|
"submitWithdraw": "Submit Request",
|
||||||
|
"submitting": "Submitting...",
|
||||||
"totalCommission": "Total Commission",
|
"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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,21 @@
|
|||||||
"noImage": "No Image",
|
"noImage": "No Image",
|
||||||
"placeholder": "Enter captcha code...",
|
"placeholder": "Enter captcha code...",
|
||||||
"refresh": "Refresh captcha",
|
"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"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"get": "Get Code",
|
"get": "Get Code",
|
||||||
"login": {
|
"login": {
|
||||||
|
|||||||
@@ -1,11 +1,37 @@
|
|||||||
{
|
{
|
||||||
|
"accountInfo": "收款信息",
|
||||||
|
"accountPlaceholder": "请输入银行卡、支付宝、USDT 地址等收款信息",
|
||||||
|
"accountRequired": "请填写收款信息",
|
||||||
|
"accountTooLong": "收款信息不能超过 200 个字符",
|
||||||
|
"amountInvalid": "请输入有效金额",
|
||||||
|
"amountPositive": "提现金额必须大于 0",
|
||||||
|
"applyTime": "申请时间",
|
||||||
|
"applyWithdraw": "申请提现",
|
||||||
|
"cancel": "取消",
|
||||||
"commissionInfo": "佣金信息",
|
"commissionInfo": "佣金信息",
|
||||||
"commissionRate": "佣金比例",
|
"commissionRate": "佣金比例",
|
||||||
"copyInviteLink": "复制邀请链接",
|
"copyInviteLink": "复制邀请链接",
|
||||||
"copySuccess": "复制成功",
|
"copySuccess": "复制成功",
|
||||||
|
"currentCommission": "当前可见佣金",
|
||||||
"inviteCode": "邀请码",
|
"inviteCode": "邀请码",
|
||||||
"inviteRecords": "邀请记录",
|
"inviteRecords": "邀请记录",
|
||||||
|
"noReason": "无",
|
||||||
|
"rejectReason": "拒绝原因",
|
||||||
"registrationTime": "注册时间",
|
"registrationTime": "注册时间",
|
||||||
|
"submitWithdraw": "提交申请",
|
||||||
|
"submitting": "提交中...",
|
||||||
"totalCommission": "累计佣金",
|
"totalCommission": "累计佣金",
|
||||||
"userIdentifier": "用户标识"
|
"unknownStatus": "未知状态",
|
||||||
|
"userIdentifier": "用户标识",
|
||||||
|
"withdrawAmount": "提现金额",
|
||||||
|
"withdrawAmountPlaceholder": "请输入提现金额,单位为元",
|
||||||
|
"withdrawDescription": "填写提现金额和收款信息后提交申请,等待后台审核。",
|
||||||
|
"withdrawError": "提现申请提交失败",
|
||||||
|
"withdrawRecords": "提现记录",
|
||||||
|
"withdrawStatus": {
|
||||||
|
"approved": "已通过",
|
||||||
|
"pending": "审核中",
|
||||||
|
"rejected": "已拒绝"
|
||||||
|
},
|
||||||
|
"withdrawSuccess": "提现申请已提交"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,21 @@
|
|||||||
"noImage": "无图片",
|
"noImage": "无图片",
|
||||||
"placeholder": "请输入验证码...",
|
"placeholder": "请输入验证码...",
|
||||||
"refresh": "刷新验证码",
|
"refresh": "刷新验证码",
|
||||||
"required": "请输入验证码"
|
"required": "请输入验证码",
|
||||||
|
"sliderRequired": "请完成滑块验证",
|
||||||
|
"slider": {
|
||||||
|
"clickToVerify": "点击进行验证",
|
||||||
|
"fail": "请重试",
|
||||||
|
"hint": "拖动拼图块到对应位置",
|
||||||
|
"success": "验证成功",
|
||||||
|
"title": "安全验证"
|
||||||
|
},
|
||||||
|
"turnstile": {
|
||||||
|
"cancel": "取消",
|
||||||
|
"clickToVerify": "点击进行验证",
|
||||||
|
"success": "验证成功",
|
||||||
|
"title": "安全验证"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"get": "获取验证码",
|
"get": "获取验证码",
|
||||||
"login": {
|
"login": {
|
||||||
|
|||||||
@@ -15,9 +15,10 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function LoginForm({
|
export default function LoginForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -39,6 +40,7 @@ export default function LoginForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_login_captcha;
|
const captchaEnabled = verify.enable_user_login_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -52,14 +54,26 @@ export default function LoginForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().optional(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -70,6 +84,7 @@ export default function LoginForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -84,7 +99,10 @@ export default function LoginForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("login.emailPlaceholder", "Enter your email...")}
|
placeholder={t(
|
||||||
|
"login.emailPlaceholder",
|
||||||
|
"Enter your email..."
|
||||||
|
)}
|
||||||
type="email"
|
type="email"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -100,7 +118,10 @@ export default function LoginForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("login.passwordPlaceholder", "Enter your password...")}
|
placeholder={t(
|
||||||
|
"login.passwordPlaceholder",
|
||||||
|
"Enter your password..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -136,8 +157,8 @@ export default function LoginForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -145,6 +166,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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("login.title", "Login")}
|
{t("login.title", "Login")}
|
||||||
|
|||||||
@@ -16,10 +16,11 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
import SendCode from "../send-code";
|
import SendCode from "../send-code";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function RegisterForm({
|
export default function RegisterForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -41,6 +42,7 @@ export default function RegisterForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_register_captcha;
|
const captchaEnabled = verify.enable_user_register_captcha;
|
||||||
|
|
||||||
const handleCheckUser = async (email: string) => {
|
const handleCheckUser = async (email: string) => {
|
||||||
@@ -78,8 +80,16 @@ export default function RegisterForm({
|
|||||||
: z.string().nullish(),
|
: z.string().nullish(),
|
||||||
captcha_code:
|
captcha_code:
|
||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z
|
||||||
|
.string()
|
||||||
|
.min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().nullish(),
|
: z.string().nullish(),
|
||||||
|
slider_token:
|
||||||
|
captchaEnabled && isSlider
|
||||||
|
? z
|
||||||
|
.string()
|
||||||
|
.min(1, t("captcha.sliderRequired", "Please complete the slider"))
|
||||||
|
: z.string().optional(),
|
||||||
})
|
})
|
||||||
.superRefine(({ password, repeat_password }, ctx) => {
|
.superRefine(({ password, repeat_password }, ctx) => {
|
||||||
if (password !== repeat_password) {
|
if (password !== repeat_password) {
|
||||||
@@ -94,6 +104,9 @@ export default function RegisterForm({
|
|||||||
const form = useForm<z.infer<typeof formSchema>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
...initialValues,
|
...initialValues,
|
||||||
invite: localStorage.getItem("invite") || "",
|
invite: localStorage.getItem("invite") || "",
|
||||||
},
|
},
|
||||||
@@ -101,6 +114,7 @@ export default function RegisterForm({
|
|||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -111,6 +125,7 @@ export default function RegisterForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -130,7 +145,10 @@ export default function RegisterForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("register.emailPlaceholder", "Enter your email...")}
|
placeholder={t(
|
||||||
|
"register.emailPlaceholder",
|
||||||
|
"Enter your email..."
|
||||||
|
)}
|
||||||
type="email"
|
type="email"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -146,7 +164,10 @@ export default function RegisterForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("register.passwordPlaceholder", "Enter your password...")}
|
placeholder={t(
|
||||||
|
"register.passwordPlaceholder",
|
||||||
|
"Enter your password..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -163,7 +184,10 @@ export default function RegisterForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
placeholder={t("register.repeatPasswordPlaceholder", "Enter password again...")}
|
placeholder={t(
|
||||||
|
"register.repeatPasswordPlaceholder",
|
||||||
|
"Enter password again..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -182,7 +206,10 @@ export default function RegisterForm({
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
placeholder={t("register.codePlaceholder", "Enter code...")}
|
placeholder={t(
|
||||||
|
"register.codePlaceholder",
|
||||||
|
"Enter code..."
|
||||||
|
)}
|
||||||
type="text"
|
type="text"
|
||||||
{...field}
|
{...field}
|
||||||
value={field.value as string}
|
value={field.value as string}
|
||||||
@@ -248,8 +275,8 @@ export default function RegisterForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -257,6 +284,20 @@ export default function RegisterForm({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("register.title", "Register")}
|
{t("register.title", "Register")}
|
||||||
|
|||||||
@@ -15,10 +15,11 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
import SendCode from "../send-code";
|
import SendCode from "../send-code";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function ResetForm({
|
export default function ResetForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -41,6 +42,7 @@ export default function ResetForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -57,14 +59,26 @@ export default function ResetForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().nullish(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -75,6 +89,7 @@ export default function ResetForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,7 +104,10 @@ export default function ResetForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("reset.emailPlaceholder", "Enter your email...")}
|
placeholder={t(
|
||||||
|
"reset.emailPlaceholder",
|
||||||
|
"Enter your email..."
|
||||||
|
)}
|
||||||
type="email"
|
type="email"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -132,7 +150,10 @@ export default function ResetForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("reset.passwordPlaceholder", "Enter your new password...")}
|
placeholder={t(
|
||||||
|
"reset.passwordPlaceholder",
|
||||||
|
"Enter your new password..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -168,8 +189,8 @@ export default function ResetForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -177,6 +198,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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("reset.title", "Reset Password")}
|
{t("reset.title", "Reset Password")}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Button } from "@workspace/ui/components/button";
|
|||||||
import { Input } from "@workspace/ui/components/input";
|
import { Input } from "@workspace/ui/components/input";
|
||||||
import { Icon } from "@workspace/ui/composed/icon";
|
import { Icon } from "@workspace/ui/composed/icon";
|
||||||
import { generateCaptcha } from "@workspace/ui/services/common/auth";
|
import { generateCaptcha } from "@workspace/ui/services/common/auth";
|
||||||
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
|
import { useEffect, useImperativeHandle, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
export interface LocalCaptchaRef {
|
export interface LocalCaptchaRef {
|
||||||
@@ -15,80 +15,85 @@ interface LocalCaptchaProps {
|
|||||||
onCaptchaIdChange?: (id: string) => void;
|
onCaptchaIdChange?: (id: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const LocalCaptcha = forwardRef<LocalCaptchaRef, LocalCaptchaProps>(
|
const LocalCaptcha = ({
|
||||||
({ value, onChange, onCaptchaIdChange }, ref) => {
|
value,
|
||||||
const { t } = useTranslation("auth");
|
onChange,
|
||||||
const [captchaImage, setCaptchaImage] = useState("");
|
onCaptchaIdChange,
|
||||||
const [loading, setLoading] = useState(false);
|
ref,
|
||||||
|
}: LocalCaptchaProps & { ref?: RefObject<LocalCaptchaRef | null> }) => {
|
||||||
|
const { t } = useTranslation("auth");
|
||||||
|
const [captchaImage, setCaptchaImage] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
const fetchCaptcha = async () => {
|
const fetchCaptcha = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await generateCaptcha();
|
const res = await generateCaptcha();
|
||||||
const captchaData = res.data?.data;
|
const captchaData = res.data?.data;
|
||||||
if (captchaData) {
|
if (captchaData) {
|
||||||
setCaptchaImage(captchaData.image);
|
setCaptchaImage(captchaData.image);
|
||||||
onCaptchaIdChange?.(captchaData.id);
|
onCaptchaIdChange?.(captchaData.id);
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to generate captcha:", error);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
} catch (error) {
|
||||||
|
console.error("Failed to generate captcha:", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
fetchCaptcha();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useImperativeHandle(ref, () => ({
|
||||||
|
reset: () => {
|
||||||
|
onChange?.("");
|
||||||
fetchCaptcha();
|
fetchCaptcha();
|
||||||
}, []);
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
return (
|
||||||
reset: () => {
|
<div className="flex gap-2">
|
||||||
onChange?.("");
|
<Input
|
||||||
fetchCaptcha();
|
className="flex-1"
|
||||||
},
|
onChange={(e) => onChange?.(e.target.value)}
|
||||||
}));
|
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
||||||
|
value={value || ""}
|
||||||
return (
|
/>
|
||||||
<div className="flex gap-2">
|
<div className="relative h-10 w-32 flex-shrink-0">
|
||||||
<Input
|
{loading ? (
|
||||||
placeholder={t("captcha.placeholder", "Enter captcha code...")}
|
<div className="flex h-full items-center justify-center bg-muted">
|
||||||
value={value || ""}
|
<Icon className="animate-spin" icon="mdi:loading" />
|
||||||
onChange={(e) => onChange?.(e.target.value)}
|
</div>
|
||||||
className="flex-1"
|
) : captchaImage ? (
|
||||||
/>
|
<img
|
||||||
<div className="relative h-10 w-32 flex-shrink-0">
|
alt="captcha"
|
||||||
{loading ? (
|
className="h-full w-full cursor-pointer object-contain"
|
||||||
<div className="flex h-full items-center justify-center bg-muted">
|
height={40}
|
||||||
<Icon className="animate-spin" icon="mdi:loading" />
|
onClick={fetchCaptcha}
|
||||||
</div>
|
src={captchaImage}
|
||||||
) : captchaImage ? (
|
title={t("captcha.clickToRefresh", "Click to refresh")}
|
||||||
<img
|
width={120}
|
||||||
src={captchaImage}
|
/>
|
||||||
alt="captcha"
|
) : (
|
||||||
className="h-full w-full cursor-pointer object-contain"
|
<div className="flex h-full items-center justify-center bg-muted text-muted-foreground text-xs">
|
||||||
onClick={fetchCaptcha}
|
{t("captcha.noImage", "No Image")}
|
||||||
title={t("captcha.clickToRefresh", "Click to refresh")}
|
</div>
|
||||||
/>
|
)}
|
||||||
) : (
|
|
||||||
<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>
|
|
||||||
</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";
|
LocalCaptcha.displayName = "LocalCaptcha";
|
||||||
|
|
||||||
|
|||||||
@@ -16,10 +16,11 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
import SendCode from "../send-code";
|
import SendCode from "../send-code";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function LoginForm({
|
export default function LoginForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -39,6 +40,7 @@ export default function LoginForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_login_captcha;
|
const captchaEnabled = verify.enable_user_login_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -54,16 +56,28 @@ export default function LoginForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().optional(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const [mode, setMode] = useState<"password" | "code">("password");
|
const [mode, setMode] = useState<"password" | "code">("password");
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -74,6 +88,7 @@ export default function LoginForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -104,7 +119,10 @@ export default function LoginForm({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
placeholder={t("register.areaCodePlaceholder", "Area code...")}
|
placeholder={t(
|
||||||
|
"register.areaCodePlaceholder",
|
||||||
|
"Area code..."
|
||||||
|
)}
|
||||||
simple
|
simple
|
||||||
value={field.value}
|
value={field.value}
|
||||||
/>
|
/>
|
||||||
@@ -115,7 +133,10 @@ export default function LoginForm({
|
|||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
className="rounded-l-none"
|
className="rounded-l-none"
|
||||||
placeholder={t("register.telephonePlaceholder", "Enter your telephone...")}
|
placeholder={t(
|
||||||
|
"register.telephonePlaceholder",
|
||||||
|
"Enter your telephone..."
|
||||||
|
)}
|
||||||
type="tel"
|
type="tel"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -137,7 +158,10 @@ export default function LoginForm({
|
|||||||
placeholder={
|
placeholder={
|
||||||
mode === "code"
|
mode === "code"
|
||||||
? t("register.codePlaceholder", "Enter code...")
|
? t("register.codePlaceholder", "Enter code...")
|
||||||
: t("login.passwordPlaceholder", "Enter your password...")
|
: t(
|
||||||
|
"login.passwordPlaceholder",
|
||||||
|
"Enter your password..."
|
||||||
|
)
|
||||||
}
|
}
|
||||||
type={mode === "code" ? "text" : "password"}
|
type={mode === "code" ? "text" : "password"}
|
||||||
{...field}
|
{...field}
|
||||||
@@ -202,8 +226,8 @@ export default function LoginForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -211,6 +235,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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("login.title", "Login")}
|
{t("login.title", "Login")}
|
||||||
|
|||||||
@@ -17,10 +17,11 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
import SendCode from "../send-code";
|
import SendCode from "../send-code";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function RegisterForm({
|
export default function RegisterForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -41,6 +42,7 @@ export default function RegisterForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_register_captcha;
|
const captchaEnabled = verify.enable_user_register_captcha;
|
||||||
|
|
||||||
const formSchema = z
|
const formSchema = z
|
||||||
@@ -57,8 +59,16 @@ export default function RegisterForm({
|
|||||||
: z.string().nullish(),
|
: z.string().nullish(),
|
||||||
captcha_code:
|
captcha_code:
|
||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z
|
||||||
|
.string()
|
||||||
|
.min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().nullish(),
|
: z.string().nullish(),
|
||||||
|
slider_token:
|
||||||
|
captchaEnabled && isSlider
|
||||||
|
? z
|
||||||
|
.string()
|
||||||
|
.min(1, t("captcha.sliderRequired", "Please complete the slider"))
|
||||||
|
: z.string().optional(),
|
||||||
})
|
})
|
||||||
.superRefine(({ password, repeat_password }, ctx) => {
|
.superRefine(({ password, repeat_password }, ctx) => {
|
||||||
if (password !== repeat_password) {
|
if (password !== repeat_password) {
|
||||||
@@ -73,6 +83,9 @@ export default function RegisterForm({
|
|||||||
const form = useForm<z.infer<typeof formSchema>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
...initialValues,
|
...initialValues,
|
||||||
telephone_area_code: initialValues?.telephone_area_code || "1",
|
telephone_area_code: initialValues?.telephone_area_code || "1",
|
||||||
invite: localStorage.getItem("invite") || "",
|
invite: localStorage.getItem("invite") || "",
|
||||||
@@ -81,6 +94,7 @@ export default function RegisterForm({
|
|||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -91,6 +105,7 @@ export default function RegisterForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -126,7 +141,10 @@ export default function RegisterForm({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
placeholder={t("register.areaCodePlaceholder", "Area code...")}
|
placeholder={t(
|
||||||
|
"register.areaCodePlaceholder",
|
||||||
|
"Area code..."
|
||||||
|
)}
|
||||||
simple
|
simple
|
||||||
value={field.value}
|
value={field.value}
|
||||||
whitelist={enable_whitelist ? whitelist : []}
|
whitelist={enable_whitelist ? whitelist : []}
|
||||||
@@ -138,7 +156,10 @@ export default function RegisterForm({
|
|||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
className="rounded-l-none"
|
className="rounded-l-none"
|
||||||
placeholder={t("register.telephonePlaceholder", "Enter your telephone...")}
|
placeholder={t(
|
||||||
|
"register.telephonePlaceholder",
|
||||||
|
"Enter your telephone..."
|
||||||
|
)}
|
||||||
type="tel"
|
type="tel"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -155,7 +176,10 @@ export default function RegisterForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("register.passwordPlaceholder", "Enter your password...")}
|
placeholder={t(
|
||||||
|
"register.passwordPlaceholder",
|
||||||
|
"Enter your password..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -172,7 +196,10 @@ export default function RegisterForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
placeholder={t("register.repeatPasswordPlaceholder", "Enter password again...")}
|
placeholder={t(
|
||||||
|
"register.repeatPasswordPlaceholder",
|
||||||
|
"Enter password again..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -190,7 +217,10 @@ export default function RegisterForm({
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
placeholder={t("register.codePlaceholder", "Enter code...")}
|
placeholder={t(
|
||||||
|
"register.codePlaceholder",
|
||||||
|
"Enter code..."
|
||||||
|
)}
|
||||||
type="text"
|
type="text"
|
||||||
{...field}
|
{...field}
|
||||||
value={field.value as string}
|
value={field.value as string}
|
||||||
@@ -259,8 +289,8 @@ export default function RegisterForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -268,6 +298,20 @@ export default function RegisterForm({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("register.title", "Register")}
|
{t("register.title", "Register")}
|
||||||
|
|||||||
@@ -16,10 +16,11 @@ import { useForm } from "react-hook-form";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
||||||
import SendCode from "../send-code";
|
import SendCode from "../send-code";
|
||||||
|
import SliderCaptcha, { type SliderCaptchaRef } from "../slider-captcha";
|
||||||
import type { TurnstileRef } from "../turnstile";
|
import type { TurnstileRef } from "../turnstile";
|
||||||
import CloudFlareTurnstile from "../turnstile";
|
import CloudFlareTurnstile from "../turnstile";
|
||||||
import LocalCaptcha, { type LocalCaptchaRef } from "../local-captcha";
|
|
||||||
|
|
||||||
export default function ResetForm({
|
export default function ResetForm({
|
||||||
loading,
|
loading,
|
||||||
@@ -41,6 +42,7 @@ export default function ResetForm({
|
|||||||
|
|
||||||
const isTurnstile = verify.captcha_type === "turnstile";
|
const isTurnstile = verify.captcha_type === "turnstile";
|
||||||
const isLocal = verify.captcha_type === "local";
|
const isLocal = verify.captcha_type === "local";
|
||||||
|
const isSlider = verify.captcha_type === "slider";
|
||||||
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
const captchaEnabled = verify.enable_user_reset_password_captcha;
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
@@ -56,14 +58,26 @@ export default function ResetForm({
|
|||||||
captchaEnabled && isLocal
|
captchaEnabled && isLocal
|
||||||
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
? z.string().min(1, t("captcha.required", "Please enter captcha code"))
|
||||||
: z.string().nullish(),
|
: 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>>({
|
const form = useForm<z.infer<typeof formSchema>>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: initialValues,
|
defaultValues: {
|
||||||
|
cf_token: "",
|
||||||
|
captcha_code: "",
|
||||||
|
slider_token: "",
|
||||||
|
...initialValues,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const turnstile = useRef<TurnstileRef>(null);
|
const turnstile = useRef<TurnstileRef>(null);
|
||||||
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
const localCaptcha = useRef<LocalCaptchaRef>(null);
|
||||||
|
const sliderCaptcha = useRef<SliderCaptchaRef>(null);
|
||||||
const handleSubmit = form.handleSubmit((data) => {
|
const handleSubmit = form.handleSubmit((data) => {
|
||||||
try {
|
try {
|
||||||
// Add captcha_id for local captcha
|
// Add captcha_id for local captcha
|
||||||
@@ -74,6 +88,7 @@ export default function ResetForm({
|
|||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
turnstile.current?.reset();
|
turnstile.current?.reset();
|
||||||
localCaptcha.current?.reset();
|
localCaptcha.current?.reset();
|
||||||
|
sliderCaptcha.current?.reset();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -104,7 +119,10 @@ export default function ResetForm({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
placeholder={t("register.areaCodePlaceholder", "Area code...")}
|
placeholder={t(
|
||||||
|
"register.areaCodePlaceholder",
|
||||||
|
"Area code..."
|
||||||
|
)}
|
||||||
simple
|
simple
|
||||||
value={field.value}
|
value={field.value}
|
||||||
/>
|
/>
|
||||||
@@ -115,7 +133,10 @@ export default function ResetForm({
|
|||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
className="rounded-l-none"
|
className="rounded-l-none"
|
||||||
placeholder={t("register.telephonePlaceholder", "Enter your telephone...")}
|
placeholder={t(
|
||||||
|
"register.telephonePlaceholder",
|
||||||
|
"Enter your telephone..."
|
||||||
|
)}
|
||||||
type="tel"
|
type="tel"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -133,7 +154,10 @@ export default function ResetForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("register.codePlaceholder", "Enter code...")}
|
placeholder={t(
|
||||||
|
"register.codePlaceholder",
|
||||||
|
"Enter code..."
|
||||||
|
)}
|
||||||
type="text"
|
type="text"
|
||||||
{...field}
|
{...field}
|
||||||
value={field.value as string}
|
value={field.value as string}
|
||||||
@@ -159,7 +183,10 @@ export default function ResetForm({
|
|||||||
<FormItem>
|
<FormItem>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input
|
<Input
|
||||||
placeholder={t("reset.passwordPlaceholder", "Enter your new password...")}
|
placeholder={t(
|
||||||
|
"reset.passwordPlaceholder",
|
||||||
|
"Enter your new password..."
|
||||||
|
)}
|
||||||
type="password"
|
type="password"
|
||||||
{...field}
|
{...field}
|
||||||
/>
|
/>
|
||||||
@@ -195,8 +222,8 @@ export default function ResetForm({
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<LocalCaptcha
|
<LocalCaptcha
|
||||||
{...field}
|
{...field}
|
||||||
ref={localCaptcha}
|
|
||||||
onCaptchaIdChange={setCaptchaId}
|
onCaptchaIdChange={setCaptchaId}
|
||||||
|
ref={localCaptcha}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
@@ -204,6 +231,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">
|
<Button disabled={loading} type="submit">
|
||||||
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
{loading && <Icon className="animate-spin" icon="mdi:loading" />}
|
||||||
{t("reset.title", "Reset Password")}
|
{t("reset.title", "Reset Password")}
|
||||||
|
|||||||
@@ -0,0 +1,355 @@
|
|||||||
|
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 {
|
||||||
|
generateCaptcha,
|
||||||
|
verifyCaptchaSlider,
|
||||||
|
} from "@workspace/ui/services/common/auth";
|
||||||
|
import { 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 generateCaptcha();
|
||||||
|
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();
|
||||||
|
|
||||||
|
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 verifyCaptchaSlider({
|
||||||
|
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,7 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
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 { 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 { useTranslation } from "react-i18next";
|
||||||
import Turnstile, { useTurnstile } from "react-turnstile";
|
import Turnstile, { useTurnstile } from "react-turnstile";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
@@ -24,47 +37,119 @@ const CloudFlareTurnstile = function CloudFlareTurnstile({
|
|||||||
const { common } = useGlobalStore();
|
const { common } = useGlobalStore();
|
||||||
const { verify } = common;
|
const { verify } = common;
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const { i18n } = useTranslation();
|
const { i18n, t } = useTranslation("auth");
|
||||||
const locale = i18n.language;
|
const locale = i18n.language;
|
||||||
const turnstile = useTurnstile();
|
const turnstile = useTurnstile();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [verified, setVerified] = useState(false);
|
||||||
|
|
||||||
useImperativeHandle(
|
useImperativeHandle(
|
||||||
ref,
|
ref,
|
||||||
() => ({
|
() => ({
|
||||||
reset: () => turnstile.reset(),
|
reset: () => {
|
||||||
|
setVerified(false);
|
||||||
|
onChange("");
|
||||||
|
turnstile.reset();
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
[turnstile]
|
[turnstile, onChange]
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (value === "") {
|
if (value === "") {
|
||||||
|
setVerified(false);
|
||||||
turnstile.reset();
|
turnstile.reset();
|
||||||
}
|
}
|
||||||
}, [turnstile, value]);
|
}, [turnstile, value]);
|
||||||
|
|
||||||
|
const handleOpen = () => {
|
||||||
|
if (verified) return;
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!verify.turnstile_site_key) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
verify.turnstile_site_key && (
|
<>
|
||||||
<Turnstile
|
{/* Trigger button */}
|
||||||
fixedSize
|
<button
|
||||||
id={id}
|
className={`relative flex w-full items-center gap-3 rounded-md border px-4 py-3 text-sm transition-colors ${
|
||||||
language={locale.toLowerCase()}
|
verified
|
||||||
onExpire={() => {
|
? "border-green-400 bg-green-50 text-green-700 dark:bg-green-950/30"
|
||||||
onChange();
|
: "border-input bg-background hover:bg-muted"
|
||||||
turnstile.reset();
|
}`}
|
||||||
|
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={() => {
|
open={open}
|
||||||
onChange();
|
>
|
||||||
turnstile.reset();
|
<DialogContent className="flex w-auto flex-col items-center gap-4 p-6">
|
||||||
}}
|
<DialogHeader>
|
||||||
onVerify={(token) => onChange(token)}
|
<DialogTitle>
|
||||||
// onError={() => {
|
{t("captcha.turnstile.title", "Security Verification")}
|
||||||
// onChange();
|
</DialogTitle>
|
||||||
// turnstile.reset();
|
</DialogHeader>
|
||||||
// }}
|
<Turnstile
|
||||||
sitekey={verify.turnstile_site_key}
|
fixedSize
|
||||||
theme={resolvedTheme as "light" | "dark"}
|
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>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Button } from "@workspace/ui/components/button";
|
import { Button } from "@workspace/ui/components/button";
|
||||||
import {
|
import {
|
||||||
@@ -9,29 +10,146 @@ import {
|
|||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@workspace/ui/components/card";
|
} from "@workspace/ui/components/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@workspace/ui/components/dialog";
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
FormControl,
|
||||||
|
FormField,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormMessage,
|
||||||
|
} from "@workspace/ui/components/form";
|
||||||
|
import { Input } from "@workspace/ui/components/input";
|
||||||
|
import { Textarea } from "@workspace/ui/components/textarea";
|
||||||
|
import type { ProListActions } from "@workspace/ui/composed/pro-list/pro-list";
|
||||||
import { ProList } from "@workspace/ui/composed/pro-list/pro-list";
|
import { ProList } from "@workspace/ui/composed/pro-list/pro-list";
|
||||||
import {
|
import {
|
||||||
|
commissionWithdraw,
|
||||||
queryUserAffiliate,
|
queryUserAffiliate,
|
||||||
queryUserAffiliateList,
|
queryUserAffiliateList,
|
||||||
|
queryWithdrawalLog,
|
||||||
} from "@workspace/ui/services/user/user";
|
} from "@workspace/ui/services/user/user";
|
||||||
import { formatDate } from "@workspace/ui/utils/formatting";
|
import { formatDate } from "@workspace/ui/utils/formatting";
|
||||||
|
import { unitConversion } from "@workspace/ui/utils/unit-conversions";
|
||||||
import { Copy } from "lucide-react";
|
import { Copy } from "lucide-react";
|
||||||
|
import { useRef, useState, useTransition } from "react";
|
||||||
import { CopyToClipboard } from "react-copy-to-clipboard";
|
import { CopyToClipboard } from "react-copy-to-clipboard";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { z } from "zod";
|
||||||
import { Display } from "@/components/display";
|
import { Display } from "@/components/display";
|
||||||
import { useGlobalStore } from "@/stores/global";
|
import { useGlobalStore } from "@/stores/global";
|
||||||
|
|
||||||
|
function getWithdrawalStatusMeta(
|
||||||
|
status: number,
|
||||||
|
t: ReturnType<typeof useTranslation<"affiliate">>["t"]
|
||||||
|
) {
|
||||||
|
switch (status) {
|
||||||
|
case 1:
|
||||||
|
return {
|
||||||
|
label: t("withdrawal.status.approved", "Approved"),
|
||||||
|
className: "bg-emerald-500/10 text-emerald-600",
|
||||||
|
};
|
||||||
|
case 2:
|
||||||
|
return {
|
||||||
|
label: t("withdrawal.status.rejected", "Rejected"),
|
||||||
|
className: "bg-destructive/10 text-destructive",
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return {
|
||||||
|
label: t("withdrawal.status.pending", "Pending"),
|
||||||
|
className: "bg-amber-500/10 text-amber-600",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default function Affiliate() {
|
export default function Affiliate() {
|
||||||
const { t } = useTranslation("affiliate");
|
const { t } = useTranslation("affiliate");
|
||||||
const { user, common } = useGlobalStore();
|
const { user, common, getUserInfo } = useGlobalStore();
|
||||||
const { data } = useQuery({
|
const [withdrawalOpen, setWithdrawalOpen] = useState(false);
|
||||||
|
const [submitting, startTransition] = useTransition();
|
||||||
|
const withdrawalListActionRef = useRef<ProListActions | undefined>(undefined);
|
||||||
|
|
||||||
|
const affiliateQuery = useQuery({
|
||||||
queryKey: ["queryUserAffiliate"],
|
queryKey: ["queryUserAffiliate"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await queryUserAffiliate();
|
const response = await queryUserAffiliate();
|
||||||
return response.data.data;
|
return response.data.data;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const availableCommission = Number(
|
||||||
|
user?.commission ?? affiliateQuery.data?.total_commission ?? 0
|
||||||
|
);
|
||||||
|
const withdrawalFormSchema = z.object({
|
||||||
|
amount: z
|
||||||
|
.number()
|
||||||
|
.int(t("withdrawal.validation.amountInvalid", "Amount is invalid"))
|
||||||
|
.positive(
|
||||||
|
t(
|
||||||
|
"withdrawal.validation.amountPositive",
|
||||||
|
"Amount must be greater than 0"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.max(
|
||||||
|
availableCommission,
|
||||||
|
t(
|
||||||
|
"withdrawal.validation.amountExceeded",
|
||||||
|
"Amount cannot exceed available commission"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
content: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(
|
||||||
|
1,
|
||||||
|
t(
|
||||||
|
"withdrawal.validation.contentRequired",
|
||||||
|
"Withdrawal info is required"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.max(
|
||||||
|
1000,
|
||||||
|
t("withdrawal.validation.contentTooLong", "Withdrawal info is too long")
|
||||||
|
),
|
||||||
|
});
|
||||||
|
const withdrawalForm = useForm<z.infer<typeof withdrawalFormSchema>>({
|
||||||
|
resolver: zodResolver(withdrawalFormSchema),
|
||||||
|
defaultValues: {
|
||||||
|
amount: 0,
|
||||||
|
content: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const submitWithdrawal = (values: z.infer<typeof withdrawalFormSchema>) => {
|
||||||
|
startTransition(async () => {
|
||||||
|
await commissionWithdraw({
|
||||||
|
amount: values.amount,
|
||||||
|
content: values.content.trim(),
|
||||||
|
});
|
||||||
|
toast.success(
|
||||||
|
t("withdrawal.submitSuccess", "Withdrawal request submitted")
|
||||||
|
);
|
||||||
|
await Promise.all([
|
||||||
|
affiliateQuery.refetch(),
|
||||||
|
getUserInfo(),
|
||||||
|
withdrawalListActionRef.current?.refresh(),
|
||||||
|
]);
|
||||||
|
setWithdrawalOpen(false);
|
||||||
|
withdrawalForm.reset({
|
||||||
|
amount: 0,
|
||||||
|
content: "",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
@@ -43,15 +161,146 @@ export default function Affiliate() {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="flex items-baseline gap-2">
|
<div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
|
||||||
<span className="font-bold text-3xl">
|
<div className="flex items-baseline gap-2">
|
||||||
<Display type="currency" value={data?.total_commission} />
|
<span className="font-bold text-3xl">
|
||||||
</span>
|
<Display
|
||||||
<span className="text-muted-foreground text-sm">
|
type="currency"
|
||||||
({t("commissionRate", "Commission Rate")}:{" "}
|
value={affiliateQuery.data?.total_commission}
|
||||||
{user?.referral_percentage || common?.invite?.referral_percentage}
|
/>
|
||||||
%)
|
</span>
|
||||||
</span>
|
<span className="text-muted-foreground text-sm">
|
||||||
|
({t("commissionRate", "Commission Rate")}:{" "}
|
||||||
|
{user?.referral_percentage ||
|
||||||
|
common?.invite?.referral_percentage}
|
||||||
|
%)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-start gap-2 md:items-end">
|
||||||
|
<div className="text-muted-foreground text-sm">
|
||||||
|
{t(
|
||||||
|
"withdrawal.availableCommission",
|
||||||
|
"Available for withdrawal"
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="font-semibold text-xl">
|
||||||
|
<Display type="currency" value={availableCommission} />
|
||||||
|
</div>
|
||||||
|
<Dialog onOpenChange={setWithdrawalOpen} open={withdrawalOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button>
|
||||||
|
{t("withdrawal.apply", "Apply for Withdrawal")}
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{t("withdrawal.applyTitle", "Apply for Withdrawal")}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{t(
|
||||||
|
"withdrawal.applyDescription",
|
||||||
|
"Enter the withdrawal amount and payout details."
|
||||||
|
)}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<Form {...withdrawalForm}>
|
||||||
|
<form
|
||||||
|
className="space-y-4"
|
||||||
|
id="withdrawal-form"
|
||||||
|
onSubmit={withdrawalForm.handleSubmit(submitWithdrawal)}
|
||||||
|
>
|
||||||
|
<FormField
|
||||||
|
control={withdrawalForm.control}
|
||||||
|
name="amount"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>
|
||||||
|
{t("withdrawal.amount", "Amount")}
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
inputMode="decimal"
|
||||||
|
min="0"
|
||||||
|
onChange={(event) => {
|
||||||
|
const cents = unitConversion(
|
||||||
|
"dollarsToCents",
|
||||||
|
Number(event.target.value || 0)
|
||||||
|
);
|
||||||
|
field.onChange(Number(cents) || 0);
|
||||||
|
}}
|
||||||
|
placeholder={t(
|
||||||
|
"withdrawal.amountPlaceholder",
|
||||||
|
"Enter withdrawal amount"
|
||||||
|
)}
|
||||||
|
step="0.01"
|
||||||
|
type="number"
|
||||||
|
value={
|
||||||
|
field.value
|
||||||
|
? unitConversion(
|
||||||
|
"centsToDollars",
|
||||||
|
Number(field.value)
|
||||||
|
)
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
{t("withdrawal.amountHint", "Available")}:{" "}
|
||||||
|
<Display
|
||||||
|
type="currency"
|
||||||
|
value={availableCommission}
|
||||||
|
/>
|
||||||
|
</p>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={withdrawalForm.control}
|
||||||
|
name="content"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>
|
||||||
|
{t("withdrawal.content", "Payout Information")}
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Textarea
|
||||||
|
placeholder={t(
|
||||||
|
"withdrawal.contentPlaceholder",
|
||||||
|
"Bank account, wallet address, recipient name, or other payout details"
|
||||||
|
)}
|
||||||
|
rows={4}
|
||||||
|
{...field}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
disabled={submitting}
|
||||||
|
onClick={() => setWithdrawalOpen(false)}
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
{t("withdrawal.cancel", "Cancel")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
disabled={submitting || availableCommission <= 0}
|
||||||
|
form="withdrawal-form"
|
||||||
|
type="submit"
|
||||||
|
>
|
||||||
|
{submitting
|
||||||
|
? t("withdrawal.submitting", "Submitting...")
|
||||||
|
: t("withdrawal.submit", "Submit Withdrawal")}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -82,6 +331,67 @@ export default function Affiliate() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
<ProList<API.WithdrawalLog, Record<string, unknown>>
|
||||||
|
action={withdrawalListActionRef}
|
||||||
|
header={{
|
||||||
|
title: t("withdrawal.records", "Withdrawal Records"),
|
||||||
|
}}
|
||||||
|
renderItem={(item) => {
|
||||||
|
const statusMeta = getWithdrawalStatusMeta(item.status, t);
|
||||||
|
return (
|
||||||
|
<Card className="overflow-hidden">
|
||||||
|
<CardContent className="space-y-3 p-4 text-sm">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="font-semibold text-lg">
|
||||||
|
<Display type="currency" value={item.amount} />
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={`inline-flex rounded-full px-3 py-1 font-medium text-xs ${statusMeta.className}`}
|
||||||
|
>
|
||||||
|
{statusMeta.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<ul className="grid gap-3 md:grid-cols-2">
|
||||||
|
<li className="flex flex-col gap-1">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{t("withdrawal.record.content", "Payout Information")}
|
||||||
|
</span>
|
||||||
|
<span className="whitespace-pre-wrap break-words">
|
||||||
|
{item.content}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
<li className="flex flex-col gap-1">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{t("withdrawal.record.createdAt", "Created At")}
|
||||||
|
</span>
|
||||||
|
<time>{formatDate(item.created_at)}</time>
|
||||||
|
</li>
|
||||||
|
{item.reason ? (
|
||||||
|
<li className="flex flex-col gap-1 md:col-span-2">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{t("withdrawal.record.reason", "Reject Reason")}
|
||||||
|
</span>
|
||||||
|
<span className="whitespace-pre-wrap break-words text-destructive">
|
||||||
|
{item.reason}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
) : null}
|
||||||
|
</ul>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
request={async (pagination) => {
|
||||||
|
const response = await queryWithdrawalLog({
|
||||||
|
page: pagination.page,
|
||||||
|
size: pagination.size,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
list: response.data.data?.list || [],
|
||||||
|
total: response.data.data?.total || 0,
|
||||||
|
};
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<ProList<API.UserAffiliate, Record<string, unknown>>
|
<ProList<API.UserAffiliate, Record<string, unknown>>
|
||||||
header={{
|
header={{
|
||||||
title: t("inviteRecords", "Invite Records"),
|
title: t("inviteRecords", "Invite Records"),
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ const FormSchema = z.object({
|
|||||||
enable_balance_notify: z.boolean(),
|
enable_balance_notify: z.boolean(),
|
||||||
enable_login_notify: z.boolean(),
|
enable_login_notify: z.boolean(),
|
||||||
enable_subscribe_notify: z.boolean(),
|
enable_subscribe_notify: z.boolean(),
|
||||||
enable_trade_notify: z.boolean(),
|
// enable_trade_notify: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function NotifySettings() {
|
export default function NotifySettings() {
|
||||||
@@ -39,7 +39,7 @@ export default function NotifySettings() {
|
|||||||
enable_balance_notify: user?.enable_balance_notify ?? false,
|
enable_balance_notify: user?.enable_balance_notify ?? false,
|
||||||
enable_login_notify: user?.enable_login_notify ?? false,
|
enable_login_notify: user?.enable_login_notify ?? false,
|
||||||
enable_subscribe_notify: user?.enable_subscribe_notify ?? false,
|
enable_subscribe_notify: user?.enable_subscribe_notify ?? false,
|
||||||
enable_trade_notify: user?.enable_trade_notify ?? false,
|
// enable_trade_notify: user?.enable_trade_notify ?? false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -80,10 +80,10 @@ export default function NotifySettings() {
|
|||||||
name: "enable_subscribe_notify",
|
name: "enable_subscribe_notify",
|
||||||
label: t("notify.subscribe", "Subscribe"),
|
label: t("notify.subscribe", "Subscribe"),
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
name: "enable_trade_notify",
|
// name: "enable_trade_notify",
|
||||||
label: t("notify.finance", "Finance"),
|
// label: t("notify.finance", "Finance"),
|
||||||
},
|
// },
|
||||||
].map(({ name, label }) => (
|
].map(({ name, label }) => (
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
|
|||||||
@@ -1,20 +1,33 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@workspace/ui/components/card";
|
import {
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@workspace/ui/components/select";
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@workspace/ui/components/card";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@workspace/ui/components/select";
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@workspace/ui/components/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@workspace/ui/components/tabs";
|
||||||
import { Icon } from "@workspace/ui/composed/icon";
|
import { Icon } from "@workspace/ui/composed/icon";
|
||||||
import { queryUserSubscribe } from "@workspace/ui/services/user/user";
|
|
||||||
import { getUserTrafficStats } from "@workspace/ui/services/user/traffic";
|
import { getUserTrafficStats } from "@workspace/ui/services/user/traffic";
|
||||||
|
import { queryUserSubscribe } from "@workspace/ui/services/user/user";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import TrafficTrendChart from "./traffic-trend-chart";
|
|
||||||
import TrafficRatioChart from "./traffic-ratio-chart";
|
import TrafficRatioChart from "./traffic-ratio-chart";
|
||||||
import TrafficStatsCards from "./traffic-stats-cards";
|
import TrafficStatsCards from "./traffic-stats-cards";
|
||||||
|
import TrafficTrendChart from "./traffic-trend-chart";
|
||||||
|
|
||||||
export default function TrafficStatistics() {
|
export default function TrafficStatistics() {
|
||||||
const { t } = useTranslation("traffic");
|
const { t } = useTranslation("traffic");
|
||||||
const [days, setDays] = useState<7 | 30>(7);
|
const [days, setDays] = useState<7 | 30>(7);
|
||||||
const [selectedSubscribeId, setSelectedSubscribeId] = useState<string | null>(null);
|
const [selectedSubscribeId, setSelectedSubscribeId] = useState<string | null>(
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
// 查询用户订阅列表
|
// 查询用户订阅列表
|
||||||
const { data: userSubscribe = [] } = useQuery({
|
const { data: userSubscribe = [] } = useQuery({
|
||||||
@@ -26,7 +39,8 @@ export default function TrafficStatistics() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 使用 id_str 字段,避免 JavaScript 精度丢失
|
// 使用 id_str 字段,避免 JavaScript 精度丢失
|
||||||
const activeSubscribeId = selectedSubscribeId || (userSubscribe[0]?.id_str || null);
|
const activeSubscribeId =
|
||||||
|
selectedSubscribeId || userSubscribe[0]?.id_str || null;
|
||||||
|
|
||||||
// 查询流量统计数据
|
// 查询流量统计数据
|
||||||
const { data: trafficStats, isLoading } = useQuery({
|
const { data: trafficStats, isLoading } = useQuery({
|
||||||
@@ -54,11 +68,13 @@ export default function TrafficStatistics() {
|
|||||||
{/* 订阅选择 */}
|
{/* 订阅选择 */}
|
||||||
{userSubscribe.length > 1 && (
|
{userSubscribe.length > 1 && (
|
||||||
<Select
|
<Select
|
||||||
value={activeSubscribeId || undefined}
|
|
||||||
onValueChange={(value) => setSelectedSubscribeId(value)}
|
onValueChange={(value) => setSelectedSubscribeId(value)}
|
||||||
|
value={activeSubscribeId || undefined}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-full md:w-[200px]">
|
<SelectTrigger className="w-full md:w-[200px]">
|
||||||
<SelectValue placeholder={t("selectSubscription", "Select Subscription")} />
|
<SelectValue
|
||||||
|
placeholder={t("selectSubscription", "Select Subscription")}
|
||||||
|
/>
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{userSubscribe.map((sub) => (
|
{userSubscribe.map((sub) => (
|
||||||
@@ -70,7 +86,10 @@ export default function TrafficStatistics() {
|
|||||||
</Select>
|
</Select>
|
||||||
)}
|
)}
|
||||||
{/* 时间范围切换 */}
|
{/* 时间范围切换 */}
|
||||||
<Tabs value={String(days)} onValueChange={(value) => setDays(Number(value) as 7 | 30)}>
|
<Tabs
|
||||||
|
onValueChange={(value) => setDays(Number(value) as 7 | 30)}
|
||||||
|
value={String(days)}
|
||||||
|
>
|
||||||
<TabsList>
|
<TabsList>
|
||||||
<TabsTrigger value="7">{t("days7", "7 Days")}</TabsTrigger>
|
<TabsTrigger value="7">{t("days7", "7 Days")}</TabsTrigger>
|
||||||
<TabsTrigger value="30">{t("days30", "30 Days")}</TabsTrigger>
|
<TabsTrigger value="30">{t("days30", "30 Days")}</TabsTrigger>
|
||||||
@@ -87,7 +106,9 @@ export default function TrafficStatistics() {
|
|||||||
{/* 流量趋势图 */}
|
{/* 流量趋势图 */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">{t("trafficTrend", "Traffic Trend")}</CardTitle>
|
<CardTitle className="text-base">
|
||||||
|
{t("trafficTrend", "Traffic Trend")}
|
||||||
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
@@ -107,17 +128,21 @@ export default function TrafficStatistics() {
|
|||||||
{/* 流量占比图 */}
|
{/* 流量占比图 */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-base">{t("trafficRatio", "Upload/Download Ratio")}</CardTitle>
|
<CardTitle className="text-base">
|
||||||
|
{t("trafficRatio", "Upload/Download Ratio")}
|
||||||
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<div className="flex h-[300px] items-center justify-center">
|
<div className="flex h-[300px] items-center justify-center">
|
||||||
<Icon className="size-8 animate-spin" icon="uil:spinner" />
|
<Icon className="size-8 animate-spin" icon="uil:spinner" />
|
||||||
</div>
|
</div>
|
||||||
) : trafficStats && (trafficStats.total_upload > 0 || trafficStats.total_download > 0) ? (
|
) : trafficStats &&
|
||||||
|
(trafficStats.total_upload > 0 ||
|
||||||
|
trafficStats.total_download > 0) ? (
|
||||||
<TrafficRatioChart
|
<TrafficRatioChart
|
||||||
upload={trafficStats.total_upload}
|
|
||||||
download={trafficStats.total_download}
|
download={trafficStats.total_download}
|
||||||
|
upload={trafficStats.total_upload}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||||
@@ -129,4 +154,4 @@ export default function TrafficStatistics() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,22 @@
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from "recharts";
|
import {
|
||||||
|
Cell,
|
||||||
|
Legend,
|
||||||
|
Pie,
|
||||||
|
PieChart,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Tooltip,
|
||||||
|
} from "recharts";
|
||||||
|
|
||||||
interface TrafficRatioChartProps {
|
interface TrafficRatioChartProps {
|
||||||
upload: number;
|
upload: number;
|
||||||
download: number;
|
download: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TrafficRatioChart({ upload, download }: TrafficRatioChartProps) {
|
export default function TrafficRatioChart({
|
||||||
|
upload,
|
||||||
|
download,
|
||||||
|
}: TrafficRatioChartProps) {
|
||||||
const { t } = useTranslation("traffic");
|
const { t } = useTranslation("traffic");
|
||||||
|
|
||||||
const data = [
|
const data = [
|
||||||
@@ -31,20 +41,22 @@ export default function TrafficRatioChart({ upload, download }: TrafficRatioChar
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResponsiveContainer width="100%" height={300}>
|
<ResponsiveContainer height={300} width="100%">
|
||||||
<PieChart>
|
<PieChart>
|
||||||
<Pie
|
<Pie
|
||||||
data={data}
|
|
||||||
cx="50%"
|
cx="50%"
|
||||||
cy="50%"
|
cy="50%"
|
||||||
labelLine={false}
|
data={data}
|
||||||
label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(1)}%`}
|
|
||||||
outerRadius={80}
|
|
||||||
fill="#8884d8"
|
|
||||||
dataKey="value"
|
dataKey="value"
|
||||||
|
fill="#8884d8"
|
||||||
|
label={({ name, percent }) =>
|
||||||
|
`${name}: ${(percent * 100).toFixed(1)}%`
|
||||||
|
}
|
||||||
|
labelLine={false}
|
||||||
|
outerRadius={80}
|
||||||
>
|
>
|
||||||
{data.map((_, index) => (
|
{data.map((_, index) => (
|
||||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
<Cell fill={COLORS[index % COLORS.length]} key={`cell-${index}`} />
|
||||||
))}
|
))}
|
||||||
</Pie>
|
</Pie>
|
||||||
<Tooltip formatter={(value: number) => formatTraffic(value)} />
|
<Tooltip formatter={(value: number) => formatTraffic(value)} />
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ export default function TrafficStatsCards({ stats }: TrafficStatsCardsProps) {
|
|||||||
<Card key={card.title}>
|
<Card key={card.title}>
|
||||||
<CardContent className="flex items-center justify-between p-6">
|
<CardContent className="flex items-center justify-between p-6">
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
<span className="text-muted-foreground text-sm">{card.title}</span>
|
<span className="text-muted-foreground text-sm">
|
||||||
|
{card.title}
|
||||||
|
</span>
|
||||||
<span className="font-bold text-2xl">
|
<span className="font-bold text-2xl">
|
||||||
<Display type="traffic" value={card.value} />
|
<Display type="traffic" value={card.value} />
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -2,14 +2,14 @@ import type { GetUserTrafficStatsResponse } from "@workspace/ui/services/user/tr
|
|||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import {
|
import {
|
||||||
LineChart,
|
CartesianGrid,
|
||||||
|
Legend,
|
||||||
Line,
|
Line,
|
||||||
|
LineChart,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Tooltip,
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
Legend,
|
|
||||||
ResponsiveContainer,
|
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
|
|
||||||
interface TrafficTrendChartProps {
|
interface TrafficTrendChartProps {
|
||||||
@@ -28,7 +28,8 @@ export default function TrafficTrendChart({ data }: TrafficTrendChartProps) {
|
|||||||
|
|
||||||
// 格式化流量显示
|
// 格式化流量显示
|
||||||
const formatTraffic = (value: number | string) => {
|
const formatTraffic = (value: number | string) => {
|
||||||
const numValue = typeof value === "string" ? parseFloat(value) : value;
|
const numValue =
|
||||||
|
typeof value === "string" ? Number.parseFloat(value) : value;
|
||||||
if (numValue >= 1024) {
|
if (numValue >= 1024) {
|
||||||
return `${(numValue / 1024).toFixed(2)} GB`;
|
return `${(numValue / 1024).toFixed(2)} GB`;
|
||||||
}
|
}
|
||||||
@@ -36,44 +37,52 @@ export default function TrafficTrendChart({ data }: TrafficTrendChartProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResponsiveContainer width="100%" height={300}>
|
<ResponsiveContainer height={300} width="100%">
|
||||||
<LineChart data={chartData}>
|
<LineChart data={chartData}>
|
||||||
<CartesianGrid strokeDasharray="3 3" />
|
<CartesianGrid strokeDasharray="3 3" />
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="date"
|
dataKey="date"
|
||||||
label={{ value: t("date", "Date"), position: "insideBottom", offset: -5 }}
|
label={{
|
||||||
|
value: t("date", "Date"),
|
||||||
|
position: "insideBottom",
|
||||||
|
offset: -5,
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
label={{ value: t("traffic", "Traffic (MB)"), angle: -90, position: "insideLeft" }}
|
label={{
|
||||||
|
value: t("traffic", "Traffic (MB)"),
|
||||||
|
angle: -90,
|
||||||
|
position: "insideLeft",
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<Tooltip
|
<Tooltip
|
||||||
formatter={(value: number | string) => formatTraffic(value)}
|
formatter={(value: number | string) => formatTraffic(value)}
|
||||||
labelStyle={{ color: "#000" }}
|
labelStyle={{ color: "#000" }}
|
||||||
/>
|
/>
|
||||||
<Legend
|
<Legend
|
||||||
verticalAlign="bottom"
|
|
||||||
height={36}
|
height={36}
|
||||||
|
verticalAlign="bottom"
|
||||||
wrapperStyle={{
|
wrapperStyle={{
|
||||||
position: "absolute",
|
position: "absolute",
|
||||||
width: "444px",
|
width: "444px",
|
||||||
height: "36px",
|
height: "36px",
|
||||||
left: "5px",
|
left: "5px",
|
||||||
bottom: "-5px"
|
bottom: "-5px",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Line
|
<Line
|
||||||
type="monotone"
|
|
||||||
dataKey="upload"
|
dataKey="upload"
|
||||||
stroke="#10b981"
|
|
||||||
name={t("upload", "Upload")}
|
name={t("upload", "Upload")}
|
||||||
|
stroke="#10b981"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
|
type="monotone"
|
||||||
/>
|
/>
|
||||||
<Line
|
<Line
|
||||||
type="monotone"
|
|
||||||
dataKey="download"
|
dataKey="download"
|
||||||
stroke="#3b82f6"
|
|
||||||
name={t("download", "Download")}
|
name={t("download", "Download")}
|
||||||
|
stroke="#3b82f6"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
|
type="monotone"
|
||||||
/>
|
/>
|
||||||
</LineChart>
|
</LineChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
|
|||||||
@@ -49,7 +49,9 @@
|
|||||||
"motion": "^12.23.24",
|
"motion": "^12.23.24",
|
||||||
"qrcode.react": "^4.2.0",
|
"qrcode.react": "^4.2.0",
|
||||||
"radash": "^12.1.1",
|
"radash": "^12.1.1",
|
||||||
|
"react": "^19.2.0",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
"react-copy-to-clipboard": "^5.1.0",
|
||||||
|
"react-dom": "^19.2.0",
|
||||||
"react-helmet-async": "^2.0.5",
|
"react-helmet-async": "^2.0.5",
|
||||||
"react-turnstile": "^1.1.4",
|
"react-turnstile": "^1.1.4",
|
||||||
"zustand": "^5.0.8",
|
"zustand": "^5.0.8",
|
||||||
@@ -85,7 +87,9 @@
|
|||||||
"framer-motion": "^12.23.24",
|
"framer-motion": "^12.23.24",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.1.1",
|
||||||
"qrcode.react": "^4.2.0",
|
"qrcode.react": "^4.2.0",
|
||||||
|
"react": "^19.2.0",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
"react-copy-to-clipboard": "^5.1.0",
|
||||||
|
"react-dom": "^19.2.0",
|
||||||
"react-helmet-async": "^2.0.5",
|
"react-helmet-async": "^2.0.5",
|
||||||
"react-turnstile": "^1.1.4",
|
"react-turnstile": "^1.1.4",
|
||||||
"zustand": "^5.0.8",
|
"zustand": "^5.0.8",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export const onRequest: PagesFunction<Env> = async (context) => {
|
|||||||
|
|
||||||
const apiBase = (env.API_BASE_URL || "https://api.ppanel.dev").replace(
|
const apiBase = (env.API_BASE_URL || "https://api.ppanel.dev").replace(
|
||||||
/\/$/,
|
/\/$/,
|
||||||
"",
|
""
|
||||||
);
|
);
|
||||||
|
|
||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
@@ -41,11 +41,11 @@ export const onRequest: PagesFunction<Env> = async (context) => {
|
|||||||
responseHeaders.set("Access-Control-Allow-Origin", url.origin);
|
responseHeaders.set("Access-Control-Allow-Origin", url.origin);
|
||||||
responseHeaders.set(
|
responseHeaders.set(
|
||||||
"Access-Control-Allow-Methods",
|
"Access-Control-Allow-Methods",
|
||||||
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
|
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
|
||||||
);
|
);
|
||||||
responseHeaders.set(
|
responseHeaders.set(
|
||||||
"Access-Control-Allow-Headers",
|
"Access-Control-Allow-Headers",
|
||||||
"Content-Type, Authorization",
|
"Content-Type, Authorization"
|
||||||
);
|
);
|
||||||
|
|
||||||
if (request.method === "OPTIONS") {
|
if (request.method === "OPTIONS") {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
|
|
||||||
[context.admin.environment]
|
[context.admin.environment]
|
||||||
NODE_VERSION = "20"
|
NODE_VERSION = "20"
|
||||||
|
VITE_API_BASE_URL = "https://tapi.hifast.biz"
|
||||||
|
|
||||||
# User 用户前台应用
|
# User 用户前台应用
|
||||||
[context.user]
|
[context.user]
|
||||||
|
|||||||
+2
-1
@@ -24,7 +24,8 @@
|
|||||||
"i18n:sync": "turbo i18n:sync",
|
"i18n:sync": "turbo i18n:sync",
|
||||||
"i18n:status": "turbo i18n:status",
|
"i18n:status": "turbo i18n:status",
|
||||||
"prepare": "husky && npx gitmoji -i",
|
"prepare": "husky && npx gitmoji -i",
|
||||||
"release": "semantic-release"
|
"release": "semantic-release",
|
||||||
|
"sync": "bash scripts/sync-upstream.sh"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
|
|||||||
@@ -43,5 +43,6 @@ function PopoverAnchor({
|
|||||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||||
}
|
}
|
||||||
|
const PopoverClose = PopoverPrimitive.Close;
|
||||||
|
|
||||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
|
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor, PopoverClose };
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ function SheetContent({
|
|||||||
<SheetPortal>
|
<SheetPortal>
|
||||||
<SheetOverlay />
|
<SheetOverlay />
|
||||||
<SheetPrimitive.Content
|
<SheetPrimitive.Content
|
||||||
|
aria-describedby={undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
"fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||||
side === "right" &&
|
side === "right" &&
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import type { ReactNode } from "react";
|
|||||||
interface ConfirmationButtonProps {
|
interface ConfirmationButtonProps {
|
||||||
trigger: ReactNode;
|
trigger: ReactNode;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: ReactNode;
|
||||||
onConfirm: () => void | Promise<void>;
|
onConfirm: () => void | Promise<void>;
|
||||||
cancelText?: string;
|
cancelText?: string;
|
||||||
confirmText?: string;
|
confirmText?: string;
|
||||||
@@ -36,7 +36,13 @@ export const ConfirmButton: React.FC<ConfirmationButtonProps> = ({
|
|||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||||
<AlertDialogDescription>{description}</AlertDialogDescription>
|
<AlertDialogDescription asChild>
|
||||||
|
{typeof description === "string" ? (
|
||||||
|
<span>{description}</span>
|
||||||
|
) : (
|
||||||
|
<div>{description}</div>
|
||||||
|
)}
|
||||||
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>{cancelText}</AlertDialogCancel>
|
<AlertDialogCancel>{cancelText}</AlertDialogCancel>
|
||||||
|
|||||||
@@ -53,11 +53,13 @@ export function DatePicker({
|
|||||||
)}
|
)}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
<span className="truncate">{value ? intlFormat(value) : <span>{placeholder}</span>}</span>
|
<span className="truncate">
|
||||||
|
{value ? intlFormat(value) : <span>{placeholder}</span>}
|
||||||
|
</span>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{value && (
|
{value && (
|
||||||
<span
|
<span
|
||||||
className="flex items-center cursor-pointer"
|
className="flex cursor-pointer items-center"
|
||||||
onClick={handleClear}
|
onClick={handleClear}
|
||||||
onMouseDown={handleClear}
|
onMouseDown={handleClear}
|
||||||
role="button"
|
role="button"
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user