Compare commits

...

151 Commits
v1.3.0 ... main

Author SHA1 Message Date
3c0e544c97 feat: Gengx 2026-02-06 20:26:46 -08:00
7df01e454c feat: 修改配置文件 2026-02-06 20:16:21 -08:00
d05cd8ed3d 更新 README.md
Some checks failed
CI / build (20.15.1) (push) Failing after 19m20s
2026-02-02 23:56:16 -05:00
5ddf9ade01 feat: 2 (#2)
Some checks failed
CI / build (20.15.1) (push) Failing after 19m30s
2026-01-27 20:14:52 -08:00
3b93b95177 🐛 fix: Ci
Some checks failed
CI / build (20.15.1) (push) Has been cancelled
2026-01-27 20:11:44 -08:00
57b841525d feat(ci): Ci
Some checks failed
CI / build (20.15.1) (push) Failing after 14m59s
2026-01-05 04:20:01 -08:00
1e147c8298 feat: Ci
Some checks failed
CI / build (20.15.1) (push) Failing after 14m49s
2026-01-05 03:55:10 -08:00
7419d8ebcd feat: 0
Some checks failed
CI / build (20.15.1) (push) Failing after 14m41s
2026-01-05 03:24:27 -08:00
56a955ae81 feat: 1
All checks were successful
CI / build (20.15.1) (push) Successful in 14m4s
2026-01-05 03:04:09 -08:00
e3aa52af01 merge(main): 合并 develop 到 main 并同步 CI/Docker 修复
Some checks failed
CI / build (20.15.1) (push) Failing after 16m25s
2026-01-03 22:03:52 -08:00
cf55495c1f ci(docker): 更新工作流中的镜像名称和容器名称
All checks were successful
CI / build (20.15.1) (push) Successful in 22m38s
将工作流中的 ppanel 相关镜像和容器名称统一更新为 fastvpn
修复 develop 分支名称拼写错误
2026-01-03 20:32:31 -08:00
c381a2b2ba fix(docker): 修正Dockerfile中的用户创建命令和CI分支条件
Some checks failed
CI / build (20.15.1) (push) Failing after 15m20s
修复Dockerfile中使用addgroup/adduser命令导致的兼容性问题,改用groupadd/useradd
修正CI配置中分支条件判断错误,将dev改为develop
2026-01-03 20:10:53 -08:00
43c909d1f2 ci: 更新构建任务的运行主机为fastvpn-admin01
Some checks failed
CI / build (20.15.1) (push) Failing after 16m8s
2026-01-03 19:50:27 -08:00
9eff6aa40d ci(workflow): 更新分支名称和API地址配置
Some checks failed
CI / build (20.15.1) (push) Has been cancelled
将dev分支重命名为develop分支
统一所有分支的API地址为https://api.hifast.biz
2026-01-03 19:47:44 -08:00
a211035025 ci(workflow): 更新构建任务运行的服务器节点
将构建任务从 fastvpn-admin01 迁移到 fastvpn-admin-web01 节点执行
2026-01-03 19:46:11 -08:00
aa745079db chore: 移除不再使用的GitHub工作流和模板文件
删除以下不再需要的文件:
- GitHub issue和pull request模板
- 自动合并、发布和issue管理的工作流
- VS Code配置文件
2026-01-03 19:44:33 -08:00
11942e2b9f docs: 添加项目说明文档和初始化配置
ci: 添加docker工作流配置并更新项目名称
2026-01-03 19:43:40 -08:00
b31c70a5c1 🐛 fix: 修改样式 2025-12-15 18:30:29 -08:00
75db379624 🐛 fix: 修改样式 2025-12-15 18:29:56 -08:00
c8401af672 🐛 fix: 更新next版本 2025-12-07 05:59:23 -08:00
semantic-release-bot
ea3964ebe5 🔖 chore(release): v1.6.1 [skip ci]
## [1.6.1](https://github.com/perfect-panel/ppanel-web/compare/v1.6.0...v1.6.1) (2025-11-05)

### 🐛 Bug Fixes

* Fixing issues with generating standard and quantum-resistant encryption keys ([5eac6a9](https://github.com/perfect-panel/ppanel-web/commit/5eac6a9))
2025-11-05 04:45:55 +00:00
web
5eac6a9f4a 🐛 fix: Fixing issues with generating standard and quantum-resistant encryption keys 2025-11-04 20:40:53 -08:00
web@ppanel
2182400adc
Merge pull request #61 from Ember-Moth/main
fix: 服务器编辑时合并协议默认配置
2025-11-04 19:51:05 -08:00
Ember Moth
5318b9cf44
Refactor protocol configuration logic in server form 2025-11-02 16:48:41 +08:00
semantic-release-bot
705391f82a 🔖 chore(release): v1.6.0 [skip ci]
# [1.6.0](https://github.com/perfect-panel/ppanel-web/compare/v1.5.4...v1.6.0) (2025-10-28)

###  Features

* Add server installation dialog and commands ([4429c9d](https://github.com/perfect-panel/ppanel-web/commit/4429c9d))

### 🐛 Bug Fixes

* Add typeRoots configuration to ensure type definitions are resolved correctly ([ad60ea9](https://github.com/perfect-panel/ppanel-web/commit/ad60ea9))
2025-10-28 09:13:37 +00:00
web
4429c9ddc9 feat: Add server installation dialog and commands 2025-10-28 02:10:12 -07:00
web
ad60ea9b18 🐛 fix: Add typeRoots configuration to ensure type definitions are resolved correctly 2025-10-27 04:05:20 -07:00
semantic-release-bot
5025fd1103 🔖 chore(release): v1.5.4 [skip ci]
## [1.5.4](https://github.com/perfect-panel/ppanel-web/compare/v1.5.3...v1.5.4) (2025-10-26)

### 🐛 Bug Fixes

* Update generateRealityKeyPair to use async key generation ([e60e369](https://github.com/perfect-panel/ppanel-web/commit/e60e369))
* Update the wallet localization file and add new fields such as automatic reset and recharge ([88aa965](https://github.com/perfect-panel/ppanel-web/commit/88aa965))
2025-10-26 18:24:43 +00:00
web
88aa9656b2 🐛 fix: Update the wallet localization file and add new fields such as automatic reset and recharge 2025-10-26 11:20:52 -07:00
web
e60e369bbe 🐛 fix: Update generateRealityKeyPair to use async key generation 2025-10-26 08:48:52 -07:00
semantic-release-bot
c3d0ef8317 🔖 chore(release): v1.5.3 [skip ci]
## [1.5.3](https://github.com/perfect-panel/ppanel-web/compare/v1.5.2...v1.5.3) (2025-10-21)

### 🐛 Bug Fixes

* Fix bugs ([a46657d](https://github.com/perfect-panel/ppanel-web/commit/a46657d))
* Fix dependencies ([8bd25d6](https://github.com/perfect-panel/ppanel-web/commit/8bd25d6))
* Remove unnecessary migration function code and add device configuration options ([521a7a9](https://github.com/perfect-panel/ppanel-web/commit/521a7a9))
* Update bun.lockb to reflect dependency changes ([ca892dd](https://github.com/perfect-panel/ppanel-web/commit/ca892dd))
2025-10-21 12:32:02 +00:00
web
8bd25d651b 🐛 fix: Fix dependencies 2025-10-21 05:28:40 -07:00
web
ca892dd359 🐛 fix: Update bun.lockb to reflect dependency changes 2025-10-21 04:38:50 -07:00
web
521a7a97fb 🐛 fix: Remove unnecessary migration function code and add device configuration options 2025-10-21 04:33:29 -07:00
web
a46657d5ef 🐛 fix: Fix bugs 2025-10-21 04:10:34 -07:00
semantic-release-bot
c2bfee1f31 🔖 chore(release): v1.5.2 [skip ci]
## [1.5.2](https://github.com/perfect-panel/ppanel-web/compare/v1.5.1...v1.5.2) (2025-09-29)

### 🐛 Bug Fixes

* Add step attribute to datetime-local inputs for precise time selection in forms ([32fd181](https://github.com/perfect-panel/ppanel-web/commit/32fd181))
* Rename 'hysteria2' to 'hysteria' across protocol definitions and schemas for consistency ([5816dd5](https://github.com/perfect-panel/ppanel-web/commit/5816dd5))
* Update protocol options in ServerConfig for accuracy and consistency ([9266529](https://github.com/perfect-panel/ppanel-web/commit/9266529))
2025-09-29 10:01:27 +00:00
web
32fd181b52 🐛 fix: Add step attribute to datetime-local inputs for precise time selection in forms 2025-09-29 02:43:39 -07:00
web
5816dd5198 🐛 fix: Rename 'hysteria2' to 'hysteria' across protocol definitions and schemas for consistency 2025-09-29 02:32:28 -07:00
web
92665293ec 🐛 fix: Update protocol options in ServerConfig for accuracy and consistency 2025-09-29 02:18:16 -07:00
semantic-release-bot
ec1e402419 🔖 chore(release): v1.5.1 [skip ci]
## [1.5.1](https://github.com/perfect-panel/ppanel-web/compare/v1.5.0...v1.5.1) (2025-09-28)

### 🐛 Bug Fixes

* Simplify protocol enable checks by removing unnecessary false comparisons ([4828700](https://github.com/perfect-panel/ppanel-web/commit/4828700))
2025-09-28 16:24:12 +00:00
web
4828700776 🐛 fix: Simplify protocol enable checks by removing unnecessary false comparisons 2025-09-28 09:19:54 -07:00
semantic-release-bot
35e1cef18e 🔖 chore(release): v1.5.0 [skip ci]
# [1.5.0](https://github.com/perfect-panel/ppanel-web/compare/v1.4.8...v1.5.0) (2025-09-28)

###  Features

* Update server configuration translations for multiple languages ([fc43de1](https://github.com/perfect-panel/ppanel-web/commit/fc43de1))

### 🐛 Bug Fixes

* Add DynamicMultiplier component for managing node multipliers and update ServersPage layout ([bb6671c](https://github.com/perfect-panel/ppanel-web/commit/bb6671c))
* Remove unnecessary blank lines in multiple index files for cleaner code structure ([6a823b8](https://github.com/perfect-panel/ppanel-web/commit/6a823b8))
* Remove unused ratio variable from server traffic log and server form for cleaner code ([55034dc](https://github.com/perfect-panel/ppanel-web/commit/55034dc))
* Update Badge variants and restructure traffic ratio display in ServersPage ([3d778e5](https://github.com/perfect-panel/ppanel-web/commit/3d778e5))
* Update minimum ratio value to 0 in protocol fields and adjust related schemas; enhance unit conversion in ServerConfig ([3b6ef17](https://github.com/perfect-panel/ppanel-web/commit/3b6ef17))
* Update protocol fields to use 'obfs' instead of 'security' and adjust related configurations ([4abdd36](https://github.com/perfect-panel/ppanel-web/commit/4abdd36))
2025-09-28 16:03:36 +00:00
web
55034dc97d 🐛 fix: Remove unused ratio variable from server traffic log and server form for cleaner code 2025-09-28 09:01:03 -07:00
web
6a823b8faa 🐛 fix: Remove unnecessary blank lines in multiple index files for cleaner code structure 2025-09-28 08:49:52 -07:00
web
3b6ef177ba 🐛 fix: Update minimum ratio value to 0 in protocol fields and adjust related schemas; enhance unit conversion in ServerConfig 2025-09-28 08:48:17 -07:00
web
3d778e5e36 🐛 fix: Update Badge variants and restructure traffic ratio display in ServersPage 2025-09-28 07:23:28 -07:00
web
4abdd367ee 🐛 fix: Update protocol fields to use 'obfs' instead of 'security' and adjust related configurations 2025-09-28 06:57:41 -07:00
web
fc43de16f0 feat: Update server configuration translations for multiple languages
- Added new keys for server configuration actions and descriptions in Russian, Thai, Turkish, Ukrainian, Vietnamese, Chinese (Simplified and Traditional).
- Removed outdated configuration structure and replaced it with a more organized server_config object.
- Enhanced the dynamic Inputs component to support textarea input type for better user experience.
2025-09-24 06:05:24 -07:00
web
bb6671c14f 🐛 fix: Add DynamicMultiplier component for managing node multipliers and update ServersPage layout 2025-09-24 03:00:37 -07:00
semantic-release-bot
47f66030db 🔖 chore(release): v1.4.8 [skip ci]
## [1.4.8](https://github.com/perfect-panel/ppanel-web/compare/v1.4.7...v1.4.8) (2025-09-23)

### 🐛 Bug Fixes

* Rename 'server_id' to 'protocol' in NodesPage and clean up unused imports and code in ServerConfig ([70b3484](https://github.com/perfect-panel/ppanel-web/commit/70b3484))
* Update announcement page to display timeline of announcements with Markdown content ([3c036eb](https://github.com/perfect-panel/ppanel-web/commit/3c036eb))
* Update Empty component to support border prop and adjust usage in various pages ([ce9ab89](https://github.com/perfect-panel/ppanel-web/commit/ce9ab89))
2025-09-23 13:11:32 +00:00
web
70b3484f98 🐛 fix: Rename 'server_id' to 'protocol' in NodesPage and clean up unused imports and code in ServerConfig 2025-09-23 06:08:36 -07:00
web
3c036eb09c 🐛 fix: Update announcement page to display timeline of announcements with Markdown content 2025-09-23 05:48:25 -07:00
web
ce9ab89c1c 🐛 fix: Update Empty component to support border prop and adjust usage in various pages 2025-09-23 05:46:21 -07:00
semantic-release-bot
bb0a811432 🔖 chore(release): v1.4.7 [skip ci]
## [1.4.7](https://github.com/perfect-panel/ppanel-web/compare/v1.4.6...v1.4.7) (2025-09-23)

### 🐛 Bug Fixes

* Add unique key to ProTable for improved rendering with user ID filters ([2bff15f](https://github.com/perfect-panel/ppanel-web/commit/2bff15f))
* Adjust layout spacing and chart aspect ratio in ServerConfig component ([05a61d8](https://github.com/perfect-panel/ppanel-web/commit/05a61d8))
* Refactor server ID cell rendering for improved readability and consistency ([0345b7c](https://github.com/perfect-panel/ppanel-web/commit/0345b7c))
* Update announcement page to format creation date and enhance content display ([8445e30](https://github.com/perfect-panel/ppanel-web/commit/8445e30))
* Update OnlineUsersCell to display user count with icon instead of badge ([7a4ebdf](https://github.com/perfect-panel/ppanel-web/commit/7a4ebdf))
* Update subscribe name fallback to return '--' instead of 'Unknown' ([0a07d25](https://github.com/perfect-panel/ppanel-web/commit/0a07d25))
2025-09-23 12:16:40 +00:00
web
8445e302e6 🐛 fix: Update announcement page to format creation date and enhance content display 2025-09-23 05:12:36 -07:00
web
2bff15fd13 🐛 fix: Add unique key to ProTable for improved rendering with user ID filters 2025-09-23 05:04:33 -07:00
web
0345b7cced 🐛 fix: Refactor server ID cell rendering for improved readability and consistency 2025-09-23 05:01:17 -07:00
web
7a4ebdf985 🐛 fix: Update OnlineUsersCell to display user count with icon instead of badge 2025-09-23 04:46:33 -07:00
web
05a61d8bf2 🐛 fix: Adjust layout spacing and chart aspect ratio in ServerConfig component 2025-09-23 04:42:55 -07:00
web
0a07d2578e 🐛 fix: Update subscribe name fallback to return '--' instead of 'Unknown' 2025-09-23 04:40:35 -07:00
semantic-release-bot
ee05a73834 🔖 chore(release): v1.4.6 [skip ci]
## [1.4.6](https://github.com/perfect-panel/ppanel-web/compare/v1.4.5...v1.4.6) (2025-09-17)

### 🎫 Chores

* Merge branch 'main' into develop ([41f06bf](https://github.com/perfect-panel/ppanel-web/commit/41f06bf))

### 🐛 Bug Fixes

* Add loaded state to node, server, and subscribe stores for better loading management ([13dce0c](https://github.com/perfect-panel/ppanel-web/commit/13dce0c))
* Removed node metadata fields in subscription schema to simplify structure ([0cadd83](https://github.com/perfect-panel/ppanel-web/commit/0cadd83))
2025-09-17 14:29:53 +00:00
web
13dce0c20b 🐛 fix: Add loaded state to node, server, and subscribe stores for better loading management 2025-09-17 07:26:56 -07:00
web
41f06bfe54 🔧 chore: Merge branch 'main' into develop 2025-09-17 03:21:49 -07:00
web
0cadd83e45 🐛 fix: Removed node metadata fields in subscription schema to simplify structure 2025-09-17 03:19:31 -07:00
semantic-release-bot
d7879a8654 🔖 chore(release): v1.4.5 [skip ci]
## [1.4.5](https://github.com/perfect-panel/ppanel-web/compare/v1.4.4...v1.4.5) (2025-09-17)

### ♻ Code Refactoring

* Replace useQuery with Zustand store for subscription and node data management ([c6dd0b6](https://github.com/perfect-panel/ppanel-web/commit/c6dd0b6))
* Simplify TemplatePreview component structure by consolidating Sheet and Button elements ([1b715c5](https://github.com/perfect-panel/ppanel-web/commit/1b715c5))

### 🐛 Bug Fixes

*  Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning ([bd67ece](https://github.com/perfect-panel/ppanel-web/commit/bd67ece))
* Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes ([a3c5e31](https://github.com/perfect-panel/ppanel-web/commit/a3c5e31))
* Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly ([e94405d](https://github.com/perfect-panel/ppanel-web/commit/e94405d))
* Add subscribeSchema for subscription management with detailed proxy and user information ([49b3dcc](https://github.com/perfect-panel/ppanel-web/commit/49b3dcc))
* Enhance server ID display in ServerTrafficLogPage with badges and server ratio ([6dfac27](https://github.com/perfect-panel/ppanel-web/commit/6dfac27))
* Update platform handling in Content component to ensure available platforms are correctly filtered and displayed ([1dde708](https://github.com/perfect-panel/ppanel-web/commit/1dde708))
2025-09-17 10:13:51 +00:00
web
49b3dcc591 🐛 fix: Add subscribeSchema for subscription management with detailed proxy and user information 2025-09-17 03:10:44 -07:00
web
e94405d1cd 🐛 fix: Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly 2025-09-17 03:03:12 -07:00
web
1dde7088bc 🐛 fix: Update platform handling in Content component to ensure available platforms are correctly filtered and displayed 2025-09-17 02:55:33 -07:00
web
bd67ece479 🐛 fix: Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning 2025-09-17 02:45:16 -07:00
web
a3c5e31094 🐛 fix: Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes 2025-09-17 02:35:53 -07:00
web
1b715c5f8b ♻️ refactor: Simplify TemplatePreview component structure by consolidating Sheet and Button elements 2025-09-17 02:29:29 -07:00
web
6dfac27bc3 🐛 fix: Enhance server ID display in ServerTrafficLogPage with badges and server ratio 2025-09-17 02:24:54 -07:00
web
c6dd0b63f2 ♻️ refactor: Replace useQuery with Zustand store for subscription and node data management 2025-09-17 02:20:54 -07:00
semantic-release-bot
bdd53b1551 🔖 chore(release): v1.4.4 [skip ci]
## [1.4.4](https://github.com/perfect-panel/ppanel-web/compare/v1.4.3...v1.4.4) (2025-09-16)

### 🐛 Bug Fixes

* Add minimum value constraint for count and user limit inputs in CouponForm ([6991b69](https://github.com/perfect-panel/ppanel-web/commit/6991b69))
* Add protocol-related constants, default configurations, field definitions, and validation modes ([d685407](https://github.com/perfect-panel/ppanel-web/commit/d685407))
* Added the enabled field in the protocol configuration, updated the related type definition and default configuration ([2b0cf9a](https://github.com/perfect-panel/ppanel-web/commit/2b0cf9a))
* Filter available protocols to exclude disabled ones in NodeForm ([982d288](https://github.com/perfect-panel/ppanel-web/commit/982d288))
* Refactor key generation logic and update dependencies for ML-KEM-768 integration ([b8f630f](https://github.com/perfect-panel/ppanel-web/commit/b8f630f))
2025-09-16 17:42:46 +00:00
web
982d2882e9 🐛 fix: Filter available protocols to exclude disabled ones in NodeForm 2025-09-16 10:30:49 -07:00
web
2b0cf9a46d 🐛 fix: Added the enabled field in the protocol configuration, updated the related type definition and default configuration 2025-09-16 10:17:39 -07:00
web
d6854076fe 🐛 fix: Add protocol-related constants, default configurations, field definitions, and validation modes 2025-09-16 04:50:05 -07:00
web
6991b69d40 🐛 fix: Add minimum value constraint for count and user limit inputs in CouponForm 2025-09-16 04:33:42 -07:00
web
b8f630f8ab 🐛 fix: Refactor key generation logic and update dependencies for ML-KEM-768 integration 2025-09-16 04:32:16 -07:00
semantic-release-bot
5ce5d62b22 🔖 chore(release): v1.4.3 [skip ci]
## [1.4.3](https://github.com/perfect-panel/ppanel-web/compare/v1.4.2...v1.4.3) (2025-09-16)

### 🐛 Bug Fixes

* Add success toast message for sorting in nodes and servers pages ([2d5175d](https://github.com/perfect-panel/ppanel-web/commit/2d5175d))
* Implement encryption and obfuscation features in protocol configuration ([54de16b](https://github.com/perfect-panel/ppanel-web/commit/54de16b))
* Refactor toB64 function to toB64Url for URL-safe base64 encoding in VlessX25519Pair generation ([8700cf6](https://github.com/perfect-panel/ppanel-web/commit/8700cf6))
* Simplify initialValues assignment and update node submission logic in NodesPage ([05d6c89](https://github.com/perfect-panel/ppanel-web/commit/05d6c89))
* Update bun.lockb to reflect dependency changes ([ebcebd7](https://github.com/perfect-panel/ppanel-web/commit/ebcebd7))
2025-09-16 05:13:48 +00:00
web
2d5175d70f 🐛 fix: Add success toast message for sorting in nodes and servers pages 2025-09-15 21:51:02 -07:00
web
05d6c8947c 🐛 fix: Simplify initialValues assignment and update node submission logic in NodesPage 2025-09-15 21:39:13 -07:00
web
8700cf6a91 🐛 fix: Refactor toB64 function to toB64Url for URL-safe base64 encoding in VlessX25519Pair generation 2025-09-15 21:12:25 -07:00
web
ebcebd7ddf 🐛 fix: Update bun.lockb to reflect dependency changes 2025-09-15 09:45:08 -07:00
web
54de16bdd5 🐛 fix: Implement encryption and obfuscation features in protocol configuration 2025-09-15 09:35:03 -07:00
semantic-release-bot
597a01885b 🔖 chore(release): v1.4.2 [skip ci]
## [1.4.2](https://github.com/perfect-panel/ppanel-web/compare/v1.4.1...v1.4.2) (2025-09-15)

### 🐛 Bug Fixes

* Add GitHub template repository link to ProtocolForm header for easier access ([8a0baf3](https://github.com/perfect-panel/ppanel-web/commit/8a0baf3))
* Add readOnly prop to MonacoEditor and TemplatePreview components for improved content handling ([c4c4d5a](https://github.com/perfect-panel/ppanel-web/commit/c4c4d5a))
2025-09-15 11:12:27 +00:00
web
8a0baf3a61 🐛 fix: Add GitHub template repository link to ProtocolForm header for easier access 2025-09-15 04:09:14 -07:00
web
c4c4d5aea3 🐛 fix: Add readOnly prop to MonacoEditor and TemplatePreview components for improved content handling 2025-09-15 03:50:15 -07:00
semantic-release-bot
15540bfe16 🔖 chore(release): v1.4.1 [skip ci]
## [1.4.1](https://github.com/perfect-panel/ppanel-web/compare/v1.4.0...v1.4.1) (2025-09-15)

### 🐛 Bug Fixes

* Add copy subscription functionality to user subscription dashboard and improve localization for new features ([e2a357f](https://github.com/perfect-panel/ppanel-web/commit/e2a357f))
* Simplify handleInputBlur function by removing unnecessary setTimeout ([6341562](https://github.com/perfect-panel/ppanel-web/commit/6341562))
* Update TemplatePreview to use MonacoEditor for content display and improve error handling ([1d52642](https://github.com/perfect-panel/ppanel-web/commit/1d52642))
* Update user dashboard link to correct path ([131693b](https://github.com/perfect-panel/ppanel-web/commit/131693b))
2025-09-15 06:21:43 +00:00
web
634156206a 🐛 fix: Simplify handleInputBlur function by removing unnecessary setTimeout 2025-09-14 23:18:42 -07:00
web
e2a357fea7 🐛 fix: Add copy subscription functionality to user subscription dashboard and improve localization for new features 2025-09-14 23:09:59 -07:00
web
1d52642cb7 🐛 fix: Update TemplatePreview to use MonacoEditor for content display and improve error handling 2025-09-14 22:54:50 -07:00
web
131693b604 🐛 fix: Update user dashboard link to correct path 2025-09-14 08:30:24 -07:00
semantic-release-bot
d3999c640c 🔖 chore(release): v1.4.0 [skip ci]
# [1.4.0](https://github.com/perfect-panel/ppanel-web/compare/v1.3.0...v1.4.0) (2025-09-14)

### ♻ Code Refactoring

* **logs**: Add localization files and update existing translations for multiple languages ([2f20ac9](https://github.com/perfect-panel/ppanel-web/commit/2f20ac9))
* **subscribe-form**: Replace server_group and server with node_tags and nodes in default values and form schema ([38dda84](https://github.com/perfect-panel/ppanel-web/commit/38dda84))
* Add localization updates for log and server files across multiple languages ([2bcd4cf](https://github.com/perfect-panel/ppanel-web/commit/2bcd4cf))
* Clean up NodeForm and ServerForm components by removing unused functions and optimizing state management ([10250d9](https://github.com/perfect-panel/ppanel-web/commit/10250d9))
* Enhance log pages with Badge component and update translations ([a4de9df](https://github.com/perfect-panel/ppanel-web/commit/a4de9df))
* Make 'scheme' field optional in client form schema ([f4a1237](https://github.com/perfect-panel/ppanel-web/commit/f4a1237))
* Refactor server management API endpoints and typings ([4f7cc80](https://github.com/perfect-panel/ppanel-web/commit/4f7cc80))
* Remove application management forms and related configurations ([0c43844](https://github.com/perfect-panel/ppanel-web/commit/0c43844))
* Remove default options from TagInput component for improved flexibility ([6a3bb70](https://github.com/perfect-panel/ppanel-web/commit/6a3bb70))
* Remove unused preview state variables and add sort order to node properties ([e63f823](https://github.com/perfect-panel/ppanel-web/commit/e63f823))
* Rename buildScheme to buildSchema and update imports in server form components ([ee98e7e](https://github.com/perfect-panel/ppanel-web/commit/ee98e7e))
* Simplify node display in subscribe form and remove unused Badge import ([551135d](https://github.com/perfect-panel/ppanel-web/commit/551135d))
* Update bun.lockb to reflect dependency changes ([ba2b50e](https://github.com/perfect-panel/ppanel-web/commit/ba2b50e))
* Update component imports and improve code consistency ([59faeab](https://github.com/perfect-panel/ppanel-web/commit/59faeab))
* Update dependencies and improve code consistency across multiple files ([e37ae49](https://github.com/perfect-panel/ppanel-web/commit/e37ae49))
* Update localization files and service imports ([d4b37e4](https://github.com/perfect-panel/ppanel-web/commit/d4b37e4))

###  Features

* **config**: Add translations for server configuration in multiple languages ([f9a7ece](https://github.com/perfect-panel/ppanel-web/commit/f9a7ece))
* **logs**: Add various log pages for tracking user activities and system events ([d85af49](https://github.com/perfect-panel/ppanel-web/commit/d85af49))
* Add bandwidth fields and placeholders for upload and download in server configuration forms; update localization files for multiple languages ([3e5402f](https://github.com/perfect-panel/ppanel-web/commit/3e5402f))
* Add batch delete functionality and enhance chart tooltips in statistics cards ([c4f536e](https://github.com/perfect-panel/ppanel-web/commit/c4f536e))
* Add language support and descriptions in product localization files ([fd48856](https://github.com/perfect-panel/ppanel-web/commit/fd48856))
* Add log cleanup settings and update localization files ([6ccf9b8](https://github.com/perfect-panel/ppanel-web/commit/6ccf9b8))
* Add queryNodeTag function and integrate tag retrieval in NodeForm and SubscribeForm components ([4563c57](https://github.com/perfect-panel/ppanel-web/commit/4563c57))
* Add quota management features and localization updates ([fce627b](https://github.com/perfect-panel/ppanel-web/commit/fce627b))
* Add server form component with protocol configuration and localization support ([217ddce](https://github.com/perfect-panel/ppanel-web/commit/217ddce))
* Enhance TagInput component with option handling and improved tag addition logic ([b6e778d](https://github.com/perfect-panel/ppanel-web/commit/b6e778d))
* Implement data migration functionality and update localization files ([6d81bfd](https://github.com/perfect-panel/ppanel-web/commit/6d81bfd))
* Refactor user detail and subscription management components ([973c06f](https://github.com/perfect-panel/ppanel-web/commit/973c06f))
* Update server list fetching logic and adjust query parameters ([5272360](https://github.com/perfect-panel/ppanel-web/commit/5272360))

### 🐛 Bug Fixes

* **page**: Refine version checking logic and remove unnecessary comments for clarity ([26176a7](https://github.com/perfect-panel/ppanel-web/commit/26176a7))
* Add localization updates and new utility functions ([4da5960](https://github.com/perfect-panel/ppanel-web/commit/4da5960))
* Add user_subscribe_id filter to SubscribeLogPage and update typings; disable eslint in service index files ([ab6f6a6](https://github.com/perfect-panel/ppanel-web/commit/ab6f6a6))
* Added system version card and system log dialog components; updated statistics page to include total server and user statistics ([fe69980](https://github.com/perfect-panel/ppanel-web/commit/fe69980))
* Adjust timestamp calculations to use milliseconds instead of seconds in quota broadcast form submission ([8dffd69](https://github.com/perfect-panel/ppanel-web/commit/8dffd69))
* Correct cookie key format for sidebar state retrieval ([9e01f4f](https://github.com/perfect-panel/ppanel-web/commit/9e01f4f))
* Improve UI for protocol status display in server form component ([461fdb1](https://github.com/perfect-panel/ppanel-web/commit/461fdb1))
* Increase pagination size limit for server and node lists to improve data retrieval ([7c0a312](https://github.com/perfect-panel/ppanel-web/commit/7c0a312))
* Optimize Task Manager to use milliseconds to calculate timers, and simplify import statements ([d8fa13b](https://github.com/perfect-panel/ppanel-web/commit/d8fa13b))
* Refactor protocol status display for improved readability in server form component ([f700be0](https://github.com/perfect-panel/ppanel-web/commit/f700be0))
* Remove GroupTable and related components, simplify SubscribeTable and update language handling in subscription forms ([1ab9b39](https://github.com/perfect-panel/ppanel-web/commit/1ab9b39))
* Remove redundant transport label from localization files ([88ce8d7](https://github.com/perfect-panel/ppanel-web/commit/88ce8d7))
* Remove unnecessary comments and improve variable handling in GoTemplateEditor; ensure zero value displays as empty in EnhancedInput ([c4a47a4](https://github.com/perfect-panel/ppanel-web/commit/c4a47a4))
* Remove unnecessary comments to simplify code readability ([a988cb3](https://github.com/perfect-panel/ppanel-web/commit/a988cb3))
* Replace MarkdownEditor with HTMLEditor in EmailBroadcastForm; simplify content rendering in EmailTaskManager; disable eslint in service index files ([e2d83ec](https://github.com/perfect-panel/ppanel-web/commit/e2d83ec))
* Replace redundant icon rendering with a single instance in system version card component ([e4429a5](https://github.com/perfect-panel/ppanel-web/commit/e4429a5))
* Update billing URL fetching logic and improve version handling in system version card component ([1c8d4af](https://github.com/perfect-panel/ppanel-web/commit/1c8d4af))
* Update condition for plugin field in PROTOCOL_FIELDS to include specific plugins ([6376ec1](https://github.com/perfect-panel/ppanel-web/commit/6376ec1))
* Update getAppSubLink function to improve URL handling and encoding logic ([351fffc](https://github.com/perfect-panel/ppanel-web/commit/351fffc))
* Update order_id to order_no in BalanceLogPage and related typings; enhance timezone switch component with additional features and localization updates ([ac36075](https://github.com/perfect-panel/ppanel-web/commit/ac36075))
* Update protocol plugin handling and add new options in typings ([6ca2433](https://github.com/perfect-panel/ppanel-web/commit/6ca2433))
* Update release URLs to include 'v' prefix for versioning in system version card component ([1d526b5](https://github.com/perfect-panel/ppanel-web/commit/1d526b5))
* Update SidebarLeft component styles to enhance hover effects ([e4fbd5c](https://github.com/perfect-panel/ppanel-web/commit/e4fbd5c))
* Update validation for days and gift_value fields in QuotaBroadcastForm; set default values to avoid errors ([39d746f](https://github.com/perfect-panel/ppanel-web/commit/39d746f))

### 📝 Documentation

* Merge branch 'main' into develop ([d7f8b3b](https://github.com/perfect-panel/ppanel-web/commit/d7f8b3b))
2025-09-14 13:49:50 +00:00
web
d8fa13bebc 🐛 fix: Optimize Task Manager to use milliseconds to calculate timers, and simplify import statements 2025-09-14 02:58:44 -07:00
web
f700be095a 🐛 fix: Refactor protocol status display for improved readability in server form component 2025-09-14 00:39:18 -07:00
web
461fdb1219 🐛 fix: Improve UI for protocol status display in server form component 2025-09-13 23:31:55 -07:00
web
6ca24333da 🐛 fix: Update protocol plugin handling and add new options in typings 2025-09-13 23:17:21 -07:00
web
8dffd69b48 🐛 fix: Adjust timestamp calculations to use milliseconds instead of seconds in quota broadcast form submission 2025-09-13 22:51:57 -07:00
web
1d526b5973 🐛 fix: Update release URLs to include 'v' prefix for versioning in system version card component 2025-09-13 05:18:06 -07:00
web
1c8d4afad0 🐛 fix: Update billing URL fetching logic and improve version handling in system version card component 2025-09-13 05:11:23 -07:00
web
e4429a5c4d 🐛 fix: Replace redundant icon rendering with a single instance in system version card component 2025-09-13 04:17:38 -07:00
web
fe699809a4 🐛 fix: Added system version card and system log dialog components; updated statistics page to include total server and user statistics 2025-09-13 04:07:31 -07:00
web
3e5402f2fc feat: Add bandwidth fields and placeholders for upload and download in server configuration forms; update localization files for multiple languages 2025-09-13 02:59:10 -07:00
web
c4a47a47dd 🐛 fix: Remove unnecessary comments and improve variable handling in GoTemplateEditor; ensure zero value displays as empty in EnhancedInput 2025-09-13 02:23:42 -07:00
web
6376ec1a79 🐛 fix: Update condition for plugin field in PROTOCOL_FIELDS to include specific plugins 2025-09-13 01:36:04 -07:00
web
a988cb3c50 🐛 fix: Remove unnecessary comments to simplify code readability 2025-09-12 21:39:15 -07:00
web
f9a7ece9bf feat(config): Add translations for server configuration in multiple languages 2025-09-12 21:32:14 -07:00
web
39d746f0a1 🐛 fix: Update validation for days and gift_value fields in QuotaBroadcastForm; set default values to avoid errors 2025-09-12 19:05:56 -07:00
web
fce627ba11 feat: Add quota management features and localization updates 2025-09-11 03:34:36 -07:00
web
e2d83ec9e6 🐛 fix: Replace MarkdownEditor with HTMLEditor in EmailBroadcastForm; simplify content rendering in EmailTaskManager; disable eslint in service index files 2025-09-08 03:24:21 -07:00
web
ab6f6a64c2 🐛 fix: Add user_subscribe_id filter to SubscribeLogPage and update typings; disable eslint in service index files 2025-09-06 01:24:26 -07:00
web
ac36075e7b 🐛 fix: Update order_id to order_no in BalanceLogPage and related typings; enhance timezone switch component with additional features and localization updates 2025-09-05 08:50:57 -07:00
web
a4de9df1fc ♻️ refactor: Enhance log pages with Badge component and update translations 2025-09-05 07:14:57 -07:00
web
d7f8b3b707 📝 docs: Merge branch 'main' into develop 2025-09-05 04:55:51 -07:00
web
88ce8d7f85 🐛 fix: Remove redundant transport label from localization files 2025-09-05 04:53:55 -07:00
web
2bcd4cf30c ♻️ refactor: Add localization updates for log and server files across multiple languages
- Added new keys for "server", "subscribe", "detail", "pending", "sending", "sent", and "unknown" in log.json files for various languages.
- Introduced a "type" object with transaction types (Recharge, Withdraw, Purchase, Refund, Reward, Commission) in log.json files for multiple languages.
- Updated "traffic_ratio" to "Ratio" and added "transport" in servers.json for English localization.
- Ensured consistency and accuracy in translations for all affected languages including German, English, Spanish, French, Russian, Chinese, and more.
2025-09-05 04:48:10 -07:00
web
351fffcc78 🐛 fix: Update getAppSubLink function to improve URL handling and encoding logic 2025-09-04 22:51:59 -07:00
web
4da59609b4 🐛 fix: Add localization updates and new utility functions 2025-09-04 22:30:33 -07:00
web
e4fbd5c754 🐛 fix: Update SidebarLeft component styles to enhance hover effects 2025-09-04 05:12:24 -07:00
web
fd48856019 feat: Add language support and descriptions in product localization files
- Added language, languageDescription, and languagePlaceholder fields to product.json for multiple locales (ja-JP, ko-KR, no-NO, pl-PL, pt-BR, ro-RO, ru-RU, th-TH, tr-TR, uk-UA, vi-VN, zh-HK).
- Removed group-related fields from product.json for cleaner structure.
- Updated API calls in user services to include language parameter for subscription retrieval.
- Enhanced type definitions for subscription requests to accommodate language parameter.
2025-09-04 01:26:50 -07:00
web
1ab9b39e8a 🐛 fix: Remove GroupTable and related components, simplify SubscribeTable and update language handling in subscription forms 2025-09-03 15:46:36 -07:00
web
4563c570ac feat: Add queryNodeTag function and integrate tag retrieval in NodeForm and SubscribeForm components 2025-09-03 09:59:54 -07:00
web
9e01f4f590 🐛 fix: Correct cookie key format for sidebar state retrieval 2025-09-03 09:41:23 -07:00
web
7c0a312163 🐛 fix: Increase pagination size limit for server and node lists to improve data retrieval 2025-09-03 09:16:36 -07:00
web
10250d9e34 ♻️ refactor: Clean up NodeForm and ServerForm components by removing unused functions and optimizing state management 2025-09-03 08:58:18 -07:00
web
6a3bb7016e ♻️ refactor: Remove default options from TagInput component for improved flexibility 2025-09-03 07:59:29 -07:00
web
b6e778d482 feat: Enhance TagInput component with option handling and improved tag addition logic 2025-09-03 07:57:48 -07:00
web
e63f823b0b ♻️ refactor: Remove unused preview state variables and add sort order to node properties 2025-09-03 07:20:44 -07:00
web
c4f536eb05 feat: Add batch delete functionality and enhance chart tooltips in statistics cards 2025-09-03 07:17:21 -07:00
web
f4a1237619 ♻️ refactor: Make 'scheme' field optional in client form schema 2025-09-03 03:01:04 -07:00
web
5272360c77 feat: Update server list fetching logic and adjust query parameters 2025-09-03 02:23:24 -07:00
web
6d81bfdaeb feat: Implement data migration functionality and update localization files 2025-09-03 01:56:21 -07:00
web
59faeab34a ♻️ refactor: Update component imports and improve code consistency
- Refactored sidebar component to include additional sheet elements and improved accessibility with SheetHeader, SheetTitle, and SheetDescription.
- Updated skeleton component for better readability and consistency in class names.
- Refined slider component by standardizing import statements and enhancing class name formatting.
- Enhanced sonner component with consistent import statements and improved class name formatting.
- Standardized switch component imports and class names for better readability.
- Improved table component structure and class name consistency across various elements.
- Refactored tabs component for better readability and consistent class name formatting.
- Updated textarea component for improved readability and consistency in class names.
- Fixed timeline component to safely access getBoundingClientRect.
- Refactored toggle group and toggle components for improved readability and consistency in class names.
- Updated tooltip component for better readability and consistent class name formatting.
- Enhanced enhanced-input component to support generic types for better type safety.
- Refactored use-mobile hook for improved readability and consistency.
- Updated countries utility to make certain properties optional for better flexibility.
- Refined tailwind configuration for improved readability and consistency in theme settings.
2025-09-02 06:00:28 -07:00
web
6ccf9b8bdc feat: Add log cleanup settings and update localization files
- Introduced log cleanup settings in the admin panel, allowing configuration of automatic log clearing and retention periods.
- Updated English, Spanish, French, German, and other localization files to include new log cleanup settings.
- Added new fields for referral percentage and first purchase only in user settings.
- Implemented API endpoints for getting and updating log settings.
- Enhanced the admin dashboard with a new log cleanup form component.
2025-09-01 10:25:04 -07:00
web
d4b37e4997 ♻️ refactor: Update localization files and service imports 2025-08-27 08:49:06 -07:00
web
ba2b50e972 ♻️ refactor: Update bun.lockb to reflect dependency changes 2025-08-27 08:06:47 -07:00
web
e37ae49960 ♻️ refactor: Update dependencies and improve code consistency across multiple files 2025-08-27 08:03:03 -07:00
web
973c06f0fa feat: Refactor user detail and subscription management components 2025-08-27 06:28:51 -07:00
web
2f20ac95da ♻️ refactor(logs): Add localization files and update existing translations for multiple languages 2025-08-26 12:10:17 -07:00
web
551135de77 ♻️ refactor: Simplify node display in subscribe form and remove unused Badge import 2025-08-26 11:38:45 -07:00
web
ee98e7e513 ♻️ refactor: Rename buildScheme to buildSchema and update imports in server form components 2025-08-26 11:37:13 -07:00
web
38dda842c0 ♻️ refactor(subscribe-form): Replace server_group and server with node_tags and nodes in default values and form schema 2025-08-26 11:34:01 -07:00
web
d85af491aa feat(logs): Add various log pages for tracking user activities and system events 2025-08-26 11:29:12 -07:00
web
4f7cc807af ♻️ refactor: Refactor server management API endpoints and typings 2025-08-26 09:37:15 -07:00
lyndon986
327f98cfa7
renew README.zh-CN.md 2025-08-26 02:00:08 +10:00
lyndon986
01ff6ec908
renew README.md 2025-08-26 01:59:28 +10:00
lyndon986
b41296eb44
renew README.md 2025-08-26 01:58:49 +10:00
web
217ddce60c feat: Add server form component with protocol configuration and localization support 2025-08-23 09:10:05 -07:00
web
26176a7afa 🐛 fix(page): Refine version checking logic and remove unnecessary comments for clarity 2025-08-18 03:04:17 -07:00
web
0c43844a6f ♻️ refactor: Remove application management forms and related configurations 2025-08-18 02:55:37 -07:00
474 changed files with 27511 additions and 14417 deletions

790
.gitea/workflows/docker.yml Normal file
View File

@ -0,0 +1,790 @@
name: CI
on:
push:
branches:
- main
- develop
- cicd
pull_request:
branches:
- main
- develop
- cicd
env:
DOMAIN_URL: git.kxsw.us
REPO: ${{ vars.REPO }}
TELEGRAM_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
TELEGRAM_CHAT_ID: "-4940243803"
DOCKER_REGISTRY: registry.kxsw.us
DOCKER_BUILDKIT: 1
DOCKER_API_VERSION: "1.44"
# Host SSH - 根据分支动态选择
SSH_HOST: ${{ github.ref_name == 'main' && vars.PRO_SSH_HOST || (github.ref_name == 'develop' && vars.DEV_SSH_HOST || vars.PRO_SSH_HOST) }}
SSH_PORT: ${{ github.ref_name == 'main' && vars.PRO_SSH_PORT || (github.ref_name == 'develop' && vars.DEV_SSH_PORT || vars.PRO_SSH_PORT) }}
SSH_USER: ${{ github.ref_name == 'main' && vars.PRO_SSH_USER || (github.ref_name == 'dedevelopv' && vars.DEV_SSH_USER || vars.PRO_SSH_USER) }}
SSH_PASSWORD: ${{ github.ref_name == 'main' && vars.PRO_SSH_PASSWORD || (github.ref_name == 'dedevelopv' && vars.DEV_SSH_PASSWORD || vars.PRO_SSH_PASSWORD) }}
jobs:
build:
runs-on: fastvpn-admin01
container:
image: node:20
strategy:
matrix:
# 只有node支持版本号别名
node: ['20.15.1']
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: 缓存服务健康检查
id: cache-health
continue-on-error: true
run: |
echo "检查缓存服务可用性..."
# 设置缓存可用性标志
CACHE_AVAILABLE=true
# 测试GitHub Actions缓存API
if ! curl -s --connect-timeout 10 --max-time 30 "https://api.github.com/repos/${{ github.repository }}/actions/caches" > /dev/null 2>&1; then
echo "⚠️ GitHub Actions缓存服务不可用将跳过缓存步骤"
CACHE_AVAILABLE=false
else
echo "✅ 缓存服务可用"
fi
echo "CACHE_AVAILABLE=$CACHE_AVAILABLE" >> $GITHUB_ENV
echo "cache-available=$CACHE_AVAILABLE" >> $GITHUB_OUTPUT
- name: 缓存降级提示
if: env.CACHE_AVAILABLE == 'false'
run: |
echo "🔄 缓存服务不可用,构建将在无缓存模式下进行"
echo "⏱️ 这可能会增加构建时间,但不会影响构建结果"
echo "📦 所有依赖将重新下载和安装"
- name: Install system tools (jq, docker, curl)
run: |
set -e
export DEBIAN_FRONTEND=noninteractive
echo "Waiting for apt/dpkg locks (unattended-upgrades) to release..."
# Wait up to 300s for unattended-upgrades/apt/dpkg locks
end=$((SECONDS+300))
while true; do
LOCKS_BUSY=0
# If unattended-upgrades is running, mark busy
if pgrep -x unattended-upgrades >/dev/null 2>&1; then LOCKS_BUSY=1; fi
# If fuser exists, check common lock files
if command -v fuser >/dev/null 2>&1; then
if fuser /var/lib/dpkg/lock >/dev/null 2>&1 \
|| fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 \
|| fuser /var/lib/apt/lists/lock >/dev/null 2>&1; then
LOCKS_BUSY=1
fi
fi
# Break if not busy
if [ "$LOCKS_BUSY" -eq 0 ]; then break; fi
# Timeout after ~5 minutes
if [ $SECONDS -ge $end ]; then
echo "Timeout waiting for apt/dpkg locks, proceeding with Dpkg::Lock::Timeout..."
break
fi
echo "Still waiting for locks..."; sleep 5
done
apt-get update -y -o Dpkg::Lock::Timeout=600
# 基础工具和GPG
apt-get install -y -o Dpkg::Lock::Timeout=600 jq curl ca-certificates gnupg
# 配置Docker官方源安装新版CLI与Buildx插件支持 API 1.44+
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian $(. /etc/os-release && echo $VERSION_CODENAME) stable" > /etc/apt/sources.list.d/docker.list
apt-get update -y -o Dpkg::Lock::Timeout=600
apt-get install -y -o Dpkg::Lock::Timeout=600 docker-ce-cli docker-buildx-plugin
docker --version
jq --version
curl --version
- name: Set up Docker Buildx
run: |
# Check if buildx is available
if docker buildx version >/dev/null 2>&1; then
echo "Docker Buildx is available"
# Create builder if it doesn't exist
if ! docker buildx ls | grep -q "builder"; then
docker buildx create --name builder --driver docker-container
fi
# Use the builder
docker buildx use builder
docker buildx inspect --bootstrap
else
echo "Docker Buildx not available, using regular docker build"
fi
- name: Install Bun
run: |
echo "=== Installing Bun ==="
echo "Current working directory: $(pwd)"
echo "Current user: $(whoami)"
echo "Home directory: $HOME"
# 设置Bun安装路径
export BUN_INSTALL="$HOME/.bun"
echo "BUN_INSTALL=$BUN_INSTALL" >> $GITHUB_ENV
echo "PATH=$BUN_INSTALL/bin:${PATH}" >> $GITHUB_ENV
# 检查缓存是否存在
if [ -d "$BUN_INSTALL" ]; then
echo "✅ Bun cache found at $BUN_INSTALL"
ls -la "$BUN_INSTALL" || true
else
echo "❌ No Bun cache found, will install fresh"
fi
# 安装Bun
curl -fsSL https://bun.sh/install | bash
# 验证安装
"$BUN_INSTALL/bin/bun" --version
echo "✅ Bun installed successfully"
- name: Configure npm registry (npmmirror) and canvas mirror
run: |
echo "registry=https://registry.npmmirror.com" >> .npmrc
echo "canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas" >> .npmrc
- name: Install dependencies cache (Bun)
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: ~/.bun
key: bun-${{ runner.os }}-${{ matrix.node }}-${{ hashFiles('bun.lock') }}
restore-keys: |
bun-${{ runner.os }}-${{ matrix.node }}-
bun-${{ runner.os }}-
- name: Install dependencies cache (node_modules)
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: |
node_modules
apps/*/node_modules
packages/*/node_modules
key: node-modules-${{ runner.os }}-${{ matrix.node }}-${{ hashFiles('bun.lock', 'package.json', 'apps/*/package.json', 'packages/*/package.json') }}
restore-keys: |
node-modules-${{ runner.os }}-${{ matrix.node }}-
node-modules-${{ runner.os }}-
- name: 缓存状态检查和设置
run: |
echo "=== 缓存状态检查 ==="
echo "检查缓存恢复状态..."
# 检查各种缓存目录
echo "Bun缓存: $([ -d ~/.bun ] && echo '✅ 已发现' || echo '❌ 缺失')"
echo "node_modules: $([ -d node_modules ] && echo '✅ 已发现' || echo '❌ 缺失')"
echo "Turbo缓存: $([ -d .turbo ] && echo '✅ 已发现' || echo '❌ 缺失')"
# 显示缓存大小
if [ -d ~/.bun ]; then
echo "Bun缓存大小: $(du -sh ~/.bun 2>/dev/null || echo '未知')"
fi
if [ -d node_modules ]; then
echo "node_modules大小: $(du -sh node_modules 2>/dev/null || echo '未知')"
fi
if [ -d .turbo ]; then
echo "Turbo缓存大小: $(du -sh .turbo 2>/dev/null || echo '未知')"
fi
echo "=== 缓存设置 ==="
# 确保缓存目录存在且权限正确
mkdir -p ~/.bun ~/.cache .turbo
chmod -R 755 ~/.bun ~/.cache .turbo 2>/dev/null || true
# 设置Bun环境变量
echo "BUN_INSTALL_CACHE_DIR=$HOME/.cache/bun" >> $GITHUB_ENV
echo "BUN_INSTALL_BIN_DIR=$HOME/.bun/bin" >> $GITHUB_ENV
echo "✅ 缓存目录已准备完成"
- name: Turborepo cache (.turbo)
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: .turbo
key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json') }}-${{ hashFiles('apps//package.json') }}-${{ hashFiles('packages//package.json') }}-${{ hashFiles('bun.lock') }}
restore-keys: |
turbo-${{ runner.os }}-${{ hashFiles('turbo.json') }}-${{ hashFiles('apps//package.json') }}-${{ hashFiles('packages//package.json') }}-
turbo-${{ runner.os }}-${{ hashFiles('turbo.json') }}-
turbo-${{ runner.os }}-
- name: 安装依赖 (bun)
run: |
echo "=== 依赖安装调试信息 ==="
echo "当前目录: $(pwd)"
echo "Bun版本: $(bun --version)"
# 检查node_modules缓存状态
if [ -d "node_modules" ]; then
echo "✅ 发现node_modules缓存"
echo "node_modules大小: $(du -sh node_modules 2>/dev/null || echo '未知')"
else
echo "❌ 未发现node_modules缓存"
fi
# 检查bun.lock文件
if [ -f "bun.lock" ]; then
echo "✅ 发现bun.lock文件"
else
echo "❌ 未发现bun.lock文件"
fi
echo "=== 开始安装依赖 ==="
echo "安装开始时间: $(date)"
bun install --frozen-lockfile
echo "安装完成时间: $(date)"
echo "=== 依赖安装完成 ==="
echo "最终node_modules大小: $(du -sh node_modules 2>/dev/null || echo '未知')"
# 验证缓存效果
echo "=== 缓存效果验证 ==="
if [ -d "node_modules" ]; then
echo "✅ 依赖安装成功"
echo "包数量: $(ls node_modules | wc -l 2>/dev/null || echo '未知')"
else
echo "⚠️ 依赖可能未完全安装"
fi
- name: Decide build target (admin/user/both)
run: |
set -e
COMMIT_MSG="${{ github.event.head_commit.message }}"
BUILD_TARGET="both"
if echo "$COMMIT_MSG" | grep -qi "\[admin-only\]"; then
BUILD_TARGET="admin"
elif echo "$COMMIT_MSG" | grep -qi "\[user-only\]"; then
BUILD_TARGET="user"
else
if git rev-parse HEAD^ >/dev/null 2>&1; then
RANGE="HEAD^..HEAD"
else
RANGE="$(git rev-list --max-parents=0 HEAD)..HEAD"
fi
CHANGED=$(git diff --name-only $RANGE || true)
ADMIN_MATCH=$(echo "$CHANGED" | grep -E '^(apps/admin/|docker/ppanel-admin-web/)' || true)
USER_MATCH=$(echo "$CHANGED" | grep -E '^(apps/user/|docker/ppanel-user-web/)' || true)
PACKAGE_MATCH=$(echo "$CHANGED" | grep -E '^(packages/|turbo.json|package.json|bun.lock)' || true)
if [ -n "$PACKAGE_MATCH" ]; then
BUILD_TARGET="both"
else
if [ -n "$ADMIN_MATCH" ] && [ -z "$USER_MATCH" ]; then BUILD_TARGET="admin"; fi
if [ -n "$USER_MATCH" ] && [ -z "$ADMIN_MATCH" ]; then BUILD_TARGET="user"; fi
if [ -n "$ADMIN_MATCH" ] && [ -n "$USER_MATCH" ]; then BUILD_TARGET="both"; fi
fi
fi
echo "BUILD_TARGET=$BUILD_TARGET" >> $GITHUB_ENV
echo "Decided BUILD_TARGET=$BUILD_TARGET"
- name: Read version from package.json
run: |
if [ "$BUILD_TARGET" = "admin" ]; then
VERSION=$(jq -r .version apps/admin/package.json)
echo "使用 admin 应用版本: $VERSION"
elif [ "$BUILD_TARGET" = "user" ]; then
VERSION=$(jq -r .version apps/user/package.json)
echo "使用 user 应用版本: $VERSION"
else
# both 或其他情况使用根目录版本
VERSION=$(jq -r .version package.json)
echo "使用根目录版本: $VERSION"
fi
if [ "$VERSION" = "null" ] || [ -z "$VERSION" ] || [ "$VERSION" = "undefined" ]; then
echo "检测到版本为空,回退到根目录版本"
VERSION=$(jq -r .version package.json)
fi
echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: 根据分支动态设置API地址
run: |
if [ "${{ github.ref_name }}" = "main" ]; then
echo "NEXT_PUBLIC_API_URL=https://api.hifast.biz" >> $GITHUB_ENV
echo "为main分支设置生产环境API地址"
elif [ "${{ github.ref_name }}" = "develop" ]; then
echo "NEXT_PUBLIC_API_URL=https://api.hifast.biz" >> $GITHUB_ENV
echo "为 develop 分支设置开发环境API地址"
else
echo "NEXT_PUBLIC_API_URL=https://api.hifast.biz" >> $GITHUB_ENV
echo "为其他分支设置默认API地址"
fi
echo "BRANCH=${{ github.ref_name }}" >> $GITHUB_ENV
- name: Cache Next.js build artifacts (.next/cache)
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: |
apps/admin/.next/cache
apps/user/.next/cache
key: nextcache-${{ runner.os }}-${{ hashFiles('apps//package.json') }}-${{ hashFiles('packages//package.json') }}-${{ hashFiles('turbo.json') }}-${{ hashFiles('bun.lock') }}
restore-keys: |
nextcache-${{ runner.os }}-${{ hashFiles('apps//package.json') }}-${{ hashFiles('packages//package.json') }}-
nextcache-${{ runner.os }}-
- name: Cache build outputs
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: |
apps/admin/.next
apps/user/.next
apps/admin/dist
apps/user/dist
key: build-${{ runner.os }}-${{ hashFiles('apps//*.ts', 'apps//*.tsx', 'apps//*.js', 'apps//*.jsx') }}-${{ hashFiles('packages//*.ts', 'packages//*.tsx') }}-${{ hashFiles('bun.lock') }}
restore-keys: |
build-${{ runner.os }}-${{ hashFiles('apps//*.ts', 'apps//*.tsx', 'apps//*.js', 'apps//*.jsx') }}-
build-${{ runner.os }}-
- name: Cache ESLint
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: |
.eslintcache
apps/admin/.eslintcache
apps/user/.eslintcache
key: eslint-${{ runner.os }}-${{ hashFiles('.eslintrc*', 'apps//.eslintrc*', 'packages//.eslintrc*') }}-${{ hashFiles('bun.lock') }}
restore-keys: |
eslint-${{ runner.os }}-
- name: Cache TypeScript
if: env.CACHE_AVAILABLE == 'true'
uses: actions/cache@v4
continue-on-error: true
with:
path: |
.tsbuildinfo
apps/admin/.tsbuildinfo
apps/user/.tsbuildinfo
packages//.tsbuildinfo
key: typescript-${{ runner.os }}-${{ hashFiles('tsconfig*.json', 'apps//tsconfig*.json', 'packages//tsconfig*.json') }}-${{ hashFiles('bun.lock') }}
restore-keys: |
typescript-${{ runner.os }}-
- name: 构建管理面板
if: env.BUILD_TARGET == 'admin' || env.BUILD_TARGET == 'both'
run: bun run build --filter=ppanel-admin-web
- name: 构建用户面板
if: env.BUILD_TARGET == 'user' || env.BUILD_TARGET == 'both'
run: bun run build --filter=ppanel-user-web
- name: 构建并推送管理面板Docker镜像
if: env.BUILD_TARGET == 'admin' || env.BUILD_TARGET == 'both'
run: |
if docker buildx version >/dev/null 2>&1; then
echo "使用docker buildx进行优化构建"
docker buildx build \
--platform linux/amd64 \
--cache-from type=registry,ref=${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:cache \
--cache-to type=registry,ref=${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:cache,mode=max \
-f ./docker/ppanel-admin-web/Dockerfile \
-t ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }} \
--push .
else
echo "使用常规docker构建"
docker build -f ./docker/ppanel-admin-web/Dockerfile -t ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }} .
docker push ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }}
fi
- name: 构建并推送用户面板Docker镜像
if: env.BUILD_TARGET == 'user' || env.BUILD_TARGET == 'both'
run: |
if docker buildx version >/dev/null 2>&1; then
echo "使用docker buildx进行优化构建"
docker buildx build \
--platform linux/amd64 \
--cache-from type=registry,ref=${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:cache \
--cache-to type=registry,ref=${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:cache,mode=max \
-f ./docker/ppanel-user-web/Dockerfile \
-t ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:${{ env.VERSION }} \
--push .
else
echo "使用常规docker构建"
docker build -f ./docker/ppanel-user-web/Dockerfile -t ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:${{ env.VERSION }} .
docker push ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:${{ env.VERSION }}
fi
- name: SSH连接预检查
if: env.BUILD_TARGET == 'admin' || env.BUILD_TARGET == 'user' || env.BUILD_TARGET == 'both'
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ env.SSH_HOST }}
username: ${{ env.SSH_USER }}
password: ${{ env.SSH_PASSWORD }}
port: ${{ env.SSH_PORT }}
timeout: 300s
command_timeout: 600s
debug: true
script: |
echo "=== SSH连接测试 ==="
echo "连接时间: $(date)"
echo "服务器主机名: $(hostname)"
echo "当前用户: $(whoami)"
echo "系统信息: $(uname -a)"
echo "Docker版本: $(docker --version 2>/dev/null || echo 'Docker未安装')"
echo "✅ SSH连接成功"
- name: 部署管理面板到服务器
if: env.BUILD_TARGET == 'admin' || env.BUILD_TARGET == 'both'
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ env.SSH_HOST }}
username: ${{ env.SSH_USER }}
password: ${{ env.SSH_PASSWORD }}
port: ${{ env.SSH_PORT }}
timeout: 300s
command_timeout: 600s
script: |
echo "=== SSH变量调试信息 ==="
echo "DOCKER_REGISTRY: ${{ env.DOCKER_REGISTRY }}"
echo "VERSION: ${{ env.VERSION }}"
echo "NEXT_PUBLIC_API_URL: ${{ env.NEXT_PUBLIC_API_URL }}"
echo "BRANCH: ${{ env.BRANCH }}"
echo "=== 部署管理面板 ==="
# 网络连通性检查
echo "检查镜像服务器连通性..."
REGISTRY_HOST=$(echo "${{ env.DOCKER_REGISTRY }}" | sed 's|https\?://||' | cut -d'/' -f1)
echo "镜像仓库地址: $REGISTRY_HOST"
if ping -c 3 "$REGISTRY_HOST" > /dev/null 2>&1; then
echo "✅ 镜像服务器连通性正常"
else
echo "⚠️ 镜像服务器ping失败但继续尝试拉取镜像"
fi
# 检查Docker登录状态
echo "检查Docker登录状态..."
if docker info > /dev/null 2>&1; then
echo "✅ Docker服务正常"
else
echo "❌ Docker服务异常"
exit 1
fi
# 拉取镜像(带重试)
echo "拉取Docker镜像..."
for i in {1..3}; do
echo "尝试拉取镜像 ($i/3): ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }}"
if docker pull ${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }}; then
echo "✅ 镜像拉取成功"
break
else
echo "❌ 镜像拉取失败,重试 $i/3"
echo "检查网络和镜像仓库状态..."
# 显示详细错误信息
echo "--- 网络诊断信息 ---"
echo "DNS解析测试:"
nslookup "$REGISTRY_HOST" || echo "DNS解析失败"
echo "网络连通性测试:"
ping -c 2 "$REGISTRY_HOST" || echo "ping失败"
echo "Docker镜像仓库连接测试:"
curl -I "https://$REGISTRY_HOST/v2/" 2>/dev/null || echo "仓库API访问失败"
sleep 5
if [ $i -eq 3 ]; then
echo "❌ 镜像拉取失败,部署终止"
echo "请检查:"
echo "1. 网络连接是否正常"
echo "2. 镜像仓库是否可访问"
echo "3. 镜像标签是否存在"
echo "4. Docker登录凭据是否正确"
exit 1
fi
fi
done
# 安全停止和移除容器
echo "检查现有容器状态..."
CONTAINER_NAME="fastvpn-admin-web"
# 检查容器是否存在
if docker ps -aq -f name=$CONTAINER_NAME | grep -q .; then
echo "发现现有容器,开始清理..."
# 检查容器是否正在运行
if docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
echo "停止运行中的容器..."
docker stop $CONTAINER_NAME --time=15 || true
sleep 5
fi
# 检查容器是否正在被移除
echo "检查容器移除状态..."
for i in {1..15}; do
# 尝试获取容器状态
CONTAINER_STATUS=$(docker inspect $CONTAINER_NAME --format='{{.State.Status}}' 2>/dev/null || echo "not_found")
if [ "$CONTAINER_STATUS" = "not_found" ]; then
echo "✅ 容器已不存在"
break
elif [ "$CONTAINER_STATUS" = "removing" ]; then
echo "⏳ 容器正在移除中,等待完成... $i/15"
sleep 3
else
echo "尝试移除容器... $i/15"
if docker rm -f $CONTAINER_NAME 2>/dev/null; then
echo "✅ 容器移除成功"
break
else
echo "⚠️ 容器移除失败,重试..."
sleep 2
fi
fi
# 最后一次尝试强制清理
if [ $i -eq 15 ]; then
echo "🔧 执行强制清理..."
docker kill $CONTAINER_NAME 2>/dev/null || true
sleep 2
docker rm -f $CONTAINER_NAME 2>/dev/null || true
sleep 2
fi
done
else
echo "✅ 未发现现有容器"
fi
echo "启动新容器..."
docker run -d \
--network host \
--name fastvpn-admin-web \
--restart unless-stopped \
-p 3001:3000 \
-e NEXT_PUBLIC_API_URL=${{ env.NEXT_PUBLIC_API_URL }} \
${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-admin-web:${{ env.VERSION }}
# 验证容器启动
echo "验证容器启动状态..."
for i in {1..10}; do
if docker ps -q -f name=fastvpn-admin-web | grep -q .; then
echo "✅ 管理面板部署成功"
docker ps -f name=fastvpn-admin-web --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
exit 0
else
echo "等待容器启动... $i/10"
sleep 3
fi
done
echo "❌ 管理面板部署失败 - 容器未能正常启动"
docker logs fastvpn-admin-web || true
exit 1
- name: 部署用户面板到服务器
if: env.BUILD_TARGET == 'user' || env.BUILD_TARGET == 'both'
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ env.SSH_HOST }}
username: ${{ env.SSH_USER }}
password: ${{ env.SSH_PASSWORD }}
port: ${{ env.SSH_PORT }}
timeout: 300s
command_timeout: 600s
debug: true
script: |
echo "=== SSH变量调试信息 ==="
echo "DOCKER_REGISTRY: ${{ env.DOCKER_REGISTRY }}"
echo "VERSION: ${{ env.VERSION }}"
echo "NEXT_PUBLIC_API_URL: ${{ env.NEXT_PUBLIC_API_URL }}"
echo "BRANCH: ${{ env.BRANCH }}"
echo "=== 部署用户面板 ==="
# 网络连通性检查
echo "检查镜像服务器连通性..."
REGISTRY_HOST=$(echo "${{ env.DOCKER_REGISTRY }}" | sed 's|https\?://||' | cut -d'/' -f1)
echo "镜像仓库地址: $REGISTRY_HOST"
if ping -c 3 "$REGISTRY_HOST" > /dev/null 2>&1; then
echo "✅ 镜像服务器连通性正常"
else
echo "⚠️ 镜像服务器ping失败但继续尝试拉取镜像"
fi
# 检查Docker登录状态
echo "检查Docker登录状态..."
if docker info > /dev/null 2>&1; then
echo "✅ Docker服务正常"
else
echo "❌ Docker服务异常"
exit 1
fi
# 拉取镜像(带重试)
echo "拉取Docker镜像..."
for i in {1..3}; do
echo "尝试拉取镜像 ($i/3): ${{ env.DOCKER_REGISTRY }}/ppanel/ppanel-user-web:${{ env.VERSION }}"
if docker pull ${{ env.DOCKER_REGISTRY }}/ppanel/ppanel-user-web:${{ env.VERSION }}; then
echo "✅ 镜像拉取成功"
break
else
echo "❌ 镜像拉取失败,重试 $i/3"
echo "检查网络和镜像仓库状态..."
# 显示详细错误信息
echo "--- 网络诊断信息 ---"
echo "DNS解析测试:"
nslookup "$REGISTRY_HOST" || echo "DNS解析失败"
echo "网络连通性测试:"
ping -c 2 "$REGISTRY_HOST" || echo "ping失败"
echo "Docker镜像仓库连接测试:"
curl -I "https://$REGISTRY_HOST/v2/" 2>/dev/null || echo "仓库API访问失败"
sleep 5
if [ $i -eq 3 ]; then
echo "❌ 镜像拉取失败,部署终止"
echo "请检查:"
echo "1. 网络连接是否正常"
echo "2. 镜像仓库是否可访问"
echo "3. 镜像标签是否存在"
echo "4. Docker登录凭据是否正确"
exit 1
fi
fi
done
# 安全停止和移除容器
echo "检查现有容器状态..."
CONTAINER_NAME="ppanel-user-web"
# 检查容器是否存在
if docker ps -aq -f name=$CONTAINER_NAME | grep -q .; then
echo "发现现有容器,开始清理..."
# 检查容器是否正在运行
if docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
echo "停止运行中的容器..."
docker stop $CONTAINER_NAME --time=15 || true
sleep 5
fi
# 检查容器是否正在被移除
echo "检查容器移除状态..."
for i in {1..15}; do
# 尝试获取容器状态
CONTAINER_STATUS=$(docker inspect $CONTAINER_NAME --format='{{.State.Status}}' 2>/dev/null || echo "not_found")
if [ "$CONTAINER_STATUS" = "not_found" ]; then
echo "✅ 容器已不存在"
break
elif [ "$CONTAINER_STATUS" = "removing" ]; then
echo "⏳ 容器正在移除中,等待完成... $i/15"
sleep 3
else
echo "尝试移除容器... $i/15"
if docker rm -f $CONTAINER_NAME 2>/dev/null; then
echo "✅ 容器移除成功"
break
else
echo "⚠️ 容器移除失败,重试..."
sleep 2
fi
fi
# 最后一次尝试强制清理
if [ $i -eq 15 ]; then
echo "🔧 执行强制清理..."
docker kill $CONTAINER_NAME 2>/dev/null || true
sleep 2
docker rm -f $CONTAINER_NAME 2>/dev/null || true
sleep 2
fi
done
else
echo "✅ 未发现现有容器"
fi
echo "启动新容器..."
docker run -d \
--network host \
--name fastvpn-user-web \
--restart unless-stopped \
-p 3002:3000 \
-e NEXT_PUBLIC_API_URL=${{ env.NEXT_PUBLIC_API_URL }} \
${{ env.DOCKER_REGISTRY }}/ppanel/fastvpn-user-web:${{ env.VERSION }}
# 验证容器启动
echo "验证容器启动状态..."
for i in {1..10}; do
if docker ps -q -f name=fastvpn-user-web | grep -q .; then
echo "✅ 用户面板部署成功"
docker ps -f name=fastvpn-user-web --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
exit 0
else
echo "等待容器启动... $i/10"
sleep 3
fi
done
echo "❌ 用户面板部署失败 - 容器未能正常启动"
docker logs fastvpn-user-web || true
exit 1
# 步骤5: TG通知 (成功)
- name: 📱 发送成功通知到Telegram
if: success()
uses: appleboy/telegram-action@master
with:
token: ${{ env.TELEGRAM_BOT_TOKEN }}
to: ${{ env.TELEGRAM_CHAT_ID }}
message: |
✅ 部署成功!
📦 项目: ${{ github.repository }}
🌿 分支: ${{ github.ref_name }}
🔖 版本: ${{ env.VERSION }}
🎯 构建目标: ${{ env.BUILD_TARGET }}
🔗 API地址: ${{ env.NEXT_PUBLIC_API_URL }}
📝 提交: ${{ github.sha }}
👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }}
🚀 服务已成功部署到生产环境
# 步骤5: TG通知 (失败)
- name: 📱 发送失败通知到Telegram
if: failure()
uses: appleboy/telegram-action@master
with:
token: ${{ env.TELEGRAM_BOT_TOKEN }}
to: ${{ env.TELEGRAM_CHAT_ID }}
message: |
❌ 部署失败!
📦 项目: ${{ github.repository }}
🌿 分支: ${{ github.ref_name }}
🔖 版本: ${{ env.VERSION }}
🎯 构建目标: ${{ env.BUILD_TARGET }}
📝 提交: ${{ github.sha }}
👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }}
⚠️ 请检查构建日志获取详细信息

View File

@ -1,45 +0,0 @@
name: '🐛 反馈缺陷 Bug Report'
description: '反馈一个问题缺陷 | Report an bug'
title: '[Bug] '
labels: '🐛 Bug'
body:
- type: dropdown
attributes:
label: '💻 系统环境 | Operating System'
options:
- Windows
- macOS
- Ubuntu
- Other Linux
- Other
validations:
required: true
- type: dropdown
attributes:
label: '🌐 浏览器 | Browser'
options:
- Chrome
- Edge
- Safari
- Firefox
- Other
validations:
required: true
- type: textarea
attributes:
label: '🐛 问题描述 | Bug Description'
description: A clear and concise description of the bug.
validations:
required: true
- type: textarea
attributes:
label: '🚦 期望结果 | Expected Behavior'
description: A clear and concise description of what you expected to happen.
- type: textarea
attributes:
label: '📷 复现步骤 | Recurrence Steps'
description: A clear and concise description of how to recurrence.
- type: textarea
attributes:
label: '📝 补充信息 | Additional Information'
description: If your problem needs further explanation, or if the issue you're seeing cannot be reproduced in a gist, please add more information here.

View File

@ -1,21 +0,0 @@
name: '🌠 功能需求 Feature Request'
description: '需求或建议 | Suggest an idea'
title: '[Request] '
labels: '🌠 Feature Request'
body:
- type: textarea
attributes:
label: '🥰 需求描述 | Feature Description'
description: Please add a clear and concise description of the problem you are seeking to solve with this feature request.
validations:
required: true
- type: textarea
attributes:
label: '🧐 解决方案 | Proposed Solution'
description: Describe the solution you'd like in a clear and concise manner.
validations:
required: true
- type: textarea
attributes:
label: '📝 补充信息 | Additional Information'
description: Add any other context about the problem here.

View File

@ -1,15 +0,0 @@
name: '😇 疑问或帮助 Help Wanted'
description: '疑问或需要帮助 | Need help'
title: '[Question] '
labels: '😇 Help Wanted'
body:
- type: textarea
attributes:
label: '🧐 问题描述 | Proposed Solution'
description: A clear and concise description of the proplem.
validations:
required: true
- type: textarea
attributes:
label: '📝 补充信息 | Additional Information'
description: Add any other context about the problem here.

View File

@ -1,7 +0,0 @@
---
name: '📝 其他 Other'
about: '其他问题 | Other issues'
title: ''
labels: ''
assignees: ''
---

View File

@ -1,17 +0,0 @@
#### 💻 变更类型 | Change Type
<!-- For change type, change [ ] to [x]. -->
- \[ ] ✨ feat
- \[ ] 🐛 fix
- \[ ] 💄 style
- \[ ] 🔨 chore
- \[ ] 📝 docs
#### 🔀 变更说明 | Description of Change
<!-- Thank you for your Pull Request. Please provide a description above. -->
#### 📝 补充信息 | Additional Information
<!-- Add any other context about the Pull Request here. -->

View File

@ -1,30 +0,0 @@
name: Dependabot Auto Merge
on:
pull_request_target:
types: [labeled, edited]
jobs:
merge:
if: contains(github.event.pull_request.labels.*.name, 'dependencies')
name: Dependabot Auto Merge
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install deps
run: pnpm install
- name: Merge
uses: ahmadnassri/action-dependabot-auto-merge@v2
with:
command: merge
target: minor
github-token: ${{ secrets.GH_TOKEN }}

View File

@ -1,22 +0,0 @@
name: Issue Check Inactive
on:
schedule:
- cron: '0 0 */15 * *'
permissions:
contents: read
jobs:
issue-check-inactive:
permissions:
issues: write # for actions-cool/issues-helper to update issues
pull-requests: write # for actions-cool/issues-helper to update PRs
runs-on: ubuntu-latest
steps:
- name: check-inactive
uses: actions-cool/issues-helper@v3
with:
actions: 'check-inactive'
inactive-label: 'Inactive'
inactive-day: 30

View File

@ -1,46 +0,0 @@
name: Issue Close Require
on:
schedule:
- cron: '0 0 * * *'
permissions:
contents: read
jobs:
issue-close-require:
permissions:
issues: write # for actions-cool/issues-helper to update issues
pull-requests: write # for actions-cool/issues-helper to update PRs
runs-on: ubuntu-latest
steps:
- name: need reproduce
uses: actions-cool/issues-helper@v3
with:
actions: 'close-issues'
labels: '✅ Fixed'
inactive-day: 3
body: |
Since the issue was labeled with `✅ Fixed`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
由于该 issue 被标记为已修复,同时 3 天未收到回应。现关闭 issue若有任何问题可评论回复。
- name: need reproduce
uses: actions-cool/issues-helper@v3
with:
actions: 'close-issues'
labels: '🤔 Need Reproduce'
inactive-day: 3
body: |
Since the issue was labeled with `🤔 Need Reproduce`, but no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
由于该 issue 被标记为需要更多信息,却 3 天未收到回应。现关闭 issue若有任何问题可评论回复。
- name: need reproduce
uses: actions-cool/issues-helper@v3
with:
actions: 'close-issues'
labels: "🙅🏻‍♀️ WON'T DO"
inactive-day: 3
body: |
Since the issue was labeled with `🙅🏻‍♀️ WON'T DO`, and no response in 3 days. This issue will be closed. If you have any questions, you can comment and reply.
由于该 issue 被标记为暂不处理,同时 3 天未收到回应。现关闭 issue若有任何问题可评论回复。

View File

@ -1,25 +0,0 @@
name: Issue Remove Inactive
on:
issues:
types: [edited]
issue_comment:
types: [created, edited]
permissions:
contents: read
jobs:
issue-remove-inactive:
permissions:
issues: write # for actions-cool/issues-helper to update issues
pull-requests: write # for actions-cool/issues-helper to update PRs
runs-on: ubuntu-latest
steps:
- name: remove inactive
if: github.event.issue.state == 'open' && github.actor == github.event.issue.user.login
uses: actions-cool/issues-helper@v3
with:
actions: 'remove-labels'
issue-number: ${{ github.event.issue.number }}
labels: 'Inactive'

View File

@ -1,89 +0,0 @@
name: Publish Release Assets
on:
release:
types: [published]
permissions:
contents: write
jobs:
publish:
name: Publish Release Assets
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 'latest'
- name: Cache Bun dependencies
uses: actions/cache@v3
with:
path: |
~/.bun
key: ${{ runner.os }}-bun-cache-${{ hashFiles('**/bun.lockb') }}
restore-keys: |
${{ runner.os }}-bun-cache-
- name: Install deps
run: bun install --cache
- name: Build
run: bun run build
- name: Run publish script
run: |
chmod +x scripts/publish.sh
./scripts/publish.sh
- name: Upload tar.gz file to release
uses: softprops/action-gh-release@v2
with:
files: |
out/ppanel-admin-web.tar.gz
out/ppanel-user-web.tar.gz
token: ${{ secrets.GITHUB_TOKEN }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Install jq
run: sudo apt-get install -y jq
- name: Extract version from package.json
id: version
run: echo "PPANEL_VERSION=$(jq -r '.version' package.json)" >> $GITHUB_ENV
- name: Build and push Docker image for ppanel-admin-web
uses: docker/build-push-action@v6
with:
context: .
file: ./docker/ppanel-admin-web/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ secrets.DOCKER_USERNAME }}/ppanel-admin-web:latest
${{ secrets.DOCKER_USERNAME }}/ppanel-admin-web:${{ env.PPANEL_VERSION }}
- name: Build and push Docker image for ppanel-user-web
uses: docker/build-push-action@v6
with:
context: .
file: ./docker/ppanel-user-web/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: |
${{ secrets.DOCKER_USERNAME }}/ppanel-user-web:latest
${{ secrets.DOCKER_USERNAME }}/ppanel-user-web:${{ env.PPANEL_VERSION }}

View File

@ -1,42 +0,0 @@
name: Build and Release
on:
push:
branches: [main, next, beta]
permissions:
contents: write
jobs:
release:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 'latest'
- name: Cache Bun dependencies
uses: actions/cache@v3
with:
path: |
~/.bun
node_modules
key: ${{ runner.os }}-bun-cache-${{ hashFiles('**/bun.lockb') }}
restore-keys: |
${{ runner.os }}-bun-cache-
- name: Install deps
run: bun install
- name: Build
run: bun run build
- name: Release
id: release
run: bun run release
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}

View File

@ -0,0 +1,16 @@
我已找到导致页面显示异常的两个主要原因:
1. **标签值重复**:“到期通知”的内容区域错误地使用了 `value='verify'`(与“验证邮件”重复),导致点击标签时无法正确匹配。
2. **强制渲染属性**:部分标签页使用了 `forceMount` 属性,导致内容即使未被选中也保留在页面上。由于表单已配置 `shouldUnregister: false`,我们可以安全地移除该属性,让未选中的标签页自动隐藏。
**修改计划:**
编辑 `apps/admin/app/dashboard/auth-control/forms/email-settings-form.tsx` 文件:
1. **修正标签关联**:将第 474 行的 `value='verify'` 修改为 `value='expiration'`
2. **优化显示逻辑**:移除以下位置的 `forceMount` 属性,确保只有当前选中的标签页才会显示:
- SMTP 设置 (第 260 行)
- 到期通知 (第 474 行)
- 维护通知 (第 519 行)
这样修改后,点击对应的标签将只显示对应的内容,且“全部显示”的问题将得到解决。

15
.vscode/settings.json vendored
View File

@ -1,15 +0,0 @@
{
"eslint.workingDirectories": [
{
"mode": "auto"
}
],
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"*.ts": "${capture}.js",
"*.js": "${capture}.js.map, ${capture}.min.js, ${capture}.d.ts",
"*.jsx": "${capture}.js",
"*.tsx": "${capture}.ts",
"README.md": "*.md, LICENSE"
}
}

View File

@ -1,39 +1,284 @@
<a name="readme-top"></a>
# Changelog
# [1.3.0](https://github.com/perfect-panel/ppanel-web/compare/v1.2.0...v1.3.0) (2025-08-15)
### ♻ Code Refactoring
* Refactoring and adding multiple features ([65c9b9f](https://github.com/perfect-panel/ppanel-web/commit/65c9b9f))
### ✨ Features
* **api**: Add getClient API endpoint to retrieve subscription applications ([7a279e6](https://github.com/perfect-panel/ppanel-web/commit/7a279e6))
* **marketing**: Add marketing management features and localization updates ([ea08de0](https://github.com/perfect-panel/ppanel-web/commit/ea08de0))
* **protocol**: Add template preview functionality with localization support ([0448d21](https://github.com/perfect-panel/ppanel-web/commit/0448d21))
* **subscribe**: Update subscription management localization and add new fields ([1d9b0a4](https://github.com/perfect-panel/ppanel-web/commit/1d9b0a4))
## [1.6.1](https://github.com/perfect-panel/ppanel-web/compare/v1.6.0...v1.6.1) (2025-11-05)
### 🐛 Bug Fixes
* **bun**: Update bun.lockb to reflect dependency changes ([bbcd018](https://github.com/perfect-panel/ppanel-web/commit/bbcd018))
* **editor**: Add Go template editor component and update related schemas ([9d9c3cd](https://github.com/perfect-panel/ppanel-web/commit/9d9c3cd))
* **editor**: Enhance Go Template Editor to support trimmed template tags and improve range/end matching ([641ed5e](https://github.com/perfect-panel/ppanel-web/commit/641ed5e))
* **editor**: Enhance Go Template Editor with schema support and improved completion ([5b21d8a](https://github.com/perfect-panel/ppanel-web/commit/5b21d8a))
* **enhaced-input**: Disable autocomplete for EnhancedInput component ([f190c68](https://github.com/perfect-panel/ppanel-web/commit/f190c68))
* **global**: Add user agent limit settings to subscription configuration ([822416d](https://github.com/perfect-panel/ppanel-web/commit/822416d))
* **locales**: Update 'conf' output format to use uppercase 'CONF' ([fce9119](https://github.com/perfect-panel/ppanel-web/commit/fce9119))
* **locales**: Update "userAccount" label to "user" in multiple localization files ([48415e9](https://github.com/perfect-panel/ppanel-web/commit/48415e9))
* **protocol-form**: Swap 'description' and 'user_agent' columns for improved clarity in the table ([72a4106](https://github.com/perfect-panel/ppanel-web/commit/72a4106))
* **protocol-form**: Update protocol options descriptions for clarity and add new security and transport options ([e5d4deb](https://github.com/perfect-panel/ppanel-web/commit/e5d4deb))
* **protocol**: Add 'conf' output format option and update translations ([292efdf](https://github.com/perfect-panel/ppanel-web/commit/292efdf))
* **protpcp-form**: Rename 'schema' to 'scheme' for consistency across the application ([6ab2ba9](https://github.com/perfect-panel/ppanel-web/commit/6ab2ba9))
* **register**: Update localization files to include trial subscription settings and descriptions ([33daa1f](https://github.com/perfect-panel/ppanel-web/commit/33daa1f))
* **system**: Add time unit translations for user registration settings in multiple languages ([296a6c1](https://github.com/perfect-panel/ppanel-web/commit/296a6c1))
* Update privacy policy and terms of service schemas to use correct field names ([0e6ba5b](https://github.com/perfect-panel/ppanel-web/commit/0e6ba5b))
* Fixing issues with generating standard and quantum-resistant encryption keys ([5eac6a9](https://github.com/perfect-panel/ppanel-web/commit/5eac6a9))
<a name="readme-top"></a>
# Changelog
# [1.6.0](https://github.com/perfect-panel/ppanel-web/compare/v1.5.4...v1.6.0) (2025-10-28)
### ✨ Features
- Add server installation dialog and commands ([4429c9d](https://github.com/perfect-panel/ppanel-web/commit/4429c9d))
### 🐛 Bug Fixes
- Add typeRoots configuration to ensure type definitions are resolved correctly ([ad60ea9](https://github.com/perfect-panel/ppanel-web/commit/ad60ea9))
<a name="readme-top"></a>
# Changelog
## [1.5.4](https://github.com/perfect-panel/ppanel-web/compare/v1.5.3...v1.5.4) (2025-10-26)
### 🐛 Bug Fixes
- Update generateRealityKeyPair to use async key generation ([e60e369](https://github.com/perfect-panel/ppanel-web/commit/e60e369))
- Update the wallet localization file and add new fields such as automatic reset and recharge ([88aa965](https://github.com/perfect-panel/ppanel-web/commit/88aa965))
## [1.5.3](https://github.com/perfect-panel/ppanel-web/compare/v1.5.2...v1.5.3) (2025-10-21)
### 🐛 Bug Fixes
- Fix bugs ([a46657d](https://github.com/perfect-panel/ppanel-web/commit/a46657d))
- Fix dependencies ([8bd25d6](https://github.com/perfect-panel/ppanel-web/commit/8bd25d6))
- Remove unnecessary migration function code and add device configuration options ([521a7a9](https://github.com/perfect-panel/ppanel-web/commit/521a7a9))
- Update bun.lockb to reflect dependency changes ([ca892dd](https://github.com/perfect-panel/ppanel-web/commit/ca892dd))
<a name="readme-top"></a>
# Changelog
## [1.5.2](https://github.com/perfect-panel/ppanel-web/compare/v1.5.1...v1.5.2) (2025-09-29)
### 🐛 Bug Fixes
- Add step attribute to datetime-local inputs for precise time selection in forms ([32fd181](https://github.com/perfect-panel/ppanel-web/commit/32fd181))
- Rename 'hysteria2' to 'hysteria' across protocol definitions and schemas for consistency ([5816dd5](https://github.com/perfect-panel/ppanel-web/commit/5816dd5))
- Update protocol options in ServerConfig for accuracy and consistency ([9266529](https://github.com/perfect-panel/ppanel-web/commit/9266529))
## [1.5.1](https://github.com/perfect-panel/ppanel-web/compare/v1.5.0...v1.5.1) (2025-09-28)
### 🐛 Bug Fixes
- Simplify protocol enable checks by removing unnecessary false comparisons ([4828700](https://github.com/perfect-panel/ppanel-web/commit/4828700))
# [1.5.0](https://github.com/perfect-panel/ppanel-web/compare/v1.4.8...v1.5.0) (2025-09-28)
### ✨ Features
- Update server configuration translations for multiple languages ([fc43de1](https://github.com/perfect-panel/ppanel-web/commit/fc43de1))
### 🐛 Bug Fixes
- Add DynamicMultiplier component for managing node multipliers and update ServersPage layout ([bb6671c](https://github.com/perfect-panel/ppanel-web/commit/bb6671c))
- Remove unnecessary blank lines in multiple index files for cleaner code structure ([6a823b8](https://github.com/perfect-panel/ppanel-web/commit/6a823b8))
- Remove unused ratio variable from server traffic log and server form for cleaner code ([55034dc](https://github.com/perfect-panel/ppanel-web/commit/55034dc))
- Update Badge variants and restructure traffic ratio display in ServersPage ([3d778e5](https://github.com/perfect-panel/ppanel-web/commit/3d778e5))
- Update minimum ratio value to 0 in protocol fields and adjust related schemas; enhance unit conversion in ServerConfig ([3b6ef17](https://github.com/perfect-panel/ppanel-web/commit/3b6ef17))
- Update protocol fields to use 'obfs' instead of 'security' and adjust related configurations ([4abdd36](https://github.com/perfect-panel/ppanel-web/commit/4abdd36))
<a name="readme-top"></a>
# Changelog
## [1.4.8](https://github.com/perfect-panel/ppanel-web/compare/v1.4.7...v1.4.8) (2025-09-23)
### 🐛 Bug Fixes
- Rename 'server_id' to 'protocol' in NodesPage and clean up unused imports and code in ServerConfig ([70b3484](https://github.com/perfect-panel/ppanel-web/commit/70b3484))
- Update announcement page to display timeline of announcements with Markdown content ([3c036eb](https://github.com/perfect-panel/ppanel-web/commit/3c036eb))
- Update Empty component to support border prop and adjust usage in various pages ([ce9ab89](https://github.com/perfect-panel/ppanel-web/commit/ce9ab89))
## [1.4.7](https://github.com/perfect-panel/ppanel-web/compare/v1.4.6...v1.4.7) (2025-09-23)
### 🐛 Bug Fixes
- Add unique key to ProTable for improved rendering with user ID filters ([2bff15f](https://github.com/perfect-panel/ppanel-web/commit/2bff15f))
- Adjust layout spacing and chart aspect ratio in ServerConfig component ([05a61d8](https://github.com/perfect-panel/ppanel-web/commit/05a61d8))
- Refactor server ID cell rendering for improved readability and consistency ([0345b7c](https://github.com/perfect-panel/ppanel-web/commit/0345b7c))
- Update announcement page to format creation date and enhance content display ([8445e30](https://github.com/perfect-panel/ppanel-web/commit/8445e30))
- Update OnlineUsersCell to display user count with icon instead of badge ([7a4ebdf](https://github.com/perfect-panel/ppanel-web/commit/7a4ebdf))
- Update subscribe name fallback to return '--' instead of 'Unknown' ([0a07d25](https://github.com/perfect-panel/ppanel-web/commit/0a07d25))
## [1.4.6](https://github.com/perfect-panel/ppanel-web/compare/v1.4.5...v1.4.6) (2025-09-17)
### 🎫 Chores
- Merge branch 'main' into develop ([41f06bf](https://github.com/perfect-panel/ppanel-web/commit/41f06bf))
### 🐛 Bug Fixes
- Add loaded state to node, server, and subscribe stores for better loading management ([13dce0c](https://github.com/perfect-panel/ppanel-web/commit/13dce0c))
- Removed node metadata fields in subscription schema to simplify structure ([0cadd83](https://github.com/perfect-panel/ppanel-web/commit/0cadd83))
## [1.4.5](https://github.com/perfect-panel/ppanel-web/compare/v1.4.4...v1.4.5) (2025-09-17)
### ♻ Code Refactoring
- Replace useQuery with Zustand store for subscription and node data management ([c6dd0b6](https://github.com/perfect-panel/ppanel-web/commit/c6dd0b6))
- Simplify TemplatePreview component structure by consolidating Sheet and Button elements ([1b715c5](https://github.com/perfect-panel/ppanel-web/commit/1b715c5))
### 🐛 Bug Fixes
- Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning ([bd67ece](https://github.com/perfect-panel/ppanel-web/commit/bd67ece))
- Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes ([a3c5e31](https://github.com/perfect-panel/ppanel-web/commit/a3c5e31))
- Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly ([e94405d](https://github.com/perfect-panel/ppanel-web/commit/e94405d))
- Add subscribeSchema for subscription management with detailed proxy and user information ([49b3dcc](https://github.com/perfect-panel/ppanel-web/commit/49b3dcc))
- Enhance server ID display in ServerTrafficLogPage with badges and server ratio ([6dfac27](https://github.com/perfect-panel/ppanel-web/commit/6dfac27))
- Update platform handling in Content component to ensure available platforms are correctly filtered and displayed ([1dde708](https://github.com/perfect-panel/ppanel-web/commit/1dde708))
<a name="readme-top"></a>
# Changelog
## [1.4.4](https://github.com/perfect-panel/ppanel-web/compare/v1.4.3...v1.4.4) (2025-09-16)
### 🐛 Bug Fixes
- Add minimum value constraint for count and user limit inputs in CouponForm ([6991b69](https://github.com/perfect-panel/ppanel-web/commit/6991b69))
- Add protocol-related constants, default configurations, field definitions, and validation modes ([d685407](https://github.com/perfect-panel/ppanel-web/commit/d685407))
- Added the enabled field in the protocol configuration, updated the related type definition and default configuration ([2b0cf9a](https://github.com/perfect-panel/ppanel-web/commit/2b0cf9a))
- Filter available protocols to exclude disabled ones in NodeForm ([982d288](https://github.com/perfect-panel/ppanel-web/commit/982d288))
- Refactor key generation logic and update dependencies for ML-KEM-768 integration ([b8f630f](https://github.com/perfect-panel/ppanel-web/commit/b8f630f))
<a name="readme-top"></a>
# Changelog
## [1.4.3](https://github.com/perfect-panel/ppanel-web/compare/v1.4.2...v1.4.3) (2025-09-16)
### 🐛 Bug Fixes
- Add success toast message for sorting in nodes and servers pages ([2d5175d](https://github.com/perfect-panel/ppanel-web/commit/2d5175d))
- Implement encryption and obfuscation features in protocol configuration ([54de16b](https://github.com/perfect-panel/ppanel-web/commit/54de16b))
- Refactor toB64 function to toB64Url for URL-safe base64 encoding in VlessX25519Pair generation ([8700cf6](https://github.com/perfect-panel/ppanel-web/commit/8700cf6))
- Simplify initialValues assignment and update node submission logic in NodesPage ([05d6c89](https://github.com/perfect-panel/ppanel-web/commit/05d6c89))
- Update bun.lockb to reflect dependency changes ([ebcebd7](https://github.com/perfect-panel/ppanel-web/commit/ebcebd7))
<a name="readme-top"></a>
# Changelog
## [1.4.2](https://github.com/perfect-panel/ppanel-web/compare/v1.4.1...v1.4.2) (2025-09-15)
### 🐛 Bug Fixes
- Add GitHub template repository link to ProtocolForm header for easier access ([8a0baf3](https://github.com/perfect-panel/ppanel-web/commit/8a0baf3))
- Add readOnly prop to MonacoEditor and TemplatePreview components for improved content handling ([c4c4d5a](https://github.com/perfect-panel/ppanel-web/commit/c4c4d5a))
## [1.4.1](https://github.com/perfect-panel/ppanel-web/compare/v1.4.0...v1.4.1) (2025-09-15)
### 🐛 Bug Fixes
- Add copy subscription functionality to user subscription dashboard and improve localization for new features ([e2a357f](https://github.com/perfect-panel/ppanel-web/commit/e2a357f))
- Simplify handleInputBlur function by removing unnecessary setTimeout ([6341562](https://github.com/perfect-panel/ppanel-web/commit/6341562))
- Update TemplatePreview to use MonacoEditor for content display and improve error handling ([1d52642](https://github.com/perfect-panel/ppanel-web/commit/1d52642))
- Update user dashboard link to correct path ([131693b](https://github.com/perfect-panel/ppanel-web/commit/131693b))
<a name="readme-top"></a>
# Changelog
# [1.4.0](https://github.com/perfect-panel/ppanel-web/compare/v1.3.0...v1.4.0) (2025-09-14)
### ♻ Code Refactoring
- **logs**: Add localization files and update existing translations for multiple languages ([2f20ac9](https://github.com/perfect-panel/ppanel-web/commit/2f20ac9))
- **subscribe-form**: Replace server_group and server with node_tags and nodes in default values and form schema ([38dda84](https://github.com/perfect-panel/ppanel-web/commit/38dda84))
- Add localization updates for log and server files across multiple languages ([2bcd4cf](https://github.com/perfect-panel/ppanel-web/commit/2bcd4cf))
- Clean up NodeForm and ServerForm components by removing unused functions and optimizing state management ([10250d9](https://github.com/perfect-panel/ppanel-web/commit/10250d9))
- Enhance log pages with Badge component and update translations ([a4de9df](https://github.com/perfect-panel/ppanel-web/commit/a4de9df))
- Make 'scheme' field optional in client form schema ([f4a1237](https://github.com/perfect-panel/ppanel-web/commit/f4a1237))
- Refactor server management API endpoints and typings ([4f7cc80](https://github.com/perfect-panel/ppanel-web/commit/4f7cc80))
- Remove application management forms and related configurations ([0c43844](https://github.com/perfect-panel/ppanel-web/commit/0c43844))
- Remove default options from TagInput component for improved flexibility ([6a3bb70](https://github.com/perfect-panel/ppanel-web/commit/6a3bb70))
- Remove unused preview state variables and add sort order to node properties ([e63f823](https://github.com/perfect-panel/ppanel-web/commit/e63f823))
- Rename buildScheme to buildSchema and update imports in server form components ([ee98e7e](https://github.com/perfect-panel/ppanel-web/commit/ee98e7e))
- Simplify node display in subscribe form and remove unused Badge import ([551135d](https://github.com/perfect-panel/ppanel-web/commit/551135d))
- Update bun.lockb to reflect dependency changes ([ba2b50e](https://github.com/perfect-panel/ppanel-web/commit/ba2b50e))
- Update component imports and improve code consistency ([59faeab](https://github.com/perfect-panel/ppanel-web/commit/59faeab))
- Update dependencies and improve code consistency across multiple files ([e37ae49](https://github.com/perfect-panel/ppanel-web/commit/e37ae49))
- Update localization files and service imports ([d4b37e4](https://github.com/perfect-panel/ppanel-web/commit/d4b37e4))
### ✨ Features
- **config**: Add translations for server configuration in multiple languages ([f9a7ece](https://github.com/perfect-panel/ppanel-web/commit/f9a7ece))
- **logs**: Add various log pages for tracking user activities and system events ([d85af49](https://github.com/perfect-panel/ppanel-web/commit/d85af49))
- Add bandwidth fields and placeholders for upload and download in server configuration forms; update localization files for multiple languages ([3e5402f](https://github.com/perfect-panel/ppanel-web/commit/3e5402f))
- Add batch delete functionality and enhance chart tooltips in statistics cards ([c4f536e](https://github.com/perfect-panel/ppanel-web/commit/c4f536e))
- Add language support and descriptions in product localization files ([fd48856](https://github.com/perfect-panel/ppanel-web/commit/fd48856))
- Add log cleanup settings and update localization files ([6ccf9b8](https://github.com/perfect-panel/ppanel-web/commit/6ccf9b8))
- Add queryNodeTag function and integrate tag retrieval in NodeForm and SubscribeForm components ([4563c57](https://github.com/perfect-panel/ppanel-web/commit/4563c57))
- Add quota management features and localization updates ([fce627b](https://github.com/perfect-panel/ppanel-web/commit/fce627b))
- Add server form component with protocol configuration and localization support ([217ddce](https://github.com/perfect-panel/ppanel-web/commit/217ddce))
- Enhance TagInput component with option handling and improved tag addition logic ([b6e778d](https://github.com/perfect-panel/ppanel-web/commit/b6e778d))
- Implement data migration functionality and update localization files ([6d81bfd](https://github.com/perfect-panel/ppanel-web/commit/6d81bfd))
- Refactor user detail and subscription management components ([973c06f](https://github.com/perfect-panel/ppanel-web/commit/973c06f))
- Update server list fetching logic and adjust query parameters ([5272360](https://github.com/perfect-panel/ppanel-web/commit/5272360))
### 🐛 Bug Fixes
- **page**: Refine version checking logic and remove unnecessary comments for clarity ([26176a7](https://github.com/perfect-panel/ppanel-web/commit/26176a7))
- Add localization updates and new utility functions ([4da5960](https://github.com/perfect-panel/ppanel-web/commit/4da5960))
- Add user_subscribe_id filter to SubscribeLogPage and update typings; disable eslint in service index files ([ab6f6a6](https://github.com/perfect-panel/ppanel-web/commit/ab6f6a6))
- Added system version card and system log dialog components; updated statistics page to include total server and user statistics ([fe69980](https://github.com/perfect-panel/ppanel-web/commit/fe69980))
- Adjust timestamp calculations to use milliseconds instead of seconds in quota broadcast form submission ([8dffd69](https://github.com/perfect-panel/ppanel-web/commit/8dffd69))
- Correct cookie key format for sidebar state retrieval ([9e01f4f](https://github.com/perfect-panel/ppanel-web/commit/9e01f4f))
- Improve UI for protocol status display in server form component ([461fdb1](https://github.com/perfect-panel/ppanel-web/commit/461fdb1))
- Increase pagination size limit for server and node lists to improve data retrieval ([7c0a312](https://github.com/perfect-panel/ppanel-web/commit/7c0a312))
- Optimize Task Manager to use milliseconds to calculate timers, and simplify import statements ([d8fa13b](https://github.com/perfect-panel/ppanel-web/commit/d8fa13b))
- Refactor protocol status display for improved readability in server form component ([f700be0](https://github.com/perfect-panel/ppanel-web/commit/f700be0))
- Remove GroupTable and related components, simplify SubscribeTable and update language handling in subscription forms ([1ab9b39](https://github.com/perfect-panel/ppanel-web/commit/1ab9b39))
- Remove redundant transport label from localization files ([88ce8d7](https://github.com/perfect-panel/ppanel-web/commit/88ce8d7))
- Remove unnecessary comments and improve variable handling in GoTemplateEditor; ensure zero value displays as empty in EnhancedInput ([c4a47a4](https://github.com/perfect-panel/ppanel-web/commit/c4a47a4))
- Remove unnecessary comments to simplify code readability ([a988cb3](https://github.com/perfect-panel/ppanel-web/commit/a988cb3))
- Replace MarkdownEditor with HTMLEditor in EmailBroadcastForm; simplify content rendering in EmailTaskManager; disable eslint in service index files ([e2d83ec](https://github.com/perfect-panel/ppanel-web/commit/e2d83ec))
- Replace redundant icon rendering with a single instance in system version card component ([e4429a5](https://github.com/perfect-panel/ppanel-web/commit/e4429a5))
- Update billing URL fetching logic and improve version handling in system version card component ([1c8d4af](https://github.com/perfect-panel/ppanel-web/commit/1c8d4af))
- Update condition for plugin field in PROTOCOL_FIELDS to include specific plugins ([6376ec1](https://github.com/perfect-panel/ppanel-web/commit/6376ec1))
- Update getAppSubLink function to improve URL handling and encoding logic ([351fffc](https://github.com/perfect-panel/ppanel-web/commit/351fffc))
- Update order_id to order_no in BalanceLogPage and related typings; enhance timezone switch component with additional features and localization updates ([ac36075](https://github.com/perfect-panel/ppanel-web/commit/ac36075))
- Update protocol plugin handling and add new options in typings ([6ca2433](https://github.com/perfect-panel/ppanel-web/commit/6ca2433))
- Update release URLs to include 'v' prefix for versioning in system version card component ([1d526b5](https://github.com/perfect-panel/ppanel-web/commit/1d526b5))
- Update SidebarLeft component styles to enhance hover effects ([e4fbd5c](https://github.com/perfect-panel/ppanel-web/commit/e4fbd5c))
- Update validation for days and gift_value fields in QuotaBroadcastForm; set default values to avoid errors ([39d746f](https://github.com/perfect-panel/ppanel-web/commit/39d746f))
### 📝 Documentation
- Merge branch 'main' into develop ([d7f8b3b](https://github.com/perfect-panel/ppanel-web/commit/d7f8b3b))
<a name="readme-top"></a>
# Changelog
# [1.3.0](https://github.com/perfect-panel/ppanel-web/compare/v1.2.0...v1.3.0) (2025-08-15)
### ♻ Code Refactoring
- Refactoring and adding multiple features ([65c9b9f](https://github.com/perfect-panel/ppanel-web/commit/65c9b9f))
### ✨ Features
- **api**: Add getClient API endpoint to retrieve subscription applications ([7a279e6](https://github.com/perfect-panel/ppanel-web/commit/7a279e6))
- **marketing**: Add marketing management features and localization updates ([ea08de0](https://github.com/perfect-panel/ppanel-web/commit/ea08de0))
- **protocol**: Add template preview functionality with localization support ([0448d21](https://github.com/perfect-panel/ppanel-web/commit/0448d21))
- **subscribe**: Update subscription management localization and add new fields ([1d9b0a4](https://github.com/perfect-panel/ppanel-web/commit/1d9b0a4))
### 🐛 Bug Fixes
- **bun**: Update bun.lockb to reflect dependency changes ([bbcd018](https://github.com/perfect-panel/ppanel-web/commit/bbcd018))
- **editor**: Add Go template editor component and update related schemas ([9d9c3cd](https://github.com/perfect-panel/ppanel-web/commit/9d9c3cd))
- **editor**: Enhance Go Template Editor to support trimmed template tags and improve range/end matching ([641ed5e](https://github.com/perfect-panel/ppanel-web/commit/641ed5e))
- **editor**: Enhance Go Template Editor with schema support and improved completion ([5b21d8a](https://github.com/perfect-panel/ppanel-web/commit/5b21d8a))
- **enhaced-input**: Disable autocomplete for EnhancedInput component ([f190c68](https://github.com/perfect-panel/ppanel-web/commit/f190c68))
- **global**: Add user agent limit settings to subscription configuration ([822416d](https://github.com/perfect-panel/ppanel-web/commit/822416d))
- **locales**: Update 'conf' output format to use uppercase 'CONF' ([fce9119](https://github.com/perfect-panel/ppanel-web/commit/fce9119))
- **locales**: Update "userAccount" label to "user" in multiple localization files ([48415e9](https://github.com/perfect-panel/ppanel-web/commit/48415e9))
- **protocol-form**: Swap 'description' and 'user_agent' columns for improved clarity in the table ([72a4106](https://github.com/perfect-panel/ppanel-web/commit/72a4106))
- **protocol-form**: Update protocol options descriptions for clarity and add new security and transport options ([e5d4deb](https://github.com/perfect-panel/ppanel-web/commit/e5d4deb))
- **protocol**: Add 'conf' output format option and update translations ([292efdf](https://github.com/perfect-panel/ppanel-web/commit/292efdf))
- **protpcp-form**: Rename 'schema' to 'scheme' for consistency across the application ([6ab2ba9](https://github.com/perfect-panel/ppanel-web/commit/6ab2ba9))
- **register**: Update localization files to include trial subscription settings and descriptions ([33daa1f](https://github.com/perfect-panel/ppanel-web/commit/33daa1f))
- **system**: Add time unit translations for user registration settings in multiple languages ([296a6c1](https://github.com/perfect-panel/ppanel-web/commit/296a6c1))
- Update privacy policy and terms of service schemas to use correct field names ([0e6ba5b](https://github.com/perfect-panel/ppanel-web/commit/0e6ba5b))
<a name="readme-top"></a>

View File

@ -4,7 +4,7 @@
<img width="160" src="https://raw.githubusercontent.com/perfect-panel/ppanel-assets/refs/heads/main/logo.svg">
<h1>PPanel web</h1>
<h1>PPanel web hifastvpn</h1>
This is a PPanel web powered by PPanel
@ -34,6 +34,19 @@ English
</div>
> **Article 1.**
> All human beings are born free and equal in dignity and rights.
> They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.
>
> **Article 12.**
> No one shall be subjected to arbitrary interference with his privacy, family, home or correspondence, nor to attacks upon his honour and reputation.
> Everyone has the right to the protection of the law against such interference or attacks.
>
> **Article 19.**
> Everyone has the right to freedom of opinion and expression; this right includes freedom to hold opinions without interference and to seek, receive and impart information and ideas through any media and regardless of frontiers.
>
> _Source: [United Nations Universal Declaration of Human Rights (UN.org)](https://www.un.org/sites/un2.un.org/files/2021/03/udhr.pdf)_
## 📦 Application List
| 📦 Application | 🖼️ Preview |

View File

@ -6,7 +6,7 @@
<h1>PPanel 前端</h1>
这是由 PPanel 提供支持的前端
这是由 PPanel 提供支持的前端1
[英文](./README.md)
·
@ -34,6 +34,19 @@
</div>
> **第一条**
> 人人生而自由,在尊严与权利上一律平等。
> 他们赋有理性与良知,应当以兄弟般的精神彼此相待。
>
> **第十二条**
> 任何人的隐私、家庭、住宅和通信不得任意干涉,其名誉与荣誉不得加以攻击。
> 人人有权受到法律的保护,以免遭受这种干涉或攻击。
>
> **第十九条**
> 人人有思想与表达的自由;此项自由包括持有主张而不受干预,以及通过任何媒介、无论国界,自由寻求、接受和传播信息与思想。
>
> _来源 [United Nations Universal Declaration of Human Rights (UN.org)](https://www.un.org/sites/un2.un.org/files/2021/03/udhr.pdf)_
## 📦 Application List
| 📦 Application | 🖼️ Preview |

View File

@ -225,6 +225,7 @@ export default function AdsForm<T extends Record<string, any>>({
<FormControl>
<EnhancedInput
type='datetime-local'
step='1'
placeholder={t('form.enterStartTime')}
value={field.value ? new Date(field.value).toISOString().slice(0, 16) : ''}
min={Number(new Date().toISOString().slice(0, 16))}
@ -253,6 +254,7 @@ export default function AdsForm<T extends Record<string, any>>({
<FormControl>
<EnhancedInput
type='datetime-local'
step='1'
placeholder={t('form.enterEndTime')}
value={
field.value ? new Date(field.value).toISOString().slice(0, 16) : ''

View File

@ -2,11 +2,11 @@
import { ProTable, ProTableActions } from '@/components/pro-table';
import { createAds, deleteAds, getAdsList, updateAds } from '@/services/admin/ads';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';

View File

@ -1,282 +0,0 @@
'use client';
import {
getApplication,
getApplicationConfig,
updateApplicationConfig,
} from '@/services/admin/system';
import { zodResolver } from '@hookform/resolvers/zod';
import { Icon } from '@iconify/react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Textarea } from '@workspace/ui/components/textarea';
import { Combobox } from '@workspace/ui/custom-components/combobox';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
import { DicesIcon } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { uid } from 'radash';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const formSchema = z.object({
app_id: z.number().optional(),
encryption_key: z.string().optional(),
encryption_method: z.string().optional(),
startup_picture: z.string().optional(),
startup_picture_skip_time: z.number().optional(),
domains: z.array(z.string()).optional(),
});
type FormSchema = z.infer<typeof formSchema>;
export default function ConfigForm() {
const t = useTranslations('product.app');
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: {
app_id: 0,
encryption_key: '',
encryption_method: '',
startup_picture: '',
startup_picture_skip_time: 0,
domains: [],
},
});
const { data, refetch } = useQuery({
queryKey: ['getApplicationConfig'],
queryFn: async () => {
const { data } = await getApplicationConfig();
return data.data;
},
});
const { data: applications } = useQuery({
queryKey: ['getApplication'],
queryFn: async () => {
const { data } = await getApplication();
return data.data?.applications || [];
},
});
useEffect(() => {
if (data) {
form.reset(data);
}
}, [data, form]);
async function onSubmit(values: FormSchema) {
setLoading(true);
try {
await updateApplicationConfig({
...values,
domains: values.domains?.filter((domain) => domain),
} as API.ApplicationConfig);
toast.success(t('updateSuccess'));
refetch();
setOpen(false);
} catch (error) {
/* empty */
} finally {
setLoading(false);
}
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant='outline'>
<Icon icon='mdi:cog' className='mr-2' />
{t('config')}
</Button>
</SheetTrigger>
<SheetContent className='w-[520px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('configApp')}</SheetTitle>
</SheetHeader>
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
<Form {...form}>
<form className='space-y-4 py-4'>
<FormField
control={form.control}
name='app_id'
render={({ field }) => (
<FormItem>
<FormLabel>{t('selectApp')}</FormLabel>
<FormDescription>{t('selectAppDescription')}</FormDescription>
<FormControl>
<Combobox
{...field}
options={
applications?.map((app) => ({
label: app.name,
value: app.id,
})) || []
}
value={field.value}
onChange={(value) => form.setValue(field.name, value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='encryption_key'
render={({ field }) => (
<FormItem>
<FormLabel>{t('communicationKey')}</FormLabel>
<FormDescription>{t('communicationKeyDescription')}</FormDescription>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={(value) => form.setValue(field.name, value as string)}
suffix={
<div className='bg-muted flex h-9 items-center text-nowrap px-3'>
<DicesIcon
onClick={() => {
const id = uid(32).toLowerCase();
const formatted = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;
form.setValue(field.name, formatted);
}}
className='cursor-pointer'
/>
</div>
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='encryption_method'
render={({ field }) => (
<FormItem>
<FormLabel>{t('encryption')}</FormLabel>
<FormDescription>{t('encryptionDescription')}</FormDescription>
<FormControl>
<Combobox
options={[
{ label: 'none', value: 'none' },
{ label: 'AES', value: 'aes' },
]}
value={field.value}
onChange={(value) => form.setValue(field.name, value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='startup_picture'
render={({ field }) => (
<FormItem>
<FormLabel>{t('startupPicture')}</FormLabel>
<FormDescription>{t('startupPictureDescription')}</FormDescription>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={(value) => form.setValue(field.name, value as string)}
suffix={
<UploadImage
className='bg-muted h-9 rounded-none border-none px-2'
onChange={(value) => form.setValue('startup_picture', value as string)}
/>
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='startup_picture_skip_time'
render={({ field }) => (
<FormItem>
<FormLabel>{t('startupPictureSkip')}</FormLabel>
<FormDescription>{t('startupPictureSkipDescription')}</FormDescription>
<FormControl>
<EnhancedInput
{...field}
type='number'
min={0}
suffix='S'
value={field.value}
onValueChange={(value) =>
form.setValue('startup_picture_skip_time', Number(value))
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='domains'
render={({ field }) => (
<FormItem className='px-1'>
<FormLabel>{t('backupDomains')}</FormLabel>
<FormDescription>{t('backupDomainsDescription')}</FormDescription>
<FormControl>
<Textarea
className='h-28'
placeholder='example.com'
value={field.value?.join('\n')}
onChange={(e) => {
form.setValue(field.name, e.target.value.split('\n'));
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button onClick={form.handleSubmit(onSubmit)} disabled={loading}>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -1,303 +0,0 @@
'use client';
import { getSubscribeType } from '@/services/admin/system';
import { zodResolver } from '@hookform/resolvers/zod';
import { Icon } from '@iconify/react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { UploadImage } from '@workspace/ui/custom-components/upload-image';
import { useTranslations } from 'next-intl';
import { assign, shake } from 'radash';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const platforms = ['windows', 'macos', 'linux', 'android', 'ios', 'harmony'];
const defaultValues = {
subscribe_type: 'Clash',
name: '',
icon: '',
url: '',
};
const versionSchema = z.object({
url: z.string(),
version: z.string().optional(),
description: z.string().optional(),
is_default: z.boolean().optional(),
});
const formSchema = z.object({
icon: z.string(),
name: z.string(),
subscribe_type: z.string(),
platform: z.object({
windows: z.array(versionSchema).optional(),
macos: z.array(versionSchema).optional(),
linux: z.array(versionSchema).optional(),
android: z.array(versionSchema).optional(),
ios: z.array(versionSchema).optional(),
harmony: z.array(versionSchema).optional(),
}),
});
interface FormProps<T> {
trigger: React.ReactNode | string;
title: string;
initialValues?: Partial<T>;
onSubmit: (values: T) => Promise<boolean>;
loading?: boolean;
}
export default function SubscribeAppForm<
T extends API.CreateApplicationRequest | API.UpdateApplicationRequest,
>({ trigger, title, loading, initialValues, onSubmit }: FormProps<T>) {
const t = useTranslations('product.app');
const [open, setOpen] = useState(false);
type FormSchema = z.infer<typeof formSchema>;
const form = useForm<FormSchema>({
resolver: zodResolver(formSchema),
defaultValues: assign(
defaultValues,
shake(initialValues, (value) => value === null),
),
});
useEffect(() => {
form.reset(
assign(
defaultValues,
shake(initialValues, (value) => value === null),
),
);
}, [form, initialValues]);
const { data: subscribe_types } = useQuery<string[]>({
queryKey: ['getSubscribeType'],
queryFn: async () => {
const { data } = await getSubscribeType();
return data.data?.subscribe_types || [];
},
});
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
{typeof trigger === 'string' ? <Button>{trigger}</Button> : trigger}
</SheetTrigger>
<SheetContent className='w-[520px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='h-[calc(100dvh-48px-36px-36px)]'>
<Form {...form}>
<form className='space-y-4 py-4'>
<div className='grid grid-cols-2 gap-4'>
<FormField
control={form.control}
name='icon'
render={({ field }) => (
<FormItem className='col-span-2'>
<FormLabel>{t('appIcon')}</FormLabel>
<FormControl>
<EnhancedInput
required
suffix={
<UploadImage
className='bg-muted h-9 rounded-none border-none px-2'
onChange={(value) => {
form.setValue(field.name, value as string);
}}
/>
}
value={field.value}
onValueChange={(value) => {
form.setValue(field.name, value as string);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('appName')}</FormLabel>
<FormControl>
<EnhancedInput
required
type='text'
value={field.value}
onValueChange={(value) => {
form.setValue(field.name, value as string);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='subscribe_type'
render={({ field }) => (
<FormItem>
<FormLabel>{t('subscriptionProtocol')}</FormLabel>
<FormControl>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder={t('subscriptionProtocol')} />
</SelectTrigger>
<SelectContent>
{subscribe_types?.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormItem>
<FormLabel>{t('platform')}</FormLabel>
<Tabs defaultValue={platforms[0]}>
<TabsList>
{platforms.map((platform) => (
<TabsTrigger key={platform} value={platform} className='uppercase'>
{platform}
</TabsTrigger>
))}
</TabsList>
{platforms.map((platform) => (
<TabsContent key={platform} value={platform}>
<FormField
control={form.control}
name={`platform.${platform as keyof FormSchema['platform']}`}
render={({ field }) => (
<FormItem>
<FormControl>
<ArrayInput
isReverse
className='grid grid-cols-3 gap-4'
fields={[
{
name: 'version',
type: 'text',
placeholder: t('version'),
defaultValue: '1.0.0',
},
{
name: 'description',
type: 'text',
placeholder: t('description'),
},
{
name: 'is_default',
type: 'boolean',
placeholder: t('defaultVersion'),
},
{
name: 'url',
type: 'text',
placeholder: t('downloadLink'),
className: 'col-span-3',
},
]}
value={field.value}
onChange={(value) => {
const filteredValue = value.filter((item) => item.url);
const newDefaultIndex = value.findIndex(
(item, idx) =>
item.is_default &&
(!field.value?.[idx] || !field.value[idx].is_default),
);
let finalValue = filteredValue;
if (newDefaultIndex >= 0 && filteredValue[newDefaultIndex]) {
finalValue = filteredValue.map((item, index) => ({
...item,
is_default: index === newDefaultIndex,
}));
} else if (
!filteredValue.some((item) => item.is_default) &&
filteredValue.length > 0
) {
finalValue = filteredValue.map((item, index) => ({
...item,
is_default: index === 0,
}));
}
form.setValue(field.name, finalValue as any);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
))}
</Tabs>
</FormItem>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button
onClick={form.handleSubmit(async (values) => {
const success = await onSubmit(values as unknown as T);
if (success) setOpen(false);
})}
disabled={loading}
>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -1,143 +0,0 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
createApplication,
deleteApplication,
getApplication,
updateApplication,
} from '@/services/admin/system';
import { Button } from '@workspace/ui/components/button';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { useTranslations } from 'next-intl';
import Image from 'next/legacy/image';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import ConfigForm from './config';
import SubscribeAppForm from './form';
export default function SubscribeApp() {
const t = useTranslations('product.app');
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.ApplicationResponseInfo, Record<string, unknown>>
action={ref}
header={{
title: t('appList'),
toolbar: (
<div className='flex items-center gap-2'>
<ConfigForm />
<SubscribeAppForm<API.CreateApplicationRequest>
trigger={t('create')}
title={t('createApp')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createApplication(values);
toast.success(t('createSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>
</div>
),
}}
request={async (_pagination, filters) => {
const { data } = await getApplication();
return {
list: data.data?.applications || [],
total: 0,
};
}}
columns={[
{
accessorKey: 'icon',
header: t('appIcon'),
cell: ({ row }) => (
<Image
src={row.getValue('icon')}
alt={row.getValue('name')}
className='h-8 w-8 rounded-md'
width={32}
height={32}
/>
),
},
{
accessorKey: 'name',
header: t('appName'),
},
{
accessorKey: 'subscribe_type',
header: t('subscriptionProtocol'),
cell: ({ row }) => row.getValue('subscribe_type'),
},
]}
actions={{
render: (row) => [
<SubscribeAppForm<API.UpdateApplicationRequest>
key='edit'
trigger={<Button>{t('edit')}</Button>}
title={t('editApp')}
loading={loading}
initialValues={{
...row,
}}
onSubmit={async (values) => {
setLoading(true);
try {
await updateApplication({
...values,
id: row.id,
});
toast.success(t('updateSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await deleteApplication({ id: row.id! });
toast.success(t('deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
],
batchRender: (rows) => [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('batchDelete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await Promise.all(rows.map((row) => deleteApplication({ id: row.id! })));
toast.success(t('deleteSuccess'));
ref.current?.reset();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
],
}}
/>
);
}

View File

@ -61,6 +61,7 @@ export default function AppleForm() {
return data.data;
},
enabled: open,
});
const form = useForm<AppleFormData>({

View File

@ -34,8 +34,8 @@ import { z } from 'zod';
const deviceSchema = z.object({
id: z.number(),
method: z.string().default('device'),
enabled: z.boolean().default(false),
method: z.string(),
enabled: z.boolean(),
config: z
.object({
show_ads: z.boolean().optional(),

View File

@ -1,48 +0,0 @@
'use client';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { LogsTable } from '../log';
export default function EmailLogsTable() {
const t = useTranslations('auth-control');
const [open, setOpen] = useState(false);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:email-newsletter' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('email.logs')}</p>
<p className='text-muted-foreground text-sm'>{t('email.logsDescription')}</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</SheetTrigger>
<SheetContent className='w-[800px] max-w-full md:max-w-screen-lg'>
<SheetHeader>
<SheetTitle>{t('email.logs')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<div className='px-6 pt-4'>
<LogsTable type='email' />
</div>
</ScrollArea>
</SheetContent>
</Sheet>
);
}

View File

@ -40,23 +40,23 @@ import { z } from 'zod';
const emailSettingsSchema = z.object({
id: z.number(),
method: z.string().default('email'),
enabled: z.boolean().default(false),
method: z.string(),
enabled: z.boolean(),
config: z
.object({
enable_verify: z.boolean().default(false),
enable_domain_suffix: z.boolean().default(false),
enable_verify: z.boolean(),
enable_domain_suffix: z.boolean(),
domain_suffix_list: z.string().optional(),
verify_email_template: z.string().optional(),
expiration_email_template: z.string().optional(),
maintenance_email_template: z.string().optional(),
traffic_exceed_email_template: z.string().optional(),
platform: z.string().default('smtp'),
platform: z.string(),
platform_config: z
.object({
host: z.string().optional(),
port: z.coerce.number().optional(),
ssl: z.boolean().default(false),
port: z.number().optional(),
ssl: z.boolean(),
user: z.string().optional(),
pass: z.string().optional(),
from: z.string().optional(),
@ -87,6 +87,7 @@ export default function EmailSettingsForm() {
const form = useForm<EmailSettingsFormData>({
resolver: zodResolver(emailSettingsSchema),
shouldUnregister: false,
defaultValues: {
id: 0,
method: 'email',
@ -416,8 +417,8 @@ export default function EmailSettingsForm() {
<FormControl>
<HTMLEditor
placeholder={t('email.inputPlaceholder')}
value={field.value}
onBlur={field.onChange}
value={field.value ?? ''}
onChange={field.onChange}
/>
</FormControl>
<div className='mt-4 space-y-2 border-t pt-4'>
@ -480,8 +481,8 @@ export default function EmailSettingsForm() {
<FormControl>
<HTMLEditor
placeholder={t('email.inputPlaceholder')}
value={field.value}
onBlur={field.onChange}
value={field.value ?? ''}
onChange={field.onChange}
/>
</FormControl>
<div className='mt-4 space-y-2 border-t pt-4'>
@ -525,8 +526,8 @@ export default function EmailSettingsForm() {
<FormControl>
<HTMLEditor
placeholder={t('email.inputPlaceholder')}
value={field.value}
onBlur={field.onChange}
value={field.value ?? ''}
onChange={field.onChange}
/>
</FormControl>
<div className='mt-4 space-y-2 border-t pt-4'>
@ -580,8 +581,8 @@ export default function EmailSettingsForm() {
<FormControl>
<HTMLEditor
placeholder={t('email.inputPlaceholder')}
value={field.value}
onBlur={field.onChange}
value={field.value ?? ''}
onChange={field.onChange}
/>
</FormControl>
<div className='mt-4 space-y-2 border-t pt-4'>

View File

@ -52,7 +52,7 @@ export default function FacebookForm() {
});
return data.data;
},
// 移除 enabled: open现在默认加载数据
enabled: open,
});
const form = useForm<FacebookFormData>({

View File

@ -53,6 +53,7 @@ export default function GithubForm() {
return data.data;
},
enabled: open,
});
const form = useForm<GithubFormData>({

View File

@ -33,8 +33,8 @@ import { z } from 'zod';
const googleSchema = z.object({
id: z.number(),
method: z.string().default('google'),
enabled: z.boolean().default(false),
method: z.string().default('google').optional(),
enabled: z.boolean().default(false).optional(),
config: z
.object({
client_id: z.string().optional(),

View File

@ -1,48 +0,0 @@
'use client';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { LogsTable } from '../log';
export default function PhoneLogsTable() {
const t = useTranslations('auth-control');
const [open, setOpen] = useState(false);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:phone-log' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('phone.logs')}</p>
<p className='text-muted-foreground text-sm'>{t('phone.logsDescription')}</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</SheetTrigger>
<SheetContent className='w-[800px] max-w-full md:max-w-screen-lg'>
<SheetHeader>
<SheetTitle>{t('phone.logs')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<div className='px-6 pt-4'>
<LogsTable type='mobile' />
</div>
</ScrollArea>
</SheetContent>
</Sheet>
);
}

View File

@ -49,8 +49,8 @@ import { z } from 'zod';
const phoneSettingsSchema = z.object({
id: z.number(),
method: z.string().default('mobile'),
enabled: z.boolean().default(false),
method: z.string(),
enabled: z.boolean(),
config: z
.object({
enable_whitelist: z.boolean().optional(),

View File

@ -53,6 +53,7 @@ export default function TelegramForm() {
return data.data;
},
enabled: open,
});
const form = useForm<TelegramFormData>({

View File

@ -1,104 +0,0 @@
import { ProTable, ProTableActions } from '@/components/pro-table';
import { getMessageLogList } from '@/services/admin/log';
import { Badge } from '@workspace/ui/components/badge';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef } from 'react';
export function LogsTable({ type }: { type: 'email' | 'mobile' }) {
const t = useTranslations('auth-control.log');
const ref = useRef<ProTableActions>(null);
return (
<ProTable<
API.MessageLog,
{
platform?: string;
to?: string;
subject?: string;
content?: string;
status?: number;
}
>
action={ref}
header={{
title: t(`${type}Log`),
}}
columns={[
{
accessorKey: 'id',
header: 'ID',
},
{
accessorKey: 'platform',
header: t('platform'),
},
{
accessorKey: 'to',
header: t('to'),
},
{
accessorKey: 'subject',
header: t('subject'),
},
{
accessorKey: 'content',
header: t('content'),
},
{
accessorKey: 'status',
header: t('status'),
cell: ({ row }) => {
const status = row.getValue('status');
const text = status === 1 ? t('sendSuccess') : t('sendFailed');
return <Badge variant={status === 1 ? 'default' : 'destructive'}>{text}</Badge>;
},
},
{
accessorKey: 'created_at',
header: t('createdAt'),
cell: ({ row }) => formatDate(row.getValue('created_at')),
},
{
accessorKey: 'updated_at',
header: t('updatedAt'),
cell: ({ row }) => formatDate(row.getValue('updated_at')),
},
]}
params={[
{
key: 'to',
placeholder: t('to'),
},
{
key: 'subject',
placeholder: t('subject'),
},
{
key: 'content',
placeholder: t('content'),
},
{
key: 'status',
placeholder: t('status'),
options: [
{ label: t('sendSuccess'), value: '1' },
{ label: t('sendFailed'), value: '0' },
],
},
]}
request={async (pagination, filter) => {
const { data } = await getMessageLogList({
...pagination,
...filter,
status: filter.status === undefined ? undefined : Number(filter.status),
type: type,
});
return {
list: data.data?.list || [],
total: data.data?.total || 0,
};
}}
/>
);
}

View File

@ -4,28 +4,20 @@ import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/
import { useTranslations } from 'next-intl';
import AppleForm from './forms/apple-form';
import DeviceForm from './forms/device-form';
import EmailLogsTable from './forms/email-logs-table';
import EmailSettingsForm from './forms/email-settings-form';
import FacebookForm from './forms/facebook-form';
import GithubForm from './forms/github-form';
import GoogleForm from './forms/google-form';
import PhoneLogsTable from './forms/phone-logs-table';
import PhoneSettingsForm from './forms/phone-settings-form';
import TelegramForm from './forms/telegram-form';
export default function Page() {
const t = useTranslations('auth-control');
// 定义表单配置
const formSections = [
{
title: t('communicationMethods'),
forms: [
{ component: EmailSettingsForm },
{ component: EmailLogsTable },
{ component: PhoneSettingsForm },
{ component: PhoneLogsTable },
],
forms: [{ component: EmailSettingsForm }, { component: PhoneSettingsForm }],
},
{
title: t('socialAuthMethods'),

View File

@ -1,8 +1,7 @@
'use client';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
@ -81,16 +80,7 @@ export default function CouponForm<T extends Record<string, any>>({
const type = form.watch('type');
const { data: subscribe } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.Subscribe[];
},
});
const { subscribes } = useSubscribe();
return (
<Sheet open={open} onOpenChange={setOpen}>
@ -247,9 +237,9 @@ export default function CouponForm<T extends Record<string, any>>({
onChange={(value) => {
form.setValue(field.name, value);
}}
options={subscribe?.map((item: API.Subscribe) => ({
value: item.id,
label: item.name,
options={subscribes?.map((item) => ({
value: item.id!,
label: item.name!,
}))}
/>
</FormControl>
@ -267,7 +257,7 @@ export default function CouponForm<T extends Record<string, any>>({
<DatePicker
placeholder={t('form.enterValue')}
value={field.value}
disabled={(date) => date < new Date(Date.now() - 24 * 60 * 60 * 1000)}
disabled={(date: Date) => date < new Date(Date.now() - 24 * 60 * 60 * 1000)}
onChange={(value) => {
form.setValue(field.name, value);
}}
@ -307,6 +297,7 @@ export default function CouponForm<T extends Record<string, any>>({
<EnhancedInput
placeholder={t('form.countPlaceholder')}
type='number'
min={0}
step={1}
{...field}
onValueChange={(value) => {
@ -328,6 +319,7 @@ export default function CouponForm<T extends Record<string, any>>({
<EnhancedInput
placeholder={t('form.userLimitPlaceholder')}
type='number'
min={0}
step={1}
{...field}
onValueChange={(value) => {

View File

@ -9,13 +9,12 @@ import {
getCouponList,
updateCoupon,
} from '@/services/admin/coupon';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useQuery } from '@tanstack/react-query';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
@ -24,16 +23,7 @@ import CouponForm from './coupon-form';
export default function Page() {
const t = useTranslations('coupon');
const [loading, setLoading] = useState(false);
const { data } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const { subscribes } = useSubscribe();
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.Coupon, { group_id: number; query: string }>
@ -67,8 +57,8 @@ export default function Page() {
{
key: 'subscribe',
placeholder: t('subscribe'),
options: data?.map((item) => ({
label: item.name,
options: subscribes?.map((item) => ({
label: item.name!,
value: String(item.id),
})),
},

View File

@ -8,10 +8,10 @@ import {
getDocumentList,
updateDocument,
} from '@/services/admin/document';
import { formatDate } from '@/utils/common';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';

View File

@ -5,7 +5,7 @@ import { cookies } from 'next/headers';
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const cookieStore = await cookies();
const defaultOpen = cookieStore.get('sidebar:state')?.value === 'true';
const defaultOpen = cookieStore.get('sidebar_state')?.value === 'true';
return (
<SidebarProvider defaultOpen={defaultOpen}>
<SidebarLeft />

View File

@ -0,0 +1,84 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { Display } from '@/components/display';
import { OrderLink } from '@/components/order-link';
import { ProTable } from '@/components/pro-table';
import { filterBalanceLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function BalanceLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const getBalanceTypeText = (type: number) => {
const typeText = t(`type.${type}`);
if (typeText === `log.type.${type}`) {
return `${t('unknown')} (${type})`;
}
return typeText;
};
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
};
return (
<ProTable<API.BalanceLog, { search?: string }>
header={{ title: t('title.balance') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'amount',
header: t('column.amount'),
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
},
{
accessorKey: 'order_no',
header: t('column.orderNo'),
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
},
{
accessorKey: 'balance',
header: t('column.balance'),
cell: ({ row }) => <Display type='currency' value={row.original.balance} />,
},
{
accessorKey: 'type',
header: t('column.type'),
cell: ({ row }) => <Badge>{getBalanceTypeText(row.original.type)}</Badge>,
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
]}
request={async (pagination, filter) => {
const { data } = await filterBalanceLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,79 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { Display } from '@/components/display';
import { OrderLink } from '@/components/order-link';
import { ProTable } from '@/components/pro-table';
import { filterCommissionLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function CommissionLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const getCommissionTypeText = (type: number) => {
const typeText = t(`type.${type}`);
if (typeText === `log.type.${type}`) {
return `${t('unknown')} (${type})`;
}
return typeText;
};
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
};
return (
<ProTable<API.CommissionLog, { search?: string }>
header={{ title: t('title.commission') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'amount',
header: t('column.amount'),
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
},
{
accessorKey: 'order_no',
header: t('column.orderNo'),
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
},
{
accessorKey: 'type',
header: t('column.type'),
cell: ({ row }) => <Badge>{getCommissionTypeText(row.original.type)}</Badge>,
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
]}
request={async (pagination, filter) => {
const { data } = await filterCommissionLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,84 @@
'use client';
import { ProTable } from '@/components/pro-table';
import { filterEmailLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function EmailLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
search: sp.get('search') || undefined,
date: sp.get('date') || today,
};
return (
<ProTable<API.MessageLog, { search?: string }>
header={{ title: t('title.email') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'platform',
header: t('column.platform'),
cell: ({ row }) => <Badge>{row.getValue('platform')}</Badge>,
},
{ accessorKey: 'to', header: t('column.to') },
{ accessorKey: 'subject', header: t('column.subject') },
{
accessorKey: 'content',
header: t('column.content'),
cell: ({ row }) => (
<pre className='max-w-[480px] overflow-auto whitespace-pre-wrap break-words text-xs'>
{JSON.stringify(row.original.content || {}, null, 2)}
</pre>
),
},
{
accessorKey: 'status',
header: t('column.status'),
cell: ({ row }) => {
const status = row.original.status;
const getStatusVariant = (status: any) => {
if (status === 1) {
return 'default';
} else if (status === 0) {
return 'destructive';
}
return 'outline';
};
const getStatusText = (status: any) => {
if (status === 1) return t('sent');
if (status === 0) return t('failed');
return t('unknown');
};
return <Badge variant={getStatusVariant(status)}>{getStatusText(status)}</Badge>;
},
},
{
accessorKey: 'created_at',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.created_at),
},
]}
params={[{ key: 'search' }, { key: 'date', type: 'date' }]}
request={async (pagination, filter) => {
const { data } = await filterEmailLog({
page: pagination.page,
size: pagination.size,
search: filter?.search,
date: (filter as any)?.date,
});
const list = ((data?.data?.list || []) as API.MessageLog[]) || [];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,92 @@
'use client';
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { Display } from '@/components/display';
import { OrderLink } from '@/components/order-link';
import { ProTable } from '@/components/pro-table';
import { filterGiftLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function GiftLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const getGiftTypeText = (type: number) => {
const typeText = t(`type.${type}`);
if (typeText === `log.type.${type}`) {
return `${t('unknown')} (${type})`;
}
return typeText;
};
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
};
return (
<ProTable<API.GiftLog, { search?: string }>
header={{ title: t('title.gift') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'subscribe_id',
header: t('column.subscribe'),
cell: ({ row }) => (
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
),
},
{
accessorKey: 'order_no',
header: t('column.orderNo'),
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
},
{
accessorKey: 'amount',
header: t('column.amount'),
cell: ({ row }) => <Display type='currency' value={row.original.amount} />,
},
{
accessorKey: 'balance',
header: t('column.balance'),
cell: ({ row }) => <Display type='currency' value={row.original.balance} />,
},
{
accessorKey: 'type',
header: t('column.type'),
cell: ({ row }) => <Badge>{getGiftTypeText(row.original.type)}</Badge>,
},
{ accessorKey: 'remark', header: t('column.remark') },
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
]}
request={async (pagination, filter) => {
const { data } = await filterGiftLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,100 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { IpLink } from '@/components/ip-link';
import { ProTable } from '@/components/pro-table';
import { filterLoginLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@workspace/ui/components/tooltip';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function LoginLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
};
return (
<ProTable<API.LoginLog, { date?: string; user_id?: number }>
header={{ title: t('title.login') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => (
<div>
<Badge className='capitalize'>{row.original.method}</Badge>{' '}
<UserDetail id={Number(row.original.user_id)} />
</div>
),
},
{
accessorKey: 'login_ip',
header: t('column.ip'),
cell: ({ row }) => <IpLink ip={String((row.original as any).login_ip || '')} />,
},
{
accessorKey: 'user_agent',
header: t('column.userAgent'),
cell: ({ row }) => {
const userAgent = String(row.original.user_agent || '');
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
</TooltipTrigger>
<TooltipContent>
<p className='max-w-md break-words'>{userAgent}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
},
},
{
accessorKey: 'success',
header: t('column.success'),
cell: ({ row }) => (
<Badge variant={row.original.success ? 'default' : 'destructive'}>
{row.original.success ? t('success') : t('failed')}
</Badge>
),
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
]}
request={async (pagination, filter) => {
const { data } = await filterLoginLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
});
const list = ((data?.data?.list || []) as API.LoginLog[]) || [];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,83 @@
'use client';
import { ProTable } from '@/components/pro-table';
import { filterMobileLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function MobileLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
search: sp.get('search') || undefined,
date: sp.get('date') || today,
};
return (
<ProTable<API.MessageLog, { search?: string }>
header={{ title: t('title.mobile') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'platform',
header: t('column.platform'),
cell: ({ row }) => <Badge>{row.getValue('platform')}</Badge>,
},
{ accessorKey: 'to', header: t('column.to') },
{ accessorKey: 'subject', header: t('column.subject') },
{
accessorKey: 'content',
header: t('column.content'),
cell: ({ row }) => (
<pre className='max-w-[480px] overflow-auto whitespace-pre-wrap break-words text-xs'>
{JSON.stringify(row.original.content || {}, null, 2)}
</pre>
),
},
{
accessorKey: 'status',
header: t('column.status'),
cell: ({ row }) => {
const status = row.original.status;
const getStatusVariant = (status: any) => {
if (status === 1) {
return 'default';
} else if (status === 0) {
return 'destructive';
}
return 'outline';
};
const getStatusText = (status: any) => {
if (status === 1) return t('sent');
if (status === 0) return t('failed');
return t('unknown');
};
return <Badge variant={getStatusVariant(status)}>{getStatusText(status)}</Badge>;
},
},
{
accessorKey: 'created_at',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.created_at),
},
]}
params={[{ key: 'search' }, { key: 'date', type: 'date' }]}
request={async (pagination, filter) => {
const { data } = await filterMobileLog({
page: pagination.page,
size: pagination.size,
search: filter?.search,
date: (filter as any)?.date,
});
const list = ((data?.data?.list || []) as API.MessageLog[]) || [];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,95 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { IpLink } from '@/components/ip-link';
import { ProTable } from '@/components/pro-table';
import { filterRegisterLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@workspace/ui/components/tooltip';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function RegisterLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
};
return (
<ProTable<API.RegisterLog, { date?: string; user_id?: number }>
header={{ title: t('title.register') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'auth_method',
header: t('column.identifier'),
cell: ({ row }) => (
<div className='flex items-center'>
<Badge className='capitalize'>{row.original.auth_method}</Badge>
<span className='ml-1 text-sm'>{row.original.identifier}</span>
</div>
),
},
{
accessorKey: 'register_ip',
header: t('column.ip'),
cell: ({ row }) => <IpLink ip={String((row.original as any).register_ip || '')} />,
},
{
accessorKey: 'user_agent',
header: t('column.userAgent'),
cell: ({ row }) => {
const userAgent = String(row.original.user_agent || '');
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
</TooltipTrigger>
<TooltipContent>
<p className='max-w-md break-words'>{userAgent}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
},
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
]}
request={async (pagination, filter) => {
const { data } = await filterRegisterLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,82 @@
'use client';
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { OrderLink } from '@/components/order-link';
import { ProTable } from '@/components/pro-table';
import { filterResetSubscribeLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function ResetSubscribeLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const getResetSubscribeTypeText = (type: number) => {
const typeText = t(`type.${type}`);
if (typeText === `log.type.${type}`) {
return `${t('unknown')} (${type})`;
}
return typeText;
};
const initialFilters = {
date: sp.get('date') || today,
user_subscribe_id: sp.get('user_subscribe_id')
? Number(sp.get('user_subscribe_id'))
: undefined,
};
return (
<ProTable<API.ResetSubscribeLog, { date?: string; user_subscribe_id?: number }>
header={{ title: t('title.resetSubscribe') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'user_subscribe_id',
header: t('column.subscribeId'),
cell: ({ row }) => (
<UserSubscribeDetail id={Number(row.original.user_subscribe_id)} enabled hoverCard />
),
},
{
accessorKey: 'type',
header: t('column.type'),
cell: ({ row }) => <Badge>{getResetSubscribeTypeText(row.original.type)}</Badge>,
},
{
accessorKey: 'order_no',
header: t('column.orderNo'),
cell: ({ row }) => <OrderLink orderId={row.original.order_no} />,
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
]}
request={async (pagination, filter) => {
const { data } = await filterResetSubscribeLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_subscribe_id: (filter as any)?.user_subscribe_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,86 @@
'use client';
import { ProTable } from '@/components/pro-table';
import { filterServerTrafficLog } from '@/services/admin/log';
import { useServer } from '@/store/server';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { formatBytes } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
export default function ServerTrafficLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const { getServerName, getServerById } = useServer();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
};
return (
<ProTable<API.ServerTrafficLog, { date?: string; server_id?: number }>
header={{ title: t('title.serverTraffic') }}
initialFilters={initialFilters}
actions={{
render: (row) => [
<Button key='detail' asChild>
<Link
href={`/dashboard/log/traffic-details?date=${row.date}&server_id=${row.server_id}`}
>
{t('detail')}
</Link>
</Button>,
],
}}
columns={[
{
accessorKey: 'server_id',
header: t('column.server'),
cell: ({ row }) => {
return (
<div className='flex items-center gap-2'>
<Badge>{row.original.server_id}</Badge>
<span>{getServerName(row.original.server_id)}</span>
</div>
);
},
},
{
accessorKey: 'upload',
header: t('column.upload'),
cell: ({ row }) => formatBytes(row.original.upload),
},
{
accessorKey: 'download',
header: t('column.download'),
cell: ({ row }) => formatBytes(row.original.download),
},
{
accessorKey: 'total',
header: t('column.total'),
cell: ({ row }) => formatBytes(row.original.total),
},
{ accessorKey: 'date', header: t('column.date') },
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'server_id', placeholder: t('column.serverId') },
]}
request={async (pagination, filter) => {
const { data } = await filterServerTrafficLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
server_id: (filter as any)?.server_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,95 @@
'use client';
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { ProTable } from '@/components/pro-table';
import { filterUserSubscribeTrafficLog } from '@/services/admin/log';
import { Button } from '@workspace/ui/components/button';
import { formatBytes } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
export default function SubscribeTrafficLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
user_subscribe_id: sp.get('user_subscribe_id')
? Number(sp.get('user_subscribe_id'))
: undefined,
};
return (
<ProTable<
API.UserSubscribeTrafficLog,
{ date?: string; user_id?: number; user_subscribe_id?: number }
>
header={{ title: t('title.subscribeTraffic') }}
initialFilters={initialFilters}
actions={{
render: (row) => [
<Button key='detail' asChild>
<Link
href={`/dashboard/log/traffic-details?date=${row.date}&user_id=${row.user_id}&subscribe_id=${row.subscribe_id}`}
>
{t('detail')}
</Link>
</Button>,
],
}}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'subscribe_id',
header: t('column.subscribe'),
cell: ({ row }) => (
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
),
},
{
accessorKey: 'upload',
header: t('column.upload'),
cell: ({ row }) => formatBytes(row.original.upload),
},
{
accessorKey: 'download',
header: t('column.download'),
cell: ({ row }) => formatBytes(row.original.download),
},
{
accessorKey: 'total',
header: t('column.total'),
cell: ({ row }) => formatBytes(row.original.total),
},
{
accessorKey: 'date',
header: t('column.date'),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
]}
request={async (pagination, filter) => {
const { data } = await filterUserSubscribeTrafficLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
user_subscribe_id: (filter as any)?.user_subscribe_id,
});
const list = ((data?.data?.list || []) as API.UserSubscribeTrafficLog[]) || [];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,96 @@
'use client';
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { IpLink } from '@/components/ip-link';
import { ProTable } from '@/components/pro-table';
import { filterSubscribeLog } from '@/services/admin/log';
import { formatDate } from '@/utils/common';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@workspace/ui/components/tooltip';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function SubscribeLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
user_subscribe_id: sp.get('user_subscribe_id')
? Number(sp.get('user_subscribe_id'))
: undefined,
};
return (
<ProTable<API.SubscribeLog, { date?: string; user_id?: number }>
header={{ title: t('title.subscribe') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'user',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'user_subscribe_id',
header: t('column.subscribe'),
cell: ({ row }) => (
<UserSubscribeDetail id={Number(row.original.user_subscribe_id)} enabled hoverCard />
),
},
{
accessorKey: 'client_ip',
header: t('column.ip'),
cell: ({ row }) => <IpLink ip={String((row.original as any).client_ip || '')} />,
},
{
accessorKey: 'user_agent',
header: t('column.userAgent'),
cell: ({ row }) => {
const userAgent = String(row.original.user_agent || '');
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className='max-w-48 cursor-help truncate'>{userAgent}</div>
</TooltipTrigger>
<TooltipContent>
<p className='max-w-md break-words'>{userAgent}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
},
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'user_id', placeholder: t('column.userId') },
{ key: 'user_subscribe_id', placeholder: t('column.subscribeId') },
]}
request={async (pagination, filter) => {
const { data } = await filterSubscribeLog({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
user_id: (filter as any)?.user_id,
user_subscribe_id: (filter as any)?.user_subscribe_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -0,0 +1,88 @@
'use client';
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { ProTable } from '@/components/pro-table';
import { filterTrafficLogDetails } from '@/services/admin/log';
import { useServer } from '@/store/server';
import { formatDate } from '@/utils/common';
import { formatBytes } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
export default function TrafficDetailsPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const { getServerName } = useServer();
const today = new Date().toISOString().split('T')[0];
const initialFilters = {
date: sp.get('date') || today,
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
user_id: sp.get('user_id') ? Number(sp.get('user_id')) : undefined,
subscribe_id: sp.get('subscribe_id') ? Number(sp.get('subscribe_id')) : undefined,
};
return (
<ProTable<API.TrafficLogDetails, { search?: string }>
header={{ title: t('title.trafficDetails') }}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'server_id',
header: t('column.server'),
cell: ({ row }) => (
<span>
{getServerName(row.original.server_id)} ({row.original.server_id})
</span>
),
},
{
accessorKey: 'user_id',
header: t('column.user'),
cell: ({ row }) => <UserDetail id={Number(row.original.user_id)} />,
},
{
accessorKey: 'subscribe_id',
header: t('column.subscribe'),
cell: ({ row }) => (
<UserSubscribeDetail id={Number(row.original.subscribe_id)} enabled hoverCard />
),
},
{
accessorKey: 'upload',
header: t('column.upload'),
cell: ({ row }) => formatBytes(row.original.upload),
},
{
accessorKey: 'download',
header: t('column.download'),
cell: ({ row }) => formatBytes(row.original.download),
},
{
accessorKey: 'timestamp',
header: t('column.time'),
cell: ({ row }) => formatDate(row.original.timestamp),
},
]}
params={[
{ key: 'date', type: 'date' },
{ key: 'server_id', placeholder: t('column.serverId') },
{ key: 'user_id', placeholder: t('column.userId') },
{ key: 'subscribe_id', placeholder: t('column.subscribeId') },
]}
request={async (pagination, filter) => {
const { data } = await filterTrafficLogDetails({
page: pagination.page,
size: pagination.size,
date: (filter as any)?.date,
server_id: (filter as any)?.server_id,
user_id: (filter as any)?.user_id,
subscribe_id: (filter as any)?.subscribe_id,
});
const list = (data?.data?.list || []) as any[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
/>
);
}

View File

@ -31,7 +31,7 @@ import {
} from '@workspace/ui/components/sheet';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import { Textarea } from '@workspace/ui/components/textarea';
import { MarkdownEditor } from '@workspace/ui/custom-components/editor';
import { HTMLEditor } from '@workspace/ui/custom-components/editor';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
@ -47,7 +47,7 @@ export default function EmailBroadcastForm() {
const emailBroadcastSchema = z.object({
subject: z.string().min(1, t('subject') + ' ' + t('cannotBeEmpty')),
content: z.string().min(1, t('content') + ' ' + t('cannotBeEmpty')),
scope: z.string().default('all'),
scope: z.number(),
register_start_time: z.string().optional(),
register_end_time: z.string().optional(),
additional: z
@ -83,7 +83,7 @@ export default function EmailBroadcastForm() {
defaultValues: {
subject: '',
content: '',
scope: 'all',
scope: 1, // ScopeAll
register_start_time: '',
register_end_time: '',
additional: '',
@ -99,7 +99,7 @@ export default function EmailBroadcastForm() {
try {
// Call API to get actual recipient count
const scope = formData.scope || 'all';
const scope = formData.scope || 1; // Default to ScopeAll
// Convert dates to timestamps if they exist
let register_start_time: number = 0;
@ -153,8 +153,10 @@ export default function EmailBroadcastForm() {
// Listen to form changes
const watchedValues = form.watch();
// Use useEffect to respond to form changes
// Use useEffect to respond to form changes, but only when sheet is open
useEffect(() => {
if (!open) return; // Only calculate when sheet is open
const debounceTimer = setTimeout(() => {
calculateRecipients();
}, 500); // Add debounce to avoid too frequent API calls
@ -162,6 +164,7 @@ export default function EmailBroadcastForm() {
return () => clearTimeout(debounceTimer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
open, // Add open dependency
watchedValues.scope,
watchedValues.register_start_time,
watchedValues.register_end_time,
@ -286,7 +289,7 @@ export default function EmailBroadcastForm() {
<FormItem>
<FormLabel>{t('content')}</FormLabel>
<FormControl>
<MarkdownEditor
<HTMLEditor
value={field.value}
onChange={(value) => {
form.setValue(field.name, value || '');
@ -310,20 +313,27 @@ export default function EmailBroadcastForm() {
render={({ field }) => (
<FormItem>
<FormLabel>{t('sendScope')}</FormLabel>
<Select onValueChange={field.onChange} value={field.value || 'all'}>
<Select
onValueChange={(value) => field.onChange(parseInt(value))}
value={field.value?.toString() || '1'}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('selectSendScope')} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value='all'>{t('allUsers')}</SelectItem>
<SelectItem value='active'>{t('subscribedUsersOnly')}</SelectItem>
<SelectItem value='expired'>
<SelectItem value='1'>{t('allUsers')}</SelectItem> {/* ScopeAll */}
<SelectItem value='2'>{t('subscribedUsersOnly')}</SelectItem>{' '}
{/* ScopeActive */}
<SelectItem value='3'>
{t('expiredSubscriptionUsersOnly')}
</SelectItem>
<SelectItem value='none'>{t('noSubscriptionUsersOnly')}</SelectItem>
<SelectItem value='skip'>{t('specificUsersOnly')}</SelectItem>
</SelectItem>{' '}
{/* ScopeExpired */}
<SelectItem value='4'>{t('noSubscriptionUsersOnly')}</SelectItem>{' '}
{/* ScopeNone */}
<SelectItem value='5'>{t('specificUsersOnly')}</SelectItem>{' '}
{/* ScopeSkip */}
</SelectContent>
</Select>
<FormDescription>{t('sendScopeDescription')}</FormDescription>
@ -356,7 +366,8 @@ export default function EmailBroadcastForm() {
<FormControl>
<EnhancedInput
type='datetime-local'
disabled={form.watch('scope') === 'skip'}
step='1'
disabled={form.watch('scope') === 5} // ScopeSkip
value={field.value}
onValueChange={field.onChange}
/>
@ -374,7 +385,8 @@ export default function EmailBroadcastForm() {
<FormControl>
<EnhancedInput
type='datetime-local'
disabled={form.watch('scope') === 'skip'}
step='1'
disabled={form.watch('scope') === 5} // ScopeSkip
value={field.value}
onValueChange={field.onChange}
/>
@ -415,6 +427,7 @@ export default function EmailBroadcastForm() {
<FormControl>
<EnhancedInput
type='datetime-local'
step='1'
placeholder={t('leaveEmptyForImmediateSend')}
value={field.value}
onValueChange={field.onChange}

View File

@ -1,11 +1,8 @@
'use client';
import { ProTable } from '@/components/pro-table';
import {
getBatchSendEmailTaskList,
getBatchSendEmailTaskStatus,
stopBatchSendEmailTask,
} from '@/services/admin/marketing';
import { ProTable, ProTableActions } from '@/components/pro-table';
import { getBatchSendEmailTaskList, stopBatchSendEmailTask } from '@/services/admin/marketing';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import {
@ -24,46 +21,24 @@ import {
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Icon } from '@workspace/ui/custom-components/icon';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
export default function EmailTaskManager() {
const t = useTranslations('marketing');
const [refreshing, setRefreshing] = useState<Record<number, boolean>>({});
const ref = useRef<ProTableActions>(null);
const [selectedTask, setSelectedTask] = useState<API.BatchSendEmailTask | null>(null);
const [open, setOpen] = useState(false);
// Get task status
const refreshTaskStatus = async (taskId: number) => {
setRefreshing((prev) => ({ ...prev, [taskId]: true }));
try {
const response = await getBatchSendEmailTaskStatus({
id: taskId,
});
const taskStatus = response.data?.data;
if (taskStatus) {
// Just show success message, ProTable will auto-refresh
toast.success(t('taskStatusRefreshed'));
}
} catch (error) {
console.error('Failed to refresh task status:', error);
toast.error(t('failedToRefreshTaskStatus'));
} finally {
setRefreshing((prev) => ({ ...prev, [taskId]: false }));
}
};
// Stop task
const stopTask = async (taskId: number) => {
try {
await stopBatchSendEmailTask({
id: taskId,
});
toast.success(t('taskStoppedSuccessfully'));
await refreshTaskStatus(taskId);
ref.current?.refresh();
} catch (error) {
console.error('Failed to stop task:', error);
toast.error(t('failedToStopTask'));
@ -86,7 +61,7 @@ export default function EmailTaskManager() {
};
return (
<Sheet>
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
@ -110,11 +85,11 @@ export default function EmailTaskManager() {
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-env(safe-area-inset-top))] px-6'>
<div className='mt-4 space-y-4'>
<ProTable<API.BatchSendEmailTask, API.GetBatchSendEmailTaskListParams>
action={ref}
columns={[
{
accessorKey: 'subject',
header: t('subject'),
size: 200,
cell: ({ row }) => (
<div
className='max-w-[200px] truncate font-medium'
@ -127,29 +102,28 @@ export default function EmailTaskManager() {
{
accessorKey: 'scope',
header: t('recipientType'),
size: 120,
cell: ({ row }) => {
const scope = row.getValue('scope') as string;
const scope = row.original.scope;
const scopeLabels = {
all: t('allUsers'),
active: t('subscribedUsers'),
expired: t('expiredUsers'),
none: t('nonSubscribers'),
skip: t('specificUsers'),
1: t('allUsers'), // ScopeAll
2: t('subscribedUsers'), // ScopeActive
3: t('expiredUsers'), // ScopeExpired
4: t('nonSubscribers'), // ScopeNone
5: t('specificUsers'), // ScopeSkip
};
return scopeLabels[scope as keyof typeof scopeLabels] || scope;
return (
scopeLabels[scope as keyof typeof scopeLabels] || `${t('scope')} ${scope}`
);
},
},
{
accessorKey: 'status',
header: t('status'),
size: 100,
cell: ({ row }) => getStatusBadge(row.getValue('status') as number),
},
{
accessorKey: 'progress',
header: t('progress'),
size: 150,
cell: ({ row }) => {
const task = row.original as API.BatchSendEmailTask;
const progress = task.total > 0 ? (task.current / task.total) * 100 : 0;
@ -171,24 +145,22 @@ export default function EmailTaskManager() {
);
},
},
{
accessorKey: 'created_at',
header: t('createdAt'),
size: 150,
cell: ({ row }) => {
const createdAt = row.getValue('created_at') as number;
return formatDate(createdAt);
},
},
{
accessorKey: 'scheduled',
header: t('sendTime'),
size: 150,
cell: ({ row }) => {
const scheduled = row.getValue('scheduled') as number;
return scheduled && scheduled > 0 ? formatDate(scheduled) : '--';
},
},
{
accessorKey: 'created_at',
header: t('createdAt'),
cell: ({ row }) => {
const createdAt = row.getValue('created_at') as number;
return formatDate(createdAt);
},
},
]}
request={async (pagination, filters) => {
const response = await getBatchSendEmailTaskList({
@ -215,11 +187,11 @@ export default function EmailTaskManager() {
key: 'scope',
placeholder: t('sendScope'),
options: [
{ label: t('allUsers'), value: 'all' },
{ label: t('subscribedUsers'), value: 'active' },
{ label: t('expiredUsers'), value: 'expired' },
{ label: t('nonSubscribers'), value: 'none' },
{ label: t('specificUsers'), value: 'skip' },
{ label: t('allUsers'), value: '1' },
{ label: t('subscribedUsers'), value: '2' },
{ label: t('expiredUsers'), value: '3' },
{ label: t('nonSubscribers'), value: '4' },
{ label: t('specificUsers'), value: '5' },
],
},
]}
@ -253,10 +225,7 @@ export default function EmailTaskManager() {
<h4 className='text-muted-foreground mb-2 text-sm font-medium'>
{t('content')}
</h4>
<div
className='prose prose-sm max-w-none'
dangerouslySetInnerHTML={{ __html: selectedTask.content }}
/>
<div dangerouslySetInnerHTML={{ __html: selectedTask.content }} />
</div>
{selectedTask.additional && (
<div>
@ -271,18 +240,6 @@ export default function EmailTaskManager() {
</ScrollArea>
</DialogContent>
</Dialog>,
<Button
key='refresh'
variant='outline'
size='icon'
onClick={() => refreshTaskStatus(row.id)}
disabled={refreshing[row.id]}
>
{refreshing[row.id] && (
<Icon icon='mdi:loading' className='mr-2 h-3 w-3 animate-spin' />
)}
<Icon icon='mdi:refresh' className='h-3 w-3' />
</Button>,
...([0, 1].includes(row.status)
? [
<Button key='stop' variant='destructive' onClick={() => stopTask(row.id)}>

View File

@ -4,6 +4,8 @@ import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/
import { useTranslations } from 'next-intl';
import EmailBroadcastForm from './email/broadcast-form';
import EmailTaskManager from './email/task-manager';
import QuotaBroadcastForm from './quota/broadcast-form';
import QuotaTaskManager from './quota/task-manager';
export default function MarketingPage() {
const t = useTranslations('marketing');
@ -13,6 +15,10 @@ export default function MarketingPage() {
title: t('emailMarketing'),
forms: [{ component: EmailBroadcastForm }, { component: EmailTaskManager }],
},
{
title: t('quotaService'),
forms: [{ component: QuotaBroadcastForm }, { component: QuotaTaskManager }],
},
];
return (

View File

@ -0,0 +1,446 @@
'use client';
import { Display } from '@/components/display';
import { createQuotaTask, queryQuotaTaskPreCount } from '@/services/admin/marketing';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { RadioGroup, RadioGroupItem } from '@workspace/ui/components/radio-group';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Switch } from '@workspace/ui/components/switch';
import { Combobox } from '@workspace/ui/custom-components/combobox';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { unitConversion } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
export default function QuotaBroadcastForm() {
const t = useTranslations('marketing');
// Define schema with internationalized error messages
const quotaBroadcastSchema = z.object({
subscribers: z.array(z.number()).min(1, t('pleaseSelectSubscribers')),
is_active: z.boolean(),
start_time: z.string().optional(),
end_time: z.string().optional(),
reset_traffic: z.boolean(),
days: z.number().optional(),
gift_type: z.number(),
gift_value: z.number().optional(),
});
type QuotaBroadcastFormData = z.infer<typeof quotaBroadcastSchema>;
const form = useForm<QuotaBroadcastFormData>({
resolver: zodResolver(quotaBroadcastSchema),
mode: 'onChange', // Enable real-time validation
defaultValues: {
subscribers: [],
is_active: true,
start_time: '',
end_time: '',
reset_traffic: false,
days: 0,
gift_type: 1,
gift_value: 0,
},
});
const [recipients, setRecipients] = useState<number>(0);
const [isCalculating, setIsCalculating] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [open, setOpen] = useState(false);
const { subscribes } = useSubscribe();
// Calculate recipient count
const calculateRecipients = async () => {
setIsCalculating(true);
try {
const formData = form.getValues();
let start_time: number = 0;
let end_time: number = 0;
if (formData.start_time) {
start_time = new Date(formData.start_time).getTime();
}
if (formData.end_time) {
end_time = new Date(formData.end_time).getTime();
}
const response = await queryQuotaTaskPreCount({
subscribers: formData.subscribers,
is_active: formData.is_active,
start_time,
end_time,
});
if (response.data?.data?.count !== undefined) {
setRecipients(response.data.data.count);
}
} catch (error) {
console.error('Failed to calculate recipients:', error);
toast.error(t('failedToCalculateRecipients'));
setRecipients(0);
} finally {
setIsCalculating(false);
}
};
// Watch form values and recalculate recipients only when sheet is open
const watchedValues = form.watch();
useEffect(() => {
if (!open) return; // Only calculate when sheet is open
const debounceTimer = setTimeout(() => {
calculateRecipients();
}, 500); // Add debounce to avoid too frequent API calls
return () => clearTimeout(debounceTimer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
open,
watchedValues.subscribers,
watchedValues.is_active,
watchedValues.start_time,
watchedValues.end_time,
]);
const onSubmit = async (data: QuotaBroadcastFormData) => {
setIsSubmitting(true);
try {
let start_time: number = 0;
let end_time: number = 0;
if (data.start_time) {
start_time = Math.floor(new Date(data.start_time).getTime());
}
if (data.end_time) {
end_time = Math.floor(new Date(data.end_time).getTime());
}
await createQuotaTask({
subscribers: data.subscribers,
is_active: data.is_active,
start_time,
end_time,
reset_traffic: data.reset_traffic,
days: data.days || 0,
gift_type: data.gift_type,
gift_value: data.gift_value || 0,
});
toast.success(t('quotaTaskCreatedSuccessfully'));
form.reset();
setRecipients(0);
setOpen(false); // Close the sheet after successful submission
} catch (error) {
console.error('Failed to create quota task:', error);
toast.error(t('failedToCreateQuotaTask'));
} finally {
setIsSubmitting(false);
}
};
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:gift' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('quotaBroadcast')}</p>
<p className='text-muted-foreground text-sm'>{t('createAndSendQuotaTasks')}</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</SheetTrigger>
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('createQuotaTask')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-32px-env(safe-area-inset-top))] px-6'>
<Form {...form}>
<form
id='quota-broadcast-form'
onSubmit={form.handleSubmit(onSubmit)}
className='mt-4 space-y-6'
>
{/* Subscribers selection */}
<FormField
control={form.control}
name='subscribers'
render={({ field }) => (
<FormItem>
<FormLabel>{t('subscribers')}</FormLabel>
<FormControl>
<Combobox
multiple={true}
value={field.value || []}
onChange={field.onChange}
placeholder={t('pleaseSelectSubscribers')}
options={subscribes?.map((subscribe) => ({
value: subscribe.id!,
label: subscribe.name!,
children: (
<div>
<div>{subscribe.name}</div>
<div className='text-muted-foreground text-xs'>
<Display type='traffic' value={subscribe.traffic || 0} /> /{' '}
<Display type='currency' value={subscribe.unit_price || 0} />
</div>
</div>
),
}))}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Subscription count info and active status */}
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
<FormField
control={form.control}
name='is_active'
render={({ field }) => (
<FormItem>
<FormLabel>{t('validOnly')}</FormLabel>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
className='float-end !mt-0'
/>
</FormControl>
<FormDescription>{t('selectValidSubscriptionsOnly')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className='border-l-primary bg-primary/10 flex items-center border-l-4 px-4 py-3 text-sm'>
<span className='text-muted-foreground'>{t('subscriptionCount')}: </span>
<span className='text-primary text-lg font-medium'>
{isCalculating ? (
<Icon icon='mdi:loading' className='ml-2 h-4 w-4 animate-spin' />
) : (
recipients.toLocaleString()
)}
</span>
</div>
</div>
{/* Subscription validity period range */}
<div className='grid grid-cols-2 gap-4'>
<FormField
control={form.control}
name='start_time'
render={({ field }) => (
<FormItem>
<FormLabel>{t('subscriptionValidityStartDate')}</FormLabel>
<FormControl>
<EnhancedInput
type='datetime-local'
step='1'
value={field.value}
onValueChange={field.onChange}
/>
</FormControl>
<FormDescription>{t('includeSubscriptionsValidAfter')}</FormDescription>
</FormItem>
)}
/>
<FormField
control={form.control}
name='end_time'
render={({ field }) => (
<FormItem>
<FormLabel>{t('subscriptionValidityEndDate')}</FormLabel>
<FormControl>
<EnhancedInput
type='datetime-local'
step='1'
value={field.value}
onValueChange={field.onChange}
/>
</FormControl>
<FormDescription>{t('includeSubscriptionsValidBefore')}</FormDescription>
</FormItem>
)}
/>
</div>
{/* Reset traffic */}
<FormField
control={form.control}
name='reset_traffic'
render={({ field }) => (
<FormItem>
<FormLabel>{t('resetTraffic')}</FormLabel>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
className='float-end !mt-0'
/>
</FormControl>
<FormDescription>{t('resetTrafficDescription')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{/* Quota days */}
<FormField
control={form.control}
name='days'
render={({ field }) => (
<FormItem>
<FormLabel>{t('quotaDays')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
min={1}
value={field.value?.toString()}
onValueChange={(value) => field.onChange(parseInt(value, 10))}
/>
</FormControl>
<FormDescription>{t('numberOfDaysForTheQuota')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{/* Gift configuration */}
<FormField
control={form.control}
name='gift_type'
render={({ field }) => (
<FormItem>
<FormLabel>{t('giftType')}</FormLabel>
<FormControl>
<RadioGroup
defaultValue={String(field.value)}
onValueChange={(value) => {
field.onChange(Number(value));
form.setValue('gift_value', 0);
}}
className='flex gap-4'
>
<FormItem className='flex items-center space-x-3 space-y-0'>
<FormControl>
<RadioGroupItem value='1' />
</FormControl>
<FormLabel className='font-normal'>{t('fixedAmount')}</FormLabel>
</FormItem>
<FormItem className='flex items-center space-x-3 space-y-0'>
<FormControl>
<RadioGroupItem value='2' />
</FormControl>
<FormLabel className='font-normal'>{t('percentageAmount')}</FormLabel>
</FormItem>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* Gift amount based on type */}
{form.watch('gift_type') === 1 && (
<FormField
control={form.control}
name='gift_value'
render={({ field }) => (
<FormItem>
<FormLabel>{t('giftAmount')}</FormLabel>
<FormControl>
<EnhancedInput<number>
placeholder={t('enterAmount')}
type='number'
value={field.value}
formatInput={(value) => unitConversion('centsToDollars', value)}
formatOutput={(value) => unitConversion('dollarsToCents', value)}
onValueChange={(value) => field.onChange(value)}
min={1}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{form.watch('gift_type') === 2 && (
<FormField
control={form.control}
name='gift_value'
render={({ field }) => (
<FormItem>
<FormLabel>{t('giftAmount')}</FormLabel>
<FormControl>
<EnhancedInput
placeholder={t('enterPercentage')}
type='number'
suffix='%'
value={field.value}
onValueChange={(value) => field.onChange(value)}
min={1}
max={100}
/>
</FormControl>
<FormDescription>{t('percentageAmountDescription')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex flex-row items-center justify-end gap-2 pt-3'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button
type='submit'
form='quota-broadcast-form'
disabled={
isSubmitting || !form.formState.isValid || form.watch('subscribers').length === 0
}
>
{isSubmitting && <Icon icon='mdi:loading' className='mr-2 h-4 w-4 animate-spin' />}
{t('createQuotaTask')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,230 @@
'use client';
import { Display } from '@/components/display';
import { ProTable } from '@/components/pro-table';
import { queryQuotaTaskList } from '@/services/admin/marketing';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
export default function QuotaTaskManager() {
const t = useTranslations('marketing');
const [open, setOpen] = useState(false);
const { subscribes } = useSubscribe();
const subscribeMap =
subscribes?.reduce(
(acc, subscribe) => {
acc[subscribe.id!] = subscribe.name!;
return acc;
},
{} as Record<number, string>,
) || {};
const getStatusBadge = (status: number) => {
const statusConfig = {
0: { label: t('notStarted'), variant: 'secondary' as const },
1: { label: t('inProgress'), variant: 'default' as const },
2: { label: t('completed'), variant: 'default' as const },
};
const config = statusConfig[status as keyof typeof statusConfig] || {
label: `${t('status')} ${status}`,
variant: 'secondary' as const,
};
return <Badge variant={config.variant}>{config.label}</Badge>;
};
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:database-plus' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('quotaTaskManager')}</p>
<p className='text-muted-foreground text-sm'>{t('viewAndManageQuotaTasks')}</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</SheetTrigger>
<SheetContent className='w-[1000px] max-w-full md:max-w-screen-lg'>
<SheetHeader>
<SheetTitle>{t('quotaTasks')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-env(safe-area-inset-top))] px-6'>
<div className='mt-4 space-y-4'>
{open && (
<ProTable<API.QuotaTask, API.QueryQuotaTaskListParams>
columns={[
{
accessorKey: 'subscribers',
header: t('subscribers'),
size: 200,
cell: ({ row }) => {
const subscribers = row.getValue('subscribers') as number[];
const subscriptionNames =
subscribers?.map((id) => subscribeMap[id]).filter(Boolean) || [];
if (subscriptionNames.length === 0) {
return (
<span className='text-muted-foreground text-sm'>
{t('noSubscriptions')}
</span>
);
}
return (
<div className='flex flex-wrap gap-1'>
{subscriptionNames.map((name, index) => (
<span key={index} className='bg-muted rounded px-2 py-1 text-xs'>
{name}
</span>
))}
</div>
);
},
},
{
accessorKey: 'is_active',
header: t('validOnly'),
size: 120,
cell: ({ row }) => {
const isActive = row.getValue('is_active') as boolean;
return <span className='text-sm'>{isActive ? t('yes') : t('no')}</span>;
},
},
{
accessorKey: 'reset_traffic',
header: t('resetTraffic'),
size: 120,
cell: ({ row }) => {
const resetTraffic = row.getValue('reset_traffic') as boolean;
return <span className='text-sm'>{resetTraffic ? t('yes') : t('no')}</span>;
},
},
{
accessorKey: 'gift_value',
header: t('giftAmount'),
size: 120,
cell: ({ row }) => {
const giftValue = row.getValue('gift_value') as number;
const task = row.original as API.QuotaTask;
const giftType = task.gift_type;
return (
<div className='text-sm font-medium'>
{giftType === 1 ? (
<Display type='currency' value={giftValue} />
) : (
`${giftValue}%`
)}
</div>
);
},
},
{
accessorKey: 'days',
header: t('quotaDays'),
size: 100,
cell: ({ row }) => {
const days = row.getValue('days') as number;
return (
<span className='font-medium'>
{days} {t('days')}
</span>
);
},
},
{
accessorKey: 'time_range',
header: t('timeRange'),
size: 180,
cell: ({ row }) => {
const task = row.original as API.QuotaTask;
const startTime = task.start_time;
const endTime = task.end_time;
if (!startTime && !endTime) {
return (
<span className='text-muted-foreground text-sm'>{t('noTimeLimit')}</span>
);
}
return (
<div className='space-y-1 text-xs'>
{startTime && (
<div>
{t('startTime')}: {formatDate(startTime)}
</div>
)}
{endTime && (
<div>
{t('endTime')}: {formatDate(endTime)}
</div>
)}
</div>
);
},
},
{
accessorKey: 'status',
header: t('status'),
size: 100,
cell: ({ row }) => getStatusBadge(row.getValue('status') as number),
},
{
accessorKey: 'created_at',
header: t('createdAt'),
size: 150,
cell: ({ row }) => {
const createdAt = row.getValue('created_at') as number;
return formatDate(createdAt);
},
},
]}
request={async (pagination, filters) => {
const response = await queryQuotaTaskList({
...filters,
page: pagination.page,
size: pagination.size,
});
return {
list: response.data?.data?.list || [],
total: response.data?.data?.total || 0,
};
}}
params={[
{
key: 'status',
placeholder: t('status'),
options: [
{ label: t('notStarted'), value: '0' },
{ label: t('inProgress'), value: '1' },
{ label: t('completed'), value: '2' },
],
},
]}
/>
)}
</div>
</ScrollArea>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,367 @@
'use client';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Combobox } from '@workspace/ui/custom-components/combobox';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import TagInput from '@workspace/ui/custom-components/tag-input';
import { useTranslations } from 'next-intl';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
export type ProtocolName =
| 'shadowsocks'
| 'vmess'
| 'vless'
| 'trojan'
| 'hysteria'
| 'tuic'
| 'anytls'
| 'naive'
| 'http'
| 'socks'
| 'mieru';
const buildSchema = (t: ReturnType<typeof useTranslations>) =>
z.object({
name: z.string().trim().min(1, t('errors.nameRequired')),
server_id: z
.number({ message: t('errors.serverRequired') })
.int()
.gt(0, t('errors.serverRequired'))
.optional(),
protocol: z.string().min(1, t('errors.protocolRequired')),
address: z.string().trim().min(1, t('errors.serverAddrRequired')),
port: z
.number({ message: t('errors.portRange') })
.int()
.min(1, t('errors.portRange'))
.max(65535, t('errors.portRange')),
tags: z.array(z.string()),
});
export type NodeFormValues = z.infer<ReturnType<typeof buildSchema>>;
export default function NodeForm(props: {
trigger: string;
title: string;
loading?: boolean;
initialValues?: Partial<NodeFormValues>;
onSubmit: (values: NodeFormValues) => Promise<boolean> | boolean;
}) {
const { trigger, title, loading, initialValues, onSubmit } = props;
const t = useTranslations('nodes');
const Scheme = useMemo(() => buildSchema(t), [t]);
const [open, setOpen] = useState(false);
const [autoFilledFields, setAutoFilledFields] = useState<Set<string>>(new Set());
const addAutoFilledField = (fieldName: string) => {
setAutoFilledFields((prev) => new Set(prev).add(fieldName));
};
const removeAutoFilledField = (fieldName: string) => {
setAutoFilledFields((prev) => {
const newSet = new Set(prev);
newSet.delete(fieldName);
return newSet;
});
};
const form = useForm<NodeFormValues>({
resolver: zodResolver(Scheme),
defaultValues: {
name: '',
server_id: undefined,
protocol: '',
address: '',
port: 0,
tags: [],
...initialValues,
},
});
const serverId = form.watch('server_id');
const { servers, getAvailableProtocols } = useServer();
const { tags } = useNode();
const existingTags: string[] = tags || [];
const availableProtocols = getAvailableProtocols(serverId);
useEffect(() => {
if (initialValues) {
form.reset({
name: '',
server_id: undefined,
protocol: '',
address: '',
port: 0,
tags: [],
...initialValues,
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValues]);
function handleServerChange(nextId?: number | null) {
const id = nextId ?? undefined;
form.setValue('server_id', id);
if (!id) {
setAutoFilledFields(new Set());
return;
}
const selectedServer = servers.find((s) => s.id === id);
if (!selectedServer) return;
const currentValues = form.getValues();
const fieldsToFill: string[] = [];
if (!currentValues.name || autoFilledFields.has('name')) {
form.setValue('name', selectedServer.name as string, { shouldDirty: false });
fieldsToFill.push('name');
}
if (!currentValues.address || autoFilledFields.has('address')) {
form.setValue('address', selectedServer.address as string, { shouldDirty: false });
fieldsToFill.push('address');
}
const protocols = getAvailableProtocols(id);
const firstProtocol = protocols[0];
if (firstProtocol && (!currentValues.protocol || autoFilledFields.has('protocol'))) {
form.setValue('protocol', firstProtocol.protocol, { shouldDirty: false });
fieldsToFill.push('protocol');
if (!currentValues.port || currentValues.port === 0 || autoFilledFields.has('port')) {
const port = firstProtocol.port || 0;
form.setValue('port', port, { shouldDirty: false });
fieldsToFill.push('port');
}
}
setAutoFilledFields(new Set(fieldsToFill));
}
const handleManualFieldChange = (fieldName: keyof NodeFormValues, value: any) => {
form.setValue(fieldName, value);
removeAutoFilledField(fieldName);
};
function handleProtocolChange(nextProto?: ProtocolName | null) {
const protocol = (nextProto || '') as ProtocolName | '';
form.setValue('protocol', protocol);
if (!protocol || !serverId) {
removeAutoFilledField('protocol');
return;
}
const currentValues = form.getValues();
const isPortAutoFilled = autoFilledFields.has('port');
removeAutoFilledField('protocol');
if (!currentValues.port || currentValues.port === 0 || isPortAutoFilled) {
const protocolData = availableProtocols.find((p) => p.protocol === protocol);
if (protocolData) {
const port = protocolData.port || 0;
form.setValue('port', port, { shouldDirty: false });
addAutoFilledField('port');
}
}
}
async function handleSubmit(values: NodeFormValues) {
const result = await onSubmit(values);
if (result) {
setOpen(false);
setAutoFilledFields(new Set());
}
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button
onClick={() => {
form.reset();
setAutoFilledFields(new Set());
}}
>
{trigger}
</Button>
</SheetTrigger>
<SheetContent className='w-[560px] max-w-full'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6 pt-4'>
<Form {...form}>
<form className='grid grid-cols-1 gap-4'>
<FormField
control={form.control}
name='server_id'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server')}</FormLabel>
<FormControl>
<Combobox<number, false>
placeholder={t('select_server')}
value={field.value}
options={servers.map((s) => ({
value: s.id,
label: `${s.name} (${(s.address as any) || ''})`,
}))}
onChange={(v) => handleServerChange(v)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='protocol'
render={({ field }) => (
<FormItem>
<FormLabel>{t('protocol')}</FormLabel>
<FormControl>
<Combobox<string, false>
placeholder={t('select_protocol')}
value={field.value}
options={availableProtocols.map((p) => ({
value: p.protocol,
label: `${p.protocol}${p.port ? ` (${p.port})` : ''}`,
}))}
onChange={(v) => handleProtocolChange((v as ProtocolName) || null)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('name')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(v) => handleManualFieldChange('name', v as string)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='address'
render={({ field }) => (
<FormItem>
<FormLabel>{t('address')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(v) => handleManualFieldChange('address', v as string)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='port'
render={({ field }) => (
<FormItem>
<FormLabel>{t('port')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
type='number'
min={1}
max={65535}
placeholder='1-65535'
onValueChange={(v) => handleManualFieldChange('port', Number(v))}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='tags'
render={({ field }) => (
<FormItem>
<FormLabel>{t('tags')}</FormLabel>
<FormControl>
<TagInput
placeholder={t('tags_placeholder')}
value={field.value || []}
onChange={(v) => form.setValue(field.name, v)}
options={existingTags}
/>
</FormControl>
<FormDescription>{t('tags_description')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button
disabled={loading}
onClick={form.handleSubmit(handleSubmit, (errors) => {
const key = Object.keys(errors)[0] as keyof typeof errors;
if (key) toast.error(String(errors[key]?.message));
return false;
})}
>
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,246 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
createNode,
deleteNode,
filterNodeList,
resetSortWithNode,
toggleNodeStatus,
updateNode,
} from '@/services/admin/server';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import NodeForm from './node-form';
export default function NodesPage() {
const t = useTranslations('nodes');
const ref = useRef<ProTableActions>(null);
const [loading, setLoading] = useState(false);
// Use our zustand store for server data
const { getServerName, getServerAddress, getProtocolPort } = useServer();
const { fetchNodes, fetchTags } = useNode();
return (
<ProTable<API.Node, { search: string }>
action={ref}
header={{
title: t('pageTitle'),
toolbar: (
<NodeForm
trigger={t('create')}
title={t('drawerCreateTitle')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
const body: API.CreateNodeRequest = {
name: values.name,
server_id: Number(values.server_id!),
protocol: values.protocol,
address: values.address,
port: Number(values.port!),
tags: values.tags || [],
enabled: false,
};
await createNode(body);
toast.success(t('created'));
ref.current?.refresh();
fetchNodes();
fetchTags();
setLoading(false);
return true;
} catch (e) {
setLoading(false);
return false;
}
}}
/>
),
}}
columns={[
{
id: 'enabled',
header: t('enabled'),
cell: ({ row }) => (
<Switch
checked={row.original.enabled}
onCheckedChange={async (v) => {
await toggleNodeStatus({ id: row.original.id, enable: v });
toast.success(v ? t('enabled_on') : t('enabled_off'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
/>
),
},
{ accessorKey: 'name', header: t('name') },
{
id: 'address_port',
header: `${t('address')}:${t('port')}`,
cell: ({ row }) => `${row.original.address || '—'}:${row.original.port || '—'}`,
},
{
id: 'server_id',
header: t('server'),
cell: ({ row }) =>
`${getServerName(row.original.server_id)}:${getServerAddress(row.original.server_id)}`,
},
{
id: 'protocol',
header: ` ${t('protocol')}:${t('port')}`,
cell: ({ row }) =>
`${row.original.protocol}:${getProtocolPort(row.original.server_id, row.original.protocol)}`,
},
{
accessorKey: 'tags',
header: t('tags'),
cell: ({ row }) => (
<div className='flex flex-wrap gap-1'>
{(row.original.tags || []).length === 0
? '—'
: row.original.tags.map((tg) => (
<Badge key={tg} variant='outline'>
{tg}
</Badge>
))}
</div>
),
},
]}
params={[{ key: 'search' }]}
request={async (pagination, filter) => {
const { data } = await filterNodeList({
page: pagination.page,
size: pagination.size,
search: filter?.search || undefined,
});
const list = (data?.data?.list || []) as API.Node[];
const total = Number(data?.data?.total || list.length);
return { list, total };
}}
actions={{
render: (row) => [
<NodeForm
key='edit'
trigger={t('edit')}
title={t('drawerEditTitle')}
loading={loading}
initialValues={row}
onSubmit={async (values) => {
setLoading(true);
try {
const body: API.UpdateNodeRequest = {
...row,
...values,
} as any;
await updateNode(body);
toast.success(t('updated'));
ref.current?.refresh();
fetchNodes();
fetchTags();
setLoading(false);
return true;
} catch (e) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await deleteNode({ id: row.id } as any);
toast.success(t('deleted'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
<Button
key='copy'
variant='outline'
onClick={async () => {
const { id, enabled, created_at, updated_at, sort, ...rest } = row as any;
await createNode({
...rest,
enabled: false,
});
toast.success(t('copied'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
>
{t('copy')}
</Button>,
],
batchRender(rows) {
return [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await Promise.all(rows.map((r) => deleteNode({ id: r.id } as any)));
toast.success(t('deleted'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
];
},
}}
onSort={async (source, target, items) => {
const sourceIndex = items.findIndex((item) => String(item.id) === source);
const targetIndex = items.findIndex((item) => String(item.id) === target);
const originalSorts = items.map((item) => item.sort);
const [movedItem] = items.splice(sourceIndex, 1);
items.splice(targetIndex, 0, movedItem!);
const updatedItems = items.map((item, index) => {
const originalSort = originalSorts[index];
const newSort = originalSort !== undefined ? originalSort : item.sort;
return { ...item, sort: newSort };
});
const changedItems = updatedItems.filter((item, index) => {
return item.sort !== items[index]?.sort;
});
if (changedItems.length > 0) {
resetSortWithNode({
sort: changedItems.map((item) => ({
id: item.id,
sort: item.sort,
})) as API.SortItem[],
});
toast.success(t('sorted_success'));
}
return updatedItems;
}}
/>
);
}

View File

@ -1,24 +1,25 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useRef } from 'react';
import { Display } from '@/components/display';
import { ProTable, ProTableActions } from '@/components/pro-table';
import { getOrderList, updateOrderStatus } from '@/services/admin/order';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@workspace/ui/components/hover-card';
import { Separator } from '@workspace/ui/components/separator';
import { Combobox } from '@workspace/ui/custom-components/combobox';
import { cn } from '@workspace/ui/lib/utils';
import { formatDate } from '@workspace/ui/utils';
import { UserDetail } from '../user/user-detail';
export default function Page(props: any) {
export default function Page() {
const t = useTranslations('order');
const sp = useSearchParams();
const statusOptions = [
{ value: 1, label: t('status.1'), className: 'bg-orange-500' },
@ -30,20 +31,19 @@ export default function Page(props: any) {
const ref = useRef<ProTableActions>(null);
const { data: subscribeList } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const { subscribes, getSubscribeName } = useSubscribe();
const initialFilters = {
search: sp.get('search') || undefined,
status: sp.get('status') || undefined,
subscribe_id: sp.get('subscribe_id') || undefined,
user_id: sp.get('user_id') || undefined,
};
return (
<ProTable<API.Order, any>
action={ref}
initialFilters={initialFilters}
columns={[
{
accessorKey: 'order_no',
@ -58,9 +58,10 @@ export default function Page(props: any) {
accessorKey: 'subscribe_id',
header: t('subscribe'),
cell: ({ row }) => {
const name = subscribeList?.find(
(item) => item.id === row.getValue('subscribe_id'),
)?.name;
if (row.original.type === 4) {
return t(`type.${row.getValue('type')}`);
}
const name = getSubscribeName(row.getValue('subscribe_id'));
const quantity = row.original.quantity;
return name ? `${name} × ${quantity}` : '';
},
@ -146,7 +147,7 @@ export default function Page(props: any) {
if ([1, 3, 4].includes(row.getValue('status'))) {
return (
<Combobox<number, false>
placeholder='状态'
placeholder={t('status.0')}
value={row.original.status}
onChange={async (value) => {
await updateOrderStatus({
@ -176,25 +177,20 @@ export default function Page(props: any) {
{
key: 'subscribe_id',
placeholder: `${t('subscribe')}`,
options: subscribeList?.map((item) => ({
label: item.name,
options: subscribes?.map((item) => ({
label: item.name!,
value: String(item.id),
})),
},
{ key: 'search' },
].concat(
props.userId
? []
: [
{
key: 'user_id',
placeholder: `${t('user')} ID`,
options: undefined,
},
],
)}
{
key: 'user_id',
placeholder: `${t('user')} ID`,
options: undefined,
},
]}
request={async (pagination, filter) => {
const { data } = await getOrderList({ ...pagination, ...filter, user_id: props.userId });
const { data } = await getOrderList({ ...pagination, ...filter });
return {
list: data.data?.list || [],
total: data.data?.total || 0,

View File

@ -75,9 +75,9 @@ export default function PaymentForm<T>({
icon: z.string().optional(),
domain: z.string().optional(),
config: z.any(),
fee_mode: z.coerce.number().min(0).max(2),
fee_percent: z.coerce.number().optional(),
fee_amount: z.coerce.number().optional(),
fee_mode: z.number().min(0).max(2),
fee_percent: z.number().optional(),
fee_amount: z.number().optional(),
description: z.string().optional(),
});
@ -155,7 +155,6 @@ export default function PaymentForm<T>({
<ScrollArea className='-mx-6 h-[calc(100vh-48px-36px-36px-env(safe-area-inset-top))]'>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6 px-6 pt-4'>
{/* 基本信息分组 */}
<div className='space-y-4'>
<div className='grid grid-cols-1 gap-4 sm:grid-cols-2'>
<FormField
@ -319,7 +318,7 @@ export default function PaymentForm<T>({
}}
defaultValue={field.value}
value={field.value}
// @ts-expect-error
// @ts-expect-error - disabled prop type mismatch with SelectTrigger component
disabled={isEdit && Boolean(initialValues?.platform)}
>
<FormControl>

View File

@ -93,7 +93,7 @@ export default function PaymentTable() {
{
accessorKey: 'platform',
header: t('platform'),
cell: ({ row }) => <Badge>{t(row.getValue('platform'))}</Badge>,
cell: ({ row }) => <Badge>{t(row.original.platform)}</Badge>,
},
{
accessorKey: 'notify_url',

View File

@ -1,143 +0,0 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const formSchema = z.object({
name: z.string(),
description: z.string().optional(),
});
interface GroupFormProps<T> {
onSubmit: (data: T) => Promise<boolean> | boolean;
initialValues?: T;
loading?: boolean;
trigger: string;
title: string;
}
export default function GroupForm<T extends Record<string, any>>({
onSubmit,
initialValues,
loading,
trigger,
title,
}: GroupFormProps<T>) {
const t = useTranslations('product');
const [open, setOpen] = useState(false);
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
...initialValues,
},
});
useEffect(() => {
form?.reset(initialValues);
}, [form, initialValues]);
async function handleSubmit(data: { [x: string]: any }) {
const bool = await onSubmit(data as T);
if (bool) setOpen(false);
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button
onClick={() => {
form.reset();
setOpen(true);
}}
>
{trigger}
</Button>
</SheetTrigger>
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
<FormField
control={form.control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('group.form.name')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(value) => {
form.setValue(field.name, value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='description'
render={({ field }) => (
<FormItem>
<FormLabel>{t('group.form.description')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(value) => {
form.setValue(field.name, value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button
variant='outline'
disabled={loading}
onClick={() => {
setOpen(false);
}}
>
{t('group.form.cancel')}
</Button>
<Button disabled={loading} onClick={form.handleSubmit(handleSubmit)}>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}{' '}
{t('group.form.confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -1,141 +0,0 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
batchDeleteSubscribeGroup,
createSubscribeGroup,
deleteSubscribeGroup,
getSubscribeGroupList,
updateSubscribeGroup,
} from '@/services/admin/subscribe';
import { Button } from '@workspace/ui/components/button';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import GroupForm from './form';
const GroupTable = () => {
const t = useTranslations('product');
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.SubscribeGroup, any>
action={ref}
header={{
title: t('group.title'),
toolbar: (
<GroupForm<API.CreateSubscribeGroupRequest>
trigger={t('group.create')}
title={t('group.createSubscribeGroup')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createSubscribeGroup(values);
toast.success(t('group.createSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>
),
}}
columns={[
{
accessorKey: 'name',
header: t('group.name'),
},
{
accessorKey: 'description',
header: t('group.description'),
},
{
accessorKey: 'updated_at',
header: t('group.updatedAt'),
cell: ({ row }) => formatDate(row.getValue('updated_at')),
},
]}
request={async () => {
const { data } = await getSubscribeGroupList();
return {
list: data.data?.list || [],
total: data.data?.total || 0,
};
}}
actions={{
render: (row) => [
<GroupForm<API.SubscribeGroup>
key='edit'
trigger={t('group.edit')}
title={t('group.editSubscribeGroup')}
loading={loading}
initialValues={row}
onSubmit={async (values) => {
setLoading(true);
try {
await updateSubscribeGroup({
...row,
...values,
});
toast.success(t('group.updateSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
title={t('group.confirmDelete')}
description={t('group.deleteWarning')}
onConfirm={async () => {
await deleteSubscribeGroup({
id: row.id,
});
toast.success(t('group.deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('group.cancel')}
confirmText={t('group.confirm')}
/>,
],
batchRender(rows) {
return [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
title={t('group.confirmDelete')}
description={t('group.deleteWarning')}
onConfirm={async () => {
await batchDeleteSubscribeGroup({
ids: rows.map((item) => item.id),
});
toast.success(t('group.deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('group.cancel')}
confirmText={t('group.confirm')}
/>,
];
},
}}
/>
);
};
export default GroupTable;

View File

@ -1,25 +1,5 @@
import { getTranslations } from 'next-intl/server';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import GroupTable from './group/table';
import SubscribeTable from './subscribe-table';
export default async function Page() {
const t = await getTranslations('product');
return (
<Tabs defaultValue='subscribe'>
<TabsList>
<TabsTrigger value='subscribe'>{t('tabs.subscribe')}</TabsTrigger>
<TabsTrigger value='group'>{t('tabs.subscribeGroup')}</TabsTrigger>
</TabsList>
<TabsContent value='subscribe'>
<SubscribeTable />
</TabsContent>
<TabsContent value='group'>
<GroupTable />
</TabsContent>
</Tabs>
);
return <SubscribeTable />;
}

View File

@ -1,9 +1,8 @@
'use client';
import { getNodeGroupList, getNodeList } from '@/services/admin/server';
import { getSubscribeGroupList } from '@/services/admin/subscribe';
import useGlobalStore from '@/config/use-global';
import { useNode } from '@/store/node';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import {
Accordion,
AccordionContent,
@ -62,8 +61,9 @@ const defaultValues = {
traffic: 0,
quota: 0,
discount: [],
server_group: [],
server: [],
language: '',
node_tags: [],
nodes: [],
unit_time: 'Month',
deduction_ratio: 0,
purchase_with_discount: false,
@ -79,6 +79,9 @@ export default function SubscribeForm<T extends Record<string, any>>({
trigger,
title,
}: Readonly<SubscribeFormProps<T>>) {
const { common } = useGlobalStore();
const { currency } = common;
const t = useTranslations('product');
const [open, setOpen] = useState(false);
const updateTimeoutRef = useRef<NodeJS.Timeout | null>(null);
@ -87,7 +90,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
name: z.string(),
description: z.string().optional(),
unit_price: z.number(),
unit_time: z.string().default('Month'),
unit_time: z.string(),
replacement: z.number().optional(),
discount: z
.array(
@ -97,21 +100,21 @@ export default function SubscribeForm<T extends Record<string, any>>({
}),
)
.optional(),
inventory: z.number().optional().default(-1),
speed_limit: z.number().optional().default(0),
device_limit: z.number().optional().default(0),
traffic: z.number().optional().default(0),
quota: z.number().optional().default(0),
group_id: z.number().optional().nullish(),
server_group: z.array(z.number()).optional().default([]),
server: z.array(z.number()).optional().default([]),
deduction_ratio: z.number().optional().default(0),
allow_deduction: z.boolean().optional().default(false),
reset_cycle: z.number().optional().default(0),
renewal_reset: z.boolean().optional().default(false),
inventory: z.number().optional(),
speed_limit: z.number().optional(),
device_limit: z.number().optional(),
traffic: z.number().optional(),
quota: z.number().optional(),
language: z.string().optional(),
node_tags: z.array(z.string()).optional(),
nodes: z.array(z.number()).optional(),
deduction_ratio: z.number().optional(),
allow_deduction: z.boolean().optional(),
reset_cycle: z.number().optional(),
renewal_reset: z.boolean().optional(),
});
const form = useForm({
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: assign(
defaultValues,
@ -203,7 +206,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
});
if (hasChanges) {
form.setValue(fieldName, calculatedValues, { shouldDirty: true });
form.setValue(fieldName as any, calculatedValues, { shouldDirty: true });
}
}, 300);
},
@ -214,7 +217,11 @@ export default function SubscribeForm<T extends Record<string, any>>({
form?.reset(
assign(defaultValues, shake(initialValues, (value) => value === null) as Record<string, any>),
);
}, [form, initialValues]);
const discount = form.getValues('discount') || [];
if (discount.length > 0) {
debouncedCalculateDiscount(discount, 'discount');
}
}, [form, initialValues, open]);
useEffect(() => {
return () => {
@ -229,35 +236,11 @@ export default function SubscribeForm<T extends Record<string, any>>({
if (bool) setOpen(false);
}
const { data: group } = useQuery({
queryKey: ['getSubscribeGroupList'],
queryFn: async () => {
const { data } = await getSubscribeGroupList();
return data.data?.list as API.SubscribeGroup[];
},
});
const { getAllAvailableTags, getNodesByTag, getNodesWithoutTags } = useNode();
const { data: server } = useQuery({
queryKey: ['getNodeList', 'all'],
queryFn: async () => {
const { data } = await getNodeList({
page: 1,
size: 9999,
});
return data.data?.list;
},
});
const { data: server_groups } = useQuery({
queryKey: ['getNodeGroupList'],
queryFn: async () => {
const { data } = await getNodeGroupList();
return (data.data?.list || []) as API.ServerGroup[];
},
});
const tagGroups = getAllAvailableTags();
const unit_time = form.watch('unit_time');
const unit_price = form.watch('unit_price');
return (
<Sheet open={open} onOpenChange={setOpen}>
@ -275,7 +258,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='pt-4'>
<Tabs defaultValue='basic' className='w-full'>
@ -290,7 +273,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
</TabsTrigger>
<TabsTrigger value='servers' className='flex items-center gap-2'>
<Server className='h-4 w-4' />
{t('form.servers')}
{t('form.nodes')}
</TabsTrigger>
</TabsList>
@ -317,21 +300,20 @@ export default function SubscribeForm<T extends Record<string, any>>({
/>
<FormField
control={form.control}
name='group_id'
name='language'
render={({ field }) => (
<FormItem>
<FormLabel>{t('form.groupId')}</FormLabel>
<FormLabel>
{t('form.language')}
<span className='text-muted-foreground ml-1 text-[0.8rem]'>
{t('form.languageDescription')}
</span>
</FormLabel>
<FormControl>
<Combobox<number, false>
placeholder={t('form.selectSubscribeGroup')}
<EnhancedInput
{...field}
onChange={(value) => {
form.setValue(field.name, value || 0);
}}
options={group?.map((item) => ({
label: item.name,
value: item.id,
}))}
placeholder={t('form.languagePlaceholder')}
onValueChange={(v) => form.setValue(field.name, v as string)}
/>
</FormControl>
<FormMessage />
@ -656,9 +638,9 @@ export default function SubscribeForm<T extends Record<string, any>>({
{
name: 'discount',
type: 'number',
min: 0.01,
min: 1,
max: 100,
step: 0.01,
step: 1,
placeholder: t('form.discountPercent'),
suffix: '%',
},
@ -668,8 +650,10 @@ export default function SubscribeForm<T extends Record<string, any>>({
type: 'number',
min: 0,
step: 0.01,
prefix: currency.currency_symbol,
formatInput: (value) => unitConversion('centsToDollars', value),
formatOutput: (value) => unitConversion('dollarsToCents', value),
formatOutput: (value) =>
unitConversion('dollarsToCents', value).toString(),
},
]}
value={field.value}
@ -795,53 +779,56 @@ export default function SubscribeForm<T extends Record<string, any>>({
<div className='space-y-6'>
<FormField
control={form.control}
name='server_group'
name='node_tags'
render={({ field }) => (
<FormItem>
<FormLabel>{t('form.serverGroup')}</FormLabel>
<FormLabel>{t('form.nodeGroup')}</FormLabel>
<FormControl>
<Accordion type='single' collapsible className='w-full'>
{server_groups?.map((group: API.ServerGroup) => {
{tagGroups.map((tag) => {
const value = field.value || [];
const tagId = tag;
const nodesWithTag = getNodesByTag(tag);
return (
<AccordionItem key={group.id} value={String(group.id)}>
<AccordionItem key={tag} value={String(tag)}>
<AccordionTrigger>
<div className='flex items-center gap-2'>
<Checkbox
checked={value.includes(group.id!)}
checked={value.includes(tagId as any)}
onCheckedChange={(checked) => {
return checked
? form.setValue(field.name, [...value, group.id])
? form.setValue(field.name, [...value, tagId] as any)
: form.setValue(
field.name,
value.filter(
(value: number) => value !== group.id,
),
value.filter((v: any) => v !== tagId),
);
}}
/>
<Label>{group.name}</Label>
<Label>
{tag}
<span className='text-muted-foreground ml-2 text-xs'>
({nodesWithTag.length})
</span>
</Label>
</div>
</AccordionTrigger>
<AccordionContent>
<ul className='list-disc [&>li]:mt-2'>
{server
?.filter(
(server: API.Server) => server.group_id === group.id,
)
?.map((node: API.Server) => {
return (
<li
key={node.id}
className='flex items-center justify-between *:flex-1'
>
<span>{node.name}</span>
<span>{node.server_addr}</span>
<span className='text-right'>{node.protocol}</span>
</li>
);
})}
<ul className='space-y-1'>
{getNodesByTag(tag).map((node) => (
<li
key={node.id}
className='flex items-center justify-between gap-3'
>
<span className='flex-1'>{node.name}</span>
<span className='flex-1'>
{node.address}:{node.port}
</span>
<span className='flex-1 text-right'>
{node.protocol}
</span>
</li>
))}
</ul>
</AccordionContent>
</AccordionItem>
@ -856,38 +843,38 @@ export default function SubscribeForm<T extends Record<string, any>>({
<FormField
control={form.control}
name='server'
name='nodes'
render={({ field }) => (
<FormItem>
<FormLabel>{t('form.server')}</FormLabel>
<FormLabel>{t('form.node')}</FormLabel>
<FormControl>
<div className='flex flex-col gap-2'>
{server
?.filter((item: API.Server) => !item.group_id)
?.map((item: API.Server) => {
const value = field.value || [];
{getNodesWithoutTags().map((item) => {
const value = field.value || [];
return (
<div className='flex items-center gap-2' key={item.id}>
<Checkbox
checked={value.includes(item.id!)}
onCheckedChange={(checked) => {
return checked
? form.setValue(field.name, [...value, item.id])
: form.setValue(
field.name,
value.filter((value: number) => value !== item.id),
);
}}
/>
<Label className='flex w-full items-center justify-between *:flex-1'>
<span>{item.name}</span>
<span>{item.server_addr}</span>
<span className='text-right'>{item.protocol}</span>
</Label>
</div>
);
})}
return (
<div className='flex items-center gap-2' key={item.id}>
<Checkbox
checked={value.includes(item.id!)}
onCheckedChange={(checked) => {
return checked
? form.setValue(field.name, [...value, item.id])
: form.setValue(
field.name,
value.filter((value: number) => value !== item.id),
);
}}
/>
<Label className='flex w-full items-center justify-between gap-3'>
<span className='flex-1'>{item.name}</span>
<span className='flex-1'>
{item.address}:{item.port}
</span>
<span className='flex-1 text-right'>{item.protocol}</span>
</Label>
</div>
);
})}
</div>
</FormControl>
<FormMessage />
@ -916,7 +903,8 @@ export default function SubscribeForm<T extends Record<string, any>>({
const keys = Object.keys(errors);
for (const key of keys) {
const formattedKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
toast.error(`${t(`form.${formattedKey}`)} is ${errors[key]?.message}`);
const error = (errors as any)[key];
toast.error(`${t(`form.${formattedKey}`)} is ${error?.message}`);
return false;
}
})}

View File

@ -6,12 +6,11 @@ import {
batchDeleteSubscribe,
createSubscribe,
deleteSubscribe,
getSubscribeGroupList,
getSubscribeList,
subscribeSort,
updateSubscribe,
} from '@/services/admin/subscribe';
import { useQuery } from '@tanstack/react-query';
import { useSubscribe } from '@/store/subscribe';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
@ -24,17 +23,8 @@ import SubscribeForm from './subscribe-form';
export default function SubscribeTable() {
const t = useTranslations('product');
const [loading, setLoading] = useState(false);
const { data: groups } = useQuery({
queryKey: ['getSubscribeGroupList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeGroupList({
page: 1,
size: 9999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const ref = useRef<ProTableActions>(null);
const { fetchSubscribes } = useSubscribe();
return (
<ProTable<API.SubscribeItem, { group_id: number; query: string }>
action={ref}
@ -54,6 +44,7 @@ export default function SubscribeTable() {
});
toast.success(t('createSuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
@ -67,14 +58,6 @@ export default function SubscribeTable() {
),
}}
params={[
{
key: 'group_id',
placeholder: t('subscribeGroup'),
options: groups?.map((item) => ({
label: item.name,
value: String(item.id),
})),
},
{
key: 'search',
},
@ -103,6 +86,7 @@ export default function SubscribeTable() {
show: checked,
} as API.UpdateSubscribeRequest);
ref.current?.refresh();
fetchSubscribes();
}}
/>
);
@ -121,6 +105,7 @@ export default function SubscribeTable() {
sell: checked,
} as API.UpdateSubscribeRequest);
ref.current?.refresh();
fetchSubscribes();
}}
/>
);
@ -176,11 +161,11 @@ export default function SubscribeTable() {
cell: ({ row }) => <Display type='number' value={row.getValue('quota')} unlimited />,
},
{
accessorKey: 'group_id',
header: t('subscribeGroup'),
accessorKey: 'language',
header: t('language'),
cell: ({ row }) => {
const name = groups?.find((group) => group.id === row.getValue('group_id'))?.name;
return name ? <Badge variant='outline'>{name}</Badge> : '--';
const language = row.getValue('language') as string;
return language ? <Badge variant='outline'>{language}</Badge> : '--';
},
},
{
@ -206,6 +191,7 @@ export default function SubscribeTable() {
} as API.UpdateSubscribeRequest);
toast.success(t('updateSuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
} catch (error) {
@ -226,6 +212,7 @@ export default function SubscribeTable() {
});
toast.success(t('deleteSuccess'));
ref.current?.refresh();
fetchSubscribes();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@ -244,6 +231,7 @@ export default function SubscribeTable() {
} as API.CreateSubscribeRequest);
toast.success(t('copySuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
} catch (error) {
@ -268,6 +256,7 @@ export default function SubscribeTable() {
toast.success(t('deleteSuccess'));
ref.current?.reset();
fetchSubscribes();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}

View File

@ -1,126 +0,0 @@
import { z } from 'zod';
export const protocols = ['shadowsocks', 'vmess', 'vless', 'trojan', 'hysteria2', 'tuic', 'anytls'];
const nullableString = z.string().nullish();
const portSchema = z.number().max(65535).nullish();
const securityConfigSchema = z
.object({
sni: nullableString,
allow_insecure: z.boolean().nullable().default(false),
fingerprint: nullableString,
reality_private_key: nullableString,
reality_public_key: nullableString,
reality_short_id: nullableString,
reality_server_addr: nullableString,
reality_server_port: portSchema,
})
.nullish();
const transportConfigSchema = z
.object({
path: nullableString,
host: nullableString,
service_name: nullableString,
})
.nullish();
const baseProtocolSchema = z.object({
port: portSchema,
transport: z.string(),
transport_config: transportConfigSchema,
security: z.string(),
security_config: securityConfigSchema,
});
const shadowsocksSchema = z.object({
method: z.string(),
port: portSchema,
server_key: nullableString,
});
const vmessSchema = baseProtocolSchema;
const vlessSchema = baseProtocolSchema.extend({
flow: nullableString,
});
const trojanSchema = baseProtocolSchema;
const hysteria2Schema = z.object({
port: portSchema,
hop_ports: nullableString,
hop_interval: z.number().nullish(),
obfs_password: nullableString,
security: z.string(),
security_config: securityConfigSchema,
});
const tuicSchema = z.object({
port: portSchema,
disable_sni: z.boolean().default(false),
reduce_rtt: z.boolean().default(false),
udp_relay_mode: z.string().default('native'),
congestion_controller: z.string().default('bbr'),
security_config: securityConfigSchema,
});
const anytlsSchema = z.object({
port: portSchema,
security_config: securityConfigSchema,
});
const protocolConfigSchema = z.discriminatedUnion('protocol', [
z.object({
protocol: z.literal('shadowsocks'),
config: shadowsocksSchema,
}),
z.object({
protocol: z.literal('vmess'),
config: vmessSchema,
}),
z.object({
protocol: z.literal('vless'),
config: vlessSchema,
}),
z.object({
protocol: z.literal('trojan'),
config: trojanSchema,
}),
z.object({
protocol: z.literal('hysteria2'),
config: hysteria2Schema,
}),
z.object({
protocol: z.literal('tuic'),
config: tuicSchema,
}),
z.object({
protocol: z.literal('anytls'),
config: anytlsSchema,
}),
]);
const baseFormSchema = z.object({
name: z.string(),
tags: z.array(z.string()).nullish().default([]),
country: z.string().nullish(),
city: z.string().nullish(),
server_addr: z.string(),
speed_limit: z.number().nullish(),
traffic_ratio: z.number().default(1),
group_id: z.number().nullish(),
relay_mode: z.string().nullish().default('none'),
relay_node: z
.array(
z.object({
host: z.string(),
port: portSchema,
prefix: z.string().nullish(),
}),
)
.nullish()
.default([]),
});
export const formSchema = z.intersection(baseFormSchema, protocolConfigSchema);

View File

@ -1,145 +0,0 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const formSchema = z.object({
name: z.string(),
description: z.string().optional(),
});
interface GroupFormProps<T> {
onSubmit: (data: T) => Promise<boolean> | boolean;
initialValues?: T;
loading?: boolean;
trigger: string;
title: string;
}
export default function GroupForm<T extends Record<string, any>>({
onSubmit,
initialValues,
loading,
trigger,
title,
}: GroupFormProps<T>) {
const t = useTranslations('server');
const [open, setOpen] = useState(false);
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
...initialValues,
},
});
useEffect(() => {
form?.reset(initialValues);
}, [form, initialValues]);
async function handleSubmit(data: { [x: string]: any }) {
const bool = await onSubmit(data as T);
if (bool) setOpen(false);
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button
onClick={() => {
form.reset();
setOpen(true);
}}
>
{trigger}
</Button>
</SheetTrigger>
<SheetContent className='w-[500px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 px-6 pt-4'>
<FormField
control={form.control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('groupForm.name')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(value) => {
form.setValue(field.name, value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='description'
render={({ field }) => (
<FormItem>
<FormLabel>{t('groupForm.description')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
onValueChange={(value) => {
form.setValue(field.name, value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button
variant='outline'
disabled={loading}
onClick={() => {
setOpen(false);
}}
>
{t('groupForm.cancel')}
</Button>
<Button disabled={loading} onClick={form.handleSubmit(handleSubmit)}>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}{' '}
{t('groupForm.confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -1,140 +0,0 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
batchDeleteNodeGroup,
createNodeGroup,
deleteNodeGroup,
getNodeGroupList,
updateNodeGroup,
} from '@/services/admin/server';
import { Button } from '@workspace/ui/components/button';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import GroupForm from './group-form';
export default function GroupTable() {
const t = useTranslations('server');
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.ServerGroup, any>
action={ref}
header={{
title: t('group.title'),
toolbar: (
<GroupForm<API.CreateNodeGroupRequest>
trigger={t('group.create')}
title={t('group.createNodeGroup')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createNodeGroup(values);
toast.success(t('group.createdSuccessfully'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>
),
}}
columns={[
{
accessorKey: 'name',
header: t('group.name'),
},
{
accessorKey: 'description',
header: t('group.description'),
cell: ({ row }) => <p className='line-clamp-3'>{row.getValue('description')}</p>,
},
{
accessorKey: 'updated_at',
header: t('group.updatedAt'),
cell: ({ row }) => formatDate(row.getValue('updated_at')),
},
]}
request={async () => {
const { data } = await getNodeGroupList();
return {
list: data.data?.list || [],
total: data.data?.total || 0,
};
}}
actions={{
render: (row) => [
<GroupForm<API.ServerGroup>
key='edit'
trigger={t('group.edit')}
title={t('group.editNodeGroup')}
loading={loading}
initialValues={row}
onSubmit={async (values) => {
setLoading(true);
try {
await updateNodeGroup({
...row,
...values,
});
toast.success(t('group.createdSuccessfully'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
title={t('group.confirmDelete')}
description={t('group.deleteWarning')}
onConfirm={async () => {
await deleteNodeGroup({
id: row.id!,
});
toast.success(t('group.deletedSuccessfully'));
ref.current?.refresh();
}}
cancelText={t('group.cancel')}
confirmText={t('group.confirm')}
/>,
],
batchRender(rows) {
return [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('group.delete')}</Button>}
title={t('group.confirmDelete')}
description={t('group.deleteWarning')}
onConfirm={async () => {
await batchDeleteNodeGroup({
ids: rows.map((item) => item.id),
});
toast.success(t('group.deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('group.cancel')}
confirmText={t('group.confirm')}
/>,
];
},
}}
/>
);
}

View File

@ -1,296 +0,0 @@
'use client';
import {
getNodeConfig,
getNodeMultiplier,
setNodeMultiplier,
updateNodeConfig,
} from '@/services/admin/system';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import { ChartContainer, ChartTooltip } from '@workspace/ui/components/chart';
import { Label } from '@workspace/ui/components/label';
import { Table, TableBody, TableCell, TableRow } from '@workspace/ui/components/table';
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { DicesIcon } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { uid } from 'radash';
import { useMemo, useState } from 'react';
import { Cell, Legend, Pie, PieChart } from 'recharts';
import { toast } from 'sonner';
const COLORS = [
'hsl(var(--chart-1))',
'hsl(var(--chart-2))',
'hsl(var(--chart-3))',
'hsl(var(--chart-4))',
'hsl(var(--chart-5))',
];
const MINUTES_IN_DAY = 1440; // 24 * 60
function getTimeRangeData(slots: API.TimePeriod[]) {
const timePoints = slots
.filter((slot) => slot.start_time && slot.end_time)
.flatMap((slot) => {
const [startH = 0, startM = 0] = slot.start_time.split(':').map(Number);
const [endH = 0, endM = 0] = slot?.end_time.split(':').map(Number);
const start = startH * 60 + startM;
let end = endH * 60 + endM;
if (end < start) end += MINUTES_IN_DAY;
return { start, end, multiplier: slot.multiplier };
})
.sort((a, b) => a.start - b.start);
const result = [];
let currentMinute = 0;
timePoints.forEach((point) => {
if (point.start > currentMinute) {
result.push({
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - ${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')}`,
value: point.start - currentMinute,
multiplier: 1,
});
}
result.push({
name: `${Math.floor(point.start / 60)}:${String(point.start % 60).padStart(2, '0')} - ${Math.floor((point.end / 60) % 24)}:${String(point.end % 60).padStart(2, '0')}`,
value: point.end - point.start,
multiplier: point.multiplier,
});
currentMinute = point.end % MINUTES_IN_DAY;
});
if (currentMinute < MINUTES_IN_DAY) {
result.push({
name: `${Math.floor(currentMinute / 60)}:${String(currentMinute % 60).padStart(2, '0')} - 24:00`,
value: MINUTES_IN_DAY - currentMinute,
multiplier: 1,
});
}
return result;
}
export default function NodeConfig() {
const t = useTranslations('server.config');
const { data, refetch } = useQuery({
queryKey: ['getNodeConfig'],
queryFn: async () => {
const { data } = await getNodeConfig();
return data.data;
},
});
async function updateConfig(key: string, value: unknown) {
if (data?.[key] === value) return;
try {
await updateNodeConfig({
...data,
[key]: value,
} as API.NodeConfig);
toast.success(t('saveSuccess'));
refetch();
} catch (error) {
/* empty */
}
}
const [timeSlots, setTimeSlots] = useState<API.TimePeriod[]>([]);
const { data: NodeMultiplier, refetch: refetchNodeMultiplier } = useQuery({
queryKey: ['getNodeMultiplier'],
queryFn: async () => {
const { data } = await getNodeMultiplier();
if (timeSlots.length === 0) {
setTimeSlots(data.data?.periods || []);
}
return data.data?.periods || [];
},
});
const chartTimeSlots = useMemo(() => {
return getTimeRangeData(timeSlots);
}, [timeSlots]);
const chartConfig = useMemo(() => {
return chartTimeSlots?.reduce(
(acc, item, index) => {
acc[item.name] = {
label: item.name,
color: COLORS[index % COLORS.length] || 'hsl(var(--default-chart-color))',
};
return acc;
},
{} as Record<string, { label: string; color: string }>,
);
}, [data]);
return (
<>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Label>{t('communicationKey')}</Label>
<p className='text-muted-foreground text-xs'>{t('communicationKeyDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<EnhancedInput
placeholder={t('inputPlaceholder')}
value={data?.node_secret}
onValueBlur={(value) => updateConfig('node_secret', value)}
suffix={
<div className='bg-muted flex h-9 items-center text-nowrap px-3'>
<DicesIcon
onClick={() => {
const id = uid(32).toLowerCase();
const formatted = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;
updateConfig('node_secret', formatted);
}}
className='cursor-pointer'
/>
</div>
}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('nodePullInterval')}</Label>
<p className='text-muted-foreground text-xs'>{t('nodePullIntervalDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<EnhancedInput
type='number'
min={0}
onValueBlur={(value) => updateConfig('node_pull_interval', value)}
suffix='S'
value={data?.node_pull_interval}
placeholder={t('inputPlaceholder')}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('nodePushInterval')}</Label>
<p className='text-muted-foreground text-xs'>{t('nodePushIntervalDescription')}</p>
</TableCell>
<TableCell className='text-right'>
<EnhancedInput
type='number'
min={0}
step={0.1}
value={data?.node_push_interval}
onValueBlur={(value) => updateConfig('node_push_interval', value)}
placeholder={t('inputPlaceholder')}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Label>{t('dynamicMultiplier')}</Label>
<p className='text-muted-foreground text-xs'>{t('dynamicMultiplierDescription')}</p>
</TableCell>
<TableCell className='flex justify-end gap-2'>
<Button
size='sm'
variant='outline'
onClick={() => {
setTimeSlots(NodeMultiplier || []);
}}
>
{t('reset')}
</Button>
<Button
size='sm'
onClick={() => {
setNodeMultiplier({
periods: timeSlots,
}).then(async () => {
const result = await refetchNodeMultiplier();
if (result.data) setTimeSlots(result.data);
toast.success(t('saveSuccess'));
});
}}
>
{t('save')}
</Button>
</TableCell>
</TableRow>
</TableBody>
</Table>
<div className='flex flex-col-reverse gap-8 px-4 pt-6 md:flex-row md:items-start'>
<div className='w-full md:w-1/2'>
<ChartContainer config={chartConfig} className='mx-auto aspect-[4/3] max-w-[400px]'>
<PieChart>
<Pie
data={chartTimeSlots}
cx='50%'
cy='50%'
labelLine={false}
outerRadius='80%'
fill='#8884d8'
dataKey='value'
label={({ name, percent, multiplier }) =>
`${(multiplier || 0)?.toFixed(2)}x (${(percent * 100).toFixed(0)}%)`
}
>
{chartTimeSlots.map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<ChartTooltip
content={({ payload }) => {
if (payload && payload.length) {
const data = payload[0]?.payload;
return (
<div className='bg-background rounded-lg border p-2 shadow-sm'>
<div className='grid grid-cols-2 gap-2'>
<div className='flex flex-col'>
<span className='text-muted-foreground text-[0.70rem] uppercase'>
{t('timeSlot')}
</span>
<span className='text-muted-foreground font-bold'>
{data.name || '其他'}
</span>
</div>
<div className='flex flex-col'>
<span className='text-muted-foreground text-[0.70rem] uppercase'>
{t('multiplier')}
</span>
<span className='font-bold'>{data.multiplier.toFixed(2)}x</span>
</div>
</div>
</div>
);
}
return null;
}}
/>
<Legend />
</PieChart>
</ChartContainer>
</div>
<div className='w-full md:w-1/2'>
<ArrayInput<API.TimePeriod>
fields={[
{
name: 'start_time',
prefix: t('startTime'),
type: 'time',
},
{ name: 'end_time', prefix: t('endTime'), type: 'time' },
{ name: 'multiplier', prefix: t('multiplier'), type: 'number', placeholder: '0' },
]}
value={timeSlots}
onChange={setTimeSlots}
/>
</div>
</div>
</>
);
}

View File

@ -1,251 +0,0 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { ProTable } from '@/components/pro-table';
import { getUserSubscribeById } from '@/services/admin/user';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Progress } from '@workspace/ui/components/progress';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { formatBytes, formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
interface NodeDetailDialogProps {
node: API.Server;
children?: React.ReactNode;
trigger?: React.ReactNode;
}
// 统一的用户订阅信息组件
function UserSubscribeInfo({
userId,
type,
}: {
userId: number;
type: 'account' | 'subscribeName' | 'subscribeId' | 'trafficUsage' | 'expireTime';
}) {
const { data } = useQuery({
enabled: userId !== 0,
queryKey: ['getUserSubscribeById', userId],
queryFn: async () => {
const { data } = await getUserSubscribeById({ id: userId });
return data.data;
},
});
if (!data) return <span className='text-muted-foreground'>--</span>;
switch (type) {
case 'account':
if (!data.user_id) return <span className='text-muted-foreground'>--</span>;
return <UserDetail id={data.user_id} />;
case 'subscribeName':
if (!data.subscribe?.name) return <span className='text-muted-foreground'>--</span>;
return <span className='text-sm'>{data.subscribe.name}</span>;
case 'subscribeId':
if (!data.id) return <span className='text-muted-foreground'>--</span>;
return <span className='font-mono text-sm'>{data.id}</span>;
case 'trafficUsage': {
const usedTraffic = data.upload + data.download;
const totalTraffic = data.traffic || 0;
return (
<div className='min-w-0 text-sm'>
<div className='break-words'>
{formatBytes(usedTraffic)} / {totalTraffic > 0 ? formatBytes(totalTraffic) : '无限制'}
</div>
</div>
);
}
case 'expireTime': {
if (!data.expire_time) return <span className='text-muted-foreground'>--</span>;
const isExpired = data.expire_time < Date.now() / 1000;
return (
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2'>
<span className='text-sm'>{formatDate(data.expire_time)}</span>
{isExpired && (
<Badge variant='destructive' className='w-fit px-1 py-0 text-xs'>
</Badge>
)}
</div>
);
}
default:
return <span className='text-muted-foreground'>--</span>;
}
}
export function NodeDetailDialog({ node, children, trigger }: NodeDetailDialogProps) {
const t = useTranslations('server.node');
const [open, setOpen] = useState(false);
const { status } = node;
const { online, cpu, mem, disk, updated_at } = status || {
online: {},
cpu: 0,
mem: 0,
disk: 0,
updated_at: 0,
};
const isOnline = updated_at > 0;
const onlineCount = (online && Object.keys(online).length) || 0;
// 转换在线用户数据为ProTable需要的格式
const onlineUsersData = Object.entries(online || {}).map(([uid, ips]) => ({
uid,
ips: ips as string[],
primaryIp: ips[0] || '',
allIps: (ips as string[]).join(', '),
}));
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
{trigger || (
<Button variant='outline' size='sm'>
{t('detail')}
</Button>
)}
</SheetTrigger>
<SheetContent className='w-full max-w-full sm:w-[600px] sm:max-w-screen-md'>
<SheetHeader>
<SheetTitle>
{t('nodeDetail')} - {node.name}
</SheetTitle>
</SheetHeader>
<div className='-mx-6 h-[calc(100dvh-48px-16px-env(safe-area-inset-top))] space-y-2 overflow-y-auto px-6 py-4'>
<h3 className='text-base font-medium'>{t('nodeStatus')}</h3>
<div className='space-y-3'>
<div className='flex w-full flex-col gap-2 text-sm sm:flex-row sm:items-center sm:gap-3'>
<Badge variant={isOnline ? 'default' : 'destructive'} className='w-fit text-xs'>
{isOnline ? t('normal') : t('abnormal')}
</Badge>
<span className='text-muted-foreground'>
{t('onlineCount')}: {onlineCount}
</span>
{isOnline && (
<span className='text-muted-foreground text-xs sm:text-sm'>
{t('lastUpdated')}: {formatDate(updated_at)}
</span>
)}
</div>
{isOnline && (
<div className='grid grid-cols-1 gap-3 sm:grid-cols-3'>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>CPU</span>
<span>{cpu?.toFixed(1)}%</span>
</div>
<Progress value={cpu ?? 0} className='h-1.5' max={100} />
</div>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>{t('memory')}</span>
<span>{mem?.toFixed(1)}%</span>
</div>
<Progress value={mem ?? 0} className='h-1.5' max={100} />
</div>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>{t('disk')}</span>
<span>{disk?.toFixed(1)}%</span>
</div>
<Progress value={disk ?? 0} className='h-1.5' max={100} />
</div>
</div>
)}
</div>
{isOnline && onlineCount > 0 && (
<div>
<h3 className='mb-3 text-lg font-medium'>{t('onlineUsers')}</h3>
<div className='overflow-x-auto'>
<ProTable
header={{
hidden: true,
}}
columns={[
{
accessorKey: 'allIps',
header: t('ipAddresses'),
cell: ({ row }) => {
const ips = row.original.ips;
return (
<div className='flex min-w-0 flex-col gap-1'>
{ips.map((ip: string, index: number) => (
<div key={ip} className='whitespace-nowrap text-sm'>
{index === 0 ? (
<span className='font-medium'>{ip}</span>
) : (
<span className='text-muted-foreground'>{ip}</span>
)}
</div>
))}
</div>
);
},
},
{
accessorKey: 'user',
header: t('user'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='account' />
),
},
{
accessorKey: 'subscribeName',
header: t('subscribeName'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='subscribeName' />
),
},
{
accessorKey: 'subscribeId',
header: t('subscribeId'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='subscribeId' />
),
},
{
accessorKey: 'trafficUsage',
header: t('trafficUsage'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='trafficUsage' />
),
},
{
accessorKey: 'expireTime',
header: t('expireTime'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='expireTime' />
),
},
]}
request={async () => ({
list: onlineUsersData,
total: onlineUsersData.length,
})}
/>
</div>
</div>
)}
</div>
</SheetContent>
</Sheet>
);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,266 +0,0 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { IpLink } from '@/components/ip-link';
import { ProTable } from '@/components/pro-table';
import { getUserSubscribeById } from '@/services/admin/user';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { Progress } from '@workspace/ui/components/progress';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { formatBytes, formatDate } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
export function formatPercentage(value: number): string {
return `${value.toFixed(1)}%`;
}
// 统一的用户订阅信息组件
function UserSubscribeInfo({
userId,
type,
}: {
userId: number;
type: 'account' | 'subscribeName' | 'subscribeId' | 'trafficUsage' | 'expireTime';
}) {
const { data } = useQuery({
enabled: userId !== 0,
queryKey: ['getUserSubscribeById', userId],
queryFn: async () => {
const { data } = await getUserSubscribeById({ id: userId });
return data.data;
},
});
if (!data) return <span className='text-muted-foreground'>--</span>;
switch (type) {
case 'account':
if (!data.user_id) return <span className='text-muted-foreground'>--</span>;
return <UserDetail id={data.user_id} />;
case 'subscribeName':
if (!data.subscribe?.name) return <span className='text-muted-foreground'>--</span>;
return <span className='text-sm'>{data.subscribe.name}</span>;
case 'subscribeId':
if (!data.id) return <span className='text-muted-foreground'>--</span>;
return <span className='font-mono text-sm'>{data.id}</span>;
case 'trafficUsage': {
const usedTraffic = data.upload + data.download;
const totalTraffic = data.traffic || 0;
return (
<div className='min-w-0 text-sm'>
<div className='break-words'>
{formatBytes(usedTraffic)} / {totalTraffic > 0 ? formatBytes(totalTraffic) : '无限制'}
</div>
</div>
);
}
case 'expireTime': {
if (!data.expire_time) return <span className='text-muted-foreground'>--</span>;
const isExpired = data.expire_time < Date.now() / 1000;
return (
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2'>
<span className='text-sm'>{formatDate(data.expire_time)}</span>
{isExpired && (
<Badge variant='destructive' className='w-fit px-1 py-0 text-xs'>
</Badge>
)}
</div>
);
}
default:
return <span className='text-muted-foreground'>--</span>;
}
}
export function NodeStatusCell({ status, node }: { status: API.NodeStatus; node?: API.Server }) {
const t = useTranslations('server.node');
const [open, setOpen] = useState(false);
const { online, cpu, mem, disk, updated_at } = status || {
online: {},
cpu: 0,
mem: 0,
disk: 0,
updated_at: 0,
};
const isOnline = updated_at > 0;
const badgeVariant = isOnline ? 'default' : 'destructive';
const badgeText = isOnline ? t('normal') : t('abnormal');
const onlineCount = (online && Object.keys(online).length) || 0;
// 转换在线用户数据为ProTable需要的格式
const onlineUsersData = Object.entries(online || {}).map(([uid, ips]) => ({
uid,
ips: ips as string[],
primaryIp: ips[0] || '',
allIps: (ips as string[]).join(', '),
}));
return (
<>
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<button className='hover:text-foreground flex cursor-pointer items-center gap-2 border-none bg-transparent p-0 text-left text-sm transition-colors'>
<Badge variant={badgeVariant}>{badgeText}</Badge>
<span className='text-muted-foreground'>
{t('onlineCount')}: {onlineCount}
</span>
</button>
</SheetTrigger>
{node && (
<SheetContent className='h-screen w-screen max-w-none sm:h-auto sm:w-[800px] sm:max-w-[90vw]'>
<SheetHeader>
<SheetTitle>
{t('nodeDetail')} - {node.name}
</SheetTitle>
</SheetHeader>
<div className='-mx-6 h-[calc(100vh-48px-16px)] space-y-2 overflow-y-auto px-6 py-4 sm:h-[calc(100dvh-48px-16px-env(safe-area-inset-top))]'>
<h3 className='text-base font-medium'>{t('nodeStatus')}</h3>
<div className='space-y-3'>
<div className='flex w-full flex-col gap-2 text-sm sm:flex-row sm:items-center sm:gap-3'>
<Badge variant={isOnline ? 'default' : 'destructive'} className='w-fit text-xs'>
{isOnline ? t('normal') : t('abnormal')}
</Badge>
<span className='text-muted-foreground'>
{t('onlineCount')}: {onlineCount}
</span>
{isOnline && (
<span className='text-muted-foreground text-xs sm:text-sm'>
{t('lastUpdated')}: {formatDate(updated_at)}
</span>
)}
</div>
{isOnline && (
<div className='grid grid-cols-1 gap-3 sm:grid-cols-3'>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>CPU</span>
<span>{cpu?.toFixed(1)}%</span>
</div>
<Progress value={cpu ?? 0} className='h-1.5' max={100} />
</div>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>{t('memory')}</span>
<span>{mem?.toFixed(1)}%</span>
</div>
<Progress value={mem ?? 0} className='h-1.5' max={100} />
</div>
<div className='space-y-1'>
<div className='flex justify-between text-xs'>
<span>{t('disk')}</span>
<span>{disk?.toFixed(1)}%</span>
</div>
<Progress value={disk ?? 0} className='h-1.5' max={100} />
</div>
</div>
)}
</div>
{isOnline && onlineCount > 0 && (
<div>
<h3 className='mb-3 text-lg font-medium'>{t('onlineUsers')}</h3>
<div className='overflow-x-auto'>
<ProTable
header={{
hidden: true,
}}
columns={[
{
accessorKey: 'allIps',
header: t('ipAddresses'),
cell: ({ row }) => {
const ips = row.original.ips;
return (
<div className='flex min-w-0 flex-col gap-1'>
{ips.map((ip: string, index: number) => (
<div key={ip} className='whitespace-nowrap text-sm'>
{index === 0 ? (
<IpLink ip={ip} className='font-medium' />
) : (
<IpLink ip={ip} className='text-muted-foreground' />
)}
</div>
))}
</div>
);
},
},
{
accessorKey: 'user',
header: t('user'),
cell: ({ row }) => (
<UserSubscribeInfo userId={Number(row.original.uid)} type='account' />
),
},
{
accessorKey: 'subscribeName',
header: t('subscribeName'),
cell: ({ row }) => (
<UserSubscribeInfo
userId={Number(row.original.uid)}
type='subscribeName'
/>
),
},
{
accessorKey: 'subscribeId',
header: t('subscribeId'),
cell: ({ row }) => (
<UserSubscribeInfo
userId={Number(row.original.uid)}
type='subscribeId'
/>
),
},
{
accessorKey: 'trafficUsage',
header: t('trafficUsage'),
cell: ({ row }) => (
<UserSubscribeInfo
userId={Number(row.original.uid)}
type='trafficUsage'
/>
),
},
{
accessorKey: 'expireTime',
header: t('expireTime'),
cell: ({ row }) => (
<UserSubscribeInfo
userId={Number(row.original.uid)}
type='expireTime'
/>
),
},
]}
request={async () => ({
list: onlineUsersData,
total: onlineUsersData.length,
})}
/>
</div>
</div>
)}
</div>
</SheetContent>
)}
</Sheet>
</>
);
}

View File

@ -1,320 +0,0 @@
'use client';
import { Display } from '@/components/display';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
batchDeleteNode,
createNode,
deleteNode,
getNodeGroupList,
getNodeList,
nodeSort,
updateNode,
} from '@/services/admin/server';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@workspace/ui/components/tooltip';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { cn } from '@workspace/ui/lib/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import NodeForm from './node-form';
import { NodeStatusCell } from './node-status';
export default function NodeTable() {
const t = useTranslations('server.node');
const [loading, setLoading] = useState(false);
const { data: groups } = useQuery({
queryKey: ['getNodeGroupList'],
queryFn: async () => {
const { data } = await getNodeGroupList();
return (data.data?.list || []) as API.ServerGroup[];
},
});
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.Server, { groupId: number; search: string }>
action={ref}
header={{
toolbar: (
<NodeForm<API.CreateNodeRequest>
trigger={t('create')}
title={t('createNode')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createNode({ ...values, enable: false });
toast.success(t('createSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>
),
}}
columns={[
{
accessorKey: 'id',
header: t('id'),
cell: ({ row }) => (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<Badge
variant='outline'
className={cn('text-primary-foreground', {
'bg-green-500': row.original.protocol === 'shadowsocks',
'bg-rose-500': row.original.protocol === 'vmess',
'bg-blue-500': row.original.protocol === 'vless',
'bg-yellow-500': row.original.protocol === 'trojan',
'bg-purple-500': row.original.protocol === 'hysteria2',
'bg-cyan-500': row.original.protocol === 'tuic',
'bg-gray-500': row.original.protocol === 'anytls',
})}
>
{row.getValue('id')}
</Badge>
</TooltipTrigger>
<TooltipContent>{row.original.protocol}</TooltipContent>
</Tooltip>
</TooltipProvider>
),
},
{
accessorKey: 'enable',
header: t('enable'),
cell: ({ row }) => {
return (
<Switch
checked={row.getValue('enable')}
onCheckedChange={async (checked) => {
await updateNode({
...row.original,
id: row.original.id!,
enable: checked,
} as API.UpdateNodeRequest);
ref.current?.refresh();
}}
/>
);
},
},
{
accessorKey: 'name',
header: t('name'),
},
{
accessorKey: 'server_addr',
header: t('serverAddr'),
cell: ({ row }) => {
return (
<div className='flex gap-1'>
<Badge variant='outline'>
{row.original.country} - {row.original.city}
</Badge>
<Badge variant='outline'>{row.getValue('server_addr')}</Badge>
</div>
);
},
},
{
accessorKey: 'status',
header: t('status'),
cell: ({ row }) => {
return <NodeStatusCell status={row.original?.status} node={row.original} />;
},
},
{
accessorKey: 'speed_limit',
header: t('speedLimit'),
cell: ({ row }) => (
<Display type='trafficSpeed' value={row.getValue('speed_limit')} unlimited />
),
},
{
accessorKey: 'traffic_ratio',
header: t('trafficRatio'),
cell: ({ row }) => <Badge variant='outline'>{row.getValue('traffic_ratio')} X</Badge>,
},
{
accessorKey: 'group_id',
header: t('nodeGroup'),
cell: ({ row }) => {
const name = groups?.find((group) => group.id === row.getValue('group_id'))?.name;
return name ? <Badge variant='outline'>{name}</Badge> : t('noData');
},
},
{
accessorKey: 'tags',
header: t('tags'),
cell: ({ row }) => {
const tags = (row.getValue('tags') as string[]) || [];
return tags.length > 0 ? (
<div className='flex gap-1'>
{tags.map((tag) => (
<Badge key={tag} variant='outline'>
{tag}
</Badge>
))}
</div>
) : (
t('noData')
);
},
},
]}
params={[
{
key: 'group_id',
placeholder: t('nodeGroup'),
options: groups?.map((item) => ({
label: item.name,
value: String(item.id),
})),
},
{
key: 'search',
},
]}
request={async (pagination, filter) => {
const { data } = await getNodeList({
...pagination,
...filter,
});
return {
list: data.data?.list || [],
total: data.data?.total || 0,
};
}}
actions={{
render: (row) => [
<NodeForm<API.Server>
key='edit'
trigger={t('edit')}
title={t('editNode')}
loading={loading}
initialValues={row}
onSubmit={async (values) => {
setLoading(true);
try {
await updateNode({ ...row, ...values } as API.UpdateNodeRequest);
toast.success(t('updateSuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await deleteNode({
id: row.id,
});
toast.success(t('deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
<Button
key='copy'
variant='outline'
onClick={async () => {
setLoading(true);
try {
const { id, sort, enable, updated_at, created_at, status, ...params } = row;
await createNode({
...params,
enable: false,
} as API.CreateNodeRequest);
toast.success(t('copySuccess'));
ref.current?.refresh();
setLoading(false);
return true;
} catch (error) {
setLoading(false);
return false;
}
}}
>
{t('copy')}
</Button>,
],
batchRender(rows) {
return [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
title={t('confirmDelete')}
description={t('deleteWarning')}
onConfirm={async () => {
await batchDeleteNode({
ids: rows.map((item) => item.id),
});
toast.success(t('deleteSuccess'));
ref.current?.refresh();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
];
},
}}
onSort={async (source, target, items) => {
const sourceIndex = items.findIndex((item) => String(item.id) === source);
const targetIndex = items.findIndex((item) => String(item.id) === target);
const originalSorts = items.map((item) => item.sort);
const [movedItem] = items.splice(sourceIndex, 1);
items.splice(targetIndex, 0, movedItem!);
const updatedItems = items.map((item, index) => {
const originalSort = originalSorts[index];
const newSort = originalSort !== undefined ? originalSort : item.sort;
return { ...item, sort: newSort };
});
const changedItems = updatedItems.filter((item, index) => {
return item.sort !== items[index]?.sort;
});
if (changedItems.length > 0) {
nodeSort({
sort: changedItems.map((item) => ({ id: item.id, sort: item.sort })),
});
}
return updatedItems;
}}
/>
);
}

View File

@ -1,29 +0,0 @@
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import { getTranslations } from 'next-intl/server';
import GroupTable from './group-table';
import NodeConfig from './node-config';
import NodeTable from './node-table';
export default async function Page() {
const t = await getTranslations('server');
return (
<Tabs defaultValue='node'>
<TabsList>
<TabsTrigger value='node'>{t('tabs.node')}</TabsTrigger>
<TabsTrigger value='group'>{t('tabs.nodeGroup')}</TabsTrigger>
<TabsTrigger value='config'>{t('tabs.nodeConfig')}</TabsTrigger>
</TabsList>
<TabsContent value='node'>
<NodeTable />
</TabsContent>
<TabsContent value='group'>
<GroupTable />
</TabsContent>
<TabsContent value='config'>
<NodeConfig />
</TabsContent>
</Tabs>
);
}

View File

@ -0,0 +1,121 @@
'use client';
import { getNodeMultiplier, setNodeMultiplier } from '@/services/admin/system';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import { Card, CardContent } from '@workspace/ui/components/card';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
export default function DynamicMultiplier() {
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
const [timeSlots, setTimeSlots] = useState<API.TimePeriod[]>([]);
const { data: periodsResp, refetch: refetchPeriods } = useQuery({
queryKey: ['getNodeMultiplier'],
queryFn: async () => {
const { data } = await getNodeMultiplier();
return (data.data?.periods || []) as API.TimePeriod[];
},
enabled: open,
});
useEffect(() => {
if (periodsResp) {
setTimeSlots(periodsResp);
}
}, [periodsResp]);
async function savePeriods() {
await setNodeMultiplier({ periods: timeSlots });
await refetchPeriods();
toast.success(t('server_config.saveSuccess'));
setOpen(false);
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Card>
<CardContent className='p-4'>
<div className='flex cursor-pointer items-center justify-between'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:clock-time-eight' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('server_config.dynamic_multiplier')}</p>
<p className='text-muted-foreground truncate text-sm'>
{t('server_config.dynamic_multiplier_desc')}
</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</CardContent>
</Card>
</SheetTrigger>
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('server_config.dynamic_multiplier')}</SheetTitle>
<SheetDescription>{t('server_config.dynamic_multiplier_desc')}</SheetDescription>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-60px-env(safe-area-inset-top))] px-6'>
<div className='space-y-4 pt-4'>
<ArrayInput<API.TimePeriod>
fields={[
{
name: 'start_time',
prefix: t('server_config.fields.start_time'),
type: 'time',
step: '1',
},
{
name: 'end_time',
prefix: t('server_config.fields.end_time'),
type: 'time',
step: '1',
},
{
name: 'multiplier',
prefix: t('server_config.fields.multiplier'),
type: 'number',
placeholder: '0',
},
]}
value={timeSlots}
onChange={setTimeSlots}
/>
</div>
</ScrollArea>
<SheetFooter className='flex-row justify-between pt-3'>
<Button variant='outline' onClick={() => setTimeSlots(periodsResp || [])}>
{t('server_config.fields.reset')}
</Button>
<div className='flex gap-2'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('actions.cancel')}
</Button>
<Button onClick={savePeriods}>{t('actions.save')}</Button>
</div>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,102 @@
export const protocols = [
'shadowsocks',
'vmess',
'vless',
'trojan',
'hysteria',
'tuic',
'anytls',
'socks',
'naive',
'http',
'mieru',
] as const;
// Global label map for display; fallback to raw value if missing
export const LABELS = {
// transport
'tcp': 'TCP',
'udp': 'UDP',
'websocket': 'WebSocket',
'grpc': 'gRPC',
'mkcp': 'mKCP',
'httpupgrade': 'HTTP Upgrade',
'xhttp': 'XHTTP',
// security
'none': 'NONE',
'tls': 'TLS',
'reality': 'Reality',
// fingerprint
'chrome': 'Chrome',
'firefox': 'Firefox',
'safari': 'Safari',
'ios': 'IOS',
'android': 'Android',
'edge': 'edge',
'360': '360',
'qq': 'QQ',
// multiplex
'low': 'Low',
'middle': 'Middle',
'high': 'High',
} as const;
// Flat arrays for enum-like sets
export const SS_CIPHERS = [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305',
'2022-blake3-aes-128-gcm',
'2022-blake3-aes-256-gcm',
'2022-blake3-chacha20-poly1305',
] as const;
export const TRANSPORTS = {
vmess: ['tcp', 'websocket', 'grpc'] as const,
vless: ['tcp', 'websocket', 'grpc', 'mkcp', 'httpupgrade', 'xhttp'] as const,
trojan: ['tcp', 'websocket', 'grpc'] as const,
mieru: ['tcp', 'udp'] as const,
} as const;
export const SECURITY = {
shadowsocks: ['none', 'http', 'tls'] as const,
vmess: ['none', 'tls'] as const,
vless: ['none', 'tls', 'reality'] as const,
trojan: ['tls'] as const,
hysteria: ['tls'] as const,
tuic: ['tls'] as const,
anytls: ['tls'] as const,
naive: ['none', 'tls'] as const,
http: ['none', 'tls'] as const,
} as const;
export const FLOWS = {
vless: ['none', 'xtls-rprx-direct', 'xtls-rprx-splice', 'xtls-rprx-vision'] as const,
} as const;
export const TUIC_UDP_RELAY_MODES = ['native', 'quic'] as const;
export const TUIC_CONGESTION = ['bbr', 'cubic', 'new_reno'] as const;
export const XHTTP_MODES = ['auto', 'packet-up', 'stream-up', 'stream-one'] as const;
export const ENCRYPTION_TYPES = ['none', 'mlkem768x25519plus'] as const;
export const ENCRYPTION_MODES = ['native', 'xorpub', 'random'] as const;
export const ENCRYPTION_RTT = ['0rtt', '1rtt'] as const;
export const FINGERPRINTS = [
'chrome',
'firefox',
'safari',
'ios',
'android',
'edge',
'360',
'qq',
] as const;
export const CERT_MODES = ['none', 'http', 'dns', 'self'] as const;
export const multiplexLevels = ['none', 'low', 'middle', 'high'] as const;
export function getLabel(value: string): string {
const label = (LABELS as Record<string, string>)[value];
return label ?? value.toUpperCase();
}

View File

@ -0,0 +1,192 @@
import { XHTTP_MODES } from './constants';
import type { ProtocolType } from './types';
export function getProtocolDefaultConfig(proto: ProtocolType) {
switch (proto) {
case 'shadowsocks':
return {
type: 'shadowsocks',
enable: false,
port: null,
cipher: 'chacha20-ietf-poly1305',
server_key: null,
obfs: 'none',
obfs_host: null,
obfs_path: null,
sni: null,
allow_insecure: null,
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'vmess':
return {
type: 'vmess',
enable: false,
host: null,
port: null,
transport: 'tcp',
security: 'none',
path: null,
service_name: null,
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'vless':
return {
type: 'vless',
enable: false,
host: null,
port: null,
transport: 'tcp',
security: 'none',
flow: 'none',
path: null,
service_name: null,
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
reality_server_addr: null,
reality_server_port: null,
reality_private_key: null,
reality_public_key: null,
reality_short_id: null,
xhttp_mode: XHTTP_MODES[0], // 'auto'
xhttp_extra: null,
encryption: 'none',
encryption_mode: null,
encryption_rtt: null,
encryption_ticket: null,
encryption_server_padding: null,
encryption_private_key: null,
encryption_client_padding: null,
encryption_password: null,
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'trojan':
return {
type: 'trojan',
enable: false,
host: null,
port: null,
transport: 'tcp',
security: 'tls',
path: null,
service_name: null,
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'hysteria':
return {
type: 'hysteria',
enable: false,
port: null,
hop_ports: null,
hop_interval: null,
obfs: 'none',
obfs_password: null,
security: 'tls',
up_mbps: null,
down_mbps: null,
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'tuic':
return {
type: 'tuic',
enable: false,
port: null,
disable_sni: false,
reduce_rtt: false,
udp_relay_mode: 'native',
congestion_controller: 'bbr',
security: 'tls',
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'socks':
return {
type: 'socks',
enable: false,
port: null,
ratio: 1,
} as any;
case 'naive':
return {
type: 'naive',
enable: false,
port: null,
security: 'none',
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'http':
return {
type: 'http',
enable: false,
port: null,
security: 'none',
sni: null,
allow_insecure: null,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
case 'mieru':
return {
type: 'mieru',
enable: false,
port: null,
multiplex: 'none',
transport: 'tcp',
} as any;
case 'anytls':
return {
type: 'anytls',
enable: false,
port: null,
security: 'tls',
padding_scheme: null,
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
cert_mode: 'none',
cert_dns_provider: null,
cert_dns_env: null,
ratio: 1,
} as any;
default:
return {} as any;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
// Re-export all constants
export {
ENCRYPTION_MODES,
ENCRYPTION_RTT,
ENCRYPTION_TYPES,
FINGERPRINTS,
FLOWS,
LABELS,
SECURITY,
SS_CIPHERS,
TRANSPORTS,
TUIC_CONGESTION,
TUIC_UDP_RELAY_MODES,
XHTTP_MODES,
getLabel,
multiplexLevels,
protocols,
} from './constants';
// Re-export all types
export type { FieldConfig, ProtocolType } from './types';
// Re-export all schemas
export { formSchema, protocolApiScheme } from './schemas';
// Re-export defaults
export { getProtocolDefaultConfig } from './defaults';
// Re-export fields
export { PROTOCOL_FIELDS } from './fields';

View File

@ -0,0 +1,225 @@
import { z } from 'zod';
import {
CERT_MODES,
ENCRYPTION_MODES,
ENCRYPTION_RTT,
ENCRYPTION_TYPES,
FLOWS,
multiplexLevels,
SECURITY,
SS_CIPHERS,
TRANSPORTS,
TUIC_CONGESTION,
TUIC_UDP_RELAY_MODES,
XHTTP_MODES,
} from './constants';
const nullableString = z.string().nullish();
const nullableBool = z.boolean().nullish();
const nullablePort = z.number().int().min(0).max(65535).nullish();
const nullableRatio = z.number().min(0).nullish();
const ss = z.object({
ratio: nullableRatio,
type: z.literal('shadowsocks'),
enable: nullableBool,
port: nullablePort,
cipher: z.enum(SS_CIPHERS).nullish(),
server_key: nullableString,
obfs: z.enum(['none', 'http', 'tls'] as const).nullish(),
obfs_host: nullableString,
obfs_path: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const vmess = z.object({
ratio: nullableRatio,
type: z.literal('vmess'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vmess).nullish(),
security: z.enum(SECURITY.vmess).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const vless = z.object({
ratio: nullableRatio,
type: z.literal('vless'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vless).nullish(),
security: z.enum(SECURITY.vless).nullish(),
path: nullableString,
service_name: nullableString,
flow: z.enum(FLOWS.vless).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
reality_server_addr: nullableString,
reality_server_port: nullablePort,
reality_private_key: nullableString,
reality_public_key: nullableString,
reality_short_id: nullableString,
xhttp_mode: z.enum(XHTTP_MODES).nullish(),
xhttp_extra: nullableString,
encryption: z.enum(ENCRYPTION_TYPES).nullish(),
encryption_mode: z.enum(ENCRYPTION_MODES).nullish(),
encryption_rtt: z.enum(ENCRYPTION_RTT).nullish(),
encryption_ticket: nullableString,
encryption_server_padding: nullableString,
encryption_private_key: nullableString,
encryption_client_padding: nullableString,
encryption_password: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const trojan = z.object({
ratio: nullableRatio,
type: z.literal('trojan'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.trojan).nullish(),
security: z.enum(SECURITY.trojan).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const hysteria = z.object({
ratio: nullableRatio,
type: z.literal('hysteria'),
enable: nullableBool,
hop_ports: nullableString,
hop_interval: z.number().nullish(),
obfs_password: nullableString,
obfs: z.enum(['none', 'salamander'] as const).nullish(),
port: nullablePort,
security: z.enum(SECURITY.hysteria).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
up_mbps: z.number().nullish(),
down_mbps: z.number().nullish(),
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const tuic = z.object({
ratio: nullableRatio,
type: z.literal('tuic'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
disable_sni: z.boolean().nullish(),
reduce_rtt: z.boolean().nullish(),
udp_relay_mode: z.enum(TUIC_UDP_RELAY_MODES).nullish(),
congestion_controller: z.enum(TUIC_CONGESTION).nullish(),
security: z.enum(SECURITY.tuic).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const anytls = z.object({
ratio: nullableRatio,
type: z.literal('anytls'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.anytls).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
padding_scheme: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const socks = z.object({
ratio: nullableRatio,
type: z.literal('socks'),
enable: nullableBool,
port: nullablePort,
});
const naive = z.object({
ratio: nullableRatio,
type: z.literal('naive'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.naive).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const http = z.object({
ratio: nullableRatio,
type: z.literal('http'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.http).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
cert_mode: z.enum(CERT_MODES).nullish(),
cert_dns_provider: nullableString,
cert_dns_env: nullableString,
});
const mieru = z.object({
ratio: nullableRatio,
type: z.literal('mieru'),
enable: nullableBool,
port: nullablePort,
multiplex: z.enum(multiplexLevels).nullish(),
transport: z.enum(TRANSPORTS.mieru).nullish(),
});
export const protocolApiScheme = z.discriminatedUnion('type', [
ss,
vmess,
vless,
trojan,
hysteria,
tuic,
anytls,
socks,
naive,
http,
mieru,
]);
export const formSchema = z.object({
name: z.string().min(1),
address: z.string().min(1),
country: z.string().optional(),
city: z.string().optional(),
protocols: z.array(protocolApiScheme),
});

View File

@ -0,0 +1,27 @@
import { protocols } from './constants';
export type FieldConfig = {
name: string;
type: 'input' | 'select' | 'switch' | 'number' | 'textarea';
label: string;
placeholder?: string | ((t: (key: string) => string, protocol: any) => string);
options?: readonly string[];
defaultValue?: any;
min?: number;
max?: number;
step?: number;
suffix?: string;
generate?: {
function?: () => Promise<string | Record<string, string>> | string | Record<string, string>;
functions?: {
label: string | ((t: (key: string) => string, protocol: any) => string);
function: () => Promise<string | Record<string, string>> | string | Record<string, string>;
}[];
updateFields?: Record<string, string>;
};
condition?: (protocol: any, values: any) => boolean;
group?: 'basic' | 'transport' | 'security' | 'reality' | 'obfs' | 'encryption';
gridSpan?: 1 | 2;
};
export type ProtocolType = (typeof protocols)[number];

View File

@ -0,0 +1,4 @@
export { generateMLKEM768KeyPair } from './mlkem768';
export { generateRealityShortId } from './short-id';
export { generatePassword } from './uid';
export { generateRealityKeyPair } from './x25519';

View File

@ -0,0 +1,16 @@
import mlkem from 'mlkem-wasm';
import { toB64Url } from './util';
export async function generateMLKEM768KeyPair() {
const mlkemKeyPair = await mlkem.generateKey({ name: 'ML-KEM-768' }, true, [
'encapsulateBits',
'decapsulateBits',
]);
const mlkemPublicKeyRaw = await mlkem.exportKey('raw-public', mlkemKeyPair.publicKey);
const mlkemPrivateKeyRaw = await mlkem.exportKey('raw-seed', mlkemKeyPair.privateKey);
return {
publicKey: toB64Url(new Uint8Array(mlkemPublicKeyRaw)),
privateKey: toB64Url(new Uint8Array(mlkemPrivateKeyRaw)),
};
}

View File

@ -0,0 +1,15 @@
/**
* Generate a short ID for Reality
* @returns A random hexadecimal string of length 2, 4, 6, 8, 10, 12, 14, or 16
*/
export function generateRealityShortId() {
const hex = '0123456789abcdef';
const lengths = [2, 4, 6, 8, 10, 12, 14, 16];
const idx = Math.floor(Math.random() * lengths.length);
const len = lengths[idx] ?? 16;
let out = '';
for (let i = 0; i < len; i++) {
out += hex.charAt(Math.floor(Math.random() * hex.length));
}
return out;
}

View File

@ -0,0 +1,11 @@
import { uid } from 'radash';
/**
* Generate a random password
* @param length Length of the password
* @param charset Character set to use (defaults to alphanumeric)
* @returns Randomly generated password
*/
export function generatePassword(length = 16, charset?: string) {
return uid(length, charset).toLowerCase();
}

View File

@ -0,0 +1,6 @@
export function toB64Url(bytes: Uint8Array) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}

View File

@ -0,0 +1,11 @@
import { x25519 } from '@noble/curves/ed25519.js';
import { toB64Url } from './util';
/**
* Generate a Reality key pair
* @returns An object containing the private and public keys in base64url format
*/
export function generateRealityKeyPair() {
const { secretKey, publicKey } = x25519.keygen();
return { privateKey: toB64Url(secretKey), publicKey: toB64Url(publicKey) };
}

View File

@ -0,0 +1,189 @@
'use client';
import { UserDetail } from '@/app/dashboard/user/user-detail';
import { IpLink } from '@/components/ip-link';
import { ProTable } from '@/components/pro-table';
import { getUserSubscribeById } from '@/services/admin/user';
import { formatDate } from '@/utils/common';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { formatBytes } from '@workspace/ui/utils';
import { Users } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
function UserSubscribeInfo({
subscribeId,
open,
type,
}: {
subscribeId: number;
open: boolean;
type: 'account' | 'subscribeName' | 'subscribeId' | 'trafficUsage' | 'expireTime';
}) {
const t = useTranslations('servers');
const { data } = useQuery({
enabled: subscribeId !== 0 && open,
queryKey: ['getUserSubscribeById', subscribeId],
queryFn: async () => {
const { data } = await getUserSubscribeById({ id: subscribeId });
return data.data;
},
});
if (!data) return <span className='text-muted-foreground'>--</span>;
switch (type) {
case 'account':
if (!data.user_id) return <span className='text-muted-foreground'>--</span>;
return <UserDetail id={data.user_id} />;
case 'subscribeName':
if (!data.subscribe?.name) return <span className='text-muted-foreground'>--</span>;
return <span className='text-sm'>{data.subscribe.name}</span>;
case 'subscribeId':
if (!data.id) return <span className='text-muted-foreground'>--</span>;
return <span className='font-mono text-sm'>{data.id}</span>;
case 'trafficUsage': {
const usedTraffic = data.upload + data.download;
const totalTraffic = data.traffic || 0;
return (
<div className='min-w-0 text-sm'>
<div className='break-words'>
{formatBytes(usedTraffic)} / {totalTraffic > 0 ? formatBytes(totalTraffic) : '无限制'}
</div>
</div>
);
}
case 'expireTime': {
if (!data.expire_time) return <span className='text-muted-foreground'>--</span>;
const isExpired = data.expire_time < Date.now() / 1000;
return (
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2'>
<span className='text-sm'>{formatDate(data.expire_time)}</span>
{isExpired && (
<Badge variant='destructive' className='w-fit px-1 py-0 text-xs'>
{t('expired')}
</Badge>
)}
</div>
);
}
default:
return <span className='text-muted-foreground'>--</span>;
}
}
export default function OnlineUsersCell({ status }: { status?: API.ServerStatus }) {
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<button className='hover:text-foreground text-muted-foreground flex items-center gap-2 bg-transparent p-0 text-sm'>
<Users className='h-4 w-4' /> {status?.online.length}
</button>
</SheetTrigger>
<SheetContent className='h-screen w-screen max-w-none sm:h-auto sm:w-[900px] sm:max-w-[90vw]'>
<SheetHeader>
<SheetTitle>{t('onlineUsers')}</SheetTitle>
</SheetHeader>
<div className='-mx-6 h-[calc(100vh-48px-16px)] overflow-y-auto px-6 py-4 sm:h-[calc(100dvh-48px-16px-env(safe-area-inset-top))]'>
<ProTable<API.ServerOnlineUser, Record<string, unknown>>
header={{ hidden: true }}
columns={[
{
accessorKey: 'ip',
header: t('ipAddresses'),
cell: ({ row }) => {
const ips = row.original.ip;
return (
<div className='flex min-w-0 flex-col gap-1'>
{ips.map((item, i) => (
<div className='whitespace-nowrap text-sm' key={i}>
<Badge>{item.protocol}</Badge>
<IpLink ip={item.ip} className='ml-1 font-medium' />
</div>
))}
</div>
);
},
},
{
accessorKey: 'user',
header: t('user'),
cell: ({ row }) => (
<UserSubscribeInfo
subscribeId={Number(row.original.subscribe_id)}
open={open}
type='account'
/>
),
},
{
accessorKey: 'subscription',
header: t('subscription'),
cell: ({ row }) => (
<UserSubscribeInfo
subscribeId={Number(row.original.subscribe_id)}
open={open}
type='subscribeName'
/>
),
},
{
accessorKey: 'subscribeId',
header: t('subscribeId'),
cell: ({ row }) => (
<UserSubscribeInfo
subscribeId={Number(row.original.subscribe_id)}
open={open}
type='subscribeId'
/>
),
},
{
accessorKey: 'traffic',
header: t('traffic'),
cell: ({ row }) => (
<UserSubscribeInfo
subscribeId={Number(row.original.subscribe_id)}
open={open}
type='trafficUsage'
/>
),
},
{
accessorKey: 'expireTime',
header: t('expireTime'),
cell: ({ row }) => (
<UserSubscribeInfo
subscribeId={Number(row.original.subscribe_id)}
open={open}
type='expireTime'
/>
),
},
]}
request={async () => ({
list: status?.online || [],
total: status?.online?.length || 0,
})}
/>
</div>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,327 @@
'use client';
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
createServer,
deleteServer,
filterServerList,
resetSortWithServer,
updateServer,
} from '@/services/admin/server';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { ConfirmButton } from '@workspace/ui/custom-components/confirm-button';
import { cn } from '@workspace/ui/lib/utils';
import { useTranslations } from 'next-intl';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import DynamicMultiplier from './dynamic-multiplier';
import OnlineUsersCell from './online-users-cell';
import ServerConfig from './server-config';
import ServerForm from './server-form';
import ServerInstall from './server-install';
function PctBar({ value }: { value: number }) {
const v = value.toFixed(2);
return (
<div className='min-w-24'>
<div className='text-xs leading-none'>{v}%</div>
<div className='bg-muted h-1.5 w-full rounded'>
<div className='bg-primary h-1.5 rounded' style={{ width: `${v}%` }} />
</div>
</div>
);
}
function RegionIpCell({
country,
city,
ip,
t,
}: {
country?: string;
city?: string;
ip?: string;
t: (key: string) => string;
}) {
const region = [country, city].filter(Boolean).join(' / ') || t('notAvailable');
return (
<div className='flex items-center gap-1'>
<Badge variant='outline'>{region}</Badge>
<Badge variant='secondary'>{ip || t('notAvailable')}</Badge>
</div>
);
}
export default function ServersPage() {
const t = useTranslations('servers');
const { isServerReferencedByNodes } = useNode();
const { fetchServers } = useServer();
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
return (
<div className='space-y-4'>
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
<DynamicMultiplier />
<ServerConfig />
</div>
<ProTable<API.Server, { search: string }>
action={ref}
header={{
title: t('pageTitle'),
toolbar: (
<div className='flex gap-2'>
<ServerForm
trigger={t('create')}
title={t('drawerCreateTitle')}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
await createServer(values as unknown as API.CreateServerRequest);
toast.success(t('created'));
ref.current?.refresh();
fetchServers();
setLoading(false);
return true;
} catch (e) {
setLoading(false);
return false;
}
}}
/>
</div>
),
}}
columns={[
{
accessorKey: 'id',
header: t('id'),
cell: ({ row }) => <Badge>{row.getValue('id')}</Badge>,
},
{ accessorKey: 'name', header: t('name') },
{
id: 'region_ip',
header: t('address'),
cell: ({ row }) => (
<RegionIpCell
country={row.original.country as unknown as string}
city={row.original.city as unknown as string}
ip={row.original.address as unknown as string}
t={t}
/>
),
},
{
accessorKey: 'protocols',
header: t('protocols'),
cell: ({ row }) => {
const list = row.original.protocols.filter((p) => p.enable) as API.Protocol[];
if (!list.length) return '—';
return (
<div className='flex flex-col gap-1'>
{list.map((p, idx) => {
const ratio = Number(p.ratio ?? 1) || 1;
return (
<div key={idx} className='flex items-center gap-2'>
<Badge variant='outline'>{ratio.toFixed(2)}x</Badge>
<Badge variant='secondary'>{p.type}</Badge>
<Badge variant='secondary'>{p.port}</Badge>
</div>
);
})}
</div>
);
},
},
{
id: 'status',
header: t('status'),
cell: ({ row }) => {
const offline = row.original.status.status === 'offline';
return (
<div className='flex items-center gap-2'>
<span
className={cn(
'inline-block h-2.5 w-2.5 rounded-full',
offline ? 'bg-zinc-400' : 'bg-emerald-500',
)}
/>
<span className='text-sm'>{offline ? t('offline') : t('online')}</span>
</div>
);
},
},
{
id: 'cpu',
header: t('cpu'),
cell: ({ row }) => (
<PctBar value={(row.original.status?.cpu as unknown as number) ?? 0} />
),
},
{
id: 'mem',
header: t('memory'),
cell: ({ row }) => (
<PctBar value={(row.original.status?.mem as unknown as number) ?? 0} />
),
},
{
id: 'disk',
header: t('disk'),
cell: ({ row }) => (
<PctBar value={(row.original.status?.disk as unknown as number) ?? 0} />
),
},
{
id: 'online_users',
header: t('onlineUsers'),
cell: ({ row }) => <OnlineUsersCell status={row.original.status as API.ServerStatus} />,
},
// traffic ratio moved to per-protocol configs; column removed
]}
params={[{ key: 'search' }]}
request={async (pagination, filter) => {
const { data } = await filterServerList({
page: pagination.page,
size: pagination.size,
search: filter?.search || undefined,
});
const list = (data?.data?.list || []) as API.Server[];
const total = (data?.data?.total ?? list.length) as number;
return { list, total };
}}
actions={{
render: (row) => [
<ServerForm
key='edit'
trigger={t('edit')}
title={t('drawerEditTitle')}
initialValues={row}
loading={loading}
onSubmit={async (values) => {
setLoading(true);
try {
// ServerForm already returns API-shaped body; add id for update
await updateServer({
id: row.id,
...(values as unknown as Omit<API.UpdateServerRequest, 'id'>),
});
toast.success(t('updated'));
ref.current?.refresh();
fetchServers();
setLoading(false);
return true;
} catch (e) {
setLoading(false);
return false;
}
}}
/>,
<ServerInstall key='install' server={row} />,
<ConfirmButton
key='delete'
trigger={
<Button variant='destructive' disabled={isServerReferencedByNodes(row.id)}>
{t('delete')}
</Button>
}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await deleteServer({ id: row.id } as any);
toast.success(t('deleted'));
ref.current?.refresh();
fetchServers();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
<Button
key='copy'
variant='outline'
onClick={async () => {
setLoading(true);
const { id, created_at, updated_at, last_reported_at, status, ...others } =
row as any;
const body: API.CreateServerRequest = {
name: others.name,
country: others.country,
city: others.city,
address: others.address,
protocols: others.protocols || [],
};
await createServer(body);
toast.success(t('copied'));
ref.current?.refresh();
fetchServers();
setLoading(false);
}}
>
{t('copy')}
</Button>,
],
batchRender(rows) {
const hasReferencedServers = rows.some((row) => isServerReferencedByNodes(row.id));
return [
<ConfirmButton
key='delete'
trigger={
<Button variant='destructive' disabled={hasReferencedServers}>
{t('delete')}
</Button>
}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await Promise.all(rows.map((r) => deleteServer({ id: r.id })));
toast.success(t('deleted'));
ref.current?.refresh();
fetchServers();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
/>,
];
},
}}
onSort={async (source, target, items) => {
const sourceIndex = items.findIndex((item) => String(item.id) === source);
const targetIndex = items.findIndex((item) => String(item.id) === target);
const originalSorts = items.map((item) => item.sort);
const [movedItem] = items.splice(sourceIndex, 1);
items.splice(targetIndex, 0, movedItem!);
const updatedItems = items.map((item, index) => {
const originalSort = originalSorts[index];
const newSort = originalSort !== undefined ? originalSort : item.sort;
return { ...item, sort: newSort };
});
const changedItems = updatedItems.filter((item, index) => {
return item.sort !== items[index]?.sort;
});
if (changedItems.length > 0) {
resetSortWithServer({
sort: changedItems.map((item) => ({
id: item.id,
sort: item.sort,
})) as API.SortItem[],
});
toast.success(t('sorted_success'));
}
return updatedItems;
}}
/>
</div>
);
}

View File

@ -0,0 +1,510 @@
'use client';
import { getNodeConfig, updateNodeConfig } from '@/services/admin/system';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import { Card, CardContent } from '@workspace/ui/components/card';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@workspace/ui/components/tabs';
import { Textarea } from '@workspace/ui/components/textarea';
import { ArrayInput } from '@workspace/ui/custom-components/dynamic-Inputs';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { unitConversion } from '@workspace/ui/utils';
import { DicesIcon } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { uid } from 'radash';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { SS_CIPHERS } from './form-schema';
const dnsConfigSchema = z.object({
proto: z.string(), // z.enum(['tcp', 'udp', 'tls', 'https', 'quic']),
address: z.string(),
domains: z.array(z.string()),
});
const outboundConfigSchema = z.object({
name: z.string(),
protocol: z.string(),
address: z.string(),
port: z.number(),
cipher: z.string().optional(),
password: z.string().optional(),
rules: z.array(z.string()).optional(),
});
const nodeConfigSchema = z.object({
node_secret: z.string().optional(),
node_pull_interval: z.number().optional(),
node_push_interval: z.number().optional(),
traffic_report_threshold: z.number().optional(),
ip_strategy: z.enum(['prefer_ipv4', 'prefer_ipv6']).optional(),
dns: z.array(dnsConfigSchema).optional(),
block: z.array(z.string()).optional(),
outbound: z.array(outboundConfigSchema).optional(),
});
type NodeConfigFormData = z.infer<typeof nodeConfigSchema>;
export default function ServerConfig() {
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const { data: cfgResp, refetch: refetchCfg } = useQuery({
queryKey: ['getNodeConfig'],
queryFn: async () => {
const { data } = await getNodeConfig();
return data.data as API.NodeConfig | undefined;
},
enabled: open,
});
const form = useForm<NodeConfigFormData>({
resolver: zodResolver(nodeConfigSchema),
defaultValues: {
node_secret: '',
node_pull_interval: undefined,
node_push_interval: undefined,
traffic_report_threshold: undefined,
ip_strategy: 'prefer_ipv4',
dns: [],
block: [],
outbound: [],
},
});
useEffect(() => {
if (cfgResp) {
form.reset({
node_secret: cfgResp.node_secret ?? '',
node_pull_interval: cfgResp.node_pull_interval as number | undefined,
node_push_interval: cfgResp.node_push_interval as number | undefined,
traffic_report_threshold: cfgResp.traffic_report_threshold as number | undefined,
ip_strategy:
(cfgResp.ip_strategy as 'prefer_ipv4' | 'prefer_ipv6' | undefined) || 'prefer_ipv4',
dns: cfgResp.dns || [],
block: cfgResp.block || [],
outbound: cfgResp.outbound || [],
});
}
}, [cfgResp, form]);
async function onSubmit(values: NodeConfigFormData) {
setSaving(true);
try {
await updateNodeConfig(values as API.NodeConfig);
toast.success(t('server_config.saveSuccess'));
await refetchCfg();
setOpen(false);
} finally {
setSaving(false);
}
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Card>
<CardContent className='p-4'>
<div className='flex cursor-pointer items-center justify-between'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:resistor-nodes' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('server_config.title')}</p>
<p className='text-muted-foreground truncate text-sm'>
{t('server_config.description')}
</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</CardContent>
</Card>
</SheetTrigger>
<SheetContent className='w-[720px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('server_config.title')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
<Tabs defaultValue='basic' className='pt-4'>
<TabsList className='grid w-full grid-cols-4'>
<TabsTrigger value='basic'>{t('server_config.tabs.basic')}</TabsTrigger>
<TabsTrigger value='dns'>{t('server_config.tabs.dns')}</TabsTrigger>
<TabsTrigger value='outbound'>{t('server_config.tabs.outbound')}</TabsTrigger>
<TabsTrigger value='block'>{t('server_config.tabs.block')}</TabsTrigger>
</TabsList>
<Form {...form}>
<form id='server-config-form' onSubmit={form.handleSubmit(onSubmit)} className='mt-4'>
<TabsContent value='basic' className='space-y-4'>
<FormField
control={form.control}
name='node_secret'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.communication_key')}</FormLabel>
<FormControl>
<EnhancedInput
placeholder={t('server_config.fields.communication_key_placeholder')}
value={field.value || ''}
onValueChange={field.onChange}
suffix={
<div className='bg-muted flex h-9 items-center px-3'>
<DicesIcon
onClick={() => {
const id = uid(32).toLowerCase();
const formatted = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;
form.setValue('node_secret', formatted);
}}
className='cursor-pointer'
/>
</div>
}
/>
</FormControl>
<FormDescription>
{t('server_config.fields.communication_key_desc')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='node_pull_interval'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.node_pull_interval')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
min={0}
suffix='S'
value={field.value as any}
onValueChange={field.onChange}
placeholder={t('server_config.fields.communication_key_placeholder')}
/>
</FormControl>
<FormDescription>
{t('server_config.fields.node_pull_interval_desc')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='node_push_interval'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.node_push_interval')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
min={0}
suffix='S'
step={0.1}
value={field.value as any}
onValueChange={field.onChange}
placeholder={t('server_config.fields.communication_key_placeholder')}
/>
</FormControl>
<FormDescription>
{t('server_config.fields.node_push_interval_desc')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='traffic_report_threshold'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.traffic_report_threshold')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
min={0}
suffix='MB'
value={unitConversion('bitsToMb', field.value as number | undefined)}
onValueChange={(value) => {
field.onChange(unitConversion('mbToBits', value));
}}
placeholder='1'
/>
</FormControl>
<FormDescription>
{t('server_config.fields.traffic_report_threshold_desc')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
<TabsContent value='dns' className='space-y-4'>
<FormField
control={form.control}
name='ip_strategy'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.ip_strategy')}</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue
placeholder={t('server_config.fields.ip_strategy_placeholder')}
/>
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value='prefer_ipv4'>
{t('server_config.fields.ip_strategy_ipv4')}
</SelectItem>
<SelectItem value='prefer_ipv6'>
{t('server_config.fields.ip_strategy_ipv6')}
</SelectItem>
</SelectContent>
</Select>
<FormDescription>
{t('server_config.fields.ip_strategy_desc')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='dns'
render={({ field }) => (
<FormItem>
<FormLabel>{t('server_config.fields.dns_config')}</FormLabel>
<FormControl>
<ArrayInput
className='grid grid-cols-2 gap-2'
fields={[
{
name: 'proto',
type: 'select',
placeholder: t('server_config.fields.dns_proto_placeholder'),
options: [
{ label: 'TCP', value: 'tcp' },
{ label: 'UDP', value: 'udp' },
{ label: 'TLS', value: 'tls' },
{ label: 'HTTPS', value: 'https' },
{ label: 'QUIC', value: 'quic' },
],
},
{ name: 'address', type: 'text', placeholder: '8.8.8.8:53' },
{
name: 'domains',
type: 'textarea',
className: 'col-span-2',
placeholder: t('server_config.fields.dns_domains_placeholder'),
},
]}
value={(field.value || []).map((item) => ({
...item,
domains: Array.isArray(item.domains) ? item.domains.join('\n') : '',
}))}
onChange={(values) => {
const converted = values.map((item: any) => ({
proto: item.proto,
address: item.address,
domains:
typeof item.domains === 'string'
? item.domains.split('\n').map((d: string) => d.trim())
: item.domains || [],
}));
field.onChange(converted);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
<TabsContent value='outbound' className='space-y-4'>
<FormField
control={form.control}
name='outbound'
render={({ field }) => {
return (
<FormItem>
<FormControl>
<ArrayInput
className='grid grid-cols-2 gap-2'
fields={[
{
name: 'name',
type: 'text',
className: 'col-span-2',
placeholder: t('server_config.fields.outbound_name_placeholder'),
},
{
name: 'protocol',
type: 'select',
placeholder: t(
'server_config.fields.outbound_protocol_placeholder',
),
options: [
{ label: 'HTTP', value: 'http' },
{ label: 'SOCKS', value: 'socks' },
{ label: 'Shadowsocks', value: 'shadowsocks' },
{ label: 'Brook', value: 'brook' },
{ label: 'Snell', value: 'snell' },
{ label: 'VMess', value: 'vmess' },
{ label: 'VLESS', value: 'vless' },
{ label: 'Trojan', value: 'trojan' },
{ label: 'WireGuard', value: 'wireguard' },
{ label: 'Hysteria', value: 'hysteria' },
{ label: 'TUIC', value: 'tuic' },
{ label: 'AnyTLS', value: 'anytls' },
{ label: 'Naive', value: 'naive' },
{ label: 'Direct', value: 'direct' },
{ label: 'Reject', value: 'reject' },
],
},
{
name: 'cipher',
type: 'select',
options: SS_CIPHERS.map((cipher) => ({
label: cipher,
value: cipher,
})),
visible: (item: Record<string, any>) =>
item.protocol === 'shadowsocks',
},
{
name: 'address',
type: 'text',
placeholder: t(
'server_config.fields.outbound_address_placeholder',
),
},
{
name: 'port',
type: 'number',
placeholder: t('server_config.fields.outbound_port_placeholder'),
},
{
name: 'password',
type: 'text',
placeholder: t(
'server_config.fields.outbound_password_placeholder',
),
},
{
name: 'rules',
type: 'textarea',
className: 'col-span-2',
placeholder: t('server_config.fields.outbound_rules_placeholder'),
},
]}
value={(field.value || []).map((item) => ({
...item,
rules: Array.isArray(item.rules) ? item.rules.join('\n') : '',
}))}
onChange={(values) => {
const converted = values.map((item: any) => ({
name: item.name,
protocol: item.protocol,
address: item.address,
port: item.port,
cipher: item.cipher,
password: item.password,
rules:
typeof item.rules === 'string'
? item.rules.split('\n').map((r: string) => r.trim())
: item.rules || [],
}));
field.onChange(converted);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
);
}}
/>
</TabsContent>
<TabsContent value='block' className='space-y-4'>
<FormField
control={form.control}
name='block'
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder={t('server_config.fields.block_rules_placeholder')}
value={(field.value || []).join('\n')}
onChange={(e) => {
const lines = e.target.value.split('\n').map((line) => line.trim());
field.onChange(lines);
}}
rows={10}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TabsContent>
</form>
</Form>
</Tabs>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' disabled={saving} onClick={() => setOpen(false)}>
{t('actions.cancel')}
</Button>
<Button disabled={saving} type='submit' form='server-config-form'>
<Icon icon='mdi:loading' className={saving ? 'mr-2 animate-spin' : 'hidden'} />
{t('actions.save')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,661 @@
'use client';
import { useNode } from '@/store/node';
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 {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@workspace/ui/components/dropdown-menu';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import {
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { Switch } from '@workspace/ui/components/switch';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { cn } from '@workspace/ui/lib/utils';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import {
FieldConfig,
formSchema,
getLabel,
getProtocolDefaultConfig,
PROTOCOL_FIELDS,
protocols as PROTOCOLS,
} from './form-schema';
function DynamicField({
field,
control,
form,
protocolIndex,
protocolData,
t,
}: {
field: FieldConfig;
control: any;
form: any;
protocolIndex: number;
protocolData: any;
t: (key: string) => string;
}) {
const fieldName = `protocols.${protocolIndex}.${field.name}` as const;
if (field.condition && !field.condition(protocolData, {})) {
return null;
}
const commonProps = {
control,
name: fieldName,
};
switch (field.type) {
case 'input':
return (
<FormField
{...commonProps}
render={({ field: fieldProps }) => (
<FormItem>
<FormLabel>{t(field.label)}</FormLabel>
<FormControl>
<EnhancedInput
{...fieldProps}
type='text'
placeholder={
field.placeholder
? typeof field.placeholder === 'function'
? field.placeholder(t, protocolData)
: field.placeholder
: undefined
}
onValueChange={(v) => fieldProps.onChange(v)}
suffix={
field.generate ? (
field.generate.functions && field.generate.functions.length > 0 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type='button' variant='ghost' size='sm'>
<Icon icon='mdi:key' className='h-4 w-4' />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align='end'>
{field.generate.functions.map((genFunc, idx) => (
<DropdownMenuItem
key={idx}
onClick={async () => {
const result = await genFunc.function();
if (typeof result === 'string') {
fieldProps.onChange(result);
} else if (field.generate!.updateFields) {
Object.entries(field.generate!.updateFields).forEach(
([fieldName, resultKey]) => {
const fullFieldName = `protocols.${protocolIndex}.${fieldName}`;
form.setValue(fullFieldName, (result as any)[resultKey]);
},
);
} else {
if (result.privateKey) {
fieldProps.onChange(result.privateKey);
}
}
}}
>
{typeof genFunc.label === 'function'
? genFunc.label(t, protocolData)
: genFunc.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : field.generate.function ? (
<Button
type='button'
variant='ghost'
size='sm'
onClick={async () => {
const result = await field.generate!.function!();
if (typeof result === 'string') {
fieldProps.onChange(result);
} else if (field.generate!.updateFields) {
Object.entries(field.generate!.updateFields).forEach(
([fieldName, resultKey]) => {
const fullFieldName = `protocols.${protocolIndex}.${fieldName}`;
form.setValue(fullFieldName, (result as any)[resultKey]);
},
);
} else {
if (result.privateKey) {
fieldProps.onChange(result.privateKey);
}
}
}}
>
<Icon icon='mdi:key' className='h-4 w-4' />
</Button>
) : null
) : (
field.suffix
)
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
);
case 'number':
return (
<FormField
{...commonProps}
render={({ field: fieldProps }) => (
<FormItem>
<FormLabel>{t(field.label)}</FormLabel>
<FormControl>
<EnhancedInput
{...fieldProps}
type='number'
min={field.min}
max={field.max}
step={field.step || 1}
suffix={field.suffix}
placeholder={
field.placeholder
? typeof field.placeholder === 'function'
? field.placeholder(t, protocolData)
: field.placeholder
: undefined
}
onValueChange={(v) => fieldProps.onChange(v)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
);
case 'select':
if (!field.options || field.options.length <= 1) {
return null;
}
return (
<FormField
{...commonProps}
render={({ field: fieldProps }) => (
<FormItem>
<FormLabel>{t(field.label)}</FormLabel>
<FormControl>
<Select
value={fieldProps.value ?? field.defaultValue}
onValueChange={(v) => fieldProps.onChange(v)}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('please_select')} />
</SelectTrigger>
</FormControl>
<SelectContent>
{field.options?.map((option) => (
<SelectItem key={option} value={option}>
{getLabel(option)}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
);
case 'switch':
return (
<FormField
{...commonProps}
render={({ field: fieldProps }) => (
<FormItem>
<FormLabel>{t(field.label)}</FormLabel>
<FormControl>
<div className='pt-2'>
<Switch
checked={!!fieldProps.value}
onCheckedChange={(checked) => fieldProps.onChange(checked)}
/>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
);
case 'textarea':
return (
<FormField
{...commonProps}
render={({ field: fieldProps }) => (
<FormItem className='col-span-2'>
<FormLabel>{t(field.label)}</FormLabel>
<FormControl>
<textarea
{...fieldProps}
value={fieldProps.value ?? ''}
className='border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[80px] w-full rounded-md border px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50'
placeholder={
field.placeholder
? typeof field.placeholder === 'function'
? field.placeholder(t, protocolData)
: field.placeholder
: undefined
}
onChange={(e) => fieldProps.onChange(e.target.value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
);
default:
return null;
}
}
function renderFieldsByGroup(
fields: FieldConfig[],
group: string,
control: any,
form: any,
protocolIndex: number,
protocolData: any,
t: (key: string) => string,
) {
const groupFields = fields.filter((field) => field.group === group);
if (groupFields.length === 0) return null;
return (
<div className='grid grid-cols-2 gap-4'>
{groupFields.map((field) => (
<DynamicField
key={field.name}
field={field}
control={control}
form={form}
protocolIndex={protocolIndex}
protocolData={protocolData}
t={t}
/>
))}
</div>
);
}
function renderGroupCard(
title: string,
fields: FieldConfig[],
group: string,
control: any,
form: any,
protocolIndex: number,
protocolData: any,
t: (key: string) => string,
) {
const groupFields = fields.filter((field) => field.group === group);
if (groupFields.length === 0) return null;
const visibleFields = groupFields.filter(
(field) => !field.condition || field.condition(protocolData, {}),
);
if (visibleFields.length === 0) return null;
return (
<div className='relative'>
<fieldset className='border-border rounded-lg border'>
<legend className='text-foreground bg-background ml-3 px-1 py-1 text-sm font-medium'>
{t(title)}
</legend>
<div className='p-4 pt-2'>
{renderFieldsByGroup(fields, group, control, form, protocolIndex, protocolData, t)}
</div>
</fieldset>
</div>
);
}
export default function ServerForm(props: {
trigger: string;
title: string;
loading?: boolean;
initialValues?: Partial<API.Server>;
onSubmit: (values: Partial<API.Server>) => Promise<boolean> | boolean;
}) {
const { trigger, title, loading, initialValues, onSubmit } = props;
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
const [accordionValue, setAccordionValue] = useState<string>();
const { isProtocolUsedInNodes } = useNode();
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
name: '',
address: '',
country: '',
city: '',
protocols: [] as any[],
...initialValues,
},
});
const { control } = form;
const protocolsValues = useWatch({ control, name: 'protocols' });
useEffect(() => {
if (initialValues) {
form.reset({
name: '',
address: '',
country: '',
city: '',
...initialValues,
protocols: PROTOCOLS.map((type) => {
const existingProtocol = initialValues.protocols?.find((p) => p.type === type);
const defaultConfig = getProtocolDefaultConfig(type);
return existingProtocol ? { ...defaultConfig, ...existingProtocol } : defaultConfig;
}),
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValues]);
async function handleSubmit(values: Record<string, any>) {
const filteredProtocols = (values?.protocols || []).filter((protocol: any) => {
const port = Number(protocol?.port);
return protocol && Number.isFinite(port) && port > 0 && port <= 65535;
});
const result = {
name: values.name,
country: values.country,
city: values.city,
address: values.address,
protocols: filteredProtocols,
};
const ok = await onSubmit(result);
if (ok) {
form.reset();
setOpen(false);
}
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button
onClick={() => {
if (!initialValues) {
const full = PROTOCOLS.map((t) => getProtocolDefaultConfig(t));
form.reset({
name: '',
address: '',
country: '',
city: '',
protocols: full,
});
}
setOpen(true);
}}
>
{trigger}
</Button>
</SheetTrigger>
<SheetContent className='w-[700px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{title}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))]'>
<Form {...form}>
<form className='grid grid-cols-1 gap-2 px-6 pt-4'>
<div className='grid grid-cols-2 gap-2 md:grid-cols-4'>
<FormField
control={control}
name='name'
render={({ field }) => (
<FormItem>
<FormLabel>{t('name')}</FormLabel>
<FormControl>
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={control}
name='address'
render={({ field }) => (
<FormItem>
<FormLabel>{t('address')}</FormLabel>
<FormControl>
<EnhancedInput
{...field}
placeholder={t('address_placeholder')}
onValueChange={(v) => field.onChange(v)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={control}
name='country'
render={({ field }) => (
<FormItem>
<FormLabel>{t('country')}</FormLabel>
<FormControl>
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={control}
name='city'
render={({ field }) => (
<FormItem>
<FormLabel>{t('city')}</FormLabel>
<FormControl>
<EnhancedInput {...field} onValueChange={(v) => field.onChange(v)} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className='my-3'>
<h3 className='text-foreground text-sm font-semibold'>
{t('protocol_configurations')}
</h3>
<p className='text-muted-foreground mt-1 text-xs'>
{t('protocol_configurations_desc')}
</p>
</div>
<Accordion
type='single'
collapsible
className='w-full space-y-3'
value={accordionValue}
onValueChange={setAccordionValue}
>
{PROTOCOLS.map((type) => {
const i = Math.max(
0,
PROTOCOLS.findIndex((t) => t === type),
);
const current = (protocolsValues[i] || {}) as Record<string, any>;
const isEnabled = current?.enable;
const fields = PROTOCOL_FIELDS[type] || [];
return (
<AccordionItem key={type} value={type} className='mb-2 rounded-lg border'>
<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 variant='secondary' className='text-xs'>
{current.transport.toUpperCase()}
</Badge>
)}
{current.security && current.security !== 'none' && (
<Badge variant='outline' className='text-xs'>
{current.security.toUpperCase()}
</Badge>
)}
{current.port && <Badge className='text-xs'>{current.port}</Badge>}
</div>
<div className='flex items-center gap-1'>
<span
className={cn(
'text-xs',
isEnabled ? 'text-green-500' : 'text-muted-foreground',
)}
>
{isEnabled ? t('enabled') : t('disabled')}
</span>
</div>
</div>
<Switch
className='mr-2'
checked={!!isEnabled}
disabled={Boolean(
initialValues?.id &&
isProtocolUsedInNodes(initialValues?.id || 0, type) &&
isEnabled,
)}
onCheckedChange={(checked) => {
form.setValue(`protocols.${i}.enable`, checked);
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
</AccordionTrigger>
<AccordionContent className='px-4 pb-4 pt-0'>
<div className='-mx-4 space-y-4 rounded-b-lg border-t px-4 pt-4'>
{renderGroupCard('basic', fields, 'basic', control, form, i, current, t)}
{renderGroupCard('obfs', fields, 'obfs', control, form, i, current, t)}
{renderGroupCard(
'transport',
fields,
'transport',
control,
form,
i,
current,
t,
)}
{renderGroupCard(
'security',
fields,
'security',
control,
form,
i,
current,
t,
)}
{renderGroupCard(
'reality',
fields,
'reality',
control,
form,
i,
current,
t,
)}
{renderGroupCard(
'encryption',
fields,
'encryption',
control,
form,
i,
current,
t,
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
{t('cancel')}
</Button>
<Button
disabled={loading}
onClick={form.handleSubmit(handleSubmit, (errors) => {
console.log(errors, form.getValues());
const key = Object.keys(errors)[0] as keyof typeof errors;
if (key) toast.error(String(errors[key]?.message));
return false;
})}
>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -0,0 +1,119 @@
'use client';
import { getNodeConfig } from '@/services/admin/system';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@workspace/ui/components/dialog';
import { Input } from '@workspace/ui/components/input';
import { Label } from '@workspace/ui/components/label';
import { useTranslations } from 'next-intl';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
type Props = {
server: API.Server;
};
export default function ServerInstall({ server }: Props) {
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
const [domain, setDomain] = useState('');
const { data: cfgResp } = useQuery({
queryKey: ['getNodeConfig'],
queryFn: async () => {
const { data } = await getNodeConfig();
return data.data as API.NodeConfig | undefined;
},
enabled: open,
});
useEffect(() => {
if (open) {
const host = localStorage.getItem('API_HOST') ?? window.location.origin;
setDomain(host);
}
}, [open]);
const installCommand = useMemo(() => {
const secret = cfgResp?.node_secret ?? '';
return `wget -N https://raw.githubusercontent.com/perfect-panel/ppanel-node/master/scripts/install.sh && bash install.sh --api-host ${domain} --server-id ${server.id} --secret-key ${secret}`;
}, [domain, server.id, cfgResp?.node_secret]);
async function handleCopy() {
try {
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(installCommand);
} else {
// fallback for environments without clipboard API
const el = document.createElement('textarea');
el.value = installCommand;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
toast.success(t('copied'));
setOpen(false);
} catch (error) {
toast.error(t('copyFailed'));
}
}
const onDomainChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setDomain(e.target.value);
localStorage.setItem('API_HOST', e.target.value);
}, []);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant='secondary'>{t('connect')}</Button>
</DialogTrigger>
<DialogContent className='w-[720px] max-w-full md:max-w-screen-md'>
<DialogHeader>
<DialogTitle>{t('oneClickInstall')}</DialogTitle>
</DialogHeader>
<div className='space-y-4'>
<div>
<Label>{t('apiHost')}</Label>
<div className='flex items-center gap-2'>
<Input
value={domain}
placeholder={t('apiHostPlaceholder')}
onChange={onDomainChange}
/>
</div>
</div>
<div>
<Label>{t('installCommand')}</Label>
<div className='flex flex-col gap-2'>
<textarea
readOnly
aria-label={t('installCommand')}
value={installCommand}
className='min-h-[88px] w-full rounded border p-2 font-mono text-sm'
/>
</div>
</div>
</div>
<DialogFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' onClick={() => setOpen(false)}>
{t('close')}
</Button>
<Button onClick={handleCopy}>{t('copyAndClose')}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@ -0,0 +1,450 @@
'use client';
import {
createAppVersion,
deleteAppVersion,
getAppVersionList,
updateAppVersion,
} from '@/services/admin/application';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@workspace/ui/components/dialog';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@workspace/ui/components/select';
import { Switch } from '@workspace/ui/components/switch';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@workspace/ui/components/table';
import { EnhancedInput } from '@workspace/ui/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const versionSchema = z.object({
id: z.number().optional(),
platform: z.string().min(1),
version: z.string().min(1),
min_version: z.string().optional(),
url: z.string().url(),
description: z.string().optional(),
force_update: z.boolean(),
is_default: z.boolean(),
is_in_review: z.boolean(),
});
type VersionFormData = z.infer<typeof versionSchema>;
export default function VersionPage() {
const t = useTranslations('system');
const queryClient = useQueryClient();
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [open, setOpen] = useState(false);
const [editingVersion, setEditingVersion] = useState<API.ApplicationVersion | null>(null);
const { data } = useQuery({
queryKey: ['app-versions', page, pageSize],
queryFn: async () => {
const res = await getAppVersionList({ page, size: pageSize });
return res.data?.data;
},
});
const form = useForm<VersionFormData>({
resolver: zodResolver(versionSchema),
defaultValues: {
platform: 'android',
version: '',
min_version: '',
url: '',
description: '',
force_update: false,
is_default: false,
is_in_review: false,
},
});
const createMutation = useMutation({
mutationFn: createAppVersion,
onSuccess: () => {
toast.success(t('common.saveSuccess'));
setOpen(false);
form.reset();
queryClient.invalidateQueries({ queryKey: ['app-versions'] });
},
onError: () => {
toast.error(t('common.saveFailed'));
},
});
const updateMutation = useMutation({
mutationFn: updateAppVersion,
onSuccess: () => {
toast.success(t('common.saveSuccess'));
setOpen(false);
setEditingVersion(null);
form.reset();
queryClient.invalidateQueries({ queryKey: ['app-versions'] });
},
onError: () => {
toast.error(t('common.saveFailed'));
},
});
const deleteMutation = useMutation({
mutationFn: deleteAppVersion,
onSuccess: () => {
toast.success(t('common.saveSuccess'));
queryClient.invalidateQueries({ queryKey: ['app-versions'] });
},
onError: () => {
toast.error(t('common.saveFailed'));
},
});
const onSubmit = (values: VersionFormData) => {
const payload = {
...values,
description: JSON.stringify({ 'en-US': values.description, 'zh-CN': values.description }),
};
if (editingVersion) {
updateMutation.mutate({ ...payload, id: editingVersion.id } as API.UpdateAppVersionRequest);
} else {
createMutation.mutate(payload as API.CreateAppVersionRequest);
}
};
const handleEdit = (version: API.ApplicationVersion) => {
setEditingVersion(version);
let desc = '';
if (version.description && typeof version.description === 'object') {
desc = Object.values(version.description)[0] || '';
} else if (typeof version.description === 'string') {
try {
const parsed = JSON.parse(version.description);
desc = (Object.values(parsed)[0] as string) || '';
} catch (e) {
desc = version.description;
}
}
form.reset({
platform: version.platform,
version: version.version,
min_version: version.min_version,
url: version.url,
description: desc,
force_update: version.force_update,
is_default: version.is_default,
is_in_review: version.is_in_review,
});
setOpen(true);
};
const handleDelete = (id: number) => {
if (confirm(t('version.confirmDelete'))) {
deleteMutation.mutate({ id });
}
};
const handleOpenChange = (open: boolean) => {
setOpen(open);
if (!open) {
setEditingVersion(null);
form.reset({
platform: 'android',
version: '',
min_version: '',
url: '',
description: '',
force_update: false,
is_default: false,
is_in_review: false,
});
}
};
return (
<div className='space-y-4'>
<div className='flex items-center justify-between'>
<h2 className='text-2xl font-bold tracking-tight'>{t('version.title')}</h2>
<Button onClick={() => handleOpenChange(true)}>
<Icon icon='mdi:plus' className='mr-2 h-4 w-4' />
{t('version.create')}
</Button>
</div>
<div className='rounded-md border'>
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>{t('version.platform')}</TableHead>
<TableHead>{t('version.versionNumber')}</TableHead>
<TableHead>{t('version.url')}</TableHead>
<TableHead>{t('version.force')}</TableHead>
<TableHead>{t('version.default')}</TableHead>
<TableHead>{t('version.actions')}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data?.list?.map((version: API.ApplicationVersion) => (
<TableRow key={version.id}>
<TableCell>{version.id}</TableCell>
<TableCell>{version.platform}</TableCell>
<TableCell>{version.version}</TableCell>
<TableCell className='max-w-[200px] truncate' title={version.url}>
{version.url}
</TableCell>
<TableCell>{version.force_update ? t('version.yes') : t('version.no')}</TableCell>
<TableCell>{version.is_default ? t('version.yes') : t('version.no')}</TableCell>
<TableCell>
<div className='flex space-x-2'>
<Button variant='ghost' size='icon' onClick={() => handleEdit(version)}>
<Icon icon='mdi:pencil' className='h-4 w-4' />
</Button>
<Button variant='ghost' size='icon' onClick={() => handleDelete(version.id)}>
<Icon icon='mdi:delete' className='h-4 w-4 text-red-500' />
</Button>
</div>
</TableCell>
</TableRow>
))}
{!data?.list?.length && (
<TableRow>
<TableCell colSpan={7} className='h-24 text-center'>
{t('version.noResults')}
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className='flex items-center justify-between py-2'>
<div className='text-muted-foreground text-sm'>
{t('version.total', { count: data?.total || 0 })}
</div>
<div className='flex items-center space-x-2'>
<Select value={String(pageSize)} onValueChange={(val) => setPageSize(Number(val))}>
<SelectTrigger className='w-[80px]'>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value='10'>10</SelectItem>
<SelectItem value='20'>20</SelectItem>
<SelectItem value='50'>50</SelectItem>
</SelectContent>
</Select>
<Button
variant='outline'
size='sm'
onClick={() => setPage(Math.max(1, page - 1))}
disabled={page <= 1}
>
{t('version.previous')}
</Button>
<span className='text-sm'>{t('version.page', { page })}</span>
<Button
variant='outline'
size='sm'
onClick={() => setPage(page + 1)}
disabled={!data?.list?.length || data.list.length < pageSize}
>
{t('version.next')}
</Button>
</div>
</div>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className='sm:max-w-[600px]'>
<DialogHeader>
<DialogTitle>
{editingVersion ? t('version.edit') : t('version.createVersion')}
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className='space-y-4'>
<div className='grid grid-cols-2 gap-4'>
<FormField
control={form.control}
name='platform'
render={({ field }) => (
<FormItem>
<FormLabel>{t('version.platform')}</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder={t('version.platformPlaceholder')} />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value='android'>Android</SelectItem>
<SelectItem value='ios'>iOS</SelectItem>
<SelectItem value='windows'>Windows</SelectItem>
<SelectItem value='macos'>macOS</SelectItem>
<SelectItem value='linux'>Linux</SelectItem>
<SelectItem value='harmony'>Harmony</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='version'
render={({ field }) => (
<FormItem>
<FormLabel>{t('version.versionNumber')}</FormLabel>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={field.onChange}
placeholder={t('version.versionPlaceholder')}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className='grid grid-cols-2 gap-4'>
<FormField
control={form.control}
name='min_version'
render={({ field }) => (
<FormItem>
<FormLabel>{t('version.minVersion')}</FormLabel>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={field.onChange}
placeholder={t('version.versionPlaceholder')}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='url'
render={({ field }) => (
<FormItem>
<FormLabel>{t('version.downloadUrl')}</FormLabel>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={field.onChange}
placeholder='https://...'
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name='description'
render={({ field }) => (
<FormItem>
<FormLabel>{t('version.descriptionField')}</FormLabel>
<FormControl>
<EnhancedInput
value={field.value}
onValueChange={field.onChange}
placeholder={t('version.descriptionPlaceholder')}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className='flex flex-row gap-4'>
<FormField
control={form.control}
name='force_update'
render={({ field }) => (
<FormItem className='flex flex-1 flex-row items-center justify-between rounded-lg border p-3 shadow-sm'>
<div className='space-y-0.5'>
<FormLabel>{t('version.forceUpdate')}</FormLabel>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name='is_default'
render={({ field }) => (
<FormItem className='flex flex-1 flex-row items-center justify-between rounded-lg border p-3 shadow-sm'>
<div className='space-y-0.5'>
<FormLabel>{t('version.default')}</FormLabel>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name='is_in_review'
render={({ field }) => (
<FormItem className='flex flex-1 flex-row items-center justify-between rounded-lg border p-3 shadow-sm'>
<div className='space-y-0.5'>
<FormLabel>{t('version.inReview')}</FormLabel>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</FormItem>
)}
/>
</div>
<DialogFooter>
<Button type='submit'>
{editingVersion ? t('version.update') : t('version.create')}
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
);
}

View File

@ -56,6 +56,7 @@ import { useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { subscribeSchema } from './schema';
import { TemplatePreview } from './template-preview';
const createClientFormSchema = (t: any) =>
@ -64,9 +65,9 @@ const createClientFormSchema = (t: any) =>
description: z.string().optional(),
icon: z.string().optional(),
user_agent: z.string().min(1, `User-Agent ${t('form.validation.userAgentRequiredSuffix')}`),
scheme: z.string().default(''),
template: z.string().default(''),
output_format: z.string().default(''),
scheme: z.string().optional(),
template: z.string(),
output_format: z.string(),
download_link: z.object({
windows: z.string().optional(),
mac: z.string().optional(),
@ -83,8 +84,6 @@ export function ProtocolForm() {
const t = useTranslations('subscribe');
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const [previewOpen, setPreviewOpen] = useState(false);
const [previewApplicationId, setPreviewApplicationId] = useState<number | null>(null);
const [editingClient, setEditingClient] = useState<API.SubscribeApplication | null>(null);
const tableRef = useRef<ProTableActions>(null);
@ -111,7 +110,6 @@ export function ProtocolForm() {
},
});
// API请求函数
const request = async (
pagination: { page: number; size: number },
filter: Record<string, unknown>,
@ -127,7 +125,6 @@ export function ProtocolForm() {
};
};
// 表格列定义
const columns: ColumnDef<API.SubscribeApplication, any>[] = [
{
accessorKey: 'is_default',
@ -138,7 +135,6 @@ export function ProtocolForm() {
onCheckedChange={async (checked) => {
await updateSubscribeApplication({
...row.original,
proxy_template: '',
is_default: checked,
});
tableRef.current?.refresh();
@ -289,7 +285,6 @@ export function ProtocolForm() {
if (editingClient) {
await updateSubscribeApplication({
...data,
proxy_template: '',
is_default: editingClient.is_default,
id: editingClient.id,
});
@ -319,7 +314,21 @@ export function ProtocolForm() {
columns={columns}
request={request}
header={{
title: <h2 className='text-lg font-semibold'>{t('protocol.title')}</h2>,
title: (
<div className='flex items-center justify-between'>
<h2 className='text-lg font-semibold'>{t('protocol.title')}</h2>
<a
href='https://github.com/perfect-panel/subscription-template'
target='_blank'
rel='noreferrer'
className='text-primary inline-flex items-center gap-2 rounded-md px-3 py-1 text-sm font-medium hover:underline'
>
<Icon icon='mdi:github' className='h-4 w-4' />
<span>Template Repo</span>
<Icon icon='mdi:open-in-new' className='text-muted-foreground h-4 w-4' />
</a>
</div>
),
toolbar: <Button onClick={handleAdd}>{t('actions.add')}</Button>,
}}
actions={{
@ -654,136 +663,7 @@ export function ProtocolForm() {
<FormControl>
<GoTemplateEditor
showLineNumbers
schema={{
SiteName: { type: 'string', description: 'Site name' },
SubscribeName: { type: 'string', description: 'Subscribe name' },
Proxies: {
type: 'array',
description: 'Array of proxy nodes',
items: {
type: 'object',
properties: {
Name: { type: 'string', description: 'Node name' },
Server: { type: 'string', description: 'Server host' },
Port: { type: 'number', description: 'Server port' },
Type: { type: 'string', description: 'Proxy type' },
Tags: {
type: 'array',
description: 'Node tags',
items: { type: 'string' },
},
// Security Options
Security: {
type: 'string',
description: 'Security protocol',
},
SNI: {
type: 'string',
description: 'Server Name Indication for TLS',
},
AllowInsecure: {
type: 'boolean',
description:
'Allow insecure connections (skip certificate verification)',
},
Fingerprint: {
type: 'string',
description: 'Client fingerprint for TLS connections',
},
RealityServerAddr: {
type: 'string',
description: 'Reality server address',
},
RealityServerPort: {
type: 'number',
description: 'Reality server port',
},
RealityPrivateKey: {
type: 'string',
description: 'Reality private key for authentication',
},
RealityPublicKey: {
type: 'string',
description: 'Reality public key for authentication',
},
RealityShortId: {
type: 'string',
description: 'Reality short ID for authentication',
},
// Transport Options
Transport: {
type: 'string',
description: 'Transport protocol (e.g., ws, http, grpc)',
},
Host: {
type: 'string',
description: 'For WebSocket/HTTP/HTTPS',
},
Path: { type: 'string', description: 'For HTTP/HTTPS' },
ServiceName: {
type: 'string',
description: 'For gRPC',
},
// Shadowsocks Options
Method: { type: 'string', description: 'Encryption method' },
ServerKey: {
type: 'string',
description: 'For Shadowsocks 2022',
},
// Vmess/Vless/Trojan Options
Flow: {
type: 'string',
description: 'Flow for Vmess/Vless/Trojan',
},
// Hysteria2 Options
HopPorts: {
type: 'string',
description: 'Comma-separated list of hop ports',
},
HopInterval: {
type: 'number',
description: 'Interval for hop ports in seconds',
},
ObfsPassword: {
type: 'string',
description: 'Obfuscation password for Hysteria2',
},
// Tuic Options
DisableSNI: {
type: 'boolean',
description: 'Disable SNI',
},
ReduceRtt: {
type: 'boolean',
description: 'Reduce RTT',
},
UDPRelayMode: {
type: 'string',
description: 'UDP relay mode (e.g., "full", "partial")',
},
CongestionController: {
type: 'string',
description: 'Congestion controller (e.g., "cubic", "bbr")',
},
},
},
},
UserInfo: {
type: 'object',
description: 'User information',
properties: {
Password: { type: 'string', description: 'User password' },
ExpiredAt: { type: 'string', description: 'Expiration date' },
Download: { type: 'number', description: 'Downloaded bytes' },
Upload: { type: 'number', description: 'Uploaded bytes' },
Traffic: { type: 'number', description: 'Total traffic bytes' },
SubscribeURL: {
type: 'string',
description: 'Subscription URL',
},
},
},
}}
schema={subscribeSchema}
enableSprig
value={field.value || ''}
onChange={(value) => field.onChange(value)}

View File

@ -0,0 +1,225 @@
export const subscribeSchema = {
SiteName: { type: 'string', description: 'Site name' },
SubscribeName: { type: 'string', description: 'Subscribe name' },
Proxies: {
type: 'array',
description: 'Array of proxy nodes',
items: {
type: 'object',
properties: {
Name: { type: 'string', description: 'Node name' },
Server: { type: 'string', description: 'Server host' },
Port: { type: 'number', description: 'Server port' },
Type: { type: 'string', description: 'Proxy type' },
Tags: {
type: 'array',
description: 'Node tags',
items: { type: 'string' },
},
Sort: { type: 'number', description: 'Node sort order' },
// Security Options
Security: {
type: 'string',
description: 'Security protocol',
},
SNI: {
type: 'string',
description: 'Server Name Indication for TLS',
},
AllowInsecure: {
type: 'boolean',
description: 'Allow insecure connections (skip certificate verification)',
},
Fingerprint: {
type: 'string',
description: 'Client fingerprint for TLS connections',
},
RealityServerAddr: {
type: 'string',
description: 'Reality server address',
},
RealityServerPort: {
type: 'number',
description: 'Reality server port',
},
RealityPrivateKey: {
type: 'string',
description: 'Reality private key for authentication',
},
RealityPublicKey: {
type: 'string',
description: 'Reality public key for authentication',
},
RealityShortId: {
type: 'string',
description: 'Reality short ID for authentication',
},
// Transport Options
Transport: {
type: 'string',
description: 'Transport protocol (e.g., ws, http, grpc)',
},
Host: {
type: 'string',
description: 'For WebSocket/HTTP/HTTPS',
},
Path: { type: 'string', description: 'For HTTP/HTTPS' },
ServiceName: {
type: 'string',
description: 'For gRPC',
},
// Shadowsocks Options
Method: { type: 'string', description: 'Encryption method' },
ServerKey: {
type: 'string',
description: 'For Shadowsocks 2022',
},
// Vmess/Vless/Trojan Options
Flow: {
type: 'string',
description: 'Flow for Vmess/Vless/Trojan',
},
// Hysteria2 Options
HopPorts: {
type: 'string',
description: 'Comma-separated list of hop ports',
},
HopInterval: {
type: 'number',
description: 'Interval for hop ports in seconds',
},
ObfsPassword: {
type: 'string',
description: 'Obfuscation password for Hysteria2',
},
// Tuic Options
DisableSNI: {
type: 'boolean',
description: 'Disable SNI',
},
ReduceRtt: {
type: 'boolean',
description: 'Reduce RTT',
},
UDPRelayMode: {
type: 'string',
description: 'UDP relay mode (e.g., "full", "partial")',
},
CongestionController: {
type: 'string',
description: 'Congestion controller (e.g., "cubic", "bbr")',
},
// Hysteria2 additional options
UpMbps: {
type: 'number',
description: 'Upload bandwidth in Mbps',
},
DownMbps: {
type: 'number',
description: 'Download bandwidth in Mbps',
},
// VLESS encryption options
Encryption: {
type: 'string',
description: 'Encryption type for VLESS',
},
EncryptionMode: {
type: 'string',
description: 'Encryption mode (e.g., "native", "xorpub", "random")',
},
EncryptionRtt: {
type: 'string',
description: 'Encryption RTT (e.g., "0rtt", "1rtt")',
},
EncryptionTicket: {
type: 'string',
description: 'Encryption ticket',
},
EncryptionServerPadding: {
type: 'string',
description: 'Server padding for encryption',
},
EncryptionClientPadding: {
type: 'string',
description: 'Client padding for encryption',
},
EncryptionPassword: {
type: 'string',
description: 'Encryption password',
},
EncryptionPrivateKey: {
type: 'string',
description: 'Private key for encryption',
},
// XHTTP options
XhttpMode: {
type: 'string',
description: 'XHTTP mode (e.g., "auto", "packet-up", "stream-up", "stream-one")',
},
XhttpExtra: {
type: 'string',
description: 'XHTTP extra parameters',
},
// Shadowsocks obfs options (combined with Hysteria2 obfs)
ObfsHost: {
type: 'string',
description: 'Obfuscation host',
},
ObfsPath: {
type: 'string',
description: 'Obfuscation path',
},
// Shadowsocks cipher
Cipher: {
type: 'string',
description: 'Shadowsocks cipher method',
},
// AnyTLS options
PaddingScheme: {
type: 'string',
description: 'Padding scheme for AnyTLS',
},
// Mieru options
Multiplex: {
type: 'string',
description: 'Multiplex level (e.g., "none", "low", "middle", "high")',
},
// General protocol field
Enable: {
type: 'boolean',
description: 'Whether this protocol is enabled',
},
// UUID for vmess/vless
UUID: {
type: 'string',
description: 'User UUID for vmess/vless protocols',
},
// Alternative ID for vmess
AlterId: {
type: 'number',
description: 'Alternative ID for vmess (deprecated)',
},
// Password for trojan/tuic
Password: {
type: 'string',
description: 'Password for authentication',
},
},
},
},
UserInfo: {
type: 'object',
description: 'User information',
properties: {
Password: { type: 'string', description: 'User password' },
ExpiredAt: { type: 'string', description: 'Expiration date' },
Download: { type: 'number', description: 'Downloaded bytes' },
Upload: { type: 'number', description: 'Uploaded bytes' },
Traffic: { type: 'number', description: 'Total traffic bytes' },
SubscribeURL: {
type: 'string',
description: 'Subscription URL',
},
},
},
};

View File

@ -3,9 +3,15 @@
import { previewSubscribeTemplate } from '@/services/admin/application';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@workspace/ui/components/sheet';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { MonacoEditor } from '@workspace/ui/custom-components/editor/monaco-editor';
import { Icon } from '@workspace/ui/custom-components/icon';
import { Markdown } from '@workspace/ui/custom-components/markdown';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
@ -27,7 +33,6 @@ export function TemplatePreview({ applicationId, output_format }: TemplatePrevie
const originalContent = data?.data?.data?.template || '';
const errorMessage = (error as any)?.data?.msg || error?.message || t('failed');
const displayContent = originalContent || (error ? errorMessage : '');
const getDecodedContent = () => {
if (output_format === 'base64' && originalContent) {
@ -41,49 +46,61 @@ export function TemplatePreview({ applicationId, output_format }: TemplatePrevie
};
const getDisplayContent = () => {
if (error) return errorMessage;
if (!originalContent) return '';
switch (output_format) {
case 'base64':
return `\`\`\`base64\n# ${t('base64.originalContent')}\n${displayContent}\n\n# ${t('base64.decodedContent')}\n${getDecodedContent()}\n\`\`\``;
case 'yaml':
return `\`\`\`yaml\n${displayContent}\n\`\`\``;
case 'json':
return `\`\`\`json\n${displayContent}\n\`\`\``;
case 'conf':
return `\`\`\`ini\n${displayContent}\n\`\`\``;
case 'plain':
return `\`\`\`text\n${displayContent}\n\`\`\``;
case 'base64': {
const decoded = getDecodedContent();
return `${t('base64.originalContent')}:\n${originalContent}\n\n${t('base64.decodedContent')}:\n${decoded}`;
}
default:
return displayContent;
return originalContent;
}
};
const mapLanguage = (fmt?: string) => {
switch (fmt) {
case 'json':
return 'json';
case 'yaml':
return 'yaml';
case 'base64':
return 'ini';
case 'plain':
return 'ini';
case 'conf':
return 'ini';
default:
return 'ini';
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
};
return (
<>
<Button variant='ghost' size='sm' onClick={() => setIsOpen(true)}>
<Icon icon='mdi:eye' className='mr-2 h-4 w-4' />
{t('preview')}
</Button>
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
<SheetContent className='w-[800px] max-w-[90vw] md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('title')}</SheetTitle>
</SheetHeader>
{isLoading ? (
<div className='flex items-center justify-center'>
<Icon icon='mdi:loading' className='h-6 w-6 animate-spin' />
<span className='ml-2'>{t('loading')}</span>
</div>
) : (
<div className='*:text-sm [&_pre>div>div+div]:max-h-[calc(100dvh-48px-36px-36px)] [&_pre>div>div+div]:overflow-auto'>
<Markdown>{getDisplayContent()}</Markdown>
</div>
)}
</SheetContent>
</Sheet>
</>
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button variant='ghost'>
<Icon icon='mdi:eye' className='h-4 w-4' />
{t('preview')}
</Button>
</SheetTrigger>
<SheetHeader>
<SheetTitle></SheetTitle>
</SheetHeader>
<SheetContent className='w-[800px] max-w-[90vw] pt-10 md:max-w-screen-md'>
{isLoading ? (
<div className='flex items-center justify-center'>
<Icon icon='mdi:loading' className='h-6 w-6 animate-spin' />
<span className='ml-2'>{t('loading')}</span>
</div>
) : (
<MonacoEditor
title={t('title')}
value={getDisplayContent()}
language={mapLanguage(output_format)}
showLineNumbers
readOnly
/>
)}
</SheetContent>
</Sheet>
);
}

View File

@ -38,6 +38,7 @@ const currencySchema = z.object({
access_key: z.string().optional(),
currency_unit: z.string().min(1),
currency_symbol: z.string().min(1),
fixed_rate: z.number().optional(),
});
type CurrencyFormData = z.infer<typeof currencySchema>;
@ -62,6 +63,7 @@ export default function CurrencyConfig() {
access_key: '',
currency_unit: 'USD',
currency_symbol: '$',
fixed_rate: 0,
},
});
@ -170,6 +172,26 @@ export default function CurrencyConfig() {
</FormItem>
)}
/>
<FormField
control={form.control}
name='fixed_rate'
render={({ field }) => (
<FormItem>
<FormLabel>{t('currency.fixedRate')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
placeholder={t('currency.fixedRatePlaceholder', { defaultValue: '0' })}
value={field.value}
onValueChange={(val) => field.onChange(Number(val))}
/>
</FormControl>
<FormDescription>{t('currency.fixedRateDescription')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>

View File

@ -0,0 +1,164 @@
'use client';
import { getLogSetting, updateLogSetting } from '@/services/admin/log';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@workspace/ui/components/form';
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/custom-components/enhanced-input';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const logCleanupSchema = z.object({
auto_clear: z.boolean(),
clear_days: z.number().min(1),
});
type LogCleanupFormData = z.infer<typeof logCleanupSchema>;
export default function LogCleanupForm() {
const t = useTranslations('system');
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const { data, refetch } = useQuery({
queryKey: ['getLogSetting'],
queryFn: async () => {
const { data } = await getLogSetting();
return data.data;
},
enabled: open,
});
const form = useForm<LogCleanupFormData>({
resolver: zodResolver(logCleanupSchema),
defaultValues: {
auto_clear: false,
clear_days: 30,
},
});
useEffect(() => {
if (data) {
form.reset(data);
}
}, [data, form]);
async function onSubmit(values: LogCleanupFormData) {
setLoading(true);
try {
await updateLogSetting(values as API.LogSetting);
toast.success(t('common.saveSuccess'));
refetch();
setOpen(false);
} catch (error) {
toast.error(t('common.saveFailed'));
} finally {
setLoading(false);
}
}
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<div className='flex cursor-pointer items-center justify-between transition-colors'>
<div className='flex items-center gap-3'>
<div className='bg-primary/10 flex h-10 w-10 items-center justify-center rounded-lg'>
<Icon icon='mdi:delete-sweep' className='text-primary h-5 w-5' />
</div>
<div className='flex-1'>
<p className='font-medium'>{t('logCleanup.title')}</p>
<p className='text-muted-foreground text-sm'>{t('logCleanup.description')}</p>
</div>
</div>
<Icon icon='mdi:chevron-right' className='size-6' />
</div>
</SheetTrigger>
<SheetContent className='w-[600px] max-w-full md:max-w-screen-md'>
<SheetHeader>
<SheetTitle>{t('logCleanup.title')}</SheetTitle>
</SheetHeader>
<ScrollArea className='-mx-6 h-[calc(100dvh-48px-36px-36px-env(safe-area-inset-top))] px-6'>
<Form {...form}>
<form
id='log-cleanup-form'
onSubmit={form.handleSubmit(onSubmit)}
className='space-y-2 pt-4'
>
<FormField
control={form.control}
name='auto_clear'
render={({ field }) => (
<FormItem>
<FormLabel>{t('logCleanup.autoClear')}</FormLabel>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
className='float-end !mt-0'
/>
</FormControl>
<FormDescription>{t('logCleanup.autoClearDescription')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='clear_days'
render={({ field }) => (
<FormItem>
<FormLabel>{t('logCleanup.clearDays')}</FormLabel>
<FormControl>
<EnhancedInput
type='number'
placeholder={t('logCleanup.clearDaysPlaceholder')}
value={field.value?.toString()}
onValueChange={(value) => field.onChange(Number(value))}
disabled={!form.watch('auto_clear')}
/>
</FormControl>
<FormDescription>{t('logCleanup.clearDaysDescription')}</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</ScrollArea>
<SheetFooter className='flex-row justify-end gap-2 pt-3'>
<Button variant='outline' disabled={loading} onClick={() => setOpen(false)}>
{t('common.cancel')}
</Button>
<Button disabled={loading} type='submit' form='log-cleanup-form'>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('common.save')}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
}

View File

@ -6,6 +6,7 @@ import CurrencyForm from './basic-settings/currency-form';
import PrivacyPolicyForm from './basic-settings/privacy-policy-form';
import SiteForm from './basic-settings/site-form';
import TosForm from './basic-settings/tos-form';
import LogCleanupForm from './log-cleanup/log-cleanup-form';
import InviteForm from './user-security/invite-form';
import RegisterForm from './user-security/register-form';
import VerifyCodeForm from './user-security/verify-code-form';
@ -14,7 +15,6 @@ import VerifyForm from './user-security/verify-form';
export default function Page() {
const t = useTranslations('system');
// 定义表单配置
const formSections = [
{
title: t('basicSettings'),
@ -34,6 +34,10 @@ export default function Page() {
{ component: VerifyCodeForm },
],
},
{
title: t('logSettings'),
forms: [{ component: LogCleanupForm }],
},
];
return (

View File

@ -1,7 +1,7 @@
'use client';
import { getSubscribeList } from '@/services/admin/subscribe';
import { getRegisterConfig, updateRegisterConfig } from '@/services/admin/system';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
@ -61,17 +61,7 @@ export default function RegisterConfig() {
enabled: open,
});
const { data: subscribe } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.Subscribe[];
},
enabled: open,
});
const { subscribes } = useSubscribe();
const form = useForm<RegisterFormData>({
resolver: zodResolver(registerSchema),
@ -268,12 +258,10 @@ export default function RegisterConfig() {
field.onChange(value);
}
}}
options={
subscribe?.map((item) => ({
label: item.name,
value: item.id,
})) || []
}
options={subscribes?.map((item) => ({
label: item.name!,
value: item.id!,
}))}
className='bg-secondary w-32 rounded-r-none'
/>
)}

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