Compare commits

..
280 Commits
Author SHA1 Message Date
Dot.L 588f2770b7 Merge pull request #167 from xpack-ai/feature/fix-billing-transaction
Feature/fix billing transaction
2026-04-01 17:23:01 +08:00
Liujian ad743d6ab7 Cancel the _update_wallet_cache method from being included in transactions 2026-03-30 18:17:27 +08:00
Liujian 6145d0b005 _update_wallet_cache is also included in transactions. 2026-03-30 18:01:08 +08:00
Dot.L d147fcb070 Merge pull request #166 from xpack-ai/feature/fix-billing-transaction
Feature/fix billing transaction
2026-03-30 16:40:17 +08:00
Liujian 6196b93e97 The billing processor adds transaction processing and retry mechanisms. 2026-03-30 16:00:58 +08:00
Liujian b51933d625 Fixed the issue where access remained even after the API key was deleted. 2026-03-30 15:59:49 +08:00
Liujian 40ff118798 Handling billing transactions 2026-03-27 18:36:28 +08:00
Dot.L d470677abe Merge pull request #155 from xpack-ai/revert-154-dev
Revert "Dev"
2026-03-11 15:59:28 +08:00
Dot.L 6eac3c6100 Revert "Dev" 2026-03-11 15:56:53 +08:00
Dot.L d22513730a Merge pull request #154 from xpack-ai/dev
Dev
2026-03-11 15:56:36 +08:00
Dot.L 613cece94b Merge pull request #153 from xpack-ai/open-base
user service add update_password
2026-03-11 15:25:00 +08:00
Liujian 5cd1c12323 user service add update_password 2026-03-11 15:13:28 +08:00
Dot.L dcf73b25bf Merge pull request #152 from xpack-ai/open-base
update temp_mcp_service_repository.py
2026-03-11 11:37:35 +08:00
Liujian 64a67e9c8d update temp_mcp_service_repository.py 2026-03-11 11:36:30 +08:00
Dot.L b6160af3c5 Merge pull request #150 from xpack-ai/open-base
mcp service add sort and category_id
2026-03-11 10:57:22 +08:00
Liujian 2ea41dfb75 mcp service add sort and category_id 2026-03-11 10:56:54 +08:00
Dot.L cbcc419f0b Merge pull request #149 from xpack-ai/open-base
update tenant_id type
2026-03-10 18:42:45 +08:00
Liujian 687949beb2 update tenant_id type 2026-03-10 18:41:49 +08:00
Dot.L fedaa5f5df Merge pull request #148 from xpack-ai/open-base
update sys_config index
2026-03-10 16:19:17 +08:00
Liujian c272c87e1f update sys_config index 2026-03-10 16:18:34 +08:00
Dot.L 8a052ff910 Merge pull request #147 from xpack-ai/open-base
The concept of a tenant is added as the foundation of the SaaS code.
2026-03-10 15:37:05 +08:00
Liujian d1c7a4b8c0 The concept of a tenant is added as the foundation of the SaaS code. 2026-03-10 15:33:57 +08:00
Dot.L 1a104338e8 Merge pull request #144 from xpack-ai/feature/1.4-liujian
Feature/1.4 liujian
2026-02-28 16:02:01 +08:00
Liujian 5dd47b2d01 Redis client methods supplement 2026-02-28 15:53:35 +08:00
Dot.L a28de60b1c Merge pull request #143 from xpack-ai/feature/1.4-liujian
Adjustment of some interface permissions
2026-02-26 10:29:38 +08:00
Liujian e4a807b2a0 Delete Print code 2026-02-26 10:28:18 +08:00
Liujian d0e7ed2771 Remove authentication checks from /api/common/config and /api/common/homepage 2026-02-26 10:26:00 +08:00
Dot.L 05c0088f1b Merge pull request #142 from xpack-ai/feature/1.4-liujian
Adjust the streamable-http initialization connection waiting logic
2026-02-25 15:23:08 +08:00
Liujian 7f66cfd21e Adjust the streamable-http initialization connection waiting logic 2026-02-25 15:22:10 +08:00
Dot.L 05b48f3656 Merge pull request #141 from xpack-ai/feature/1.4-liujian
Fix: Removed permission verification from the user information retrie…
2026-02-25 15:18:58 +08:00
Liujian 07fe83b7b5 Fix: Removed permission verification from the user information retrieval interface. 2026-02-25 15:18:19 +08:00
Dot.L 5fa1cd741e Merge pull request #140 from xpack-ai/feature/1.4-liujian
Adjust the streamable-http initialization connection waiting timeout
2026-02-25 11:24:50 +08:00
Liujian 3e1d986c1c Adjust the streamable-http initialization connection waiting timeout 2026-02-25 11:24:23 +08:00
Dot.L 2cf95fd1c1 Merge pull request #139 from xpack-ai/feature/1.4-liujian
Adjust the streamable-http initialization connection waiting logic
2026-02-25 11:13:53 +08:00
Liujian 09b6811391 Adjust the streamable-http initialization connection waiting logic 2026-02-25 11:13:18 +08:00
Dot.L 08d326dc1f Merge pull request #138 from xpack-ai/feature/1.4-liujian
fix: Handle None message in custom MCP event store during priming event
2026-02-24 16:28:17 +08:00
Dot.L fb23d62fb2 Merge pull request #137 from xpack-ai/feature/1.4-liujian
fix: Handle None message in custom MCP event store during priming event
2026-02-24 15:16:14 +08:00
Liujian 79400146ea fix: Handle None message in custom MCP event store during priming event 2026-02-24 15:15:09 +08:00
Dot.L 503b3bf078 Merge pull request #136 from xpack-ai/feature/1.4-liujian
API adds user role verification
2026-02-23 19:10:38 +08:00
Dot.L eb4ecff6ed Merge pull request #135 from xpack-ai/feature/1.4-liujian
API adds user role verification
2026-02-14 11:24:00 +08:00
Liujian 7f8947f070 Modify payment-related interface permissions 2026-02-14 11:23:50 +08:00
Liujian 6dca9b08cc API adds user role verification 2026-02-14 10:03:22 +08:00
lcx 06034cf46e Merge remote-tracking branch 'origin/feature/cx-1.4' 2026-02-06 15:53:17 +08:00
ningyv ffdf931cad Merge pull request #134 from xpack-ai/feature/cx-1.4
chore: upgrade Next.js version
2026-02-06 15:36:06 +08:00
lcx 24e59f18d0 chore: upgrade Next.js version 2026-02-06 15:35:16 +08:00
lcx 5a538863b1 Merge remote-tracking branch 'origin/feature/cx-1.4' into dev 2026-02-06 14:49:55 +08:00
lcx f468fe270f chore: upgrade Next.js version 2026-02-06 14:49:10 +08:00
lcx 4cc8b87de5 chore: upgrade Next.js version 2026-02-06 14:44:28 +08:00
Dot.L f6e0130035 Merge pull request #132 from xpack-ai/feature/1.4-liujian
MySQL reconnection mechanism optimization
2026-02-05 13:43:56 +08:00
Dot.L d351afb732 Merge pull request #131 from xpack-ai/feature/1.4-liujian
Version 1.4 development completed
2026-02-03 10:18:43 +08:00
Liujian fab064975d MySQL reconnection mechanism optimization 2026-02-03 10:00:02 +08:00
ningyv 30a06d74d6 Merge pull request #130 from xpack-ai/feature/cx-1.4
Feature/cx 1.4
2026-02-02 17:56:01 +08:00
Dot.L 6f882845c2 Merge pull request #129 from xpack-ai/feature/1.4-liujian
Optimize return prompt words
2026-01-29 18:26:34 +08:00
Liujian 33d66e7d3b Optimize return prompt words 2026-01-29 18:26:06 +08:00
ningyv 5654f83644 Merge pull request #128 from xpack-ai/feature/cx-1.4
feat: 1.4 - List supports search
2026-01-29 18:13:24 +08:00
lcx b7c67cc44f feat: 1.4 - List supports search 2026-01-29 18:12:35 +08:00
Dot.L 6d15420b08 Merge pull request #127 from xpack-ai/feature/1.4-liujian
Optimize return prompt words
2026-01-29 18:07:56 +08:00
Liujian 32562b9c25 Optimize return prompt words 2026-01-29 18:07:28 +08:00
Dot.L 5469eca450 Merge pull request #126 from xpack-ai/feature/1.4-liujian
Optimize return prompt words
2026-01-29 17:51:28 +08:00
ningyv 94fd46c8ca Merge pull request #125 from xpack-ai/feature/cx-1.4
feat: 1.4 - List supports search
2026-01-29 17:51:15 +08:00
Liujian ffc09b7b83 Optimize return prompt words 2026-01-29 17:50:59 +08:00
lcx f4bd572fff feat: 1.4 - List supports search 2026-01-29 17:49:57 +08:00
Dot.L 57bd964d22 Merge pull request #124 from xpack-ai/feature/1.4-liujian
Optimize return prompt words
2026-01-29 16:31:00 +08:00
Liujian 3c4e2be1dd Optimize return prompt words 2026-01-29 16:30:30 +08:00
Dot.L aac3a187d1 Merge pull request #123 from xpack-ai/feature/1.4-liujian
Added logic to disable IP login after repeated login failures
2026-01-28 19:18:17 +08:00
Liujian c0ec39f1d6 Merge remote-tracking branch 'origin/dev' into feature/1.4-liujian
# Conflicts:
#	services/admin_service/controllers/auth.py
2026-01-28 19:17:58 +08:00
Liujian 22fa608220 Added logic to disable IP login after repeated login failures 2026-01-28 19:14:07 +08:00
Dot.L e20dacde6b Merge pull request #122 from xpack-ai/feature/1.4-liujian
1. Optimized the issue of duplicate names in newly created resource g…
2026-01-28 17:24:33 +08:00
Liujian fef2e2a1f7 1. Optimized the issue of duplicate names in newly created resource groups
2. Fixed the issue of new users not being bound to the default resource group after logging in
2026-01-28 17:23:56 +08:00
ningyv 3cb1cca751 Merge pull request #121 from xpack-ai/feature/cx-1.4
Feature/cx 1.4
2026-01-28 15:59:37 +08:00
lcx 71807c0c67 feat: 1.4 - List supports search 2026-01-28 15:58:48 +08:00
lcx 14e6b5c23b feat: 1.4 - List supports search 2026-01-28 15:47:26 +08:00
Dot.L 64d5b2abfc Merge pull request #120 from xpack-ai/feature/1.4-liujian
finish 1.4 api
2026-01-28 13:57:59 +08:00
Liujian fdbb077293 Merge remote-tracking branch 'origin/dev' into feature/1.4-liujian
# Conflicts:
#	services/admin_service/services/user_wallet_history_service.py
2026-01-28 13:57:45 +08:00
Liujian 10809113f4 finish 1.4 api 2026-01-28 13:56:14 +08:00
ningyv f592178d83 Merge pull request #119 from xpack-ai/hotfix/ui-cx
Hotfix/UI cx
2026-01-16 17:38:10 +08:00
ningyv db9a5d571c Merge pull request #118 from xpack-ai/hotfix/ui-cx
fix: Limit resource group name length to 255 characters or less
2026-01-16 17:35:08 +08:00
lcx 1ebac24a3b fix: Limit resource group name length to 255 characters or less 2026-01-16 17:34:09 +08:00
Dot.L 875a7bf906 Merge pull request #117 from xpack-ai/feature/1.3-liujian
Bug fixes and prompt optimizations.
2026-01-16 17:12:45 +08:00
Liujian bf79191194 Optimize the error message for login failures. 2026-01-16 17:10:02 +08:00
Liujian 24ee3078d8 fix bug: Failed to set SQLAlchemy list cache for key xpack:resource_group: id:.... 'list' object has no attribute '__table__'"} 2026-01-16 17:09:10 +08:00
Liujian 302277bad2 fix bug: OpenAPI requestBody Not Parsed for MCP Tools 2026-01-16 17:08:47 +08:00
Dot.L 6724801d60 Merge pull request #116 from xpack-ai/feature/1.3-liujian
Feature/1.3 liujian
2026-01-15 15:19:20 +08:00
Dot.L 51338373e7 Merge pull request #115 from xpack-ai/feature/1.3-liujian
Fixed an issue where deletion failed when there were no users in the …
2026-01-08 11:21:57 +08:00
Liujian aa2fd609c6 Fixed an issue where deletion failed when there were no users in the resource group. 2026-01-08 11:20:51 +08:00
Dot.L 46bdf470c8 Merge pull request #114 from xpack-ai/feature/1.3-liujian
Fixed an issue where deletion failed when there were no users in the …
2026-01-08 11:16:11 +08:00
Liujian 6b758c3acd Fixed an issue where deletion failed when there were no users in the resource group. 2026-01-08 11:13:35 +08:00
Dot.L 1589d6ef0a Merge pull request #113 from xpack-ai/feature/1.3-liujian
fix bug: Issues with duplicate data in resource group list pagination.
2026-01-07 18:09:07 +08:00
Liujian d55cc3e216 fix bug: Issues with duplicate data in resource group list pagination. 2026-01-07 18:08:26 +08:00
ningyv e1c59da804 Merge pull request #112 from xpack-ai/hotfix/ui-cx
fix: prevent "Deny All" resource group from being set as default
2026-01-07 17:41:17 +08:00
lcx 60c9698cdd fix: prevent "Deny All" resource group from being set as default 2026-01-07 17:39:50 +08:00
Dot.L 11de1de3b1 Merge pull request #111 from xpack-ai/feature/1.3-liujian
fix bug: Deleting MCP Service causes errors in all associated Resourc…
2026-01-07 17:08:42 +08:00
Liujian c16bab66ee fix bug: Deleting MCP Service causes errors in all associated Resource Groups 2026-01-07 17:08:12 +08:00
ningyv ec3bef1cae Merge pull request #110 from xpack-ai/hotfix/ui-cx
Hotfix/UI cx
2026-01-07 16:57:03 +08:00
lcx 060bcf7f73 fix: prevent "Allow All" resource group from being set as default 2026-01-07 16:49:59 +08:00
Dot.L 8394afe581 Merge pull request #109 from xpack-ai/feature/1.3-liujian
Feature/1.3 liujian
2026-01-05 14:30:22 +08:00
ningyv 85140f8bdc Merge pull request #108 from xpack-ai/feature/1.3-cx
Feature/1.3 cx
2026-01-05 14:03:07 +08:00
ningyv 595994de8c Merge pull request #107 from xpack-ai/feature/1.3-cx
feat: add MCP service tag filtering, transaction record viewing, and …
2026-01-05 11:53:15 +08:00
lcx ff725d766f feat: add MCP service tag filtering, transaction record viewing, and various optimizations 2026-01-05 11:52:27 +08:00
ningyv c7bbd0589c Merge pull request #106 from xpack-ai/feature/1.3-cx
feat: add MCP service tag filtering, transaction record viewing, and…
2026-01-04 19:03:39 +08:00
lcx cbfc4310b5 feat: add MCP service tag filtering, transaction record viewing, and various optimizations 2026-01-04 19:02:42 +08:00
ningyv 6f83fc7a88 Merge pull request #105 from xpack-ai/feature/1.3-cx
feat: add MCP service tag filtering, transaction record viewing, and …
2025-12-31 11:38:41 +08:00
lcx 714e19a4fc feat: add MCP service tag filtering, transaction record viewing, and various optimizations 2025-12-31 11:36:57 +08:00
Dot.L 64d559dd31 Merge pull request #104 from xpack-ai/feature/1.3-liujian
Change the balance_after field to balance
2025-12-30 18:44:06 +08:00
Liujian 50637087ae Change the balance_after field to balance 2025-12-30 18:43:35 +08:00
Dot.L d9fe780665 Merge pull request #103 from xpack-ai/feature/1.3-liujian
Change the balance_after field to balance
2025-12-30 18:41:51 +08:00
Liujian fa23805b5c Change the balance_after field to balance 2025-12-30 18:41:18 +08:00
ningyv 9d5d1ce2c5 Merge pull request #102 from xpack-ai/feature/1.3-cx
feat: add MCP service tag filtering, transaction record viewing, and …
2025-12-30 18:29:36 +08:00
lcx d6dea1f1e8 feat: add MCP service tag filtering, transaction record viewing, and various optimizations 2025-12-30 18:28:25 +08:00
Dot.L f9c8a74849 Merge pull request #101 from xpack-ai/feature/1.3-liujian
The transaction list now includes "balance" and "description" fields.
2025-12-30 15:09:03 +08:00
Liujian 915a2bcf9e The transaction list now includes "balance" and "description" fields. 2025-12-30 15:08:19 +08:00
Dot.L b23662d76a Merge pull request #100 from xpack-ai/feature/1.3-liujian
The system settings support setting the tag_bar_display variable.
2025-12-29 15:44:40 +08:00
Liujian 77ca12045d The system settings support setting the tag_bar_display variable. 2025-12-29 15:43:10 +08:00
Dot.L 4f27baf93a Merge pull request #99 from xpack-ai/feature/1.3-liujian
Feature/1.3 liujian
2025-12-29 14:20:19 +08:00
Liujian 88325a0ba9 1. Users can view transaction data on the client side.
2. The MCP service list supports tag filtering.
2025-12-29 14:19:26 +08:00
Dot.L 276817e624 Merge pull request #98 from xpack-ai/feature/scripts
update frontend_build.sh
2025-12-23 14:51:31 +08:00
Liujian 3a622c452a update frontend_build.sh 2025-12-23 14:50:53 +08:00
Liujian e26e6a7f24 fix: domain check error 2025-12-23 14:16:04 +08:00
Liujian 4d590bdb80 update start script 2025-12-22 17:24:46 +08:00
ningyv 2ee39124b0 Merge pull request #97 from xpack-ai/feat/resource-group-management
Feat/resource group management
2025-12-22 16:58:54 +08:00
ningyv 20f09ce044 Merge pull request #96 from xpack-ai/feat/resource-group-management
chore: upgrade Next.js to version 15.5.9
2025-12-22 16:51:55 +08:00
lcx 65128b1d2a chore: upgrade Next.js to version 15.5.9 2025-12-22 16:51:03 +08:00
ningyv cb93e5c5aa Merge pull request #95 from xpack-ai/feat/resource-group-management
chore: upgrade Next.js to version 15.5.9
2025-12-22 16:26:50 +08:00
lcx 5ce7cc4a2a chore: upgrade Next.js to version 15.5.9 2025-12-22 16:25:07 +08:00
Dot.L 6d33d99d94 Merge pull request #94 from xpack-ai/feature/resource_group
update 1.2.0 upgrade sql
2025-12-22 13:48:08 +08:00
Liujian 15fe7b4aff update 1.2.0 upgrade sql 2025-12-22 13:47:41 +08:00
Dot.L 8f340cb3d5 Merge pull request #93 from xpack-ai/feature/resource_group
Resource group functionality complete
2025-12-22 11:08:57 +08:00
Liujian dab04242e6 Resource group service list sorted in descending order of creation time 2025-12-22 11:07:54 +08:00
ningyv a1740ab227 Merge pull request #92 from xpack-ai/feat/resource-group-management
Feat/resource group management
2025-12-19 18:30:05 +08:00
Dot.L ae57e5b431 Merge pull request #91 from xpack-ai/feature/resource_group
Feature/resource group
2025-12-18 15:50:24 +08:00
Liujian 8abc7469cd fix: service configuration information reset when "Update from OpenAPI" 2025-12-18 15:43:18 +08:00
Liujian 2309de4025 1. fix: charge fees even if the call tool fails due to MCP service not being available/under maintenance.
2. fix: OpenAPI requestBody Not Parsed for MCP Tools
2025-12-18 15:19:32 +08:00
ningyv 06b71995f3 Merge pull request #90 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-18 15:19:19 +08:00
lcx c675b273a8 feat: resource-group-management 2025-12-18 15:18:23 +08:00
ningyv 52c135a7c6 Merge pull request #89 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-18 14:19:56 +08:00
lcx fbb06d3c53 feat: resource-group-management 2025-12-18 14:17:32 +08:00
Dot.L 2c5c28c74f Merge pull request #88 from xpack-ai/feature/resource_group
fix bug
2025-12-18 11:29:37 +08:00
Liujian ab04738aff fix bug 2025-12-18 11:28:50 +08:00
ningyv 1eb0e23971 Merge pull request #87 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-18 11:21:26 +08:00
lcx 0ae8a4037d feat: resource-group-management 2025-12-18 11:20:07 +08:00
Dot.L a0c2bfe9a6 Merge pull request #86 from xpack-ai/feature/resource_group
fix bug
2025-12-18 11:10:28 +08:00
Liujian 5fa4d25e44 fix bug 2025-12-18 11:10:00 +08:00
ningyv 9f55110fb3 Merge pull request #85 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-18 10:32:49 +08:00
lcx 5fd1025340 feat: resource-group-management 2025-12-18 10:31:56 +08:00
Dot.L 01cbdbe5b0 Merge pull request #84 from xpack-ai/feature/resource_group
fix bug
2025-12-17 19:07:44 +08:00
Liujian a744f5a6c4 1. fix: No reject when input domain with special character like "test_domain.com"
2. fix: When updating service with "Update from OpenAPI" in Tools Management tab, Tool URL is removed, when reloading it is displayed again.
2025-12-17 19:05:44 +08:00
ningyv 0e58492387 Merge pull request #83 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-17 18:47:54 +08:00
lcx d518efb843 feat: resource-group-management 2025-12-17 18:46:49 +08:00
Dot.L 8fabe93710 Merge pull request #82 from xpack-ai/feature/resource_group
Feature/resource group
2025-12-17 14:44:48 +08:00
Liujian 924bee4a96 Optimize login failure message 2025-12-17 14:44:16 +08:00
Liujian 2dcd42a546 MCP calls introduce resource group restrictions. 2025-12-17 14:33:31 +08:00
Liujian f416f4c278 Merge remote-tracking branch 'origin/dev' into feature/resource_group 2025-12-17 14:13:07 +08:00
ningyv 1b6d3bc5bd Merge pull request #81 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-16 18:40:16 +08:00
lcx 5d30306ad7 feat: resource-group-management 2025-12-16 18:39:04 +08:00
Dot.L 127327e226 Merge pull request #80 from xpack-ai/feature/resource_group
fix api: /api/web/mcp_service_info
2025-12-16 17:57:41 +08:00
Liujian c82718e155 fix api: /api/web/mcp_service_info 2025-12-16 17:56:38 +08:00
Dot.L 6ad1e01814 Merge pull request #79 from xpack-ai/feature/resource_group
Add an accessible service ID field to user information.
2025-12-16 17:44:51 +08:00
Liujian 1c6773a95b Add an accessible service ID field to user information. 2025-12-16 17:44:25 +08:00
ningyv b74a042f75 Merge pull request #78 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-16 15:48:13 +08:00
lcx c5a020c65c feat: resource-group-management 2025-12-16 15:47:11 +08:00
ningyv 61004e4686 Merge pull request #77 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-16 15:37:06 +08:00
lcx ff870630fa feat: resource-group-management 2025-12-16 15:36:16 +08:00
Dot.L 1da7e2a618 Merge pull request #76 from xpack-ai/feature/resource_group
Newly registered users use the default resource group.
2025-12-16 15:03:45 +08:00
Liujian de4b1bef32 Newly registered users use the default resource group. 2025-12-16 14:56:18 +08:00
Dot.L f5ba03ca33 Merge pull request #75 from xpack-ai/feature/resource_group
Added API:/api/mcp/service/resource_group/list/unbind
2025-12-16 14:46:19 +08:00
Liujian b00fca810d Added API:/api/mcp/service/resource_group/list/unbind 2025-12-16 14:45:45 +08:00
Dot.L 132f26e565 Merge pull request #74 from xpack-ai/feature/resource_group
Added API: /api/resource_group/service/list/unbind
2025-12-16 14:33:19 +08:00
Liujian c5854a1d6f Added API: /api/resource_group/service/list/unbind 2025-12-16 14:31:28 +08:00
ningyv d0caf957fe Merge pull request #73 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-16 14:30:17 +08:00
lcx fc3f633141 feat: resource-group-management 2025-12-16 14:29:18 +08:00
ningyv ada170e525 Merge pull request #72 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-16 14:20:53 +08:00
lcx 95ec31d5c0 feat: resource-group-management 2025-12-16 14:19:42 +08:00
Dot.L a6242af7b1 Merge pull request #71 from xpack-ai/feature/resource_group
fix: fail to delete resource group
2025-12-16 13:55:06 +08:00
Liujian 028de0338e fix: fail to delete resource group 2025-12-16 13:54:36 +08:00
Dot.L e6a197e709 Merge pull request #70 from xpack-ai/feature/resource_group
Service binding resource group related interfaces completed
2025-12-16 11:18:00 +08:00
Liujian 61a313d8ff Service binding resource group related interfaces completed 2025-12-16 11:16:56 +08:00
ningyv bbe94deedb Merge pull request #69 from xpack-ai/feat/resource-group-management
feat:  resource-group-management
2025-12-15 19:19:58 +08:00
lcx 5c90b8e1ca feat: resource-group-management 2025-12-15 18:52:37 +08:00
Dot.L 23f3c07d6b Merge pull request #68 from xpack-ai/feature/resource_group
update api: /api/mcp/service/list/simple
2025-12-15 18:15:47 +08:00
Liujian 27f76d5cf0 update api: /api/mcp/service/list/simple 2025-12-15 18:14:51 +08:00
Dot.L 732fefeb7e Merge pull request #67 from xpack-ai/feature/resource_group
update api: /api/resource_group_info
2025-12-15 18:08:57 +08:00
Liujian 6fb71a48fe update api: /api/resource_group_info 2025-12-15 18:08:16 +08:00
Dot.L 3daa8eaec1 Merge pull request #66 from xpack-ai/feature/resource_group
Added default resource groups: allow all and deny all
2025-12-15 17:59:08 +08:00
Liujian 811618d8e6 Added default resource groups: allow all and deny all 2025-12-15 17:58:33 +08:00
Dot.L 67819ad4d6 Merge pull request #65 from xpack-ai/feature/resource_group
finish resource group api
2025-12-15 16:55:36 +08:00
Liujian 6405713314 finish resource group api 2025-12-15 16:54:37 +08:00
riverLethe 60a6318663 fix:set mcp server edit rules, server id and server name change rule is max length 255 2025-12-11 18:14:32 +08:00
riverLethe 3e83446a2c fix:set mcp server edit rules, server id and server name change rule is max length 255 2025-12-11 18:14:04 +08:00
Dot.L d725e9d896 Merge pull request #64 from xpack-ai/feature/mcp
Check if base_url is valid
2025-12-08 10:17:17 +08:00
riverLethe 68c4b2fcc2 Merge branch 'main' of https://github.com/xpack-ai/XPack-MCP-Market 2025-12-08 09:08:25 +08:00
riverLethe 96db00418c feat:Add more constraints for server name, server ID, and api endpoint. 2025-12-08 09:08:09 +08:00
Liujian 2def6457fe Merge remote-tracking branch 'origin/main' into feature/mcp 2025-12-07 15:54:19 +08:00
Liujian b9123d68a0 Check if base_url is valid 2025-12-07 15:51:32 +08:00
Dot.L ebbf9b22da Merge pull request #63 from xpack-ai/feature/mcp
Bug fixes and improved prompts
2025-12-07 14:09:15 +08:00
Liujian eace543d74 Check if the price is a positive number. 2025-12-07 14:03:32 +08:00
Liujian 73cd1a01a0 Fix: Issue where billing continued even after calling the mcp tool failed. 2025-12-07 13:46:21 +08:00
Liujian 8186b4c0b5 fix: User Dashboard - AuthKey Analytics: display Total spending discrepancy 2025-12-06 00:50:36 +09:00
Liujian 5023e4494c fix: The balance field has an incorrect data type; it should be Decimal. 2025-12-05 23:50:41 +09:00
Liujian e2d360d5de fix: Balance Doubled When Depositing Funds 2025-12-05 22:57:44 +09:00
Liujian 948046948a fix:Relate to transaction_id value when admin recharge for user 2025-12-05 21:50:48 +09:00
Liujian 4e3fd1afaf fix: login failed 2025-12-05 12:17:49 +09:00
Liujian e2ae502b48 fix bug:Admin upload image should support format GIF, SVG to update logo 2025-12-05 11:02:07 +09:00
Liujian 6561435a38 Merge remote-tracking branch 'origin/main' into feature/mcp 2025-12-05 10:59:48 +09:00
Liujian 1846aafc1e fix bug:
1. Service_type do not set after add server
2. Issue relate pricing when "Update from OpenAPI"
3. Failed to set SQLAlchemy cache for key Error
4. Request Body Logging in Internal Service
5. Deleted API Key Remains Valid for 5 Minutes
2025-12-05 10:27:19 +09:00
riverLethe 54654b386d feat: Upgrade Next.js and refine password/amount restrictions
This commit addresses several key updates and fixes:

1.  **Security Update:** Upgraded Next.js to fix the vulnerability identified as **CVE-2025-55182**.
2.  **Password Policy:** Globally adjusted the password requirement for "change password" operations to a minimum length of **6 characters**.
3.  **Validation Improvement:** Enhanced validation logic for amount fields during MCP (Multi-Currency Purchase/Payment, assuming this acronym) creation to ensure proper limits and constraints are applied.
2025-12-04 17:43:59 +08:00
Dot.L 755d48a2f8 Merge pull request #61 from xpack-ai/feature/mcp
Update client IP acquisition logic
2025-11-26 18:02:54 +08:00
Liujian 284880a170 Update client IP acquisition logic 2025-11-26 18:02:10 +08:00
Dot.L 950b516081 Merge pull request #60 from xpack-ai/feature/mcp
Email captcha rate limiting fix && CORS tightening via configuration
2025-11-26 17:08:41 +08:00
Liujian 0088a7b447 Merge remote-tracking branch 'origin/main' into feature/mcp 2025-11-26 17:00:29 +08:00
Liujian 19f646c318 Email captcha rate limiting fix && CORS tightening via configuration 2025-11-26 16:58:54 +08:00
Dot.L 115ac5caf7 Merge pull request #59 from xpack-ai/feature/mcp
repairing potential risks
2025-11-26 16:39:29 +08:00
Liujian 798082934e Merge remote-tracking branch 'origin/main' into feature/mcp 2025-11-26 16:21:40 +08:00
Liujian a017b0fa93 repairing potential risks 2025-11-26 16:16:23 +08:00
Liujian 877dbb6a4e MCP session keys use client fingerprints to distinguish requests from different clients. 2025-11-26 15:09:35 +08:00
Dot.L 523265e550 Merge pull request #58 from xpack-ai/feature/mcp
Payment information encryption and  wait for the initial connection to initialize successfully before processing the request
2025-11-14 18:11:01 +08:00
Liujian 5d2db84d75 update env example 2025-11-14 17:47:31 +08:00
Liujian 4826859152 Payment information encryption 2025-11-14 16:58:08 +08:00
Liujian 92f8b68f0e A new connection recovery mechanism has been added in the event of a network outage. 2025-11-14 15:50:39 +08:00
Liujian 87a4b6e2de Wait for the initial connection to initialize successfully before processing the request. 2025-11-14 15:50:00 +08:00
Dot.L 58d30344f5 Merge pull request #57 from xpack-ai/feature/mcp
Completed: OutputSchema functionality added to the MCP tools list.
2025-11-07 17:23:54 +08:00
Liujian a6064035bd Completed: OutputSchema functionality added to the MCP tools list. 2025-11-07 17:23:24 +08:00
Dot.L 141fb4758f Merge pull request #56 from xpack-ai/feature/mcp
fix bug: API enabled status error when updating service Swagger docum…
2025-11-07 16:56:07 +08:00
Liujian 5450027bbc fix bug: API enabled status error when updating service Swagger documentation 2025-11-07 16:53:25 +08:00
riverLethe 721a213bbf fix:hidden server length in marketpalce card panel 2025-11-07 14:03:38 +08:00
Dot.L 9ce81f5012 Merge pull request #55 from xpack-ai/feature/mcp
MCP tool list response adds outputSchema
2025-11-07 10:32:07 +08:00
Liujian a28f3bb680 MCP tool list response adds outputSchema 2025-11-07 10:31:29 +08:00
Dot.L 14e45235b4 Merge pull request #54 from xpack-ai/feature/synchronize_saas
update mcp session gc logic
2025-10-23 17:55:51 +08:00
Liujian 6a69d678fd update mcp session gc logic 2025-10-23 17:55:24 +08:00
Dot.L 48ba7ffd96 Merge pull request #53 from xpack-ai/feature/synchronize_saas
Translate Chinese into English
2025-10-22 23:21:23 +08:00
Liujian faa1f552e6 Translate Chinese into English 2025-10-22 23:20:57 +08:00
riverLethe b2bd2e30dd feat/ui:The server configuration allows switching between Streamable HTTP and SSE. 2025-10-22 19:59:49 +08:00
Dot.L e25e119ba1 Merge pull request #52 from xpack-ai/feature/synchronize_saas
support streamable http
2025-10-22 19:14:26 +08:00
Liujian eb1811fa3a support streamable http 2025-10-22 19:01:11 +08:00
Dot.L ee65da1665 Merge pull request #51 from xpack-ai/feature/synchronize_saas
Update Deployment Tutorial
2025-10-20 18:22:42 +08:00
Liujian bda95f756a Update Deployment Tutorial 2025-10-20 17:15:03 +08:00
Liujian ae7b6d20e4 Update Deployment Tutorial 2025-10-20 17:11:52 +08:00
Liujian 0d1dff05d6 Merge remote-tracking branch 'origin/main' into feature/synchronize_saas 2025-10-20 15:17:02 +08:00
riverLethe 434518b2b3 feat/op:uploads path use rewrite 2025-10-20 14:57:33 +08:00
Dot.L 3321efc3d4 Merge pull request #50 from xpack-ai/feature/synchronize_saas
Update Deployment Tutorial
2025-10-20 13:42:35 +08:00
Liujian 0313ced503 Update Deployment Tutorial 2025-10-20 09:19:15 +08:00
riverLethe d17e5e95dd feat/ui:concole stats top server support to show deleted item 2025-10-17 19:11:35 +08:00
Dot.L 41f9d74c5e Merge pull request #49 from xpack-ai/feature/synchronize_saas
fix drop service bug
2025-10-17 18:53:49 +08:00
Liujian 7f17b22896 fix drop service bug 2025-10-17 18:53:15 +08:00
Dot.L 186ba8ca81 Merge pull request #48 from xpack-ai/feature/synchronize_saas
Feature/synchronize saas
2025-10-17 18:38:51 +08:00
Liujian 777649f82b Delete service using software deletion 2025-10-17 18:36:58 +08:00
Liujian f042cdf911 Add annotations and translate Chinese into English 2025-10-17 16:26:14 +08:00
Liujian 7c75c07216 fix: redis cache bug 2025-10-17 15:26:01 +08:00
riverLethe 33549167d9 fix/op:if user not input api endpoint when update mcp server,need to disable save 2025-10-17 15:04:21 +08:00
Liujian 0ae689f9fe Merge remote-tracking branch 'origin/main' into feature/synchronize_saas 2025-10-17 13:47:47 +08:00
Dot.L 21c72f17ba Merge pull request #47 from xpack-ai/feature/synchronize_saas
update billing message logic
2025-10-17 13:38:22 +08:00
Liujian 76e8dbc083 update billing message logic 2025-10-17 13:37:58 +08:00
Dot.L 96abfc2752 Merge pull request #46 from xpack-ai/feature/synchronize_saas
fix mcp bug
2025-10-17 11:46:29 +08:00
Liujian a992866058 fix mcp bug 2025-10-17 11:46:08 +08:00
Dot.L 39db3d9a94 Merge pull request #45 from xpack-ai/feature/synchronize_saas
fix mcp bug
2025-10-17 10:37:45 +08:00
Liujian c71a416046 fix mcp bug 2025-10-17 10:36:24 +08:00
Dot.L 9a605cc9f0 Merge pull request #44 from xpack-ai/feature/synchronize_saas
Feature/synchronize saas
2025-10-17 10:27:21 +08:00
Liujian e8aaeefe85 update mcp param key 2025-10-17 10:13:19 +08:00
riverLethe 51d41bc3d4 feat/ui:update translation json 2025-10-17 10:04:49 +08:00
Liujian c1b224af46 Merge remote-tracking branch 'origin/main' into feature/synchronize_saas 2025-10-16 17:44:14 +08:00
riverLethe 521c1b7a07 feat:1.1 UI/UX 2025-10-16 17:35:45 +08:00
Dot.L 3c9b037ba7 Merge pull request #43 from xpack-ai/feature/synchronize_saas
Feature/synchronize saas
2025-10-16 16:55:30 +08:00
Liujian f3a1107838 update create user bug 2025-10-16 16:55:09 +08:00
Liujian d53fe311a3 update sql 2025-10-16 15:54:20 +08:00
Dot.L 407081adfc Merge pull request #42 from xpack-ai/feature/synchronize_saas
fix system config bug
2025-10-16 15:29:27 +08:00
Liujian 09704af14a fix system config bug 2025-10-16 15:28:52 +08:00
Dot.L 46d5040068 Merge pull request #41 from xpack-ai/feature/synchronize_saas
fix stats analystic bug
2025-10-16 14:52:14 +08:00
Liujian 3faa35e970 fix stats analystic bug 2025-10-16 14:51:47 +08:00
Dot.L a0e7662f76 Merge pull request #40 from xpack-ai/feature/synchronize_saas
finish stats analytics api
2025-10-16 11:17:08 +08:00
Liujian d49144afe9 finish stats analytics api 2025-10-16 11:16:41 +08:00
Dot.L 81637440d6 Merge pull request #39 from xpack-ai/feature/synchronize_saas
fix  bug
2025-10-16 10:03:37 +08:00
Liujian c949aac528 fix bug 2025-10-16 10:03:10 +08:00
Dot.L 5e08cd2ff5 Merge pull request #38 from xpack-ai/feature/synchronize_saas
Synchronize mcp service api
2025-10-15 14:50:30 +08:00
Liujian c790fbef51 Synchronize mcp service api 2025-10-15 14:49:20 +08:00
Dot.L bb9dd11869 Merge pull request #37 from xpack-ai/feature/synchronize_saas
Feature/synchronize saas
2025-10-14 18:04:42 +08:00
Liujian a0b827b32e Synchronize system configuration related APIs 2025-10-14 18:04:02 +08:00
riverLethe 7e135f4949 fix:fetch platform config error will influence project build bug 2025-10-09 09:15:36 +08:00
Dot.L 4d230db82b Merge pull request #36 from xpack-ai/feature/ui-1.0.2
feat/ui-1.0.2:when about page content is empty,need to hide about nav…
2025-10-07 09:05:51 +08:00
riverLethe 92aa83cb71 feat/ui-1.0.2:when about page content is empty,need to hide about navigation 2025-09-28 14:19:29 +08:00
Liujian ead0689b81 add wxpay 2025-08-01 18:27:19 +08:00
Liujian 5f621308ea add wxpay 2025-08-01 18:26:40 +08:00
314 changed files with 19533 additions and 20367 deletions

No files matched your search

+17 -2
View File
@@ -6,7 +6,7 @@ MYSQL_PASSWORD=mysql_ZTdhRB
MYSQL_DB=xpack
# 服务端口配置
API_PORT=8000
API_PORT=8002
ADMIN_PORT=8001
# 调试配置
@@ -24,4 +24,19 @@ RABBITMQ_HOST=xpack-rabbitmq
RABBITMQ_PORT=5672
RABBITMQ_USER=rabbitmq
RABBITMQ_PASSWORD=rabbitmq_Gs123dA
RABBITMQ_VHOST=/
RABBITMQ_VHOST=/
# Billing queue / retry settings
BILLING_QUEUE_NAME=billing.api.calls
# Max retry attempts (excluding initial consumption)
BILLING_RETRY_TIMES=3
# Base delay seconds for exponential backoff: base * 2^retry_count
BILLING_RETRY_BASE_DELAY_SECONDS=30
# Max delay seconds cap
BILLING_RETRY_MAX_DELAY_SECONDS=1800
# Payment config encryption key (Base64-encoded 32-byte random value for AES-GCM)
# Quick generation: python -c "import os,base64; print(base64.b64encode(os.urandom(32)).decode())"
PAYMENT_CONFIG_SECRET_KEY=uyyhfMJ+xpEE+IC5mPigpscekkR2ucz6Sj7sHYLhJQA=
# Optional: key ID used to support key rotation identification
PAYMENT_CONFIG_KEY_ID=default
+1
View File
@@ -0,0 +1 @@
/mcp.json
+3 -4
View File
@@ -135,8 +135,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
@@ -183,8 +182,8 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. Im Browser über Port 3000 öffnen
* **Admin‑Login**: http://{IP}:3000/admin-signin
4. Im Browser über Port 8000 öffnen
* **Admin‑Login**: http://{IP}:8000/admin-signin
* **Benutzer**: admin
* **Passwort**: 123456789
</details>
+1 -2
View File
@@ -136,8 +136,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
+3 -4
View File
@@ -135,8 +135,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
@@ -183,8 +182,8 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. Accédez à l’interface sur le port 3000
* **Connexion admin** : http://{IP}:3000/admin-signin
4. Accédez à l’interface sur le port 8000
* **Connexion admin** : http://{IP}:8000/admin-signin
* **Utilisateur** : admin
* **Mot de passe** : 123456789
</details>
+3 -4
View File
@@ -135,8 +135,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
@@ -183,8 +182,8 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. ブラウザでポート 3000 にアクセス
* **管理画面ログイン**: http://{IP}:3000/admin-signin
4. ブラウザでポート 8000 にアクセス
* **管理画面ログイン**: http://{IP}:8000/admin-signin
* **管理ユーザー**: admin
* **管理パスワード**: 123456789
</details>
+3 -4
View File
@@ -135,8 +135,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
@@ -183,8 +182,8 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. 브라우저에서 3000 포트로 접속
* **관리자 로그인 주소**: http://{IP}:3000/admin-signin
4. 브라우저에서 8000 포트로 접속
* **관리자 로그인 주소**: http://{IP}:8000/admin-signin
* **관리자 계정**: admin
* **관리자 비밀번호**: 123456789
</details>
+2 -2
View File
@@ -100,7 +100,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
支持系统包括:
- CentOS 7.9 / 8.5
- Ubuntu 20.04 / 22.04
- Ubuntu 20.04 / 22.04 / 24.04
- Debian 12.4
- 阿里云 Linux 2.1903 / 3.2104
@@ -125,7 +125,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
docker-compose up -d
```
4. 打开浏览器访问 `http://localhost:3000` 使用平台
4. 打开浏览器访问 `http://localhost:8000` 使用平台
</details>
+3 -4
View File
@@ -136,8 +136,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80"
depends_on:
- xpack-mysql
- xpack-redis
@@ -184,8 +183,8 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. 瀏覽器透過 3000 埠連線
* **管理員登入**:http://{IP}:3000/admin-signin
4. 瀏覽器透過 8000 埠連線
* **管理員登入**:http://{IP}:8000/admin-signin
* **帳號**:admin
* **密碼**:123456789
</details>
+14 -7
View File
@@ -141,8 +141,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
networks:
- xpack
ports:
- "3000:3000"
- "8002:8002"
- "8000:80" # Map port 8000 of the container to port 80 of the host, if you want to access XPack-MCP-Market in your browser at port 8000
depends_on:
- xpack-mysql
- xpack-redis
@@ -190,9 +189,9 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
<br>
4. Access `XPack-MCP-Market` in your browser at port 3000
4. Access `XPack-MCP-Market` in your browser at port 8000
* **Admin User Login Address**: http://{IP}:3000/admin
* **Admin User Login Address**: http://{IP}:8000/admin
* **Admin User**: admin
* **Admin Password**: 123456789
</details>
@@ -213,8 +212,16 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
> Requirements:
> - Node >= 22.x
> - Pnpm >= 10.x
1. Execute the frontend build script
1. Configure environment variable NEXT_PUBLIC_API_URL:
```
vi frontend/.env
```
File content:
```
NEXT_PUBLIC_API_URL=http://127.0.0.1:8001
```
2. Execute the frontend build script
```
cd scripts && ./frontend_build.sh && cd ../
```
@@ -270,7 +277,7 @@ curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
```
### Docker Build
```
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.1.0 -f ./scripts/Dockerfile ./
```
</details>
+1 -1
View File
@@ -9,7 +9,7 @@
!.yarn/plugins
!.yarn/releases
!.yarn/versions
/pnpm-lock.yaml
# testing
/coverage
+7 -7
View File
@@ -14,7 +14,7 @@ XPack WebUI is the flagship frontend interface for the MCP Store ecosystem, desi
### ✨ Key Features
- **🛍️ Comprehensive Marketplace**: Browse, search, and discover MCP services across multiple categories
- **🛍️ Comprehensive Marketplace**: Browse, search, and discover MCP servers across multiple categories
- **👤 Multi-tier Authentication**: Secure user and admin authentication systems
- **⚙️ Advanced Admin Console**: Complete service management, user administration, and revenue tracking
- **🌐 Full Internationalization**: Native support for English and Chinese with extensible i18n framework
@@ -110,7 +110,7 @@ src/
│ ├── console/ # Admin console components
│ ├── dashboard/ # User dashboard components
│ ├── marketplace/ # Marketplace components
│ ├── mcp-services/ # MCP service management
│ ├── mcp-services/ # MCP server management
│ ├── user-management/ # User administration
│ ├── revenue-management/# Revenue tracking
│ ├── system-setting/ # System configuration
@@ -129,7 +129,7 @@ src/
│ └── utils/ # Utility functions
├── services/ # Backend API integration
│ ├── marketplaceService.ts # Marketplace API
│ ├── mcpService.ts # MCP service API
│ ├── mcpService.ts # MCP server API
│ ├── userService.ts # User management API
│ ├── revenueService.ts # Revenue tracking API
│ ├── paymentChannelService.ts # Payment API
@@ -139,7 +139,7 @@ src/
├── hooks/ # App-specific hooks
│ ├── useAdminLogin.tsx # Admin authentication
│ ├── useLogin.tsx # User authentication
│ ├── useMCPServicesList.ts # MCP services data
│ ├── useMCPServicesList.ts # MCP servers data
│ ├── useMCPServiceDetail.ts # Service details
│ ├── useUserManagement.ts # User management
│ ├── useRevenueManagement.ts # Revenue data
@@ -150,7 +150,7 @@ src/
├── types/ # TypeScript type definitions
│ ├── admin.ts # Admin types
│ ├── dashboard.ts # Dashboard types
│ ├── mcp-service.ts # MCP service types
│ ├── mcp-service.ts # MCP server types
│ ├── payment.ts # Payment types
│ ├── revenue.ts # Revenue types
│ ├── system.ts # System types
@@ -166,7 +166,7 @@ src/
### Marketplace Experience
- **Service Discovery**: Advanced search and filtering capabilities for MCP services
- **Service Discovery**: Advanced search and filtering capabilities for MCP servers
- **Service Catalog**: Browse services by categories with detailed information
- **Service Details**: Comprehensive service documentation and API specifications
- **Installation Guides**: Step-by-step integration instructions for developers
@@ -178,7 +178,7 @@ src/
### Admin Console
- **MCP Services Management**: Complete CRUD operations for MCP services
- **MCP Servers Management**: Complete CRUD operations for MCP servers
- Service creation and editing with OpenAPI generator
- OpenAPI document parsing from files or URLs
- Service status management (enabled/disabled)
+2 -2
View File
@@ -47,7 +47,7 @@ const result = await rpcClient.call("marketplace.getServices", {
Located in `src/services/marketplaceService.ts`:
```typescript
// Fetch all MCP services
// Fetch all MCP servers
export async function fetchServices(): Promise<ServiceData[]>;
// Fetch service by ID
@@ -352,7 +352,7 @@ function ServicesPage() {
### Public Endpoints
- `GET /api/web/mcp_services` - List all MCP services
- `GET /api/web/mcp_services` - List all MCP servers
- `POST /api/web/mcp_service_info` - Get service details by ID
- `GET /api/web/categories` - List service categories
- `POST /api/auth/login` - User login
+4 -4
View File
@@ -58,7 +58,7 @@ src/
│ ├── console/ # Console management
│ ├── dashboard/ # Dashboard components
│ ├── marketplace/ # Marketplace components
│ ├── mcp-services/ # MCP service management
│ ├── mcp-services/ # MCP server management
│ ├── revenue-management/# Revenue tracking
│ ├── system-setting/ # System configuration
│ ├── user-management/ # User administration
@@ -77,7 +77,7 @@ src/
│ └── utils/ # Utility functions
├── services/ # Backend API integration
│ ├── marketplaceService.ts # Marketplace API
│ ├── mcpService.ts # MCP service API
│ ├── mcpService.ts # MCP server API
│ ├── userService.ts # User management API
│ ├── revenueService.ts # Revenue tracking API
│ ├── paymentChannelService.ts # Payment API
@@ -87,7 +87,7 @@ src/
├── hooks/ # App-specific hooks
│ ├── useAdminLogin.tsx # Admin authentication
│ ├── useLogin.tsx # User authentication
│ ├── useMCPServicesList.ts # MCP services data
│ ├── useMCPServicesList.ts # MCP servers data
│ ├── useMCPServiceDetail.ts # Service details
│ ├── useUserManagement.ts # User management
│ ├── useRevenueManagement.ts # Revenue data
@@ -98,7 +98,7 @@ src/
├── types/ # TypeScript type definitions
│ ├── admin.ts # Admin types
│ ├── dashboard.ts # Dashboard types
│ ├── mcp-service.ts # MCP service types
│ ├── mcp-service.ts # MCP server types
│ ├── payment.ts # Payment types
│ ├── revenue.ts # Revenue types
│ ├── system.ts # System types
+159 -152
View File
@@ -16,34 +16,34 @@ XPack WebUI supports multiple languages using react-i18next. This guide covers h
The i18n system is configured in `src/shared/lib/i18n.ts`:
```typescript
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: process.env.NODE_ENV === 'development',
fallbackLng: "en",
debug: process.env.NODE_ENV === "development",
interpolation: {
escapeValue: false,
},
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
detection: {
order: ['localStorage', 'navigator', 'htmlTag'],
caches: ['localStorage'],
},
})
export default i18n
backend: {
loadPath: "/locales/{{lng}}/{{ns}}.json",
},
detection: {
order: ["localStorage", "navigator", "htmlTag"],
caches: ["localStorage"],
},
});
export default i18n;
```
### Translation Files Structure
@@ -73,7 +73,7 @@ import { useTranslation } from '@/shared/lib/useTranslation'
function MyComponent() {
const { t } = useTranslation()
return (
<div>
<h1>{t('Welcome')}</h1>
@@ -90,7 +90,7 @@ import { useTranslation } from '@/shared/lib/useTranslation'
function MarketplaceComponent() {
const { t } = useTranslation('marketplace')
return (
<div>
<h1>{t('title')}</h1>
@@ -106,7 +106,7 @@ function MarketplaceComponent() {
function AdminComponent() {
const { t: tCommon } = useTranslation('common')
const { t: tAdmin } = useTranslation('admin')
return (
<div>
<button>{tCommon('save')}</button>
@@ -139,7 +139,7 @@ function AdminComponent() {
```typescript
function Component() {
const { t } = useTranslation()
return (
<div>
<h1>{t('welcome')}</h1>
@@ -172,7 +172,7 @@ function Component() {
```typescript
function UserProfile() {
const { t } = useTranslation()
return (
<div>
<h1>{t('user.profile.title')}</h1>
@@ -198,7 +198,7 @@ function UserProfile() {
function Component() {
const { t } = useTranslation()
const user = { name: 'John', lastLogin: new Date() }
return (
<div>
<h1>{t('greeting', { name: user.name })}</h1>
@@ -227,7 +227,7 @@ function Component() {
function Component() {
const { t } = useTranslation()
const count = 5
return (
<div>
<p>{t('item', { count })}</p>
@@ -255,7 +255,7 @@ function Component() {
function Component() {
const { t } = useTranslation()
const userGender = 'male'
return (
<button>
{t('button.save', { context: userGender })}
@@ -278,11 +278,11 @@ const languages = [
function LanguageSelector() {
const { i18n, t } = useTranslation()
const changeLanguage = (languageCode: string) => {
i18n.changeLanguage(languageCode)
}
return (
<Select
label={t('common.language')}
@@ -305,24 +305,27 @@ function LanguageSelector() {
### Programmatic Language Change
```typescript
import { useTranslation } from '@/shared/lib/useTranslation'
import { useTranslation } from "@/shared/lib/useTranslation";
function useLanguage() {
const { i18n } = useTranslation()
const changeLanguage = useCallback((language: string) => {
i18n.changeLanguage(language)
// Optionally save to user preferences
localStorage.setItem('preferred-language', language)
}, [i18n])
const getCurrentLanguage = () => i18n.language
const { i18n } = useTranslation();
const changeLanguage = useCallback(
(language: string) => {
i18n.changeLanguage(language);
// Optionally save to user preferences
localStorage.setItem("preferred-language", language);
},
[i18n]
);
const getCurrentLanguage = () => i18n.language;
return {
currentLanguage: i18n.language,
changeLanguage,
getCurrentLanguage,
}
};
}
```
@@ -373,20 +376,20 @@ i18n.init({
// ... other config
interpolation: {
format: (value, format, lng) => {
if (format === 'uppercase') return value.toUpperCase()
if (format === 'currency') {
if (format === "uppercase") return value.toUpperCase();
if (format === "currency") {
return new Intl.NumberFormat(lng, {
style: 'currency',
currency: 'USD'
}).format(value)
style: "currency",
currency: "USD",
}).format(value);
}
if (format === 'date') {
return new Intl.DateTimeFormat(lng).format(value)
if (format === "date") {
return new Intl.DateTimeFormat(lng).format(value);
}
return value
}
}
})
return value;
},
},
});
```
```json
@@ -401,27 +404,30 @@ i18n.init({
```typescript
// Custom hook with additional features
export function useAppTranslation(namespace?: string) {
const { t, i18n } = useTranslation(namespace)
const tWithFallback = useCallback((key: string, options?: any) => {
const translation = t(key, options)
// Log missing translations in development
if (process.env.NODE_ENV === 'development' && translation === key) {
console.warn(`Missing translation for key: ${key}`)
}
return translation
}, [t])
const isRTL = i18n.language === 'ar' || i18n.language === 'he'
const { t, i18n } = useTranslation(namespace);
const tWithFallback = useCallback(
(key: string, options?: any) => {
const translation = t(key, options);
// Log missing translations in development
if (process.env.NODE_ENV === "development" && translation === key) {
console.warn(`Missing translation for key: ${key}`);
}
return translation;
},
[t]
);
const isRTL = i18n.language === "ar" || i18n.language === "he";
return {
t: tWithFallback,
i18n,
isRTL,
currentLanguage: i18n.language,
}
};
}
```
@@ -458,7 +464,7 @@ export function useAppTranslation(namespace?: string) {
// en/marketplace.json - Feature-specific translations
{
"title": "MCP Store",
"subtitle": "Discover and install MCP services",
"subtitle": "Discover and install MCP servers",
"search": {
"placeholder": "Search services...",
"noResults": "No services found",
@@ -482,42 +488,45 @@ export function useAppTranslation(namespace?: string) {
```typescript
// Validation script to check for missing translations
import fs from 'fs'
import path from 'path'
import fs from "fs";
import path from "path";
function validateTranslations() {
const localesDir = path.join(process.cwd(), 'public/locales')
const languages = fs.readdirSync(localesDir)
const baseLanguage = 'en'
const baseTranslations = loadTranslations(baseLanguage)
languages.forEach(lang => {
if (lang === baseLanguage) return
const translations = loadTranslations(lang)
const missingKeys = findMissingKeys(baseTranslations, translations)
const localesDir = path.join(process.cwd(), "public/locales");
const languages = fs.readdirSync(localesDir);
const baseLanguage = "en";
const baseTranslations = loadTranslations(baseLanguage);
languages.forEach((lang) => {
if (lang === baseLanguage) return;
const translations = loadTranslations(lang);
const missingKeys = findMissingKeys(baseTranslations, translations);
if (missingKeys.length > 0) {
console.warn(`Missing translations in ${lang}:`, missingKeys)
console.warn(`Missing translations in ${lang}:`, missingKeys);
}
})
});
}
function findMissingKeys(base: any, target: any, prefix = ''): string[] {
const missing: string[] = []
Object.keys(base).forEach(key => {
const fullKey = prefix ? `${prefix}.${key}` : key
function findMissingKeys(base: any, target: any, prefix = ""): string[] {
const missing: string[] = [];
Object.keys(base).forEach((key) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (!(key in target)) {
missing.push(fullKey)
} else if (typeof base[key] === 'object' && typeof target[key] === 'object') {
missing.push(...findMissingKeys(base[key], target[key], fullKey))
missing.push(fullKey);
} else if (
typeof base[key] === "object" &&
typeof target[key] === "object"
) {
missing.push(...findMissingKeys(base[key], target[key], fullKey));
}
})
return missing
});
return missing;
}
```
@@ -525,32 +534,32 @@ function findMissingKeys(base: any, target: any, prefix = ''): string[] {
```typescript
// Extract translation keys from components
import { parse } from '@babel/parser'
import traverse from '@babel/traverse'
import fs from 'fs'
import { parse } from "@babel/parser";
import traverse from "@babel/traverse";
import fs from "fs";
function extractTranslationKeys(filePath: string): string[] {
const code = fs.readFileSync(filePath, 'utf-8')
const code = fs.readFileSync(filePath, "utf-8");
const ast = parse(code, {
sourceType: 'module',
plugins: ['typescript', 'jsx']
})
const keys: string[] = []
sourceType: "module",
plugins: ["typescript", "jsx"],
});
const keys: string[] = [];
traverse(ast, {
CallExpression(path) {
if (
path.node.callee.type === 'Identifier' &&
path.node.callee.name === 't' &&
path.node.arguments[0]?.type === 'StringLiteral'
path.node.callee.type === "Identifier" &&
path.node.callee.name === "t" &&
path.node.arguments[0]?.type === "StringLiteral"
) {
keys.push(path.node.arguments[0].value)
keys.push(path.node.arguments[0].value);
}
}
})
return keys
},
});
return keys;
}
```
@@ -560,25 +569,25 @@ function extractTranslationKeys(filePath: string): string[] {
```typescript
// Good: Descriptive, hierarchical keys
t('marketplace.service.install.button')
t('user.profile.form.validation.email.required')
t('admin.dashboard.stats.users.total')
t("marketplace.service.install.button");
t("user.profile.form.validation.email.required");
t("admin.dashboard.stats.users.total");
// Bad: Generic, flat keys
t('button1')
t('error')
t('text')
t("button1");
t("error");
t("text");
```
### 2. Consistent Namespace Usage
```typescript
// Good: Feature-based namespaces
const { t } = useTranslation('marketplace')
const { t: tCommon } = useTranslation('common')
const { t } = useTranslation("marketplace");
const { t: tCommon } = useTranslation("common");
// Bad: Mixed namespace usage
const { t } = useTranslation() // Default namespace for everything
const { t } = useTranslation(); // Default namespace for everything
```
### 3. Translation Context
@@ -601,10 +610,8 @@ const { t } = useTranslation() // Default namespace for everything
```typescript
// Good: Use interpolation
t('welcome.message', { userName: user.name })
// Bad: String concatenation
`Welcome, ${user.name}!`
t("welcome.message", { userName: user.name })// Bad: String concatenation
`Welcome, ${user.name}!`;
```
### 5. Error Message Translations
@@ -649,7 +656,7 @@ describe('MyComponent', () => {
renderWithI18n(<MyComponent />)
expect(screen.getByText('Welcome')).toBeInTheDocument()
})
it('renders in Chinese', async () => {
await i18n.changeLanguage('zh-CN')
renderWithI18n(<MyComponent />)
@@ -662,12 +669,12 @@ describe('MyComponent', () => {
```typescript
// test-utils/i18n-for-tests.ts
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
i18n.use(initReactI18next).init({
lng: 'en',
fallbackLng: 'en',
lng: "en",
fallbackLng: "en",
debug: false,
interpolation: {
escapeValue: false,
@@ -675,20 +682,20 @@ i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
'Welcome': 'Welcome',
'Goodbye': 'Goodbye',
}
Welcome: "Welcome",
Goodbye: "Goodbye",
},
},
'zh-CN': {
"zh-CN": {
translation: {
'Welcome': '欢迎',
'Goodbye': '再见',
}
}
}
})
Welcome: "欢迎",
Goodbye: "再见",
},
},
},
});
export default i18n
export default i18n;
```
## Adding New Languages
@@ -704,10 +711,10 @@ export default i18n
```typescript
// Add to language selector
const languages = [
{ code: 'en', name: 'English', flag: '🇺🇸' },
{ code: 'zh-CN', name: '中文', flag: '🇨🇳' },
{ code: 'es', name: 'Español', flag: '🇪🇸' }, // New language
]
{ code: "en", name: "English", flag: "🇺🇸" },
{ code: "zh-CN", name: "中文", flag: "🇨🇳" },
{ code: "es", name: "Español", flag: "🇪🇸" }, // New language
];
```
### 3. Update i18n Configuration
@@ -716,12 +723,12 @@ const languages = [
// Add fallback languages if needed
i18n.init({
fallbackLng: {
'zh-CN': ['zh', 'en'],
'es': ['en'],
'default': ['en']
"zh-CN": ["zh", "en"],
es: ["en"],
default: ["en"],
},
// ... other config
})
});
```
This comprehensive i18n guide ensures consistent and maintainable internationalization throughout the XPack WebUI application.
This comprehensive i18n guide ensures consistent and maintainable internationalization throughout the XPack WebUI application.
-55
View File
@@ -1,55 +0,0 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
// Enable SSR
output: "standalone",
// Optimize images
images: {
domains: [],
unoptimized: false, // Enable image optimization for SSR
},
// Webpack configuration
webpack: (config) => {
return config;
},
// Redirect configuration
async redirects() {
return [];
},
async rewrites() {
return [
{
source: "/api/:path*",
destination: `${process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"}/api/:path*`,
},
{
source: "/uploads/:path*",
destination: `${process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"}/uploads/:path*`,
},
];
},
// Headers for better performance
async headers() {
return [
{
source: "/(.*)",
headers: [
{
key: "X-Content-Type-Options",
value: "nosniff",
},
{
key: "X-XSS-Protection",
value: "1; mode=block",
},
],
},
];
},
};
module.exports = nextConfig;
+41
View File
@@ -1,10 +1,15 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: false,
output: "standalone",
experimental: {
optimizePackageImports: ["@nextui-org/react"],
},
transpilePackages: ["@nextui-org/react", "@nextui-org/theme"],
images: {
remotePatterns: [
{
@@ -12,6 +17,42 @@ const nextConfig: NextConfig = {
hostname: "**",
},
],
unoptimized: false,
},
// Redirect configuration
async redirects() {
return [];
},
async rewrites() {
return [
{
source: "/uploads/:path*",
destination: `${
process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"
}/uploads/:path*`,
},
];
},
// Headers for better performance
async headers() {
return [
{
source: "/(.*)",
headers: [
{
key: "X-Content-Type-Options",
value: "nosniff",
},
{
key: "X-XSS-Protection",
value: "1; mode=block",
},
],
},
];
},
};
+9 -7
View File
@@ -16,12 +16,15 @@
"dependencies": {
"@hookform/resolvers": "^3.3.4",
"@iconify/react": "^5.0.2",
"@internationalized/date": "^3.10.1",
"@nextui-org/react": "^2.6.11",
"@nextui-org/theme": "^2.4.5",
"@tailwindcss/typography": "^0.5.16",
"@types/crypto-js": "^4.2.2",
"@uiw/react-markdown-preview": "^5.1.5",
"@uiw/react-md-editor": "^4.0.7",
"animejs": "^4.0.2",
"async_hooks": "^1.0.0",
"crypto-js": "^4.2.0",
"framer-motion": "^11.5.6",
"i18next": "^23.8.0",
@@ -30,15 +33,14 @@
"immer": "^10.0.3",
"lottie-react": "^2.4.1",
"lucide-react": "^0.475.0",
"next": "^15.3.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"next": "^16.1.5",
"react": "^19.1.4",
"react-dom": "^19.1.4",
"react-hook-form": "^7.49.3",
"react-hot-toast": "^2.4.1",
"react-hover-video-player": "^10.0.2",
"react-i18next": "^14.0.1",
"react-icons": "^5.3.0",
"react-markdown": "^10.1.0",
"recharts": "^2.15.1",
"simplex-noise": "^4.0.3",
"swr": "^2.2.4",
@@ -48,12 +50,12 @@
},
"devDependencies": {
"@types/node": "^20.11.0",
"@types/react": "^18.2.48",
"@types/react-dom": "^18.2.18",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@types/three": "^0.177.0",
"autoprefixer": "^10.4.17",
"eslint": "^8.56.0",
"eslint-config-next": "15.0.3",
"eslint-config-next": "16.1.5",
"postcss": "^8.4.33",
"tailwindcss": "^3.4.17",
"typescript": "^5.3.3"
-15851
View File
File diff suppressed because it is too large. Load diff
+242 -12
View File
@@ -1,13 +1,243 @@
{
"**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) services.": "**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) services.",
"It allows you to transform any OpenAPI into a monetizable MCP service and build your own API store in just minutes.": "It allows you to transform any OpenAPI into a monetizable MCP service and build your own API store in just minutes.",
"✨ With XPack, you can:": "✨ With XPack, you can:",
"- ✅ **One-click OpenAPI → MCP service config**": "- ✅ **One-click OpenAPI → MCP service config**",
"- 🧾 **SEO-friendly homepage + mcp service page**": "- 🧾 **SEO-friendly homepage + mcp service page**",
"- 💳 **Built-in billing (per-call)**": "- 💳 **Built-in billing (per-call)**",
"- 👥 **User account management**": "- 👥 **User account management**",
"- 🛠 **Support Stripe Payment**": "- 🛠 **Support Stripe Payment**",
"- 🔐 **Support Email & Google OAuth Sign in**": "- 🔐 **Support Email & Google OAuth Sign in**",
"Everything is open-source and licensed under **Apache 2.0** — ready for commercial use.": "Everything is open-source and licensed under **Apache 2.0** — ready for commercial use.",
"About Us": "About Us"
}
"Server Configuration": "Server Configuration",
"Subdomain": "Subdomain",
"Enter subdomain (e.g., mysite)": "Enter subdomain (e.g., mysite)",
"Subdomain is required": "Subdomain is required",
"Subdomain must contain only lowercase letters, numbers, and hyphens": "Subdomain must contain only lowercase letters, numbers, and hyphens",
"Subdomain must be between 3 and 63 characters": "Subdomain must be between 3 and 63 characters",
"Log in to your admin account to continue": "Log in to your admin account to continue",
"Your unique subdomain for the platform": "Your unique subdomain for the platform",
"Let's get started!": "Let's get started!",
"Welcome! It's time to set up Lethe Live.": "Welcome! It's time to set up Lethe Live.",
"Start a new Ghost publication": "Start a new Ghost publication",
"Customize your design": "Customize your design",
"Craft a look that reflects your brand and style": "Craft a look that reflects your brand and style",
"Explore the editor": "Explore the editor",
"Build your audience": "Build your audience",
"Share your publication": "Share your publication",
"More questions? Check out our": "More questions? Check out our",
"Help Center": "Help Center",
"Skip onboarding": "Skip onboarding",
"Great! All tasks completed!": "Great! All tasks completed!",
"Continue to Dashboard": "Continue to Dashboard",
"Page Not Found": "Page Not Found",
"The page you're looking for doesn't exist or has been moved.": "The page you're looking for doesn't exist or has been moved.",
"This page could not be found.": "This page could not be found.",
"Back to Home": "Back to Home",
"Subdomain Change Warning": "Subdomain Change Warning",
"The subdomain has been changed. You will be automatically redirected to the new address in {{seconds}} seconds.": "The subdomain has been changed. You will be automatically redirected to the new address in {{seconds}} seconds.",
"New Address": "New Address",
"Redirect Now": "Redirect Now",
"Daily Registered Users": "Daily Registered Users",
"Daily Revenue": "Daily Revenue",
"Daily API Calls": "Daily API Calls",
"Top Servers by Calls": "Top Servers by Calls",
"Date": "Date",
"Users": "Users",
"Revenue": "Revenue",
"Calls": "Calls",
"Server Name": "Server Name",
"Call Volume": "Call Volume",
"Last 30 Days Overview": "Last 30 Days Overview",
"Sort by Call Volume": "Sort by Call Volume",
"Sort by Name": "Sort by Name",
"Total subscribers": "Total subscribers",
"Avg. open rate": "Avg. open rate",
"Avg. click rate": "Avg. click rate",
"Total Users": "Total Users",
"Total Revenue": "Total Revenue",
"Total API Calls": "Total API Calls",
"API server for machine learning tasks": "API server for machine learning tasks",
"Web Scraping Statistics": "Web Scraping Statistics",
"Total Scraped Pages": "Total Scraped Pages",
"Total number of pages scraped from the website": "Total number of pages scraped from the website",
"Scraping Growth Chart": "Scraping Growth Chart",
"New Pages": "New Pages",
"Daily growth of scraped pages over time": "Daily growth of scraped pages over time",
"Real-time data processing service": "Real-time data processing service",
"Natural language processing service": "Natural language processing service",
"Computer vision analysis tool": "Computer vision analysis tool",
"Translation and localization service": "Translation and localization service",
"Web search and indexing engine": "Web search and indexing engine",
"Cloud file storage and management": "Cloud file storage and management",
"Email delivery and management service": "Email delivery and management service",
"Weather data and forecasting API": "Weather data and forecasting API",
"Calendar synchronization service": "Calendar synchronization service",
"Settings": "Settings",
"System Settings": "System Settings",
"General": "General",
"Platform basic configuration": "Platform basic configuration",
"Homepage": "Homepage",
"Homepage content and theme settings": "Homepage content and theme settings",
"Payment Channels": "Payment Channels",
"Configure payment channels": "Configure payment channels",
"Admin Settings": "Admin Settings",
"Configure admin login credentials": "Configure admin login credentials",
"Search settings": "Search settings",
"Clear": "Clear",
"No results": "No results",
"Welcome to Your Platform!": "Welcome to Your Platform!",
"Let's set up {{platformName}} to get you started.": "Let's set up {{platformName}} to get you started.",
"Configure Platform Settings": "Configure Platform Settings",
"Set up your platform name, domain, and branding.": "Set up your platform name, domain, and branding.",
"Add MCP Services": "Add MCP Services",
"Configure and deploy your first MCP server tools.": "Configure and deploy your first MCP server tools.",
"Manage Users": "Manage Users",
"View and configure user accounts and permissions.": "View and configure user accounts and permissions.",
"Configure Payment & Billing": "Configure Payment & Billing",
"Set up payment channels and token pricing.": "Set up payment channels and token pricing.",
"Generate API Keys": "Generate API Keys",
"Create API keys for external integrations.": "Create API keys for external integrations.",
"Share Your Platform": "Share Your Platform",
"Invite users and promote your MCP platform.": "Invite users and promote your MCP platform.",
"Need help getting started? Check out our": "Need help getting started? Check out our",
"Discord Community": "Discord Community",
"Skip setup guide": "Skip setup guide",
"Excellent! Your platform is ready to go!": "Excellent! Your platform is ready to go!",
"Go to Dashboard": "Go to Dashboard",
"Platform": "Platform",
"Billing & Payments": "Billing & Payments",
"Administration": "Administration",
"Meta Data": "Meta Data",
"Extra content for search engines and social accounts": "Extra content for search engines and social accounts",
"Search": "Search",
"X Card": "X Card",
"Facebook Card": "Facebook Card",
"Meta Title": "Meta Title",
"Enter meta title": "Enter meta title",
"Recommended: 70 characters": "Recommended: 70 characters",
"Meta Description": "Meta Description",
"Enter meta description": "Enter meta description",
"Recommended: 156 characters": "Recommended: 156 characters",
"Preview": "Preview",
"Lethe Live": "Lethe Live",
"Thoughts, stories and ideas.": "Thoughts, stories and ideas.",
"Upload X Image": "Upload X Image",
"Upload Facebook Image": "Upload Facebook Image",
"Uploading...": "Uploading...",
"X Title": "X Title",
"Enter X title": "Enter X title",
"X Description": "X Description",
"Enter X description": "Enter X description",
"Facebook Title": "Facebook Title",
"Enter Facebook title": "Enter Facebook title",
"Facebook Description": "Facebook Description",
"Enter Facebook description": "Enter Facebook description",
"Meta data saved successfully": "Meta data saved successfully",
"Please select a valid image file": "Please select a valid image file",
"Image size should be less than 5MB": "Image size should be less than 5MB",
"Failed to upload image": "Failed to upload image",
"General settings": "General settings",
"Title & description": "Title & description",
"Configure your site title and description": "Configure your site title and description",
"Meta data": "Meta data",
"SEO metadata and site configuration": "SEO metadata and site configuration",
"Connect your social media accounts": "Connect your social media accounts",
"Custom domain": "Custom domain",
"Configure your custom domain settings": "Configure your custom domain settings",
"Site": "Site",
"Branding": "Branding",
"Logo, colors, and brand identity": "Logo, colors, and brand identity",
"Theme": "Theme",
"Visual theme and appearance settings": "Visual theme and appearance settings",
"Navigation": "Navigation",
"Configure site navigation and menus": "Configure site navigation and menus",
"Business": "Business",
"Payment": "Payment",
"Payment processing and billing settings": "Payment processing and billing settings",
"XPack Explore": "XPack Explore",
"Explore XPack features and integrations": "Explore XPack features and integrations",
"Advanced": "Advanced",
"Code injection": "Code injection",
"Custom code injection and scripts": "Custom code injection and scripts",
"Enter the domain you want to use": "Enter the domain you want to use",
"Enter your full domain name (e.g., www.example.com)": "Enter your full domain name (e.g., www.example.com)",
"Create your DNS records": "Create your DNS records",
"Add the following DNS records at your DNS provider": "Add the following DNS records at your DNS provider",
"DNS Records Table": "DNS Records Table",
"Type": "Type",
"Host": "Host",
"Value": "Value",
"Activate custom domain": "Activate custom domain",
"Your DNS looks good. You can activate now.": "Your DNS looks good. You can activate now.",
"Make sure your DNS records have propagated before activation.": "Make sure your DNS records have propagated before activation.",
"Activate": "Activate",
"Domain": "Domain",
"Please enter a valid URL with http:// or https://": "Please enter a valid URL with http:// or https://",
"Create MCP Server": "Create MCP Server",
"Choose how you want to create your MCP server": "Choose how you want to create your MCP server",
"Website Content Scraper": "Website Content Scraper",
"Create an MCP server that can scrape and extract content from websites": "Create an MCP server that can scrape and extract content from websites",
"OpenAPI Generator": "OpenAPI Generator",
"Generate MCP server from OpenAPI/Swagger documentation": "Generate MCP server from OpenAPI/Swagger documentation",
"Update Website Scraper": "Update Website Scraper",
"Sync from OpenAPI": "Sync from OpenAPI",
"Update Server": "Update Server",
"Add Server": "Add Server",
"Website URL": "Website URL",
"Enter the website URL (e.g., https://example.com)": "Enter the website URL (e.g., https://example.com)",
"Update website URL for content scraping": "Update website URL for content scraping",
"Enter the website URL you want to scrape content from": "Enter the website URL you want to scrape content from",
"Creating webscraper server...": "Creating webscraper server...",
"Sync server configuration from OpenAPI/Swagger documentation": "Sync server configuration from OpenAPI/Swagger documentation",
"Generate MCP server configuration from OpenAPI/Swagger documentation": "Generate MCP server configuration from OpenAPI/Swagger documentation",
"From URL": "From URL",
"Upload File": "Upload File",
"OpenAPI URL": "OpenAPI URL",
"Enter the URL to your OpenAPI/Swagger specification": "Enter the URL to your OpenAPI/Swagger specification",
"Upload OpenAPI File": "Upload OpenAPI File",
"Choose File": "Choose File",
"Supports JSON and YAML formats": "Supports JSON and YAML formats",
"Parsing OpenAPI document...": "Parsing OpenAPI document...",
"Back": "Back",
"Create Server": "Create Server",
"Generate Server": "Generate Server",
"Sync Server": "Sync Server",
"Select Type": "Select Type",
"Configure": "Configure",
"OR": "OR",
"Use Website Scraper": "Use Website Scraper",
"Use OpenAPI Generator": "Use OpenAPI Generator",
"Data scraping in progress...": "Data scraping in progress...",
"Scraped {{current}} of {{total}} pages": "Scraped {{current}} of {{total}} pages",
"Scraped {{count}} pages": "Scraped {{count}} pages",
"Modifying the URL will trigger re-scraping of the website data.": "Modifying the URL will trigger re-scraping of the website data.",
"You have modified the Website URL. This will trigger re-scraping of the website data. Are you sure you want to continue?": "You have modified the Website URL. This will trigger re-scraping of the website data. Are you sure you want to continue?",
"Scraping...": "Scraping...",
"Server Type": "Server Type",
"Edit Website URL": "Edit Website URL",
"Modifying the website URL will trigger re-scraping of the website data. This process may take some time to complete.": "Modifying the website URL will trigger re-scraping of the website data. This process may take some time to complete.",
"Please enter a valid URL": "Please enter a valid URL",
"Use the refresh button to modify the website URL": "Use the refresh button to modify the website URL",
"Cannot publish while scraping": "Cannot publish while scraping",
"Publish": "Publish",
"Unpublish": "Unpublish",
"Published": "Published",
"Unpublished": "Unpublished",
"Your brand": "Your brand",
"Support JPG, PNG, GIF, SVG. Max size 5MB": "Support JPG, PNG, GIF, SVG. Max size 5MB",
"Site title": "Site title",
"Enter site title": "Enter site title",
"Main title displayed on the home page": "Main title displayed on the home page",
"Site description": "Site description",
"Enter site description": "Enter site description",
"Secondary description displayed below the main title": "Secondary description displayed below the main title",
"Title is required": "Title is required",
"Custom Domain": "Custom Domain",
"Activate your domain": "Activate your domain",
"Set Custom Domain": "Set Custom Domain",
"Configure platform language": "Configure platform language",
"Enter title": "Enter title",
"Enter link URL": "Enter link URL",
"Configure FAQ": "Configure FAQ",
"Enter question": "Enter question",
"Enter answer": "Enter answer",
"Enable Stripe Payment": "Enable Stripe Payment",
"Toggle to enable or disable Stripe payment interface": "Toggle to enable or disable Stripe payment interface",
"Enter Secret Key": "Enter Secret Key",
"Enter Webhook Secret": "Enter Webhook Secret",
"Email Login Settings": "Email Login Settings",
"Open in new tab": "Open in new tab",
"Analyze platform usage and revenue": "Analyze platform usage and revenue",
"Change your password": "Change your password"
}
+102 -83
View File
@@ -81,7 +81,7 @@
"Free": "Free",
"Sign up now to get 100 free calls every month.": "Sign up now to get 100 free calls every month.",
"Generate and manage dynamic PowerPoints and Google Slides with your own custom branding and layouts.": "Generate and manage dynamic PowerPoints and Google Slides with your own custom branding and layouts.",
"Try for free": "Try for free",
"Sign up to get the auth key": "Sign up to get the auth key",
"Lightning Fast Setup": "Lightning Fast Setup",
"Enterprise Security": "Enterprise Security",
"Global Scale": "Global Scale",
@@ -103,7 +103,7 @@
"Build AI Agents": "Build AI Agents",
"With Incredible MCP": "With Incredible MCP",
"Instant Integration": "Instant Integration",
"Connect to global APIs and MCP services with just one config or SDK.": "Connect to global APIs and MCP services with just one config or SDK.",
"Connect to global APIs and MCP servers with just one config or SDK.": "Connect to global APIs and MCP servers with just one config or SDK.",
"Zero Overhead": "Zero Overhead",
"Flexible pay-as-you-go pricing to fuel agent growth at every stage.": "Flexible pay-as-you-go pricing to fuel agent growth at every stage.",
"Secure & Compliant": "Secure & Compliant",
@@ -119,24 +119,24 @@
"Get Started": "Get Started",
"Demo": "Demo",
"Start Deploying": "Start Deploying",
"We help these products connect to global services.": "We help these products connect to global services.",
"We help these products connect to global servers.": "We help these products connect to global servers.",
"Become a partner": "Become a partner",
"AI Design": "AI Design",
"AI Agent": "AI Agent",
"AI Browser": "AI Browser",
"Home": "Home",
"Services": "Services",
"Servers": "Servers",
"Interesting in \n becoming a partner?": "Interesting in \n becoming a partner?",
"Other Partners": "Other Partners",
"Services List": "Services List",
"Submit services": "Submit services",
"Interesting in \n becoming a services supplier?": "Interesting in \n becoming a services supplier?",
"Apply to become a supplier and provide services to global users.": "Apply to become a supplier and provide services to global users.",
"Servers List": "Servers List",
"Submit servers": "Submit servers",
"Interesting in \n becoming a servers supplier?": "Interesting in \n becoming a servers supplier?",
"Apply to become a supplier and provide servers to global users.": "Apply to become a supplier and provide servers to global users.",
"Become a supplier": "Become a supplier",
"We only list some services": "We only list some services",
"Other Services": "Other Services",
"We only list some servers": "We only list some servers",
"Other Servers": "Other Servers",
"Submit a demo": "Submit a demo",
"Number of service categories": "Number of service categories",
"Number of server categories": "Number of server categories",
"Number of MCP Tools": "Number of MCP Tools",
"Time for integration": "Time for integration",
"Daily MCP request count": "Daily MCP request count",
@@ -148,31 +148,31 @@
"It's hard to say goodbyes": "It's hard to say goodbyes",
"We're sorry to see you go. Your subscription has been cancelled.": "We're sorry to see you go. Your subscription has been cancelled.",
"Playground": "Playground",
"MCP Services Management": "MCP Services Management",
"Service List": "Service List",
"Add Service": "Add Service",
"MCP Servers Management": "MCP Servers Management",
"Server List": "Server List",
"Add Server": "Add Server",
"OpenAPI Generator": "OpenAPI Generator",
"Service Name": "Service Name",
"Service Description": "Service Description",
"Service Category": "Service Category",
"Service Status": "Service Status",
"Online": "Online",
"Offline": "Offline",
"Server Name": "Server Name",
"Server Description": "Server Description",
"Server Category": "Server Category",
"Server Status": "Server Status",
"Published": "Published",
"Unpublished": "Unpublished",
"Actions": "Actions",
"Edit": "Edit",
"Delete": "Delete",
"Toggle Status": "Toggle Status",
"Create New Service": "Create New Service",
"Edit Service": "Edit Service",
"Create New Server": "Create New Server",
"Edit Server": "Edit Server",
"Generate from OpenAPI": "Generate from OpenAPI",
"Update from OpenAPI": "Update from OpenAPI",
"Sync from OpenAPI": "Sync from OpenAPI",
"Sync service configuration from OpenAPI/Swagger documentation": "Sync service configuration from OpenAPI/Swagger documentation",
"Sync Service": "Sync Service",
"Sync server configuration from OpenAPI/Swagger documentation": "Sync server configuration from OpenAPI/Swagger documentation",
"Sync Server": "Sync Server",
"OpenAPI URL": "OpenAPI URL",
"Upload OpenAPI File": "Upload OpenAPI File",
"Generate Service": "Generate Service",
"Service Configuration": "Service Configuration",
"Generate Server": "Generate Server",
"Server Configuration": "Server Configuration",
"API Endpoint": "API Endpoint",
"Authentication": "Authentication",
"API Key": "API Key",
@@ -190,15 +190,14 @@
"Edit Tool": "Edit Tool",
"Delete Tool": "Delete Tool",
"Save Changes": "Save Changes",
"No tools configured for this service": "No tools configured for this service",
"Add tools to extend service functionality": "Add tools to extend service functionality",
"Configure and manage tools for this service": "Configure and manage tools for this service",
"No tools configured for this server": "No tools configured for this server",
"Add tools to extend server functionality": "Add tools to extend server functionality",
"Configure and manage tools for this server": "Configure and manage tools for this server",
"Add New Tool": "Add New Tool",
"Enter tool name": "Enter tool name",
"Enter tool description": "Enter tool description",
"Tool name": "Tool name",
"Tool description": "Tool description",
"Take Offline": "Take Offline",
"Platform Domain": "Platform Domain",
"Enter platform domain (e.g., example.com)": "Enter platform domain (e.g., example.com)",
"The domain name of your platform": "The domain name of your platform",
@@ -217,41 +216,36 @@
"Question": "Question",
"Answer": "Answer",
"No FAQ items available.": "No FAQ items available.",
"Enter question": "Enter question",
"Enter answer": "Enter answer",
"Insert below": "Insert below",
"Bring Online": "Bring Online",
"Short Description": "Short Description",
"Long Description": "Long Description",
"Brief description of the service": "Brief description of the service",
"Detailed description of the service": "Detailed description of the service",
"Brief description of the server": "Brief description of the server",
"Detailed description of the server": "Detailed description of the server",
"Basic Information": "Basic Information",
"API Configuration": "API Configuration",
"Authentication Type": "Authentication Type",
"Update Service": "Update Service",
"Create Service": "Create Service",
"Update Server": "Update Server",
"Create Server": "Create Server",
"Confirm Delete": "Confirm Delete",
"Are you sure you want to delete this service?": "Are you sure you want to delete this service?",
"Are you sure you want to delete this server?": "Are you sure you want to delete this server?",
"This action cannot be undone.": "This action cannot be undone.",
"Manage your MCP services, configure APIs, and monitor service status": "Manage your MCP services, configure APIs, and monitor service status",
"Search services...": "Search services...",
"Manage your MCP servers, configure APIs, and monitor server status": "Manage your MCP servers, configure APIs, and monitor server status",
"Search MCP servers": "Search MCP servers",
"Filter by category": "Filter by category",
"Filter by status": "Filter by status",
"All Categories": "All Categories",
"All Status": "All Status",
"Created": "Created",
"Last Updated": "Last Updated",
"Total Services": "Total Services",
"Online Services": "Online Services",
"Offline Services": "Offline Services",
"Service created successfully": "Service created successfully",
"Service updated successfully": "Service updated successfully",
"Service deleted successfully": "Service deleted successfully",
"Service status updated successfully": "Service status updated successfully",
"Failed to create service": "Failed to create service",
"Failed to update service": "Failed to update service",
"Failed to delete service": "Failed to delete service",
"Failed to update service status": "Failed to update service status",
"Total Servers": "Total Servers",
"Server created successfully": "Server created successfully",
"Server updated successfully": "Server updated successfully",
"Server deleted successfully": "Server deleted successfully",
"Server status updated successfully": "Server status updated successfully",
"Failed to create server": "Failed to create server",
"Failed to update server": "Failed to update server",
"Failed to delete server": "Failed to delete server",
"Failed to update server status": "Failed to update server status",
"Invalid OpenAPI URL": "Invalid OpenAPI URL",
"Failed to parse OpenAPI document": "Failed to parse OpenAPI document",
"OpenAPI document parsed successfully": "OpenAPI document parsed successfully",
@@ -261,8 +255,8 @@
"Please select a file": "Please select a file",
"File uploaded successfully": "File uploaded successfully",
"Failed to upload file": "Failed to upload file",
"Service name is required": "Service name is required",
"Service description is required": "Service description is required",
"Server name is required": "Server name is required",
"Server description is required": "Server description is required",
"API endpoint is required": "API endpoint is required",
"Documentation is required": "Documentation is required",
"Connect Your AI Agent to the Real World": "Connect Your AI Agent to the Real World",
@@ -297,13 +291,13 @@
"Login Success": "Login Success",
"Login Error": "Login Error",
"Back Home": "Back Home",
"MCP Services": "MCP Services",
"MCP Servers": "MCP Servers",
"User Management": "User Management",
"Revenue Management": "Revenue Management",
"Payment Channels": "Payment Channels",
"System Settings": "System Settings",
"Overview and analytics": "Overview and analytics",
"Manage MCP services and API tools": "Manage MCP services and API tools",
"Manage MCP servers and API tools": "Manage MCP servers and API tools",
"Manage registered users": "Manage registered users",
"View user recharge history": "View user recharge history",
"Configure payment channels": "Configure payment channels",
@@ -357,7 +351,7 @@
"No": "No",
"User Statistics": "User Statistics",
"API Calls": "API Calls",
"Services Used": "Services Used",
"Servers Used": "Servers Used",
"Total Spent": "Total Spent",
"Wallet Balance": "Wallet Balance",
"Confirm Ban User": "Confirm Ban User",
@@ -386,13 +380,12 @@
"Enter your password": "Enter your password",
"Confirm your password": "Confirm your password",
"Passwords do not match": "Passwords do not match",
"Password must be at least 8 characters": "Password must be at least 8 characters",
"Registration successful": "Registration successful",
"Registration failed": "Registration failed",
"Email already exists": "Email already exists",
"Invalid email format": "Invalid email format",
"Sign up with Google": "Sign up with Google",
"Terms of Service": "Terms of Service",
"Terms of Server": "Terms of Server",
"Privacy Policy": "Privacy Policy",
"By signing up, you agree to our": "By signing up, you agree to our",
"and": "and",
@@ -436,9 +429,9 @@
"Enable Google Login": "Enable Google Login",
"Administrator Account": "Administrator Account",
"Platform Information": "Platform Information",
"Delete Service": "Delete Service",
"Delete Server": "Delete Server",
"Parsing OpenAPI document...": "Parsing OpenAPI document...",
"Generated Service Configuration": "Generated Service Configuration",
"Generated Server Configuration": "Generated Server Configuration",
"None": "None",
"Tags": "Tags",
"Paid": "Paid",
@@ -476,7 +469,7 @@
"Enter your verification code": "Enter your verification code",
"Resend": "Resend",
"Verify Email Error": "Verify Email Error",
"Generate MCP service configuration from OpenAPI/Swagger documentation": "Generate MCP service configuration from OpenAPI/Swagger documentation",
"Generate MCP server configuration from OpenAPI/Swagger documentation": "Generate MCP server configuration from OpenAPI/Swagger documentation",
"From URL": "From URL",
"Upload File": "Upload File",
"Choose File": "Choose File",
@@ -485,7 +478,12 @@
"Invalid email address": "Invalid email address",
"Back to Home": "Back to Home",
"Enter the URL to your OpenAPI/Swagger specification": "Enter the URL to your OpenAPI/Swagger specification",
"Enter service name": "Enter service name",
"Enter server name": "Enter server name",
"Server ID": "Server ID",
"Enter server ID": "Enter server ID",
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "Modifying the ID will affect the MCP access URL. Please modify with caution.",
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?",
"The header name for the API key (e.g., X-API-Key, Authorization)": "The header name for the API key (e.g., X-API-Key, Authorization)",
"Enter API key": "Enter API key",
"Enter bearer token": "Enter bearer token",
@@ -510,7 +508,7 @@
"API Key Header Name": "API Key Header Name",
"Secret Key format is incorrect, should start with sk_": "Secret Key format is incorrect, should start with sk_",
"Webhook Secret format is incorrect, should start with whsec_": "Webhook Secret format is incorrect, should start with whsec_",
"Password must be at least 8 characters long": "Password must be at least 8 characters long",
"Password must be at least 6 characters long": "Password must be at least 6 characters long",
"OAuth 2.0 Client Secret (optional, for server-side verification)": "OAuth 2.0 Client Secret (optional, for server-side verification)",
"Authorized redirect URI configured in Google Cloud Console": "Authorized redirect URI configured in Google Cloud Console",
"Webhook signing secret for verifying Stripe events": "Webhook signing secret for verifying Stripe events",
@@ -551,7 +549,7 @@
"Select currency": "Select currency",
"Default currency for the platform": "Default currency for the platform",
"call": "call",
"No services found": "No services found",
"No servers found": "No servers found",
"free/day": "free/day",
"Account (Email)": "Account (Email)",
"Recharge Amount": "Recharge Amount",
@@ -569,7 +567,7 @@
"No tools added yet. Add your first tool using the input above.": "No tools added yet. Add your first tool using the input above.",
"Insert tool below": "Insert tool below",
"Remove tool": "Remove tool",
"Service Detail": "Service Detail",
"Server Detail": "Server Detail",
"Billing Mode": "Billing Mode",
"Enable free quota": "Enable free quota",
"Configure Stripe payment interface": "Configure Stripe payment interface",
@@ -598,9 +596,9 @@
"Platform total fund pool": "Platform total fund pool",
"Today's API Calls": "Today's API Calls",
"API call count": "API call count",
"Total MCP Services": "Total MCP Services",
"Deployed services": "Deployed services",
"This is your AI service management center. You can quickly view platform core data on the left and manage and configure your MCP services, users, payment channels, etc.": "This is your AI service management center. You can quickly view platform core data on the left and manage and configure your MCP services, users, payment channels, etc.",
"Total MCP Servers": "Total MCP Servers",
"Deployed servers": "Deployed servers",
"This is your AI server management center. You can quickly view platform core data on the left and manage and configure your MCP servers, users, payment channels, etc.": "This is your AI server management center. You can quickly view platform core data on the left and manage and configure your MCP servers, users, payment channels, etc.",
"Log In": "Log In",
"Register Date": "Register Date",
"Dashboard": "Dashboard",
@@ -646,17 +644,16 @@
"Funds will be added to your account balance": "Funds will be added to your account balance",
"Please select a payment method": "Please select a payment method",
"Manage your balance and recharge history": "Manage your balance and recharge history",
"Build incredible AI agents together": "Build incredible AI agents together",
"Balance: {{amount}}": "Balance: {{amount}}",
"Log Out": "Log Out",
"Enter your username": "Enter your username",
"Login": "Login",
"Admin Portal": "Admin Portal",
"Log in to admin console": "Log in to admin console",
"Welcome to XPack.AI Open Source": "Welcome to XPack.AI Open Source",
"Are you sure you want to delete this \"{{name}}\" service?": "Are you sure you want to delete this \"{{name}}\" service?",
"Service status toggled successfully": "Service status toggled successfully",
"Failed to toggle service status": "Failed to toggle service status",
"Log in to your admin account to continue": "Log in to your admin account to continue",
"Welcome to XPack.AI": "Welcome to XPack.AI",
"Are you sure you want to delete this \"{{name}}\" server?": "Are you sure you want to delete this \"{{name}}\" server?",
"Server status toggled successfully": "Server status toggled successfully",
"Failed to toggle server status": "Failed to toggle server status",
"Stripe configuration saved successfully": "Stripe configuration saved successfully",
"Failed to save Stripe configuration": "Failed to save Stripe configuration",
"System config updated successfully": "System config updated successfully",
@@ -691,8 +688,6 @@
"{{channelName}} config saved successfully": "{{channelName}} config saved successfully",
"{{channelName}} connection test failed": "{{channelName}} connection test failed",
"{{channelName}} connection test successful": "{{channelName}} connection test successful",
"Login successful": "Login successful",
"Logged out successfully": "Logged out successfully",
"Configure email settings": "Configure email settings",
"Email Configuration": "Email Configuration",
"Configure SMTP settings for email notifications": "Configure SMTP settings for email notifications",
@@ -766,10 +761,10 @@
"Traditional email and password authentication": "Traditional email and password authentication",
"Email/Verification Code": "Email/Verification Code",
"Passwordless login with email verification code": "Passwordless login with email verification code",
"Email service is not configured. Please configure email settings first.": "Email service is not configured. Please configure email settings first.",
"SMTP is not configured. Please configure email settings first.": "SMTP is not configured. Please configure email settings first.",
"Go to Settings": "Go to Settings",
"AI Tools Marketplace": "AI Tools Marketplace",
"A marketplace for AI tools and services. Discover and integrate powerful AI solutions for your projects.": "A marketplace for AI tools and services. Discover and integrate powerful AI solutions for your projects.",
"A marketplace for AI tools and servers. Discover and integrate powerful AI solutions for your projects.": "A marketplace for AI tools and servers. Discover and integrate powerful AI solutions for your projects.",
"Configuration": "Configuration",
"Featured Products": "Featured Products",
"Search": "Search",
@@ -778,7 +773,7 @@
"Re-enter new password": "Re-enter new password",
"Confirm new password": "Confirm new password",
"New password and confirm password do not match": "New password and confirm password do not match",
"New password must be at least 8 characters long": "New password must be at least 8 characters long",
"New password must be at least 6 characters long": "New password must be at least 6 characters long",
"New password and confirm password must be the same": "New password and confirm password must be the same",
"New Password": "New Password",
"Confirm New Password": "Confirm New Password",
@@ -799,7 +794,6 @@
"Toggle to enable or disable custom HTML injection": "Toggle to enable or disable custom HTML injection",
"Show Preview": "Show Preview",
"Hide Preview": "Hide Preview",
"Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>": "Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>",
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.": "This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.",
"Preview": "Preview",
"Note: This is a text preview. The actual HTML will be rendered when saved and enabled.": "Note: This is a text preview. The actual HTML will be rendered when saved and enabled.",
@@ -838,8 +832,6 @@
"Target": "Target",
"Add Navigation Item": "Add Navigation Item",
"Remove Navigation Item": "Remove Navigation Item",
"Enter title": "Enter title",
"Enter link URL": "Enter link URL",
"Same window": "Same window",
"New window": "New window",
"Custom HTML injection": "Custom HTML injection",
@@ -872,5 +864,32 @@
"Input": "Input",
"Output": "Output",
"1M tokens": "1M tokens",
"Total Spending": "Total Spending"
"Total Spending": "Total Spending",
"Remote": "Remote",
"Platform Logo": "Platform Logo",
"Support JPG, PNG, GIF. Max size 5MB": "Support JPG, PNG, GIF. Max size 5MB",
"(30 days)": "(30 days)",
"Sign in": "Sign in",
"or create your account": "or create your account",
"No account? Just continue—we’ll set you up.": "No account? Just continue—we’ll set you up.",
"Password must be at least 6 characters": "Password must be at least 6 characters",
"Email is required": "Email is required",
"No servers available": "No servers available",
"(Deleted)": "(Deleted)",
"Transport Type": "Transport Type",
"Server ID must be less than 255 characters": "Server ID must be less than 255 characters",
"Server Name must be less than 255 characters": "Server Name must be less than 255 characters",
"API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint must be a valid HTTP/HTTPS URL",
"Server ID is required": "Server ID is required",
"Short description is required": "Short description is required",
"Auth Key Name": "Auth Key Name",
"Search by email": "Search by email",
"Search by service name": "Search by service name",
"Select Date Range": "Select Date Range",
"Resource group name \"{{name}}\" is reserved and cannot be used": "Resource group name \"{{name}}\" is reserved and cannot be used",
"Resource group name \"{{name}}\" already exists": "Resource group name \"{{name}}\" already exists",
"Auth key name \"{{name}}\" already exists": "Auth key name \"{{name}}\" already exists",
"Start date must be before end date": "Start date must be before end date",
"Start date cannot be earlier than 30 days ago": "Start date cannot be earlier than 30 days ago",
"Resource Groups": "Resource Groups"
}
+242 -12
View File
@@ -1,13 +1,243 @@
{
"**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) services.": "**XPack** 是一个轻量级的开源 MCP(模型上下文协议)服务市场框架。",
"It allows you to transform any OpenAPI into a monetizable MCP service and build your own API store in just minutes.": "它允许您将任何 OpenAPI 转换为可盈利的 MCP 服务,并在几分钟内构建您自己的 API 商店。",
"✨ With XPack, you can:": "✨ 使用 XPack,您可以:",
"- ✅ **One-click OpenAPI → MCP service config**": "- ✅ **一键 OpenAPI → MCP 服务配置**",
"- 🧾 **SEO-friendly homepage + mcp service page**": "- 🧾 **SEO 友好的主页 + MCP 服务页面**",
"- 💳 **Built-in billing (per-call)**": "- 💳 **内置计费(按调用计费)**",
"- 👥 **User account management**": "- 👥 **用户账户管理**",
"- 🛠 **Support Stripe Payment**": "- 🛠 **支持 Stripe 支付**",
"- 🔐 **Support Email & Google OAuth Sign in**": "- 🔐 **支持邮箱和 Google OAuth 登录**",
"Everything is open-source and licensed under **Apache 2.0** — ready for commercial use.": "一切都是开源的,采用 **Apache 2.0** 许可证 — 可用于商业用途。",
"About Us": "关于我们"
}
"Server Configuration": "服务器配置",
"Subdomain": "子域名",
"Enter subdomain (e.g., mysite)": "输入子域名(例如:mysite)",
"Subdomain is required": "子域名不能为空",
"Subdomain must contain only lowercase letters, numbers, and hyphens": "子域名只能包含小写字母、数字和连字符",
"Subdomain must be between 3 and 63 characters": "子域名长度需在 3 到 63 个字符之间",
"Log in to your admin account to continue": "登录管理员账号以继续",
"Your unique subdomain for the platform": "平台的唯一子域名",
"Let's get started!": "开始设置!",
"Welcome! It's time to set up Lethe Live.": "欢迎!是时候设置 Lethe Live 了。",
"Start a new Ghost publication": "开始新的 Ghost 发布",
"Customize your design": "自定义你的设计",
"Craft a look that reflects your brand and style": "打造反映你品牌与风格的外观",
"Explore the editor": "探索编辑器",
"Build your audience": "构建你的受众",
"Share your publication": "分享你的发布内容",
"More questions? Check out our": "还有问题?请查看我们的",
"Help Center": "帮助中心",
"Skip onboarding": "跳过引导",
"Great! All tasks completed!": "太棒了!所有任务都已完成!",
"Continue to Dashboard": "进入仪表盘",
"Page Not Found": "页面未找到",
"The page you're looking for doesn't exist or has been moved.": "你要访问的页面不存在或已被移动。",
"This page could not be found.": "无法找到此页面。",
"Back to Home": "返回首页",
"Subdomain Change Warning": "子域名更改提醒",
"The subdomain has been changed. You will be automatically redirected to the new address in {{seconds}} seconds.": "子域名已更改。你将在 {{seconds}} 秒后自动跳转至新地址。",
"New Address": "新地址",
"Redirect Now": "立即跳转",
"Daily Registered Users": "每日注册用户",
"Daily Revenue": "每日营收",
"Daily API Calls": "每日 API 调用",
"Top Servers by Calls": "调用量最多的服务器",
"Date": "日期",
"Users": "用户",
"Revenue": "收入",
"Calls": "调用量",
"Server Name": "服务器名称",
"Call Volume": "调用量",
"Last 30 Days Overview": "近 30 天概览",
"Sort by Call Volume": "按调用量排序",
"Sort by Name": "按名称排序",
"Total subscribers": "订阅者总数",
"Avg. open rate": "平均打开率",
"Avg. click rate": "平均点击率",
"Total Users": "用户总数",
"Total Revenue": "总收入",
"Total API Calls": "API 调用总数",
"API server for machine learning tasks": "用于机器学习任务的 API 服务器",
"Web Scraping Statistics": "网页爬取统计",
"Total Scraped Pages": "已爬取页面总数",
"Total number of pages scraped from the website": "从网站爬取的页面总数",
"Scraping Growth Chart": "爬取增长图",
"New Pages": "新增页面",
"Daily growth of scraped pages over time": "每日新增爬取页面数量",
"Real-time data processing service": "实时数据处理服务",
"Natural language processing service": "自然语言处理服务",
"Computer vision analysis tool": "计算机视觉分析工具",
"Translation and localization service": "翻译与本地化服务",
"Web search and indexing engine": "网页搜索与索引引擎",
"Cloud file storage and management": "云端文件存储与管理",
"Email delivery and management service": "邮件投递与管理服务",
"Weather data and forecasting API": "天气数据与预测 API",
"Calendar synchronization service": "日历同步服务",
"Settings": "设置",
"System Settings": "系统设置",
"General": "通用设置",
"Platform basic configuration": "平台基础配置",
"Homepage": "首页",
"Homepage content and theme settings": "首页内容与主题设置",
"Payment Channels": "支付渠道",
"Configure payment channels": "配置支付渠道",
"Admin Settings": "管理员设置",
"Configure admin login credentials": "配置管理员登录信息",
"Search settings": "搜索设置",
"Clear": "清除",
"No results": "无结果",
"Welcome to Your Platform!": "欢迎使用你的平台!",
"Let's set up {{platformName}} to get you started.": "让我们来设置 {{platformName}},开始你的旅程。",
"Configure Platform Settings": "配置平台设置",
"Set up your platform name, domain, and branding.": "设置平台名称、域名和品牌标识。",
"Add MCP Services": "添加 MCP 服务",
"Configure and deploy your first MCP server tools.": "配置并部署你的第一个 MCP 服务器工具。",
"Manage Users": "管理用户",
"View and configure user accounts and permissions.": "查看并配置用户账号与权限。",
"Configure Payment & Billing": "配置支付与结算",
"Set up payment channels and token pricing.": "设置支付渠道与 Token 定价。",
"Generate API Keys": "生成 API Key",
"Create API keys for external integrations.": "为外部集成创建 API Key。",
"Share Your Platform": "分享你的平台",
"Invite users and promote your MCP platform.": "邀请用户并推广你的 MCP 平台。",
"Need help getting started? Check out our": "需要帮助?请查看我们的",
"Discord Community": "Discord 社区",
"Skip setup guide": "跳过设置向导",
"Excellent! Your platform is ready to go!": "太棒了!你的平台已准备就绪!",
"Go to Dashboard": "进入仪表盘",
"Platform": "平台",
"Billing & Payments": "账单与支付",
"Administration": "管理",
"Meta Data": "元数据",
"Extra content for search engines and social accounts": "用于搜索引擎与社交平台的额外信息",
"Search": "搜索",
"X Card": "X 卡片",
"Facebook Card": "Facebook 卡片",
"Meta Title": "Meta 标题",
"Enter meta title": "输入 Meta 标题",
"Recommended: 70 characters": "建议:70 个字符",
"Meta Description": "Meta 描述",
"Enter meta description": "输入 Meta 描述",
"Recommended: 156 characters": "建议:156 个字符",
"Preview": "预览",
"Lethe Live": "Lethe Live",
"Thoughts, stories and ideas.": "思想、故事与想法。",
"Upload X Image": "上传 X 图片",
"Upload Facebook Image": "上传 Facebook 图片",
"Uploading...": "上传中...",
"X Title": "X 标题",
"Enter X title": "输入 X 标题",
"X Description": "X 描述",
"Enter X description": "输入 X 描述",
"Facebook Title": "Facebook 标题",
"Enter Facebook title": "输入 Facebook 标题",
"Facebook Description": "Facebook 描述",
"Enter Facebook description": "输入 Facebook 描述",
"Meta data saved successfully": "元数据保存成功",
"Please select a valid image file": "请选择有效的图片文件",
"Image size should be less than 5MB": "图片大小应小于 5MB",
"Failed to upload image": "图片上传失败",
"General settings": "通用设置",
"Title & description": "标题与描述",
"Configure your site title and description": "配置站点标题与描述",
"Meta data": "元数据",
"SEO metadata and site configuration": "SEO 元数据与站点配置",
"Connect your social media accounts": "连接你的社交媒体账号",
"Custom domain": "自定义域名",
"Configure your custom domain settings": "配置你的自定义域名设置",
"Site": "站点",
"Branding": "品牌",
"Logo, colors, and brand identity": "Logo、颜色与品牌识别",
"Theme": "主题",
"Visual theme and appearance settings": "视觉主题与外观设置",
"Navigation": "导航",
"Configure site navigation and menus": "配置站点导航与菜单",
"Business": "业务",
"Payment": "支付",
"Payment processing and billing settings": "支付处理与结算设置",
"XPack Explore": "XPack 探索",
"Explore XPack features and integrations": "探索 XPack 的功能与集成",
"Advanced": "高级",
"Code injection": "代码注入",
"Custom code injection and scripts": "自定义代码注入与脚本",
"Enter the domain you want to use": "输入你要使用的域名",
"Enter your full domain name (e.g., www.example.com)": "输入完整域名(例如:www.example.com)",
"Create your DNS records": "创建你的 DNS 记录",
"Add the following DNS records at your DNS provider": "在你的 DNS 服务商处添加以下记录",
"DNS Records Table": "DNS 记录表",
"Type": "类型",
"Host": "主机名",
"Value": "值",
"Activate custom domain": "激活自定义域名",
"Your DNS looks good. You can activate now.": "DNS 看起来没问题。现在可以激活了。",
"Make sure your DNS records have propagated before activation.": "激活前请确保 DNS 记录已生效。",
"Activate": "激活",
"Domain": "域名",
"Please enter a valid URL with http:// or https://": "请输入包含 http:// 或 https:// 的有效 URL",
"Create MCP Server": "创建 MCP 服务器",
"Choose how you want to create your MCP server": "选择创建 MCP 服务器的方式",
"Website Content Scraper": "网站内容爬虫",
"Create an MCP server that can scrape and extract content from websites": "创建可以爬取并提取网站内容的 MCP 服务器",
"OpenAPI Generator": "OpenAPI 生成器",
"Generate MCP server from OpenAPI/Swagger documentation": "从 OpenAPI/Swagger 文档生成 MCP 服务器",
"Update Website Scraper": "更新网站爬虫",
"Sync from OpenAPI": "从 OpenAPI 同步",
"Update Server": "更新服务器",
"Add Server": "添加服务器",
"Website URL": "网站 URL",
"Enter the website URL (e.g., https://example.com)": "输入网站 URL(例如:https://example.com)",
"Update website URL for content scraping": "更新用于内容爬取的网站 URL",
"Enter the website URL you want to scrape content from": "输入你想爬取内容的网站 URL",
"Creating webscraper server...": "正在创建爬虫服务器...",
"Sync server configuration from OpenAPI/Swagger documentation": "从 OpenAPI/Swagger 文档同步服务器配置",
"Generate MCP server configuration from OpenAPI/Swagger documentation": "从 OpenAPI/Swagger 文档生成 MCP 服务器配置",
"From URL": "从 URL",
"Upload File": "上传文件",
"OpenAPI URL": "OpenAPI URL",
"Enter the URL to your OpenAPI/Swagger specification": "输入 OpenAPI/Swagger 规范的 URL",
"Upload OpenAPI File": "上传 OpenAPI 文件",
"Choose File": "选择文件",
"Supports JSON and YAML formats": "支持 JSON 与 YAML 格式",
"Parsing OpenAPI document...": "正在解析 OpenAPI 文档...",
"Back": "返回",
"Create Server": "创建服务器",
"Generate Server": "生成服务器",
"Sync Server": "同步服务器",
"Select Type": "选择类型",
"Configure": "配置",
"OR": "或",
"Use Website Scraper": "使用网站爬虫",
"Use OpenAPI Generator": "使用 OpenAPI 生成器",
"Data scraping in progress...": "数据爬取进行中...",
"Scraped {{current}} of {{total}} pages": "已爬取 {{current}} / {{total}} 个页面",
"Scraped {{count}} pages": "已爬取 {{count}} 个页面",
"Modifying the URL will trigger re-scraping of the website data.": "修改 URL 将会触发重新爬取网站数据。",
"You have modified the Website URL. This will trigger re-scraping of the website data. Are you sure you want to continue?": "你已修改网站 URL。这将触发重新爬取网站数据。确定要继续吗?",
"Scraping...": "正在爬取...",
"Server Type": "服务器类型",
"Edit Website URL": "编辑网站 URL",
"Modifying the website URL will trigger re-scraping of the website data. This process may take some time to complete.": "修改网站 URL 将触发重新爬取数据。该过程可能需要一段时间完成。",
"Please enter a valid URL": "请输入有效的 URL",
"Use the refresh button to modify the website URL": "使用刷新按钮来修改网站 URL",
"Cannot publish while scraping": "爬取未完成,无法发布",
"Publish": "发布",
"Unpublish": "取消发布",
"Published": "已发布",
"Unpublished": "未发布",
"Your brand": "你的品牌",
"Support JPG, PNG, GIF, SVG. Max size 5MB": "支持 JPG, PNG, GIF, SVG. 最大支持 5MB",
"Site title": "站点标题",
"Enter site title": "输入站点标题",
"Main title displayed on the home page": "首页显示的主标题",
"Site description": "站点描述",
"Enter site description": "输入站点描述",
"Secondary description displayed below the main title": "主标题下方显示的次标题",
"Title is required": "标题不能为空",
"Custom Domain": "自定义域名",
"Activate your domain": "激活您的域名",
"Set Custom Domain": "设置自定义域名",
"Configure platform language": "配置平台语言",
"Enter title": "输入标题",
"Enter link URL": "输入链接 URL",
"Configure FAQ": "配置常见问题",
"Enter question": "输入问题",
"Enter answer": "输入答案",
"Enable Stripe Payment": "启用 Stripe 支付",
"Toggle to enable or disable Stripe payment interface": "切换以启用或禁用 Stripe 支付接口",
"Enter Secret Key": "输入 Stripe 密钥",
"Enter Webhook Secret": "输入 Stripe Webhook 密钥",
"Email Login Settings": "邮箱登录设置",
"Open in new tab": "在新标签页打开",
"Analyze platform usage and revenue": "分析平台使用情况和收入",
"Change your password": "更改您的密码"
}
+167 -84
View File
@@ -81,7 +81,7 @@
"Free": "免费",
"Sign up now to get 100 free calls every month.": "注册即可获得每月 100 次免费调用",
"Generate and manage dynamic PowerPoints and Google Slides with your own custom branding and layouts.": "使用您自己的自定义品牌和布局生成和管理动态 PowerPoint 和 Google 幻灯片。",
"Try for free": "免费试用",
"Sign up to get the auth key": "注册以获取认证密钥",
"Lightning Fast Setup": "闪电般快速设置",
"Enterprise Security": "企业级安全",
"Global Scale": "全球规模",
@@ -103,7 +103,7 @@
"Build AI Agents": "使用令人难以置信的 MCP",
"With Incredible MCP": "构建 AI Agent",
"Instant Integration": "即时集成",
"Connect to global APIs and MCP services with just one config or SDK.": "通过一个配置或 SDK 连接到全球 API 和 MCP 服务。",
"Connect to global APIs and MCP servers with just one config or SDK.": "通过一个配置或 SDK 连接到全球 API 和 MCP 服务。",
"Zero Overhead": "零开销",
"Flexible pay-as-you-go pricing to fuel agent growth at every stage.": "灵活的按使用付费定价,为每个阶段的 Agent 增长提供动力。",
"Secure & Compliant": "安全 & 合规",
@@ -119,24 +119,24 @@
"Get Started": "立即开始",
"Demo": "演示",
"Start Deploying": "开始部署",
"We help these products connect to global services.": "我们帮助这些产品连接到全球服务。",
"We help these products connect to global servers.": "我们帮助这些产品连接到全球服务。",
"Become a partner": "成为合作伙伴",
"AI Design": "AI 设计",
"AI Agent": "AI Agent",
"AI Browser": "AI 浏览器",
"Home": "首页",
"Services": "服务",
"Servers": "服务",
"Interesting in \n becoming a partner?": "有兴趣\n 成为合作伙伴吗?",
"Other Partners": "其他合作伙伴",
"Services List": "服务列表",
"Submit services": "提交服务",
"Interesting in \n becoming a services supplier?": "有兴趣\n 成为服务供应商吗?",
"Apply to become a supplier and provide services to global users.": "申请成为供应商,为全球用户提供服务。",
"Servers List": "服务列表",
"Submit servers": "提交服务",
"Interesting in \n becoming a servers supplier?": "有兴趣\n 成为服务供应商吗?",
"Apply to become a supplier and provide servers to global users.": "申请成为供应商,为全球用户提供服务。",
"Become a supplier": "成为供应商",
"We only list some services": "我们只列出部分服务",
"Other Services": "其他服务",
"We only list some servers": "我们只列出部分服务",
"Other Servers": "其他服务",
"Submit a demo": "提交演示",
"Number of service categories": "服务分类数量",
"Number of server categories": "服务分类数量",
"Number of MCP Tools": "MCP 工具数量",
"Time for integration": "集成时间",
"Daily MCP request count": "每日 MCP 请求数量",
@@ -148,31 +148,31 @@
"It's hard to say goodbyes": "说再见总是很难",
"We're sorry to see you go. Your subscription has been cancelled.": "我们很遗憾看到您离开。您的订阅已被取消。",
"Playground": "演示环境",
"MCP Services Management": "MCP 服务管理",
"Service List": "服务列表",
"Add Service": "添加服务",
"MCP Servers Management": "MCP 服务管理",
"Server List": "服务列表",
"Add Server": "添加服务",
"OpenAPI Generator": "OpenAPI 生成器",
"Service Name": "服务名称",
"Service Description": "服务描述",
"Service Category": "服务分类",
"Service Status": "服务状态",
"Online": "上线",
"Offline": "下线",
"Server Name": "服务名称",
"Server Description": "服务描述",
"Server Category": "服务分类",
"Server Status": "服务状态",
"Published": "已发布",
"Unpublished": "未发布",
"Actions": "操作",
"Edit": "编辑",
"Delete": "删除",
"Toggle Status": "切换状态",
"Create New Service": "创建新服务",
"Edit Service": "编辑服务",
"Create New Server": "创建新服务",
"Edit Server": "编辑服务",
"Generate from OpenAPI": "从 OpenAPI 生成",
"Update from OpenAPI": "从 OpenAPI 更新",
"Sync from OpenAPI": "从 OpenAPI 同步",
"Sync service configuration from OpenAPI/Swagger documentation": "从 OpenAPI/Swagger 文档同步服务配置",
"Sync Service": "同步服务",
"Sync server configuration from OpenAPI/Swagger documentation": "从 OpenAPI/Swagger 文档同步服务配置",
"Sync Server": "同步服务",
"OpenAPI URL": "OpenAPI 地址",
"Upload OpenAPI File": "上传 OpenAPI 文件",
"Generate Service": "生成服务",
"Service Configuration": "服务配置",
"Generate Server": "生成服务",
"Server Configuration": "服务配置",
"API Endpoint": "API 端点",
"Authentication": "身份验证",
"API Key": "API 密钥",
@@ -182,7 +182,7 @@
"Markdown Documentation": "Markdown 文档",
"Save": "保存",
"Cancel": "取消",
"Service Documentation": "服务文档",
"Server Documentation": "服务文档",
"Manage Tools": "管理工具",
"Tools Count": "工具数量",
"Tool Name": "工具名称",
@@ -191,15 +191,14 @@
"Edit Tool": "编辑工具",
"Delete Tool": "删除工具",
"Save Changes": "保存更改",
"No tools configured for this service": "此服务未配置任何工具",
"Add tools to extend service functionality": "添加工具以扩展服务功能",
"Configure and manage tools for this service": "配置和管理此服务的工具",
"No tools configured for this server": "此服务未配置任何工具",
"Add tools to extend server functionality": "添加工具以扩展服务功能",
"Configure and manage tools for this server": "配置和管理此服务的工具",
"Add New Tool": "添加新工具",
"Enter tool name": "输入工具名称",
"Enter tool description": "输入工具描述",
"Tool name": "工具名称",
"Tool description": "工具描述",
"Take Offline": "下线",
"Platform Domain": "平台域名",
"Enter platform domain (e.g., example.com)": "输入平台域名(例如:example.com)",
"The domain name of your platform": "您平台的域名",
@@ -218,41 +217,36 @@
"Question": "问题",
"Answer": "答案",
"No FAQ items available.": "暂无FAQ项目。",
"Enter question": "输入问题",
"Enter answer": "输入答案",
"Insert below": "在下方插入",
"Bring Online": "上线",
"Short Description": "简短描述",
"Long Description": "详细描述",
"Brief description of the service": "服务的简短描述",
"Detailed description of the service": "服务的详细描述",
"Brief description of the server": "服务的简短描述",
"Detailed description of the server": "服务的详细描述",
"Basic Information": "基本信息",
"API Configuration": "API配置",
"Authentication Type": "认证类型",
"Update Service": "更新服务",
"Create Service": "创建服务",
"Update Server": "更新服务",
"Create Server": "创建服务",
"Confirm Delete": "确认删除",
"Are you sure you want to delete this service?": "您确定要删除此服务吗?",
"Are you sure you want to delete this server?": "您确定要删除此服务吗?",
"This action cannot be undone.": "此操作无法撤销。",
"Manage your MCP services, configure APIs, and monitor service status": "管理您的MCP服务,配置API,并监控服务状态",
"Search services...": "搜索服务...",
"Manage your MCP servers, configure APIs, and monitor server status": "管理您的MCP服务,配置API,并监控服务状态",
"Search MCP servers": "搜索服务...",
"Filter by category": "按分类筛选",
"Filter by status": "按状态筛选",
"All Categories": "所有分类",
"All Status": "所有状态",
"Created": "创建时间",
"Last Updated": "最后更新",
"Total Services": "总服务数",
"Online Services": "在线服务",
"Offline Services": "离线服务",
"Service created successfully": "服务创建成功",
"Service updated successfully": "服务更新成功",
"Service deleted successfully": "服务删除成功",
"Service status updated successfully": "服务状态更新成功",
"Failed to create service": "创建服务失败",
"Failed to update service": "更新服务失败",
"Failed to delete service": "删除服务失败",
"Failed to update service status": "更新服务状态失败",
"Total Servers": "总服务数",
"Server created successfully": "服务创建成功",
"Server updated successfully": "服务更新成功",
"Server deleted successfully": "服务删除成功",
"Server status updated successfully": "服务状态更新成功",
"Failed to create server": "创建服务失败",
"Failed to update server": "更新服务失败",
"Failed to delete server": "删除服务失败",
"Failed to update server status": "更新服务状态失败",
"Invalid OpenAPI URL": "无效的 OpenAPI 地址",
"Failed to parse OpenAPI document": "解析 OpenAPI 文档失败",
"OpenAPI document parsed successfully": "OpenAPI 文档解析成功",
@@ -262,8 +256,8 @@
"Please select a file": "请选择文件",
"File uploaded successfully": "文件上传成功",
"Failed to upload file": "文件上传失败",
"Service name is required": "服务名称为必填项",
"Service description is required": "服务描述为必填项",
"Server name is required": "服务名称为必填项",
"Server description is required": "服务描述为必填项",
"API endpoint is required": "API 端点为必填项",
"Documentation is required": "文档为必填项",
"Connect Your AI Agent to the Real World": "连接您的 AI Agent 到真实世界",
@@ -298,14 +292,15 @@
"Login Success": "登录成功",
"Login Error": "登录错误",
"Back Home": "返回首页",
"MCP Services": "MCP 服务",
"MCP Servers": "MCP 服务",
"User Management": "用户管理",
"Revenue Management": "收入管理",
"Payment Channels": "支付渠道",
"System Settings": "系统设置",
"Overview and analytics": "概览和分析",
"Manage MCP services and API tools": "管理MCP服务及API工具",
"Manage MCP servers and API tools": "管理MCP服务及API工具",
"Manage registered users": "管理注册用户",
"Manage resource groups": "管理资源组",
"View user recharge history": "查看用户充值历史",
"Configure payment channels": "配置支付渠道",
"Platform basic configuration": "平台基础配置",
@@ -358,7 +353,7 @@
"No": "否",
"User Statistics": "用户统计",
"API Calls": "API调用次数",
"Services Used": "使用的服务",
"Servers Used": "使用的服务",
"Total Spent": "总消费",
"Wallet Balance": "钱包余额",
"Confirm Ban User": "确认封禁用户",
@@ -387,13 +382,12 @@
"Enter your password": "请输入密码",
"Confirm your password": "请确认密码",
"Passwords do not match": "密码不匹配",
"Password must be at least 8 characters": "密码至少需要8个字符",
"Registration successful": "注册成功",
"Registration failed": "注册失败",
"Email already exists": "邮箱已存在",
"Invalid email format": "邮箱格式无效",
"Sign up with Google": "使用Google注册",
"Terms of Service": "服务条款",
"Terms of Server": "服务条款",
"Privacy Policy": "隐私政策",
"By signing up, you agree to our": "注册即表示您同意我们的",
"and": "和",
@@ -437,9 +431,9 @@
"Enable Google Login": "启用Google登录",
"Administrator Account": "管理员账户",
"Platform Information": "平台信息",
"Delete Service": "删除服务",
"Delete Server": "删除服务",
"Parsing OpenAPI document...": "正在解析OpenAPI文档...",
"Generated Service Configuration": "生成的服务配置",
"Generated Server Configuration": "生成的服务配置",
"None": "无",
"Tags": "标签",
"Paid": "付费",
@@ -477,7 +471,7 @@
"Enter your verification code": "输入您的验证码",
"Resend": "重新发送",
"Verify Email Error": "邮箱验证错误",
"Generate MCP service configuration from OpenAPI/Swagger documentation": "从OpenAPI/Swagger文档生成MCP服务配置",
"Generate MCP server configuration from OpenAPI/Swagger documentation": "从OpenAPI/Swagger文档生成MCP服务配置",
"From URL": "从URL",
"Upload File": "上传文件",
"Choose File": "选择文件",
@@ -486,7 +480,12 @@
"Invalid email address": "无效的邮箱地址",
"Back to Home": "返回首页",
"Enter the URL to your OpenAPI/Swagger specification": "输入您的OpenAPI/Swagger规范的URL",
"Enter service name": "输入服务名称",
"Enter server name": "输入服务名称",
"Server ID": "服务器ID",
"Enter server ID": "输入服务器ID",
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "修改ID会影响MCP的访问地址,需要谨慎修改。",
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "您已修改了服务器ID。这将影响MCP访问地址,可能会破坏现有的集成。您确定要继续吗?",
"The header name for the API key (e.g., X-API-Key, Authorization)": "API密钥的头部名称(例如:X-API-Key, Authorization)",
"Enter API key": "输入API密钥",
"Enter bearer token": "输入Bearer令牌",
@@ -511,7 +510,7 @@
"API Key Header Name": "API密钥头部名称",
"Secret Key format is incorrect, should start with sk_": "密钥格式不正确,应以sk_开头",
"Webhook Secret format is incorrect, should start with whsec_": "Webhook密钥格式不正确,应以whsec_开头",
"Password must be at least 8 characters long": "密码至少需要8个字符",
"Password must be at least 6 characters long": "密码至少需要6个字符",
"OAuth 2.0 Client Secret (optional, for server-side verification)": "OAuth 2.0 客户端密钥(可选,用于服务端验证)",
"Authorized redirect URI configured in Google Cloud Console": "在Google Cloud Console中配置的授权重定向URI",
"Webhook signing secret for verifying Stripe events": "用于验证Stripe事件的Webhook签名密钥",
@@ -553,7 +552,7 @@
"Select currency": "选择货币",
"Default currency for the platform": "平台默认货币",
"call": "调用",
"No services found": "未找到服务",
"No servers found": "未找到服务",
"free/day": "免费/天",
"Account (Email)": "账户(邮箱)",
"Recharge Amount": "充值金额",
@@ -571,7 +570,7 @@
"No tools added yet. Add your first tool using the input above.": "尚未添加工具。使用上面的输入添加您的第一个工具。",
"Insert tool below": "在下方插入工具",
"Remove tool": "移除工具",
"Service Detail": "服务详情",
"Server Detail": "服务详情",
"Billing Mode": "计费模式",
"Enable free quota": "启用免费配额",
"Configure Stripe payment interface": "配置Stripe支付接口",
@@ -600,9 +599,9 @@
"Platform total fund pool": "平台总资金池",
"Today's API Calls": "今日调用量",
"API call count": "API 调用次数",
"Total MCP Services": "MCP服务总数",
"Deployed services": "已部署的服务",
"This is your AI service management center. You can quickly view platform core data on the left and manage and configure your MCP services, users, payment channels, etc.": "这里是您的AI服务管理中心,您可以在左侧快速查看平台核心数据,在此管理和配置您的 MCP 服务、用户、支付渠道等。",
"Total MCP Servers": "MCP服务总数",
"Deployed servers": "已部署的服务",
"This is your AI server management center. You can quickly view platform core data on the left and manage and configure your MCP servers, users, payment channels, etc.": "这里是您的AI服务管理中心,您可以在左侧快速查看平台核心数据,在此管理和配置您的 MCP 服务、用户、支付渠道等。",
"Log In": "登录",
"Register Date": "注册日期",
"Dashboard": "仪表盘",
@@ -626,6 +625,8 @@
"MCP Config": "MCP配置",
"Copy full config": "复制完整配置",
"Analytics": "分析",
"Resource Group": "资源组",
"Manage Your Resource Groups": "管理您的资源组",
"Times": "次",
"No analytics data available": "无可用分析数据",
"Delete Auth Key": "删除认证密钥",
@@ -648,17 +649,16 @@
"Funds will be added to your account balance": "资金将添加到您的账户余额中",
"Please select a payment method": "请选择支付方式",
"Manage your balance and recharge history": "管理您的余额和充值历史",
"Build incredible AI agents together": "一起构建强大的 AI 代理",
"Balance: {{amount}}": "余额: {{amount}}",
"Log Out": "退出登录",
"Enter your username": "输入您的用户名",
"Login": "登录",
"Admin Portal": "管理员门户",
"Log in to admin console": "登录管理员控制台",
"Welcome to XPack.AI Open Source": "欢迎来到XPack.AI开源项目",
"Are you sure you want to delete this \"{{name}}\" service?": "您确定要删除这个\"{{name}}\"服务吗?",
"Service status toggled successfully": "服务状态切换成功",
"Failed to toggle service status": "切换服务状态失败",
"Log in to your admin account to continue": "登录管理员控制台",
"Welcome to XPack.AI": "欢迎来到XPack.AI",
"Are you sure you want to delete this \"{{name}}\" server?": "您确定要删除这个\"{{name}}\"服务吗?",
"Server status toggled successfully": "服务状态切换成功",
"Failed to toggle server status": "切换服务状态失败",
"Stripe configuration saved successfully": "Stripe 配置保存成功",
"Failed to save Stripe configuration": "保存 Stripe 配置失败",
"Failed to save {{channelName}} config": "保存{{channelName}}配置失败",
@@ -693,8 +693,6 @@
"Stripe config saved successfully": "Stripe 配置保存成功",
"Alipay config saved successfully": "支付宝配置保存成功",
"WeChat config saved successfully": "微信配置保存成功",
"Login successful": "登录成功",
"Logged out successfully": "退出登录成功",
"Configure email settings": "配置邮箱设置",
"Email Configuration": "邮箱配置",
"Configure SMTP settings for email notifications": "配置SMTP设置用于邮件通知",
@@ -768,10 +766,10 @@
"Traditional email and password authentication": "传统邮箱和密码认证",
"Email/Verification Code": "邮箱/验证码",
"Passwordless login with email verification code": "邮箱验证码登录",
"Email service is not configured. Please configure email settings first.": "邮箱服务未配置。请先配置邮箱设置。",
"SMTP is not configured. Please configure email settings first.": "SMTP未配置。请先配置邮箱设置。",
"Go to Settings": "前往设置",
"AI Tools Marketplace": "AI工具市场",
"A marketplace for AI tools and services. Discover and integrate powerful AI solutions for your projects.": "一个AI工具和服务的市场。发现并整合强大的AI解决方案,为您的项目提供支持。",
"A marketplace for AI tools and servers. Discover and integrate powerful AI solutions for your projects.": "一个AI工具和服务的市场。发现并整合强大的AI解决方案,为您的项目提供支持。",
"Configuration": "配置",
"Featured Products": "推荐产品",
"Search": "搜索",
@@ -780,7 +778,7 @@
"Re-enter new password": "重新输入新密码",
"Confirm new password": "确认新密码",
"New password and confirm password do not match": "新密码和确认密码不匹配",
"New password must be at least 8 characters long": "新密码至少需要8个字符",
"New password must be at least 6 characters long": "新密码至少需要6个字符",
"New password and confirm password must be the same": "新密码和确认密码必须相同",
"New Password": "新密码",
"Confirm New Password": "确认新密码",
@@ -801,7 +799,6 @@
"Toggle to enable or disable custom HTML injection": "切换启用或禁用自定义HTML注入",
"Show Preview": "显示预览",
"Hide Preview": "隐藏预览",
"Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>": "在此输入您的自定义HTML、CSS或JavaScript代码...\n\n示例:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>",
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.": "此HTML将全局注入到应用程序中。您可以包含脚本标签、CSS样式或任何有效的HTML。",
"Preview": "预览",
"Note: This is a text preview. The actual HTML will be rendered when saved and enabled.": "注意:这是文本预览。实际的HTML将在保存并启用后渲染。",
@@ -840,8 +837,6 @@
"Target": "目标",
"Add Navigation Item": "添加导航项",
"Remove Navigation Item": "删除导航项",
"Enter title": "输入标题",
"Enter link URL": "输入链接地址",
"Same window": "当前窗口",
"New window": "新窗口",
"Custom HTML injection": "自定义HTML注入",
@@ -874,5 +869,93 @@
"Input": "输入",
"Output": "输出",
"1M tokens": "1M tokens",
"Total Spending": "总支出"
"Total Spending": "总支出",
"Remote": "远程",
"Platform Logo": "平台Logo",
"Support JPG, PNG, GIF. Max size 5MB": "支持JPG、PNG、GIF格式,最大大小5MB",
"(30 days)": "(30天)",
"Sign in": "登录",
"or create your account": "或创建您的账户",
"No account? Just continue—we’ll set you up.": "没有账户?继续即可,我们会为您设置。",
"Password must be at least 6 characters": "密码必须至少6个字符",
"Email is required": "邮箱为必填项",
"No servers available": "没有可用服务",
"(Deleted)": "(已删除)",
"Transport Type": "传输方式",
"Server ID must be less than 255 characters": "Server ID 必须少于255个字符",
"Server Name must be less than 255 characters": "Server Name 必须少于255个字符",
"API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint 必须是一个有效的HTTP/HTTPS URL",
"Server ID is required": "Server ID 为必填项",
"Short description is required": "简短描述为必填项",
"Add": "添加",
"Add to Groups": "添加到资源组",
"Group Name": "资源组名称",
"No resource groups available": "没有可用资源组",
"Failed to load group services": "加载资源组服务失败",
"Resource group deleted successfully": "资源组删除成功",
"Added Time": "添加时间",
"No services in this group": "此资源组没有服务",
"Open Resource Group Page": "打开资源组页面",
"Remove": "删除",
"Confirm Remove": "确认删除",
"Are you sure you want to remove this \"{{name}}\" mcp server from \"{{groupName}}\" resource group?": "您确定要从 \"{{groupName}}\" 资源组中移除 \"{{name}}\" MCP 服务吗?",
"Users associated with this resource group will not be able to call the removed MCP server": "与该资源组关联的用户将无法调用已移除的 MCP 服务",
"You don't have permission to access this MCP server.": "您没有权限访问此 MCP 服务。",
"Failed to load resource groups": "加载资源组失败",
"Failed to delete resource group": "删除资源组失败",
"Failed to add service to group": "添加服务到资源组失败",
"Resource group created successfully": "资源组创建成功",
"Resource group updated successfully": "资源组更新成功",
"Services added successfully": "服务添加成功",
"Service removed successfully": "服务移除成功",
"Select resource group": "选择资源组",
"Manage your resource group. Each user has a resource group and can only access resources within their resource group": "管理您的资源组。每个用户都有一个资源组,并且只能访问其资源组内的资源",
"Please select a group to view services": "请选择一个资源组来查看服务",
"Are you sure you want to remove this \"{{name}}\" Resource Group?": "您确定要删除这个 \"{{name}}\" 资源组吗?",
"The bound users have been transferred to the following resource group": "与该资源组关联的用户已转移至以下资源组",
"Service Name": "服务名称",
"Group List": "资源组列表",
"No groups found": "没有找到资源组",
"No more groups": "没有更多资源组",
"Are you sure you want to delete this item? This action cannot be undone.": "您确定要删除这个项目吗?此操作无法撤销。",
"Create New Resource Group": "创建新资源组",
"Edit Resource Group": "编辑资源组",
"Edit Resource Group Name": "编辑资源组名称",
"Set as default": "设置为默认",
"Automatically bind default resource groups when adding users": "添加用户时自动绑定默认资源组",
"Add MCP Server": "添加 MCP 服务",
"No MCP services available": "没有可用的 MCP 服务",
"Resource Groups": "资源组",
"Resource Group Name": "资源组名称",
"Failed to remove service from group": "从资源组中移除服务失败",
"Failed to update resource group": "更新资源组失败",
"Failed to create resource group": "创建资源组失败",
"Failed to fetch simple mcp services": "获取简易MCP服务失败",
"Failed to fetch group services": "获取资源组服务失败",
"Failed to update user resource group": "更新用户资源组失败",
"Failed to load simple resource groups": "获取简易资源组失败",
"Failed to load resource group detail": "获取资源组详情失败",
"Resource Group Detail": "资源组详情",
"Current display time is UTC time": "当前显示时间为UTC时间",
"View Resource Group Detail": "查看资源组详情",
"Configure tags bar display": "配置标签栏显示",
"Failed to load orders": "加载订单失败",
"Transaction Time": "交易时间",
"All": "全部",
"Purchase": "消费",
"No orders found": "无订单",
"Account Balance": "账户余额",
"View your balance and transaction history": "查看您的余额和交易历史",
"Display tags bar": "显示标签栏",
"Front end displays tags bar and allows users to filter products based on tags.": "前端显示标签栏,允许用户根据标签过滤产品。",
"Tags Bar": "标签栏",
"Auth Key Name": "认证密钥名称",
"Search by email": "按邮箱搜索",
"Search by service name": "按服务名称搜索",
"Select Date Range": "选择日期范围",
"Resource group name \"{{name}}\" is reserved and cannot be used": "资源组名称 \"{{name}}\" 是保留名称,不能使用",
"Resource group name \"{{name}}\" already exists": "资源组名称 \"{{name}}\" 已存在",
"Auth key name \"{{name}}\" already exists": "认证密钥 \"{{name}}\" 已存在",
"Start date must be before end date": "开始日期必须早于结束日期",
"Start date cannot be earlier than 30 days ago": "开始日期不能早于30天前"
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 MiB

+92
View File
@@ -0,0 +1,92 @@
import { ApiResponse } from "@/shared/types";
import { fetchAdminAPI } from "@/rpc/admin-api";
/**
* Admin analytics API data structures based on OpenAPI spec
* GET /api/admin/stats/analytics
*/
export interface DayCountStringItem {
stats_day: string; // yyyy-mm-dd
count: string;
}
export interface DayCountNumberItem {
stats_day: string; // yyyy-mm-dd
count: number;
}
// 用户注册数据
export interface UserRegisterData {
total: number; // user register total count
today?: number; // today user register count
days: DayCountStringItem[]; // daily user register count
}
// user pay data
export interface UserPayData {
total: number; // user pay total amount
today?: number; // today user pay amount
days: DayCountNumberItem[]; // daily user pay amount
}
// MCP 调用数据
export interface MCPCallData {
total: number; // mcp call total count
today?: number; // today mcp call count
days: DayCountNumberItem[]; // daily mcp call count
}
// Top server items
export interface TopServiceItem {
id: string; // server id
name: string; // server name
short_description: string; // short description
call_count: number; // call count
is_deleted: boolean; //It means the server was deleted.
}
// admin analytics data
export interface AdminAnalyticsData {
user_register: UserRegisterData;
user_pay: UserPayData;
mcp_call: MCPCallData;
top_services: TopServiceItem[];
}
// admin analytics response body
export interface AdminAnalyticsResponse
extends ApiResponse<AdminAnalyticsData> {
success: boolean;
code: string;
error_message: string;
data: AdminAnalyticsData;
}
/**
* Get admin analytics data
* Headers: { Authorization: string }
* @param start_time - Start time timestamp (seconds)
* @param end_time - End time timestamp (seconds)
*/
export async function getAdminAnalytics(
start_time?: number,
end_time?: number
): Promise<AdminAnalyticsResponse> {
const params = new URLSearchParams();
if (start_time !== undefined) {
params.append('start', start_time.toString());
}
if (end_time !== undefined) {
params.append('end', end_time.toString());
}
const url = `/api/admin/stats/analytics${params.toString() ? `?${params.toString()}` : ''}`;
return fetchAdminAPI<AdminAnalyticsData>(url, {
method: "GET",
}) as unknown as AdminAnalyticsResponse;
}
+30
View File
@@ -0,0 +1,30 @@
import { fetchAdminAPI } from "@/rpc/admin-api";
import { ApiResponse } from "@/shared/types";
import toast from "react-hot-toast";
export enum OnboardingTaskKey {
PLATFORM_SETUP = "configure-platform-settings",
MCP_SERVICES = "add-mcp-services",
REVENUE_MANAGEMENT = "configure-platment-billings",
SHARE_PLATFORM = "share-your-platform",
}
export enum TaskStatusEnum {
COMPLETED = 1,
NOT_STARTED = 0,
}
export type TaskItem = {
task_id: OnboardingTaskKey;
task_status: TaskStatusEnum;
};
export async function updateAdminOnboardingTasks(
task: TaskItem
): Promise<boolean> {
const res = (await fetchAdminAPI<void>("/api/onboarding/task_update_status", {
method: "PUT",
body: task as unknown as BodyInit,
})) as unknown as ApiResponse<void>;
// if (!res.success) {
// toast.error(res.error_message || "Failed to update onboarding task status");
// }
return res.success;
}
+305
View File
@@ -0,0 +1,305 @@
import { SimpleMcpService } from "@/components/resource-group/AddMcpServerModal";
import { GroupService } from "@/components/resource-group/GroupServiceTable";
import { fetchAdminAPI } from "@/rpc/admin-api";
import { toast } from "react-hot-toast";
import i18n from "@/shared/lib/i18n";
export interface ResourceGroupResponse {
id: string;
name: string;
description: string;
is_default: boolean;
service_count: number;
create_at: string;
}
export interface ResourceGroupDetailResponse {
id: string;
name: string;
description: string;
is_default: boolean;
update_at: number;
create_at: string;
}
export interface ResourceGroupListResponse {
data: ResourceGroupResponse[];
total: number;
page: number;
page_size: number;
}
export interface GroupServiceListResponse {
data: GroupService[];
total: number;
page: number;
page_size: number;
}
export interface SimpleMcpServiceListResponse {
data: SimpleMcpService[];
total: number;
page: number;
page_size: number;
}
export const fetchResourceGroupDetail = async (groupId: string): Promise<ResourceGroupDetailResponse | null> => {
try {
const response = await fetchAdminAPI<ResourceGroupDetailResponse>(`/api/resource_group/info?id=${groupId}`);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to load resource group detail"));
return null;
}
return response.data || null;
} catch (error) {
console.error("Error fetching resource group detail:", error);
return null;
}
};
/**
* 获取资源组列表
*/
export const fetchResourceGroups = async (page: number, page_size: number, keyword: string): Promise<ResourceGroupListResponse> => {
try {
const response = await fetchAdminAPI<ResourceGroupResponse[]>(`/api/resource_group/list?page=${page}&page_size=${page_size}&keyword=${keyword}`);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to load resource groups"));
return {
data: [],
total: 0,
page,
page_size,
};
}
return {
data: response.data || [],
total: response.page?.total || 0,
page: response.page?.page || page,
page_size: response.page?.page_size || page_size,
};
} catch (error) {
console.error("Error fetching auth keys:", error);
return {
data: [],
total: 0,
page,
page_size,
};
}
};
/**
* 获取简易资源组列表
*/
export const fetchSimpleResourceGroups = async (): Promise<{ id: string, name: string }[]> => {
try {
const response = await fetchAdminAPI<{ id: string, name: string }[]>(`/api/resource_group/list/simple`);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to load simple resource groups"));
return []
}
return response.data || []
} catch (error) {
console.error("Error fetching auth keys:", error);
return []
}
};
/**
* 修改用户资源组
*/
export const updateUserResourceGroup = async (userId: string, resourceGroupId: string): Promise<boolean> => {
try {
const response = await fetchAdminAPI<boolean>(`/api/user_manager/resource_group`, {
method: "PUT",
body: { user_id: userId, resource_group: resourceGroupId } as unknown as BodyInit,
});
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to update user resource group"));
return false;
}
return true;
} catch (error) {
console.error("Error updating user resource group:", error);
return false
}
};
/**
* 获取指定资源组下的服务列表
*/
export const fetchGroupServices = async (id: string,page: number, page_size: number, keyword: string): Promise<GroupServiceListResponse> => {
try {
const response = await fetchAdminAPI<GroupService[]>(`/api/resource_group/service/list?id=${id}&page=${page}&page_size=${page_size}&keyword=${keyword}`);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to fetch group services"));
return {
data: [],
total: 0,
page,
page_size,
};
}
return {
data: response.data || [],
total: response.page?.total || 0,
page: response.page?.page || page,
page_size: response.page?.page_size || page_size,
};
} catch (error) {
console.error("Error fetching auth keys:", error);
return {
data: [],
total: 0,
page,
page_size,
};
}
};
/**
* 获取简易指定资源组下的服务列表
*/
export const fetchSimpleMcpServices = async (id: string): Promise<SimpleMcpService[]> => {
try {
const response = await fetchAdminAPI<SimpleMcpService[]>(`/api/resource_group/service/list/unbind?id=${id}`);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to fetch simple mcp services"));
return []
}
return response.data || []
} catch (error) {
console.error("Error fetching auth keys:", error);
return []
}
};
/**
* 创建资源组
*/
export const createResourceGroup = async (name: string, isDefault: boolean): Promise<{success: boolean, id: string}> => {
try {
const response = await fetchAdminAPI<{id: string}>(`/api/resource_group`, {
method: "POST",
body: { name: name, is_default: isDefault } as unknown as BodyInit,
});
if (!response.success) {
const errorMsg = response.error_message
if (errorMsg?.endsWith('already exists')) {
toast.error(i18n.t(errorMsg, { name: name }));
} else if(errorMsg?.endsWith('cannot be used')) {
toast.error(i18n.t(errorMsg, { name: name }));
} else {
toast.error(errorMsg || i18n.t("Failed to create resource group"));
}
return {
success: false,
id: "",
};
}
return {
success: true,
id: response.data?.id || "",
};
} catch {
return {
success: false,
id: "",
};
}
};
/**
* 更新资源组
*/
export const updateResourceGroup = async (
groupId: string,
name: string,
isDefault: boolean
): Promise<boolean> => {
try {
const response = await fetchAdminAPI<boolean>(`/api/resource_group?id=${groupId}`, {
method: "PUT",
body: { name: name, is_default: isDefault } as unknown as BodyInit,
});
if (!response.success) {
const errorMsg = response.error_message
if (errorMsg?.endsWith('already exists')) {
toast.error(i18n.t(errorMsg, { name: name }));
} else if(errorMsg?.endsWith('cannot be used')) {
toast.error(i18n.t(errorMsg, { name: name }));
} else {
toast.error(errorMsg || i18n.t("Failed to update resource group"));
}
return false;
}
return true;
} catch {
return false
}
};
/**
* 删除资源组
*/
export const deleteResourceGroup = async (
groupId: string,
transferToGroupId: string
): Promise<boolean> => {
try {
const response = await fetchAdminAPI<boolean>(`/api/resource_group?id=${groupId}&migrate_id=${transferToGroupId}`, {
method: "DELETE"
});
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to delete resource group"));
return false;
}
return true;
} catch {
return false
}
};
/**
* 从资源组中移除服务
*/
export const removeServiceFromGroup = async (
groupId: string,
serviceIds: string[]
): Promise<boolean> => {
try {
const response = await fetchAdminAPI<boolean>(`/api/resource_group/service?id=${groupId}`, {
method: "DELETE",
body: { services: serviceIds } as unknown as BodyInit,
});
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to remove service from group"));
return false;
}
return true;
} catch {
return false
}
};
/**
* 添加服务到资源组
*/
export const addServiceToGroup = async (
groupId: string,
services: string[]
): Promise<boolean> => {
try {
const response = await fetchAdminAPI<boolean>(`/api/resource_group/service?id=${groupId}`, {
method: "PUT",
body: { services: services } as unknown as BodyInit,
});
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to add service to group"));
return false;
}
return true;
} catch {
return false
}
};
+2 -2
View File
@@ -4,8 +4,8 @@ import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
import { AboutThemeSelector } from "@/components/theme/AboutThemeSelector";
export async function generateMetadata(): Promise<Metadata> {
const title = await getDynamicTitle("About");
return createBaseMetadata(title);
const platformConfig = await getDynamicTitle("About");
return createBaseMetadata(platformConfig);
}
export default async function AboutPage() {
+17 -10
View File
@@ -1,13 +1,20 @@
'use server';
"use server";
import { revalidatePath, revalidateTag } from 'next/cache';
import { revalidatePath, revalidateTag } from "next/cache";
import { headers } from "next/headers";
export async function revalidatePlatformConfig() {
// 重新验证根路径和所有子路径
revalidatePath('/', 'layout');
// 如果使用了标签缓存,也可以重新验证特定标签
revalidateTag('platform-config');
console.log('Platform config cache revalidated');
}
// Get current host for host-specific cache invalidation
const headersList = await headers();
const host = headersList.get("host") || "default";
// Revalidate root path and all sub-paths
revalidatePath("/", "layout");
// Revalidate host-specific cache tag
revalidateTag(`platform-config-${host}`, 'max');
console.info(
`Platform config cache revalidated for host: platform-config-${host}`
);
}
@@ -6,7 +6,6 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useAdminLogin } from "@/hooks/useAdminLogin";
import toast from "react-hot-toast";
const adminLoginSchema = z.object({
username: z.string().min(1, "Username is required"),
@@ -62,4 +61,4 @@ export const AdminLoginForm = () => {
</Button>
</form>
);
};
};
+13
View File
@@ -0,0 +1,13 @@
import React from "react";
import type { Metadata } from "next";
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
import ConsoleMain from "@/components/console/Main";
export async function generateMetadata(): Promise<Metadata> {
const platformConfig = await getDynamicTitle("Console");
return createBaseMetadata(platformConfig);
}
export default function AdminConsolePage() {
return <ConsoleMain />;
}
+5 -3
View File
@@ -15,8 +15,10 @@ const AdminLoginHeader = () => {
return (
<div className="flex flex-col items-center pb-6">
<DynamicLogo alt="Platform Logo" className="h-[40px]" />
<p className="text-xl font-medium mt-4">{t("Admin Portal")}</p>
<p className="text-sm text-default-500">{t("Log in to admin console")}</p>
<p className="text-xl font-medium mt-4">{t("Welcome")}</p>
<p className="text-sm text-default-500">
{t("Log in to your admin account to continue")}
</p>
</div>
);
};
@@ -28,7 +30,7 @@ const AdminLoginPageContent = () => {
const handleCheckLogin = async () => {
const res = await getAdminUser();
if (res.success) {
router.push("/console");
router.push("/admin/console");
}
};
+5 -7
View File
@@ -1,15 +1,13 @@
import React from "react";
import type { Metadata } from "next";
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
import ConsoleMain from "@/components/console/Main";
import DashboardMain from "@/components/dashboard/Main";
export async function generateMetadata(): Promise<Metadata> {
const title = await getDynamicTitle("Console");
return createBaseMetadata(title);
const platformConfig = await getDynamicTitle("Dashboard");
return createBaseMetadata(platformConfig);
}
export default function HomePage() {
return (
<ConsoleMain />
);
export default function ConsolePage() {
return <DashboardMain />;
}
-15
View File
@@ -1,15 +0,0 @@
import React from "react";
import type { Metadata } from "next";
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
import DashboardMain from "@/components/dashboard/Main";
export async function generateMetadata(): Promise<Metadata> {
const title = await getDynamicTitle("Dashboard");
return createBaseMetadata(title);
}
export default function HomePage() {
return (
<DashboardMain />
);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 11 KiB

+14 -2
View File
@@ -1,9 +1,14 @@
/* Import theme styles */
@import "../styles/themes.css";
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Import theme styles */
@import '../styles/themes.css';
input::placeholder,
textarea::placeholder {
--nextui-foreground-500: 240 5.03% 64.9%;
}
html,
body {
@@ -84,3 +89,10 @@ body {
background-size: 16px 16px; /* 每个格子的尺寸 */
background-repeat: repeat;
}
.wmde-markdown ul,
.wmde-markdown ol {
list-style-type: revert;
}
.wmde-markdown {
background-color: inherit !important;
}
+16 -11
View File
@@ -2,7 +2,11 @@ import type { Metadata } from "next";
import { Red_Hat_Display } from "next/font/google";
import ClientRootProviders from "@/shared/components/ClientRootProviders";
import "./globals.css";
import { getCachedPlatformConfig, getDynamicTitle, createBaseMetadata } from "@/shared/utils/metadata";
import {
getCachedPlatformConfig,
getDynamicTitle,
createBaseMetadata,
} from "@/shared/utils/metadata";
const redHatDisplay = Red_Hat_Display({
subsets: ["latin"],
@@ -11,8 +15,8 @@ const redHatDisplay = Red_Hat_Display({
});
export async function generateMetadata(): Promise<Metadata> {
const title = await getDynamicTitle();
return createBaseMetadata(title);
const platformConfig = await getDynamicTitle();
return createBaseMetadata(platformConfig);
}
export default async function RootLayout({
@@ -23,7 +27,7 @@ export default async function RootLayout({
const platformConfig = await getCachedPlatformConfig();
return (
<html lang="en" suppressHydrationWarning>
<html lang="en" suppressHydrationWarning data-color-mode="light">
<head>
<script
dangerouslySetInnerHTML={{
@@ -32,15 +36,16 @@ export default async function RootLayout({
`,
}}
/>
{platformConfig?.embeded_html?.is_enabled && platformConfig?.embeded_html?.html && (
<div
dangerouslySetInnerHTML={{
__html: platformConfig.embeded_html.html,
}}
/>
)}
</head>
<body className={redHatDisplay.className} suppressHydrationWarning>
{platformConfig?.embeded_html?.is_enabled &&
platformConfig?.embeded_html?.html && (
<div
dangerouslySetInnerHTML={{
__html: platformConfig.embeded_html.html,
}}
/>
)}
<ClientRootProviders initConfig={platformConfig}>
{children}
</ClientRootProviders>
+12 -14
View File
@@ -2,7 +2,7 @@
import React, { useEffect, Suspense } from "react";
import { Spinner, Button } from "@nextui-org/react";
import { useLogin } from "@/hooks/useLogin";
import { useLogin } from "@/shared/hooks/useLogin";
import { useRouter, useSearchParams } from "next/navigation";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useTranslation } from "@/shared/lib/useTranslation";
@@ -22,7 +22,7 @@ function LoginSuccessContent() {
const backHome = () => {
const dynamicParams = new URLSearchParams(searchParams?.get("state") || "");
router.push(`/login?${dynamicParams.toString()}`);
router.push(`/?${dynamicParams.toString()}`);
};
return (
@@ -31,22 +31,14 @@ function LoginSuccessContent() {
<Spinner size="lg" color="default" />
) : status === "success" ? (
<>
<Icon
fontSize={70}
className="text-success"
icon="mi:circle-check"
/>
<Icon fontSize={70} className="text-success" icon="mi:circle-check" />
<div className="text-xl font-bold text-success">
{t("Login Success")}
</div>
</>
) : (
<>
<Icon
fontSize={70}
className="text-danger"
icon="mi:circle-error"
/>
<Icon fontSize={70} className="text-danger" icon="mi:circle-error" />
<div className="text-xl font-bold text-danger">
{t("Login Error")}
</div>
@@ -59,8 +51,14 @@ function LoginSuccessContent() {
export default function LoginSuccessPage() {
return (
<Suspense fallback={<div className="flex justify-center mt-40"><Spinner size="lg" color="default" /></div>}>
<Suspense
fallback={
<div className="flex justify-center mt-40">
<Spinner size="lg" color="default" />
</div>
}
>
<LoginSuccessContent />
</Suspense>
);
}
}
+4 -4
View File
@@ -6,8 +6,8 @@ import type { ServiceData } from "@/shared/types/marketplace";
import { ThemeSelector } from "@/components/theme/ThemeSelector";
export async function generateMetadata(): Promise<Metadata> {
const title = await getDynamicTitle();
return createBaseMetadata(title);
const platformConfig = await getDynamicTitle();
return createBaseMetadata(platformConfig);
}
export default async function HomePage({
@@ -36,8 +36,8 @@ export default async function HomePage({
services = response?.data?.services || [];
total = response?.page?.total || 0;
} catch (err) {
console.error("Error fetching services:", err);
error = "Failed to load services";
console.error("Error fetching servers:", err);
error = "Failed to load servers";
}
return (
@@ -5,8 +5,6 @@ import type { Metadata } from "next";
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
import { fetchServiceById } from "@/services/marketplaceService";
import type { ServiceData } from "@/shared/types/marketplace";
import { Footer } from "@/shared/components/Footer";
import { Navigation } from "@/shared/components/Navigation";
interface ProductPageProps {
params: Promise<{ id: string }>;
@@ -32,20 +30,15 @@ export async function generateMetadata({
// use cached function to get data to generate metadata
const product = await getProductById(id);
const productName = product?.name || "Unknown";
if (product) {
const title = await getDynamicTitle(product.name);
return {
...createBaseMetadata(title),
description:
product.short_description ||
`Discover ${product.name} and its powerful tools`,
};
}
// default metadata if product not found
const defaultTitle = await getDynamicTitle("Marketplace");
return createBaseMetadata(defaultTitle);
const platformConfig = await getDynamicTitle(productName);
return {
...createBaseMetadata(platformConfig),
description:
product?.short_description ||
`Discover ${productName} and its powerful tools`,
};
}
export default async function ProductPage({ params }: ProductPageProps) {
@@ -6,8 +6,21 @@ import { Icon } from "@iconify/react/dist/iconify.js";
interface LoginButtonProps {
title: string;
icon?: string;
color?: "default" | "primary" | "secondary" | "success" | "warning" | "danger";
variant?: "solid" | "bordered" | "light" | "flat" | "faded" | "shadow" | "ghost";
color?:
| "default"
| "primary"
| "secondary"
| "success"
| "warning"
| "danger";
variant?:
| "solid"
| "bordered"
| "light"
| "flat"
| "faded"
| "shadow"
| "ghost";
onClick?: () => void;
}
@@ -29,4 +42,4 @@ export const LoginButton = ({
{title}
</Button>
);
};
};
@@ -6,12 +6,13 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { StepState } from "../page";
import { useTranslation } from "@/shared/lib/useTranslation";
import i18n from "@/shared/lib/i18n";
const emailSchema = z.object({
email: z
.string()
.email({ message: "Invalid email address" })
.min(1, { message: "Email is required" }),
.email({ message: i18n.t("Invalid email address") })
.min(1, { message: i18n.t("Email is required") }),
});
type EmailFormData = z.infer<typeof emailSchema>;
@@ -30,7 +31,7 @@ export const LoginEmailFrom = ({ setEmail, setStep }: LoginEmailFromProps) => {
formState: { errors, isSubmitting, isValid },
} = useForm<EmailFormData>({
resolver: zodResolver(emailSchema),
mode: "all",
mode: "onBlur",
});
const onSubmit = async (data: EmailFormData) => {
@@ -61,7 +62,9 @@ export const LoginEmailFrom = ({ setEmail, setStep }: LoginEmailFromProps) => {
type="submit"
color="primary"
isLoading={isSubmitting}
className="w-full"
size="lg"
className="w-full font-semibold bg-default-900"
isDisabled={!isValid}
>
{t("Continue")}
</Button>
@@ -7,15 +7,16 @@ import { z } from "zod";
import { useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useLogin } from "@/hooks/useLogin";
import { useLogin } from "@/shared/hooks/useLogin";
import { md5Encrypt } from "@/shared/utils/crypto";
import i18n from "@/shared/lib/i18n";
const emailPasswordSchema = z.object({
email: z
.string()
.email({ message: "Invalid email address" })
.min(1, { message: "Email is required" }),
password: z.string().min(6, "Password must be at least 6 characters"),
.email({ message: i18n.t("Invalid email address") })
.min(1, { message: i18n.t("Email is required") }),
password: z.string().min(6, i18n.t("Password must be at least 6 characters")),
});
type EmailPasswordFormData = z.infer<typeof emailPasswordSchema>;
@@ -37,7 +38,7 @@ export const LoginEmailPasswordForm = ({
formState: { errors, isSubmitting, isValid },
} = useForm<EmailPasswordFormData>({
resolver: zodResolver(emailPasswordSchema),
mode: "all",
mode: "onBlur",
});
const onSubmit = async (data: EmailPasswordFormData) => {
@@ -105,9 +106,11 @@ export const LoginEmailPasswordForm = ({
type="submit"
color="primary"
isLoading={isSubmitting}
className="w-full"
size="lg"
className="w-full font-semibold bg-default-900"
isDisabled={!isValid}
>
{t("Sign In")}
{t("Continue")}
</Button>
</form>
);
+88 -51
View File
@@ -1,86 +1,123 @@
"use client";
import { Divider } from "@nextui-org/react";
import { Suspense, useState } from "react";
import { useRef, useState } from "react";
import { LoginButton } from "./LoginButton";
import { useLogin } from "@/hooks/useLogin";
import { useLogin } from "@/shared/hooks/useLogin";
import { EmailVerificationForm } from "./VerifyEmail";
import { LoginEmailFrom } from "./LoginEmailFrom";
import { LoginEmailPasswordForm } from "./LoginEmailPasswordForm";
import { useTranslation } from "@/shared/lib/useTranslation";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { EmailMode } from "@/shared/types/system";
import BgCollagePattern from "@/shared/components/sign/BgCollagePattern";
import { DynamicLogo } from "@/shared/components/DynamicLogo";
export type StepState = "init" | "emailForm" | "verifyEmail";
const SignInComponent = () => {
export default function SignInComponent() {
const { t } = useTranslation();
const [email, setEmail] = useState("");
const [step, setStep] = useState<StepState>("init");
const { googleLoginOrSignUp } = useLogin();
const { loginConfig } = usePlatformConfig();
const containerRef = useRef<HTMLDivElement>(null);
// 检查是否启用了 Google 登录
const isGoogleLoginEnabled =
loginConfig?.google?.is_enabled && loginConfig?.google?.client_id;
// 检查是否启用了邮箱登录
const isEmailEnabled = loginConfig?.email?.is_enabled ?? true;
// 获取邮箱登录模式
const emailMode = loginConfig?.email?.mode ?? EmailMode.PASSWORD;
return (
<>
<div className="mt-2 flex w-full max-w-sm flex-col gap-8 rounded-large bg-content1 px-8 py-6 shadow-small backdrop-blur-sm">
{step === "verifyEmail" && <EmailVerificationForm email={email} />}
{step === "init" && isGoogleLoginEnabled && (
<LoginButton
title={t("Log in with Google")}
color="primary"
variant="solid"
icon="flat-color-icons:google"
onClick={googleLoginOrSignUp}
/>
)}
{/* OR - 只有在启用 Google 登录且有其他登录方式时才显示分隔符 */}
{isGoogleLoginEnabled && isEmailEnabled && (
<div className="flex items-center gap-4">
<Divider className="flex-1" />
<p className="shrink-0 text-tiny text-default-500">{t("OR")}</p>
<Divider className="flex-1" />
</div>
)}
{/* Login With Email */}
{step === "init" && isEmailEnabled && (
<div className="space-y-4">
{/* 邮箱/密码登录表单 */}
{emailMode === EmailMode.PASSWORD && (
<LoginEmailPasswordForm />
)}
<div
className="relative w-full min-h-screen flex items-center justify-center"
ref={containerRef}
>
{/* Background collage pattern */}
<BgCollagePattern
containerRef={containerRef}
options={{
radius: 30,
background: "#f5f5f5",
particleCount: 20000,
color: "#006fee",
colorPole: "#001aee",
}}
/>
<div className="relative z-10 w-full max-w-md">
<div className="bg-white rounded-2xl shadow-2xl p-8 backdrop-blur-lg bg-opacity-95">
<div className="mb-10">
<div className="flex gap-2 mb-4">
<DynamicLogo className="h-[32px]" hideText />
</div>
<h1 className="text-3xl font-semibold text-default-900">
{t("Sign in")} <br />
<span>{t("or create your account")}</span>
</h1>
</div>
{/* 邮箱/验证码登录表单 */}
{emailMode === EmailMode.CAPTCHA && (
<LoginEmailFrom setEmail={setEmail} setStep={setStep} />
)}
<div className="space-y-6">
{step === "verifyEmail" && (
<EmailVerificationForm email={email} />
)}
{step === "init" && isGoogleLoginEnabled && (
<LoginButton
title={t("Log in with Google")}
color="primary"
variant="solid"
icon="flat-color-icons:google"
onClick={googleLoginOrSignUp}
/>
)}
{/* OR - 只有在启用 Google 登录且有其他登录方式时才显示分隔符 */}
{isGoogleLoginEnabled && isEmailEnabled && (
<div className="flex items-center gap-4">
<Divider className="flex-1" />
<p className="shrink-0 text-tiny text-default-500">
{t("OR")}
</p>
<Divider className="flex-1" />
</div>
)}
{/* Login With Email */}
{step === "init" && isEmailEnabled && (
<div className="space-y-4">
{/* 邮箱/密码登录表单 */}
{emailMode === EmailMode.PASSWORD && (
<LoginEmailPasswordForm />
)}
{/* 邮箱/验证码登录表单 */}
{emailMode === EmailMode.CAPTCHA && (
<LoginEmailFrom setEmail={setEmail} setStep={setStep} />
)}
</div>
)}
{step !== "init" && isGoogleLoginEnabled && (
<LoginButton
title={t("Log in with Google")}
icon="flat-color-icons:google"
onClick={googleLoginOrSignUp}
/>
)}
{/* 底部提示文本 */}
{step === "init" && (
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
{t("No account? Just continue—we’ll set you up.")}
</p>
</div>
)}
</div>
</div>
)}
{step !== "init" && isGoogleLoginEnabled && (
<LoginButton
title={t("Log in with Google")}
icon="flat-color-icons:google"
onClick={googleLoginOrSignUp}
/>
)}
</div>
</div>
</>
);
};
export default function SignInWrapper() {
return (
<Suspense fallback={<></>}>
<SignInComponent />
</Suspense>
);
}
@@ -5,11 +5,11 @@ import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useEffect, useRef, useState } from "react";
import { useLogin } from "@/hooks/useLogin";
import { useLogin } from "@/shared/hooks/useLogin";
import { useTranslation } from "@/shared/lib/useTranslation";
import toast from "react-hot-toast";
import { fetchAPI } from "@/shared/rpc/common-function";
import { getEmail } from "@/utils/getEmail";
import { getEmail } from "@/shared/utils/getEmail";
const schema = z.object({
captcha: z
+10 -26
View File
@@ -2,14 +2,11 @@
import React, { useEffect, Suspense } from "react";
import { Spinner } from "@nextui-org/react";
import { Toaster } from "react-hot-toast";
import SignInComponent from "./components/SignIn";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useSearchParams } from "next/navigation";
import { useLogin } from "@/hooks/useLogin";
import { useLogin } from "@/shared/hooks/useLogin";
import { useSharedStore } from "@/shared/store/share";
import { useGlobalStore } from "@/shared/store/global";
import { DynamicLogo } from "@/shared/components/DynamicLogo";
export interface LoginFormData {
user_email: string;
@@ -17,23 +14,6 @@ export interface LoginFormData {
nick_name?: string;
}
const LoginHeader = () => {
const { t } = useTranslation();
return (
<div className="flex flex-col items-center pb-6">
<DynamicLogo
alt="Platform Logo"
className="h-[40px]"
/>
<p className="text-xl font-medium mt-4">{t("Welcome")}</p>
<p className="text-sm text-default-500">
{t("Log in to your account to continue")}
</p>
</div>
);
};
export type StepState = "init" | "emailForm" | "verifyEmail";
const LoginPageContent = () => {
@@ -58,10 +38,8 @@ const LoginPageContent = () => {
return (
<>
<div className="flex flex-col items-center justify-center w-full h-full mt-20">
<LoginHeader />
<div className="flex flex-col items-center justify-center w-full h-full">
<SignInComponent />
<Toaster />
</div>
</>
);
@@ -69,10 +47,16 @@ const LoginPageContent = () => {
const LoginPage = () => {
return (
<Suspense fallback={<div className="flex justify-center mt-40"><Spinner size="lg" color="default" /></div>}>
<Suspense
fallback={
<div className="flex justify-center">
<Spinner size="lg" color="default" />
</div>
}
>
<LoginPageContent />
</Suspense>
);
};
export default LoginPage;
export default LoginPage;
+10 -10
View File
@@ -1,7 +1,7 @@
"use client";
import React from "react";
import ReactMarkdown from "react-markdown";
import MarkdownPreview from "@uiw/react-markdown-preview";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { Card, CardBody } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
@@ -14,26 +14,26 @@ export const AboutContent: React.FC = () => {
<Card shadow="none" className="bg-transparent">
<CardBody className="space-y-4">
<h1 className="text-3xl font-bold mb-6">{t("About Us")}</h1>
<div className="leading-relaxed prose prose-sm max-w-none">
<div className="leading-relaxed max-w-none">
{platformConfig.about_page ? (
<ReactMarkdown>{platformConfig.about_page}</ReactMarkdown>
<MarkdownPreview source={platformConfig.about_page} />
) : (
<ReactMarkdown>
{`
${t("**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) services.")}
${t("It allows you to transform any OpenAPI into a monetizable MCP service and build your own API store in just minutes.")}
<MarkdownPreview
source={`
${t("**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) servers.")}
${t("It allows you to transform any OpenAPI into a monetizable MCP server and build your own API store in just minutes.")}
${t("✨ With XPack, you can:")}
${t("- ✅ **One-click OpenAPI → MCP service config**")}
${t("- 🧾 **SEO-friendly homepage + mcp service page**")}
${t("- ✅ **One-click OpenAPI → MCP server config**")}
${t("- 🧾 **SEO-friendly homepage + mcp server page**")}
${t("- 💳 **Built-in billing (per-call)**")}
${t("- 👥 **User account management**")}
${t("- 🛠 **Support Stripe Payment**")}
${t("- 🔐 **Support Email & Google OAuth Sign in**")}
${t("Everything is open-source and licensed under **Apache 2.0** — ready for commercial use.")}`}
</ReactMarkdown>
/>
)}
</div>
</CardBody>
@@ -48,8 +48,8 @@ export const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({
return;
}
if (newPassword.length < 8) {
toast.error(t("Password must be at least 8 characters long"));
if (newPassword.length < 6) {
toast.error(t("Password must be at least 6 characters long"));
return;
}
@@ -73,7 +73,7 @@ export const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({
newPassword.trim() !== "" &&
confirmPassword.trim() !== "" &&
newPassword === confirmPassword &&
newPassword.length >= 8;
newPassword.length >= 6;
return (
<Modal isOpen={isOpen} onClose={handleClose} size="md">
@@ -90,7 +90,7 @@ export const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({
type={showNewPassword ? "text" : "password"}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
description={t("Password must be at least 8 characters long")}
description={t("Password must be at least 6 characters long")}
endContent={
<button
type="button"
@@ -0,0 +1,113 @@
"use client";
import React, { useState, useRef } from "react";
import { Card, Spinner } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import toast from "react-hot-toast";
import { UploadIcon } from "lucide-react";
import { calculateFileSha256 } from "@/shared/utils/crypto";
interface UploadImageProps {
onSave: (file: File, sha256?: string) => Promise<string>;
imageUrl?: string;
setImageUrl: (imageUrl: string) => void;
className?: string;
description?: string;
}
const UploadImage: React.FC<UploadImageProps> = ({
onSave,
imageUrl,
setImageUrl,
className = "h-32 w-32",
description,
}) => {
const { t } = useTranslation();
const [isUploading, setIsUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleImageUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
const file = event.target.files?.[0];
if (!file) return;
// Validate file type
if (!file.type.startsWith("image/")) {
toast.error(t("Please select a valid image file"));
return;
}
// Validate file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
toast.error(t("Image size should be less than 5MB"));
return;
}
setIsUploading(true);
try {
const sha256 = await calculateFileSha256(file);
const imageUrl = await onSave(file, sha256);
setImageUrl(imageUrl);
} catch (error) {
console.error("Upload failed:", error);
toast.error(t("Failed to upload image"));
} finally {
setIsUploading(false);
}
};
const handleImageClick = () => {
if (!isUploading) {
fileInputRef.current?.click();
}
};
return (
<div className="space-y-2">
<Card
className={`relative group ${isUploading ? "cursor-not-allowed" : "cursor-pointer"} ${className} `}
style={{
backgroundSize: "contain",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
}}
onPress={handleImageClick}
isPressable={!isUploading}
shadow="none"
>
{imageUrl && (
<img
src={imageUrl}
alt="Uploaded"
className="w-full h-full object-contain"
/>
)}
<div
className={`absolute top-0 rounded-large right-0 bg-default-100 w-full h-full flex items-center justify-center transition-opacity duration-300 ${
imageUrl && !isUploading ? "opacity-0" : "opacity-100"
} group-hover:opacity-50 backdrop-blur-sm`}
></div>
<div
className={`absolute w-full h-full flex flex-col gap-2 items-center justify-center ${
imageUrl && !isUploading ? "opacity-0" : "opacity-100"
} group-hover:opacity-100`}
>
<span>
{isUploading ? <Spinner size="lg" /> : <UploadIcon size={48} />}
</span>
<span className="text-sm text-default-500">{description}</span>
</div>
</Card>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleImageUpload}
className="hidden"
/>
</div>
);
};
export default UploadImage;
@@ -0,0 +1,138 @@
"use client";
import React, { useState } from "react";
import { Input, Button } from "@nextui-org/react";
import { Eye, EyeOff } from "lucide-react";
import { AdminConfig } from "@/types/system";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "@/shared/lib/useTranslation";
const formSchema = z.object({
password: z
.string()
.min(1, "Password is required")
.max(100, "Password is too long")
.min(6, "Password must be at least 6 characters"),
confirmPassword: z
.string()
.min(1, "Confirm password is required")
.max(100, "Confirm password is too long")
.min(6, "Confirm password must be at least 6 characters"),
});
type FormData = z.infer<typeof formSchema>;
interface AdminConfigFormProps {
onSave: (config: AdminConfig) => Promise<boolean>;
}
export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({ onSave }) => {
const { t } = useTranslation();
const {
handleSubmit,
control,
watch,
formState: { errors, isSubmitting, isValid },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
mode: "onBlur",
});
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const onSubmit = async (data: FormData) => {
await onSave({
password: data.password,
} as AdminConfig);
};
const passwordsMatch = watch("password") === watch("confirmPassword");
return (
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col gap-4 pb-4"
>
<Controller
name="password"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Administrator Password")}
placeholder={t("Enter administrator password")}
description={t("Password must be at least 6 characters long")}
isInvalid={!!errors.password}
errorMessage={errors.password?.message}
type={showPassword ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="focus:outline-none"
>
{showPassword ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
isRequired
autoComplete="new-password"
labelPlacement="outside"
/>
)}
/>
<Controller
name="confirmPassword"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Confirm Password")}
placeholder={t("Confirm administrator password")}
description={t("Re-enter the password to confirm")}
isInvalid={
!!errors.confirmPassword ||
(!passwordsMatch && (field.value?.length || 0) > 0)
}
errorMessage={
errors.confirmPassword?.message || t("Passwords do not match")
}
type={showConfirmPassword ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="focus:outline-none"
>
{showConfirmPassword ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
autoComplete="new-password"
isRequired
labelPlacement="outside"
/>
)}
/>
<div className="flex mt-2">
<Button
type="submit"
color="primary"
isLoading={isSubmitting}
isDisabled={!isValid}
className="w-fit"
size="sm"
>
{t("Save")}
</Button>
</div>
</form>
);
};
@@ -1,5 +0,0 @@
.xpack-console-stats-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
max-width: 100%;
}
+423 -83
View File
@@ -1,105 +1,445 @@
"use client";
import React, { useState, useEffect } from "react";
import { overviewService } from "@/services/overviewService";
import { PlatformOverviewData } from "@/types/dashboard";
import "./ConsoleStats.css"
import { Alert, Card, CardBody, CardFooter } from "@nextui-org/react";
import React, { useMemo, useState, useEffect } from "react";
import {
Card,
CardBody,
CardHeader,
Tabs,
Tab,
Listbox,
ListboxItem,
Skeleton,
DateRangePicker
} from "@nextui-org/react";
import { parseDate } from "@internationalized/date";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ChartBarIcon, DollarSignIcon, ServerIcon, UserIcon } from "lucide-react";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from "recharts";
import {
getAdminAnalytics,
AdminAnalyticsData,
TopServiceItem,
} from "@/api/adminAnalytics.api";
import toast from "react-hot-toast";
interface StatCardProps {
title: string;
value: string | number;
icon: React.ReactNode;
description?: string;
// Chart data interface to match existing chart component
interface ChartDataItem {
date: string;
users: number;
revenue: number;
calls: number;
}
const StatCard: React.FC<StatCardProps> = ({ title, value, icon, description }) => {
const { t } = useTranslation();
return (
<Card shadow="none" className="border-1">
<CardBody>
<div className="flex items-center justify-between">
<div className="flex-1">
<p className="text-sm font-medium text-gray-600 mb-1">{t(title)}</p>
<p className="text-2xl font-bold text-gray-900">{value}</p>
</div>
<div className="ml-4 text-blue-500">
{icon}
</div>
</div>
</CardBody>
<CardFooter>
{description && (
<p className="text-xs text-gray-500 mt-1">{t(description)}</p>
)}
</CardFooter>
</Card>
// Transform API data to chart format
const transformToChartData = (
analytics: AdminAnalyticsData
): ChartDataItem[] => {
// Get the maximum length of days arrays to handle potential mismatches
const maxLength = Math.max(
analytics.user_register.days.length,
analytics.user_pay.days.length,
analytics.mcp_call.days.length
);
const chartData: ChartDataItem[] = [];
for (let i = 0; i < maxLength; i++) {
// Format date for display (converting from YYYY-MM-DD to MMM DD)
const userRegDay = analytics.user_register.days[i];
const payDay = analytics.user_pay.days[i];
const callDay = analytics.mcp_call.days[i];
// Use the first available date, format it nicely
const rawDate =
userRegDay?.stats_day || payDay?.stats_day || callDay?.stats_day;
const formattedDate = rawDate
? new Date(rawDate).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
})
: `Day ${i + 1}`;
chartData.push({
date: formattedDate,
users: userRegDay ? parseInt(userRegDay.count as string) || 0 : 0,
revenue: payDay ? payDay.count : 0,
calls: callDay ? callDay.count : 0,
});
}
return chartData;
};
// Render label + total value in tab header
const TabTitle: React.FC<{
label: string;
total: number | string;
}> = ({ label, total }) => (
<div className="flex flex-col items-start gap-2">
<div className="text-sm text-default-500">{label}</div>
<div className="text-2xl font-semibold text-default-900">
{typeof total === "number" ? total.toLocaleString() : total}
</div>
</div>
);
const ConsoleStats: React.FC = () => {
const { t } = useTranslation();
const [overviewData, setOverviewData] = useState<PlatformOverviewData | null>(null);
const fetchOverviewData = async () => {
try {
const data = await overviewService.getPlatformOverview();
setOverviewData(data);
} catch (err) {
console.error('Failed to fetch overview data:', err);
} finally {
}
};
// get platform overview data
useEffect(() => {
fetchOverviewData();
const [activeTab, setActiveTab] = useState<string>("users");
// State for API data
const [analyticsData, setAnalyticsData] = useState<AdminAnalyticsData | null>(
null
);
const [loading, setLoading] = useState(true);
// 日期范围状态 - 默认最近30天
const [dateRange, setDateRange] = useState<any>(() => {
const today = new Date();
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(today.getDate() - 29);
// 格式化为 YYYY-MM-DD
const formatDate = (date: Date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
return {
start: parseDate(formatDate(thirtyDaysAgo)),
end: parseDate(formatDate(today)),
};
});
// 计算最早可选日期(30天前)
const minValue = useMemo(() => {
const date = new Date();
date.setDate(date.getDate() - 30);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return parseDate(`${year}-${month}-${day}`);
}, []);
// 计算最大可选日期(今天)
const maxValue = useMemo(() => {
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return parseDate(`${year}-${month}-${day}`);
}, []);
// 校验:开始日期必须早于结束日期,且不能早于30天前
const dateValidation = useMemo(() => {
if (!dateRange?.start || !dateRange?.end) {
return { isInvalid: false, error: "" };
}
const start = dateRange.start;
const end = dateRange.end;
const minDate = minValue;
// 检查开始日期是否早于30天前
const isStartTooEarly =
start.year < minDate.year ||
(start.year === minDate.year && start.month < minDate.month) ||
(start.year === minDate.year && start.month === minDate.month && start.day < minDate.day);
if (isStartTooEarly) {
return {
isInvalid: true,
error: t("Start date cannot be earlier than 30 days ago")
};
}
// 检查开始日期是否晚于结束日期
const isEndBeforeStart =
start.year > end.year ||
(start.year === end.year && start.month > end.month) ||
(start.year === end.year && start.month === end.month && start.day >= end.day);
if (isEndBeforeStart) {
return {
isInvalid: true,
error: t("Start date must be before end date")
};
}
return { isInvalid: false, error: "" };
}, [dateRange, minValue, t]);
// 错误消息
const errorMessage = dateValidation.error;
const isInvalidDateRange = dateValidation.isInvalid;
// Fetch analytics data on component mount and when date range changes
useEffect(() => {
const fetchData = async () => {
if (!dateRange?.start || !dateRange?.end) return;
// 如果日期范围无效,不发送请求
if (isInvalidDateRange) {
setLoading(false);
return;
}
try {
setLoading(true);
// parseDate 返回的对象有 year, month, day 属性
const start = dateRange.start;
const end = dateRange.end;
// 转换日期为时间戳(秒)
const startDateTime = new Date(start.year, start.month - 1, start.day, 0, 0, 0);
const startTime = Math.floor(startDateTime.getTime() / 1000);
const endDateTime = new Date(end.year, end.month - 1, end.day, 23, 59, 59);
const endTime = Math.floor(endDateTime.getTime() / 1000);
const response = await getAdminAnalytics(startTime, endTime);
if (response.success) {
setAnalyticsData(response.data);
} else {
toast.error(
response.error_message || "Failed to load analytics data"
);
}
} catch {
toast.error("Failed to load analytics data");
} finally {
setLoading(false);
}
};
fetchData();
}, [dateRange, isInvalidDateRange]);
// Transform API data to chart format
const chartData = useMemo<ChartDataItem[]>(() => {
if (!analyticsData) return [];
return transformToChartData(analyticsData);
}, [analyticsData]);
// Format revenue as currency (USD by default)
const formatCurrency = (value: number, currency: string = "USD") =>
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
value
);
if (loading) {
return (
<div className="w-full flex flex-col gap-4 h-full">
<Skeleton className="rounded-lg" isLoaded={!loading}>
<div className="h-24 rounded-lg bg-secondary" />
</Skeleton>
<div className="flex flex-col gap-3">
<Skeleton className="w-3/5 rounded-lg" isLoaded={!loading}>
<div className="h-3 w-full rounded-lg bg-secondary" />
</Skeleton>
<Skeleton className="w-4/5 rounded-lg" isLoaded={!loading}>
<div className="h-3 w-full rounded-lg bg-secondary-300" />
</Skeleton>
<Skeleton className="w-2/5 rounded-lg" isLoaded={!loading}>
<div className="h-3 w-full rounded-lg bg-secondary-200" />
</Skeleton>
</div>
</div>
);
}
return (
<div className="space-y-6">
{/* stat card grid */}
<div className="xpack-console-stats-grid gap-4">
<StatCard
title="Total Users"
value={overviewData?.total_user.toLocaleString() || 0}
icon={
<UserIcon size={32} />
}
description="Platform registered users"
/>
<StatCard
title="Total Revenue"
value={overviewData?.total_balance.toLocaleString() || 0}
icon={
<DollarSignIcon size={32} />
}
description="Platform total fund pool"
/>
<StatCard
title="Today's API Calls"
value={overviewData?.invoke_count.today.toLocaleString() || 0}
icon={
<ChartBarIcon size={32} />
}
description="API call count"
/>
{/* 日期范围选择器 */}
<div className="flex justify-end">
<DateRangePicker
label={t("Select Date Range")}
value={dateRange}
onChange={setDateRange}
minValue={minValue}
maxValue={maxValue}
isInvalid={isInvalidDateRange}
errorMessage={errorMessage}
onKeyDown={(e) => e.preventDefault()}
onKeyUp={(e) => e.preventDefault()}
className="w-[250px]"
visibleMonths={2}
granularity="day"
/>
</div>
<StatCard
title="Total MCP Services"
value={overviewData?.total_service.toLocaleString() || 0}
icon={
<ServerIcon size={32} />
}
description="Deployed services"
/>
</div>
{/* Charts with Tabs */}
<Card shadow="none" className="border-1">
<CardHeader className="p-0 flex items-center justify-between">
<Tabs
selectedKey={activeTab}
onSelectionChange={(key) => setActiveTab(key as string)}
variant="underlined"
color="primary"
classNames={{
base: "w-full",
tab: "h-fit justify-start border-b-1 p-4",
cursor: "w-[90%]",
tabList: "w-full gap-0 p-0",
}}
>
<Tab
key="users"
title={
<TabTitle
label={t("Daily Registered Users")}
total={analyticsData?.user_register.today || 0}
/>
}
/>
<Tab
key="revenue"
title={
<TabTitle
label={t("Daily Revenue")}
total={formatCurrency(analyticsData?.user_pay.today || 0)}
/>
}
/>
<Tab
key="calls"
title={
<TabTitle
label={t("Daily API Calls")}
total={analyticsData?.mcp_call.today || 0}
/>
}
/>
</Tabs>
</CardHeader>
<CardBody>
<div className="w-full h-[300px]">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="date" />
<YAxis />
<Tooltip
labelStyle={{ color: "#374151" }}
contentStyle={{
backgroundColor: "#f9fafb",
border: "1px solid #e5e7eb",
borderRadius: "8px",
padding: "12px",
}}
/>
{activeTab === "users" && (
<Line
type="monotone"
dataKey="users"
stroke="#3b82f6"
strokeWidth={2}
dot={false}
activeDot={{ fill: "#3b82f6", strokeWidth: 2, r: 4 }}
/>
)}
{activeTab === "revenue" && (
<Line
type="monotone"
dataKey="revenue"
stroke="#10b981"
strokeWidth={2}
dot={false}
activeDot={{ fill: "#10b981", strokeWidth: 2, r: 4 }}
/>
)}
{activeTab === "calls" && (
<Line
type="monotone"
dataKey="calls"
stroke="#f59e0b"
strokeWidth={2}
dot={false}
activeDot={{ fill: "#f59e0b", strokeWidth: 2, r: 4 }}
/>
)}
</LineChart>
</ResponsiveContainer>
</div>
</CardBody>
</Card>
{/* welcome guide */}
<Alert color="primary" title={t("Welcome to XPack.AI Open Source")} description={t("This is your AI service management center. You can quickly view platform core data on the left and manage and configure your MCP services, users, payment channels, etc.")}></Alert>
{/* Top Servers List */}
<Card shadow="none" className="border-1">
<CardHeader className="pb-0 flex items-center justify-between">
<h4 className="text-lg font-semibold text-gray-900">
{t("Top Servers by Calls")}
</h4>
</CardHeader>
<CardBody>
<div>
{analyticsData?.top_services?.length ? (
<Listbox
aria-label="top servers"
selectionMode="none"
className="overflow-visible p-0"
classNames={{ list: "overflow-visible space-y-3" }}
>
{(analyticsData.top_services || []).map(
(service: TopServiceItem, index: number) => (
<ListboxItem
key={service.id}
className="p-3 bg-gray-50 data-[hover=true]:bg-gray-100 cursor-default"
classNames={{
title: "w-full",
}}
>
<div className="flex items-center justify-between w-full gap-3">
<div className="flex items-center justify-center min-w-8 w-8 h-8 bg-blue-100 text-blue-600 rounded-full text-sm font-semibold">
{index + 1}
</div>
<div className="flex flex-col items-start flex-1 overflow-hidden">
<div className="flex gap-1 w-full">
<span className="text-danger-500">
{service.is_deleted ? t("(Deleted)") : ""}
</span>
<span className="truncate w-full flex-1">
{service.name}
</span>
</div>
<span className="text-xs text-gray-500 truncate w-full">
{service.short_description}
</span>
</div>
<div className="text-right">
<div className="text-lg font-semibold text-gray-900">
{service.call_count.toLocaleString()}
</div>
<div className="text-xs text-gray-500">
{t("Calls")}
</div>
</div>
</div>
</ListboxItem>
)
)}
</Listbox>
) : (
<div className="text-center py-8 text-gray-500">
{t("No servers available")}
</div>
)}
</div>
</CardBody>
</Card>
</div>
);
};
export default ConsoleStats;
export default ConsoleStats;
@@ -15,6 +15,7 @@ interface LoginSettingsContentProps {
loginConfig: LoginConfig;
saveLoginConfig: (config: LoginConfig) => Promise<boolean>;
emailConfig: EmailConfig;
type?: "email" | "google";
}
export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
@@ -22,6 +23,7 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
loginConfig,
saveLoginConfig,
emailConfig,
type = "email",
}) => {
const [googleSubmitLoading, setGoogleSubmitLoading] = useState(false);
const [emailSubmitLoading, setEmailSubmitLoading] = useState(false);
@@ -83,20 +85,24 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
return (
<div className="space-y-4 w-full">
{/* email config */}
<EmailConfigForm
config={loginConfig}
emailConfig={emailConfig}
onSave={handleSaveLoginConfig}
isLoading={emailSubmitLoading}
onTabNavigate={onTabNavigate}
/>
{type === "email" && (
<EmailConfigForm
config={loginConfig}
emailConfig={emailConfig}
onSave={handleSaveLoginConfig}
isLoading={emailSubmitLoading}
onTabNavigate={onTabNavigate}
/>
)}
{/* google auth config */}
<GoogleAuthConfigForm
config={loginConfig.google}
onSave={handleSaveGoogleAuthConfig}
isLoading={googleSubmitLoading}
/>
{type === "google" && (
<GoogleAuthConfigForm
config={loginConfig.google}
onSave={handleSaveGoogleAuthConfig}
isLoading={googleSubmitLoading}
/>
)}
</div>
);
};
+182 -113
View File
@@ -1,156 +1,115 @@
"use client";
import React, { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "next/navigation";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useAdminStore } from "@/store/admin";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import ConsoleStats from "@/components/console/ConsoleStats";
import PaymentChannelsContent from "@/components/console/PaymentChannelsContent";
import SystemSettingsContent from "@/components/console/SystemSettingsContent";
import { SidebarItem, TabKey } from "@/shared/types/dashboard";
import { useAdminLogin } from "@/hooks/useAdminLogin";
import { MCPServicesManagement } from "@/components/mcp-services/MCPServicesManagement";
import UserManagement from "@/components/user-management/UserManagement";
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
import {
CreditCard,
DollarSign,
Home,
Settings,
Users,
ServerIcon,
} from "lucide-react";
import ConsoleSidebar from "./Sidebar";
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
import { Boxes, DollarSign, Home, ServerIcon, Users } from "lucide-react";
import OnboardingWelcome, { REQUIRED_TASK_KEYS } from "./OnboardingWelcome";
import ConsoleStats from "./ConsoleStats";
import SystemSettingsModal from "./SystemSettingsModal";
import SharePlatformModal from "./SharePlatformModal";
import {
OnboardingTaskKey,
TaskItem,
TaskStatusEnum,
updateAdminOnboardingTasks,
} from "@/api/onboard.api";
import ResourceGroupManagement from "../resource-group/resourceGroup";
const ConsoleContent: React.FC = () => {
const { t } = useTranslation();
const router = useRouter();
const searchParams = useSearchParams();
const [admin_token] = useAdminStore((state) => [state.admin_token]);
const _DefaultSubTab = "general";
const [admin_token, getAdminUser] = useAdminStore((state) => [
state.admin_token,
state.getAdminUser,
]);
const getInitialTab = (): TabKey => {
const tabFromUrl = searchParams.get("tab") as TabKey;
if (
tabFromUrl &&
[
"mcp-services",
"user-management",
"revenue-management",
"payment-channels",
"login-settings",
"system-settings",
].includes(tabFromUrl)
["mcp-services", "user-management", "revenue-management", "resource-group"].includes(
tabFromUrl
)
) {
return tabFromUrl;
}
return TabKey.CONSOLE;
};
const getInitialSubTab = (): string | undefined => {
const subTabFromUrl = searchParams.get("subtab");
return subTabFromUrl || _DefaultSubTab;
};
const [activeTab, setActiveTab] = useState<TabKey>(getInitialTab);
const [activeSubTab, setActiveSubTab] = useState<string | undefined>(
getInitialSubTab
);
const isSkipOnboarding =
typeof window !== "undefined" &&
localStorage.getItem("admin_onboarding_skip") === "1";
const [showOnboarding, setShowOnboarding] = useState<boolean>(false);
const [completedTasks, setCompletedTasks] = useState<string[]>([]);
const [isSettingsModalOpen, setIsSettingsModalOpen] =
useState<boolean>(false);
const [isShareModalOpen, setIsShareModalOpen] = useState<boolean>(false);
const [settingModalKeyword, setSettingModalKeyword] = useState<string>("");
const sidebarItems: SidebarItem[] = [
{
key: TabKey.CONSOLE,
icon: <Home size={18} />,
label: t("Dashboard"),
description: t("Overview and analytics"),
label: t("Analytics"),
description: t("Analyze platform usage and revenue"),
},
{
key: TabKey.MCP_SERVICES,
icon: <ServerIcon size={18} />,
label: t("MCP Services"),
description: t("Manage MCP services and API tools"),
label: t("MCP"),
description: t("Manage MCP servers and API tools"),
},
{
key: TabKey.USER_MANAGEMENT,
icon: <Users size={18} />,
label: t("User Management"),
label: t("User"),
description: t("Manage registered users"),
},
{
key: TabKey.RESOURCE_GROUP,
icon: <Boxes size={18} />,
label: t("Resource Group"),
description: t("Manage resource groups"),
},
{
key: TabKey.REVENUE_MANAGEMENT,
icon: <DollarSign size={18} />,
label: t("Revenue Management"),
label: t("Revenue"),
description: t("View user recharge history"),
},
{
key: TabKey.PAYMENT_CHANNELS,
icon: <CreditCard size={18} />,
label: t("Payment Channels"),
description: t("Configure payment channels"),
},
{
key: TabKey.SYSTEM_SETTINGS,
icon: <Settings size={18} />,
label: t("System Settings"),
description: t("Platform basic configuration"),
// Sub-menu items for System Settings
subItems: [
{
key: "general",
label: "General",
description: "Platform basic configuration",
},
{
key: "login-settings",
label: "Login Settings",
description: "Configure authentication methods",
},
{
key: "homepage",
label: "Homepage",
description: "Homepage content and theme settings",
},
{
key: "about-page",
label: "About Page",
description: "About page content configuration",
},
{
key: "email-admin",
label: "Email & Admin",
description: "Email and administrator settings",
},
],
},
];
// If admin is not logged in, redirect to admin login page
useEffect(() => {
if (!admin_token) {
router.push("/admin");
window.location.href =
process.env.NEXT_PUBLIC_ADMIN_LOGIN_URL || "/admin";
}
}, [admin_token, router]);
}, [admin_token]);
const handleTabNavigate = (tab: TabKey, subTab?: string) => {
setActiveTab(tab);
setActiveSubTab(subTab || _DefaultSubTab);
const handleTabNavigate = (tab: TabKey | string, _subTab?: string) => {
setActiveTab(tab as TabKey);
// update url params
if (tab === TabKey.CONSOLE) {
// when switch to dashboard, clear all query params, only keep base path
router.push("/console", { scroll: false });
window.history.pushState({}, "", "/admin/console");
} else {
// other tabs set corresponding tab params
const params = new URLSearchParams();
params.set("tab", tab);
// add subtab parameter if provided
if (subTab) {
params.set("subtab", subTab);
}
router.push(`/console?${params.toString()}`, { scroll: false });
window.history.pushState({}, "", `/admin/console?${params.toString()}`);
}
};
@@ -161,6 +120,94 @@ const ConsoleContent: React.FC = () => {
adminLogout();
};
const handleSettingsClick = () => {
setIsSettingsModalOpen(true);
};
const handleSettingsModalClose = () => {
setIsSettingsModalOpen(false);
setSettingModalKeyword("");
};
const initOnboarding = async () => {
const res = await getAdminUser();
if (!res.success) {
adminLogout();
return;
}
try {
const completedTasks: string[] = (res.data.onboarding_tasks || [])
.filter(
(task: TaskItem) => task.task_status === TaskStatusEnum.COMPLETED
)
.map((task: TaskItem) => task.task_id);
setCompletedTasks(completedTasks);
setShowOnboarding(completedTasks.length !== REQUIRED_TASK_KEYS.length);
} catch (e) {
// Fallback to show onboarding if localStorage not available
setShowOnboarding(false);
}
};
//todo: onboarding
// Initialize onboarding state from localStorage
useEffect(() => {
if (isSkipOnboarding) {
setShowOnboarding(false);
return;
}
initOnboarding();
}, []);
const handleSkipOnboarding = () => {
localStorage.setItem("admin_onboarding_skip", "1");
setShowOnboarding(false);
};
const markTaskAsCompleted = async (taskKey: OnboardingTaskKey) => {
// Mark task as completed
const next = Array.from(new Set([...completedTasks, taskKey]));
setCompletedTasks(next);
const result = await updateAdminOnboardingTasks({
task_id: taskKey,
task_status: TaskStatusEnum.COMPLETED,
});
if (!result) return;
if (next.length === REQUIRED_TASK_KEYS.length) {
localStorage.setItem("admin_onboarding_skip", "1");
setShowOnboarding(false);
}
};
const handleTaskClick = async (taskKey: OnboardingTaskKey) => {
switch (taskKey) {
case OnboardingTaskKey.PLATFORM_SETUP:
setIsSettingsModalOpen(true);
await markTaskAsCompleted(taskKey);
break;
case OnboardingTaskKey.MCP_SERVICES:
handleTabNavigate(TabKey.MCP_SERVICES);
await markTaskAsCompleted(taskKey);
break;
case OnboardingTaskKey.REVENUE_MANAGEMENT:
setSettingModalKeyword("Payment");
setIsSettingsModalOpen(true);
await markTaskAsCompleted(taskKey);
break;
case OnboardingTaskKey.SHARE_PLATFORM:
setIsShareModalOpen(true);
// 不在这里标记完成,等待实际分享后再标记
break;
}
};
const handleShareComplete = async () => {
await markTaskAsCompleted(OnboardingTaskKey.SHARE_PLATFORM);
};
const handleShareModalClose = () => {
setIsShareModalOpen(false);
};
// render different content based on activeTab
const renderContent = () => {
switch (activeTab) {
@@ -178,30 +225,30 @@ const ConsoleContent: React.FC = () => {
<RevenueManagement />
</div>
);
case TabKey.PAYMENT_CHANNELS:
case TabKey.RESOURCE_GROUP:
return (
<DashboardDemoContent
title={t("Payment Channels")}
description={t("Configure payment channels")}
>
<PaymentChannelsContent />
</DashboardDemoContent>
);
case "system-settings":
return (
<SystemSettingsContent
activeSubTab={activeSubTab}
subTab={sidebarItems
.find((item) => item.key === activeTab)
?.subItems?.find((item) => item.key === activeSubTab)}
onTabNavigate={handleTabNavigate}
/>
<div className="h-full overflow-auto">
<ResourceGroupManagement />
</div>
);
default:
return (
return showOnboarding ? (
<OnboardingWelcome
onSkipOnboarding={handleSkipOnboarding}
onTaskClick={handleTaskClick}
completedTasks={completedTasks}
/>
) : (
<DashboardDemoContent
title={t("Admin Dashboard")}
description={t("Platform management and analytics")}
title={
<div className="flex items-center gap-2">
<span>{t("Analytics")}</span>
<span className="text-primary text-lg font-medium">
{t("(30 days)")}
</span>
</div>
}
description={t("Analyze platform usage and revenue")}
>
<ConsoleStats />
</DashboardDemoContent>
@@ -215,15 +262,33 @@ const ConsoleContent: React.FC = () => {
{/* Sidebar */}
<ConsoleSidebar
activeTab={activeTab}
activeSubTab={activeSubTab}
onTabNavigate={handleTabNavigate}
onLogout={handleLogout}
sidebarItems={sidebarItems}
onSettingsClick={handleSettingsClick}
/>
{/* Main Content */}
<div className="flex-1 h-screen overflow-y-auto">{renderContent()}</div>
</div>
{/* Settings Modal */}
{isSettingsModalOpen && (
<SystemSettingsModal
isOpen={true}
onClose={handleSettingsModalClose}
keyword={settingModalKeyword}
/>
)}
{/* Share Platform Modal */}
{isShareModalOpen && (
<SharePlatformModal
isOpen={true}
onClose={handleShareModalClose}
onShareComplete={handleShareComplete}
/>
)}
</div>
);
};
@@ -244,4 +309,8 @@ const ConsoleMain: React.FC = () => {
);
};
export default ConsoleMain;
// Export the base component for direct use
export { ConsoleMain as ConsoleMainBase };
// Export with component injection support
export default withComponentInjection("console/Main", ConsoleMain);
@@ -0,0 +1,180 @@
"use client";
import React, { useEffect, useState } from "react";
import {
CheckCircle2,
Share2,
ArrowRight,
Settings,
ServerIcon,
DollarSign,
} from "lucide-react";
import {
Button,
Card,
CardBody,
Listbox,
ListboxItem,
Link,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { OnboardingTaskKey } from "@/api/onboard.api";
export const REQUIRED_TASK_KEYS = [
OnboardingTaskKey.PLATFORM_SETUP,
OnboardingTaskKey.MCP_SERVICES,
OnboardingTaskKey.REVENUE_MANAGEMENT,
OnboardingTaskKey.SHARE_PLATFORM,
];
interface OnboardingWelcomeProps {
onSkipOnboarding: () => void;
completedTasks: string[];
onTaskClick: (taskKey: OnboardingTaskKey) => void;
}
const OnboardingWelcome: React.FC<OnboardingWelcomeProps> = ({
onSkipOnboarding,
completedTasks,
onTaskClick,
}) => {
const { t } = useTranslation();
const { platformConfig } = usePlatformConfig();
const [activeTab, setActiveTab] = useState<OnboardingTaskKey | undefined>(
REQUIRED_TASK_KEYS.find((task) => !completedTasks.includes(task))
);
useEffect(() => {
setActiveTab(
REQUIRED_TASK_KEYS.find((task) => !completedTasks.includes(task))
);
}, [completedTasks]);
const tasks = [
{
key: OnboardingTaskKey.PLATFORM_SETUP,
title: t("Configure Platform Settings"),
subtitle: t("Set up your platform name, domain, and branding."),
icon: <Settings size={18} />,
},
{
key: OnboardingTaskKey.MCP_SERVICES,
title: t("Add MCP Services"),
subtitle: t("Configure and deploy your first MCP server tools."),
icon: <ServerIcon size={18} />,
},
{
key: OnboardingTaskKey.REVENUE_MANAGEMENT,
title: t("Configure Payment & Billing"),
subtitle: t("Set up payment channels and token pricing."),
icon: <DollarSign size={18} />,
},
{
key: OnboardingTaskKey.SHARE_PLATFORM,
title: t("Share Your Platform"),
subtitle: t("Invite users and promote your MCP platform."),
icon: <Share2 size={18} />,
},
];
const isTaskCompleted = (taskKey: string) => completedTasks.includes(taskKey);
return (
<div className="min-h-screen flex flex-col items-center justify-center p-6">
{/* Header */}
<div className="text-center mb-8">
<h1 className="text-2xl font-bold text-gray-900 mb-2">
{t("Welcome to {{name}}!", {
name: platformConfig.name || "your platform",
})}
</h1>
<p className="text-gray-600 text-sm">
{t("Let's set up {{name}} to get you started.", {
name: platformConfig.name || "your platform",
})}
</p>
</div>
<Card className="w-full max-w-lg border-1 overflow-visible" shadow="none">
<CardBody className="py-0 overflow-y-visible">
<Listbox
aria-label="Onboarding tasks"
className="overflow-visible"
classNames={{
list: "overflow-visible",
}}
>
{tasks.map((task, index) => (
<ListboxItem
key={task.key}
startContent={
<div
className={`flex-shrink-0 ${
!isTaskCompleted(task.key)
? "text-primary"
: "text-default-400"
}`}
>
{task.icon}
</div>
}
endContent={
isTaskCompleted(task.key) ? (
<CheckCircle2
size={18}
className="text-green-500 flex-shrink-0"
/>
) : (
<ArrowRight
size={18}
className="text-primary flex-shrink-0 group-data-[hover=true]:translate-x-1 duration-300 ease-in-out"
/>
)
}
description={activeTab === task.key ? task.subtitle : undefined}
onPress={() => {
onTaskClick(task.key);
}}
className={`py-6 gap-3 ${
!isTaskCompleted(task.key)
? "data-[hover=true]:opacity-50"
: "text-default-500 data-[hover=true]:text-default-500"
} ${activeTab === task.key ? "scale-[1.15] border-2 border-primary bg-white px-6 data-[hover=true]:opacity-100 data-[hover=true]:bg-white" : "data-[hover=true]:bg-transparent"}`}
classNames={{
title: "font-bold text-md",
}}
showDivider={
index !== tasks.length - 1 && activeTab !== task.key
}
>
{task.title}
</ListboxItem>
))}
</Listbox>
</CardBody>
</Card>
{/* Help Section */}
<div className="text-center my-6">
<p className="text-xs text-gray-500">
{t("Need help getting started? Check out our")}{" "}
<Link
href="https://discord.gg/cyZfcdCXkW"
size="sm"
className="font-medium"
target="_blank"
>
{t("Discord Community")}
</Link>
.
</p>
</div>
{/* Skip Button */}
<div className="text-center">
<Button onPress={onSkipOnboarding} size="sm" variant="bordered">
{t("Skip setup guide")}
</Button>
</div>
</div>
);
};
export default OnboardingWelcome;
@@ -6,7 +6,13 @@ import { AlipayConfigForm } from "../payment/AlipayConfigForm";
import { WechatConfigForm } from "../payment/WechatConfigForm";
import { usePaymentChannelManagement } from "@/hooks/usePaymentChannelManagement";
export const PaymentChannelsContent: React.FC = () => {
interface PaymentChannelsContentProps {
labelPlacement?: "outside" | "inside";
}
export const PaymentChannelsContent: React.FC<PaymentChannelsContentProps> = ({
labelPlacement = "inside",
}) => {
const {
stripeConfig,
alipayConfig,
@@ -30,6 +36,7 @@ export const PaymentChannelsContent: React.FC = () => {
onEnable={enableChannel}
onDisable={disableChannel}
isLoading={isStripeSaving}
labelPlacement={labelPlacement}
/>
{/* coming soon */}
{/* alipay configuration */}
@@ -0,0 +1,165 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Link as LinkIcon } from "lucide-react";
import {
Modal,
ModalContent,
ModalBody,
Button,
Image,
} from "@nextui-org/react";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { FaFacebook } from "react-icons/fa";
import { FaLinkedin } from "react-icons/fa6";
import { FaXTwitter } from "react-icons/fa6";
import { copyToClipboard } from "@/shared/utils/clipboard";
import toast from "react-hot-toast";
interface SharePlatformModalProps {
isOpen: boolean;
onClose: () => void;
onShareComplete: () => void;
}
const SharePlatformModal: React.FC<SharePlatformModalProps> = ({
isOpen,
onClose,
onShareComplete,
}) => {
const { t } = useTranslation();
const { platformConfig } = usePlatformConfig();
const handleCopyLink = async () => {
try {
const res = await copyToClipboard(window.location.origin);
onShareComplete();
if (res.success) {
toast.success(t("Copied to clipboard"));
}
} catch (err) {
console.error("Failed to copy link:", err);
}
};
const handleSocialShare = (platform: "x" | "facebook" | "linkedin") => {
const text = t(
`Just launched my first MCP Platform:{{name}} with xpack.ai 🚀
Built in minutes, no coding, ready for AI Agents 🤖
👉Go and try my MCP: {{link}}
#MCP #AI #APIs #XPack #AIagents #DevTools`,
{
name: platformConfig.name,
link: window.location.origin,
}
);
let url = "";
const shareUrl = encodeURIComponent(window.location.origin);
switch (platform) {
case "x":
url = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${shareUrl}`;
break;
case "facebook":
url = `https://www.facebook.com/sharer/sharer.php?u=${shareUrl}`;
break;
case "linkedin":
url = `https://www.linkedin.com/sharing/share-offsite/?url=${shareUrl}`;
break;
}
if (url) {
window.open(url, "_blank", "width=600,height=400");
onShareComplete();
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalContent>
<ModalBody>
{/* Header */}
<div className="my-6 flex flex-col gap-2 ">
<h2 className="text-2xl font-extrabold text-primary md:text-4xl">
{t("Your MCP Market is ready.")}
</h2>
<p className="text-2xl font-bold text-gray-900">
{t("Share your MCP to the world")}
</p>
</div>
{/* Preview Card */}
<div className="mb-6 rounded-xl border border-gray-200 bg-white p-6">
<div className="space-y-2">
<h3 className="text-xl font-semibold text-gray-900">
{platformConfig.website_title || platformConfig.name}
</h3>
<p className="text-gray-700">{platformConfig.meta_description}</p>
</div>
<div className="mt-4 flex items-center gap-2 text-sm text-gray-800">
{platformConfig.logo && (
<Image
src={platformConfig.logo}
alt={platformConfig.name}
width={20}
height={20}
/>
)}
<span className="font-semibold">{platformConfig.name}</span>
<span>•</span>
<span className="text-gray-600">{window.location.hostname}</span>
</div>
</div>
{/* Actions */}
<div className="flex flex-col items-stretch gap-4 sm:flex-row sm:items-center sm:justify-between mb-4">
{/* Social buttons */}
<div className="flex items-center gap-2">
<Button
onPress={() => handleSocialShare("x")}
title={t("Share on X")}
isIconOnly
size="lg"
variant="flat"
>
<FaXTwitter size={20} />
</Button>
<Button
onPress={() => handleSocialShare("facebook")}
title={t("Share on Facebook")}
isIconOnly
size="lg"
variant="flat"
>
<FaFacebook size={20} className="text-primary" />
</Button>
<Button
onPress={() => handleSocialShare("linkedin")}
title={t("Share on LinkedIn")}
isIconOnly
size="lg"
variant="flat"
>
<FaLinkedin size={20} className="text-blue-500" />
</Button>
</div>
{/* Copy link button */}
<Button
onPress={handleCopyLink}
size="lg"
color="primary"
className="gap-1 w-full bg-default-900"
>
<LinkIcon size={20} />
<span className="text-base font-semibold">{t("Copy link")}</span>
</Button>
</div>
</ModalBody>
</ModalContent>
</Modal>
);
};
export default SharePlatformModal;
+75 -122
View File
@@ -2,159 +2,112 @@
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Button, Divider, Link, Tooltip } from "@nextui-org/react";
import { LogOut } from "lucide-react";
import { Button, Divider, Tooltip } from "@nextui-org/react";
import { ExternalLinkIcon, LogOut, Settings } from "lucide-react";
import { DashboardSidebarProps } from "@/shared/types/dashboard";
import { DynamicLogo } from "@/shared/components/DynamicLogo";
import { FaDiscord } from "react-icons/fa";
import Link from "next/link";
const ConsoleSidebar: React.FC<DashboardSidebarProps> = ({
interface ConsoleSidebarProps extends DashboardSidebarProps {
onSettingsClick?: () => void;
}
const ConsoleSidebar: React.FC<ConsoleSidebarProps> = ({
activeTab,
activeSubTab,
onTabNavigate,
onLogout,
sidebarItems,
onSettingsClick,
}) => {
const { t } = useTranslation();
const handleSubItemClick = (parentKey: string, subKey: string) => {
onTabNavigate?.(parentKey as any, subKey);
};
// Filter out system settings from sidebar items
const filteredSidebarItems = sidebarItems.filter(
(item) => item.key !== "system-settings"
);
return (
<div className="flex h-screen">
{/* Main Sidebar */}
<div className="py-2 px-2 w-[70px] overflow-hidden border-r border-divider flex flex-col justify-between">
{/* Header */}
<div className="mb-6 mt-4 flex flex-col items-center gap-2">
<Link href={process.env.NEXT_PUBLIC_DOMAIN || "/"}>
<DynamicLogo
alt="Platform Logo"
className="max-w-full h-auto max-h-[30px]"
/>
</Link>
</div>
{/* Navigation */}
<div className="flex flex-col gap-2 flex-1">
{sidebarItems.map((item) => (
<React.Fragment key={item.key}>
<Tooltip
content={t(item.label)}
closeDelay={0}
disableAnimation
placement="right"
<>
<div className="flex h-screen">
{/* Main Sidebar */}
<div className="py-2 px-4 w-[300px] overflow-hidden border-r border-divider flex flex-col justify-between bg-default-50">
{/* Header */}
<div className="mb-6 mt-4 flex gap-2 justify-between items-center">
<Link href="/" prefetch target="_blank">
<DynamicLogo
alt="Platform Logo"
className="max-w-full h-[32px] object-contain"
/>
</Link>
<Tooltip content={t("Open in new tab")} closeDelay={0} disableAnimation>
<Link
href="/"
prefetch
target="_blank"
className="hover:text-primary"
>
<Button
key={item.key}
variant={activeTab === item.key ? "flat" : "light"}
color={activeTab === item.key ? "primary" : "default"}
startContent={item.icon}
className="w-full h-auto p-4"
onPress={() => onTabNavigate?.(item.key)}
isIconOnly
></Button>
</Tooltip>
</React.Fragment>
))}
</div>
<ExternalLinkIcon size={18} />
</Link>
</Tooltip>
</div>
<div>
<Divider className="my-2" />
{/* Navigation */}
<div className="flex flex-col gap-2 flex-1">
{filteredSidebarItems.map((item) => (
<Button
key={item.key}
variant={activeTab === item.key ? "flat" : "light"}
color={activeTab === item.key ? "primary" : "default"}
startContent={item.icon}
className="w-full h-auto p-4 justify-start"
onPress={() => onTabNavigate?.(item.key)}
>
{t(item.label)}
</Button>
))}
</div>
<div className="space-y-2">
<Tooltip
content={t("Discord")}
closeDelay={0}
disableAnimation
placement="right"
>
<div>
<Divider className="my-2" />
<div className="space-y-2">
<Button
variant="light"
startContent={<FaDiscord size={18} />}
className="w-full h-auto p-4"
className="w-full h-auto p-4 justify-start"
onPress={() => {
window.open("https://discord.gg/cyZfcdCXkW", "_blank");
}}
isIconOnly
></Button>
</Tooltip>
>
{t("Discord")}
</Button>
{/* Logout */}
<Tooltip
content={t("Log Out")}
closeDelay={0}
disableAnimation
placement="right"
>
{/* Settings */}
<Button
variant="light"
startContent={<Settings size={18} />}
className="w-full h-auto p-4 justify-start"
onPress={onSettingsClick}
>
{t("Settings")}
</Button>
{/* Logout */}
<Button
variant="light"
color="danger"
startContent={<LogOut size={18} />}
className="w-full h-auto p-4"
className="w-full h-auto p-4 justify-start"
onPress={onLogout}
isIconOnly
></Button>
</Tooltip>
>
{t("Log Out")}
</Button>
</div>
</div>
</div>
</div>
{/* Sub Menu Panel */}
{(() => {
const activeItem = sidebarItems.find((item) => item.key === activeTab);
if (!activeItem?.subItems?.length) return null;
return (
<div className="relative bg-content2/50 border-r overflow-hidden w-[240px] p-3">
<div className="mb-3 pb-2 border-b">
<h4 className="font-medium text-sm text-default-700">
{t(activeItem.label)}
</h4>
<p className="text-xs text-default-500 mt-1">
{t(activeItem.description)}
</p>
</div>
<div className="space-y-1">
{activeItem.subItems?.map((subItem) => {
const isSubActive = activeSubTab === subItem.key;
return (
<React.Fragment key={subItem.key}>
<Button
key={subItem.key}
variant={isSubActive ? "flat" : "light"}
color={isSubActive ? "primary" : "default"}
size="sm"
className={`w-full justify-start h-auto p-2 text-left ${
isSubActive
? "bg-primary/10 border border-primary/20"
: "hover:bg-default-100"
}`}
onPress={() =>
handleSubItemClick(activeItem.key, subItem.key)
}
>
<div className="flex flex-col items-start w-full">
<div className="font-medium text-xs">
{t(subItem.label)}
</div>
{subItem.description && (
<div className="text-xs opacity-60 mt-0.5 truncate w-full">
{t(subItem.description)}
</div>
)}
</div>
</Button>
</React.Fragment>
);
})}
</div>
</div>
);
})()}
</div>
</>
);
};
@@ -1,156 +0,0 @@
"use client";
import React, { useState } from "react";
import { HomepageSettings } from "@/components/system-setting/HomepageSettings";
import { AboutPageSettings } from "@/components/system-setting/AboutPageSettings";
import { EmailAndAdminSettings } from "@/components/system-setting/EmailAndAdminSettings";
import { useSystemConfigManagement } from "@/hooks/useSystemConfigManagement";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { Theme } from "@/shared/types/system";
import i18n from "@/shared/lib/i18n";
import { PlatformConfigForm } from "../system-setting/PlatformConfigForm";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import { useTranslation } from "@/shared/lib/useTranslation";
import { SidebarSubItem, TabKey } from "@/shared/types/dashboard";
import { LoginSettingsContent } from "./LoginSettingsContent";
interface SystemSettingsContentProps {
activeSubTab?: string;
subTab?: SidebarSubItem;
onTabNavigate: (tab: TabKey, subTab?: string) => void;
}
export const SystemSettingsContent: React.FC<SystemSettingsContentProps> = ({
activeSubTab,
subTab,
onTabNavigate,
}) => {
const { updateClientConfig } = usePlatformConfig();
const [isAboutLoading, setIsAboutLoading] = useState(false);
const { t } = useTranslation();
const {
// platform config
platformConfig,
platformLoading,
savePlatformConfig,
// admin config
adminConfig,
adminLoading,
saveAdminConfig,
// email config
emailConfig,
emailLoading,
saveEmailConfig,
// image upload
uploadImage,
// login config
loginConfig,
saveLoginConfig,
} = useSystemConfigManagement();
// save admin config
const handleSaveAdminConfig = async (config: typeof adminConfig) => {
await saveAdminConfig(config);
};
// save email config
const handleSaveEmailConfig = async (config: typeof emailConfig) => {
await saveEmailConfig(config);
};
// save platform config
const handleSavePlatformConfig = async (config: typeof platformConfig) => {
const result = await savePlatformConfig(config);
if (!result) return;
updateClientConfig({
platform: config,
});
if (config.language !== i18n.language) {
i18n.changeLanguage(config.language);
}
};
// handle theme change
const handleThemeChange = async (theme: Theme) => {
const updatedConfig = { ...platformConfig, theme };
const result = await savePlatformConfig(updatedConfig, "theme");
if (!result) return;
updateClientConfig({
platform: updatedConfig,
});
};
// handle about save
const handleAboutSave = async (aboutContent: string) => {
setIsAboutLoading(true);
const updatedConfig = { ...platformConfig, about_page: aboutContent };
const result = await savePlatformConfig(updatedConfig, "about");
setIsAboutLoading(false);
if (!result) return;
updateClientConfig({
platform: updatedConfig,
});
};
// Render content based on active sub tab
const renderSubTabContent = () => {
switch (activeSubTab) {
case "homepage":
return <HomepageSettings />;
case "about-page":
return (
<AboutPageSettings
config={platformConfig}
onAboutSave={handleAboutSave}
onImageUpload={uploadImage}
isAboutLoading={isAboutLoading}
/>
);
case "email-admin":
return (
<EmailAndAdminSettings
emailConfig={emailConfig}
adminConfig={adminConfig}
onSaveEmailConfig={handleSaveEmailConfig}
onSaveAdminConfig={handleSaveAdminConfig}
isLoading={emailLoading}
isAdminLoading={adminLoading}
/>
);
case "login-settings":
return (
<LoginSettingsContent
onTabNavigate={onTabNavigate}
loginConfig={loginConfig}
saveLoginConfig={saveLoginConfig}
emailConfig={emailConfig}
/>
);
case "general":
default:
return (
<PlatformConfigForm
config={platformConfig}
onSave={handleSavePlatformConfig}
onThemeChange={handleThemeChange}
isLoading={platformLoading}
/>
);
}
};
return (
<DashboardDemoContent
title={t(subTab?.label || "System Settings")}
description={t(subTab?.description || "Platform basic configuration")}
>
{renderSubTabContent()}
</DashboardDemoContent>
);
};
export default SystemSettingsContent;
@@ -0,0 +1,473 @@
"use client";
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
Modal,
ModalContent,
ModalBody,
ModalHeader,
Button,
} from "@nextui-org/react";
import { useSystemConfigManagement } from "@/hooks/useSystemConfigManagement";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { Theme } from "@/shared/types/system";
import SystemSettingsSidebar, {
SettingsGroup,
SettingsMenuItem,
} from "./SystemSettingsSidebar";
import {
AppWindow,
Captions,
Code,
CreditCard,
GhostIcon,
GlobeIcon,
LockIcon,
Mail,
Package,
Palette,
SquareMenu,
TableOfContents,
Tags,
Trello,
XIcon,
} from "lucide-react";
import SystemSettingsRightContent from "./SystemSettingsRightContent";
import { SettingModalTab } from "./console.type";
import { useHomepageConfigManagement } from "@/hooks/useHomepageConfigManagement";
import { FcGoogle } from "react-icons/fc";
import { useTranslation } from "@/shared/lib/useTranslation";
interface SystemSettingsModalProps {
isOpen: boolean;
onClose: () => void;
keyword?: string;
}
const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
isOpen,
onClose,
keyword,
}) => {
// Left menu active state
const [activeSubTab, setActiveSubTab] = useState<SettingModalTab>(
SettingModalTab.BRANDING
);
const { t } = useTranslation();
// Search state (pure frontend)
const [searchQuery, setSearchQuery] = useState<string>(keyword || "");
// Scroll container and section refs
const rightContentRef = useRef<HTMLDivElement | null>(null);
const sectionRefs = useRef<Record<string, HTMLElement | null>>({});
const titleRefs = useRef<Record<string, HTMLElement | null>>({});
const scrollingByClickRef = useRef(false);
const activeKeyRef = useRef<SettingModalTab>(SettingModalTab.BRANDING);
useEffect(() => {
activeKeyRef.current = activeSubTab;
}, [activeSubTab]);
// Load and manage config once here to avoid duplicate network calls
const { updateClientConfig } = usePlatformConfig();
const {
// platform config
platformConfig,
savePlatformConfig,
// image upload
uploadImage,
// login config
loginConfig,
saveLoginConfig,
// email config
emailConfig,
saveEmailConfig,
emailLoading,
} = useSystemConfigManagement();
const {
homepageConfig,
saveNavigationConfig,
saveEmbeddedHtmlConfig,
saveFaqConfig,
} = useHomepageConfigManagement();
const handleSavePlatformConfig = async (config: { [key: string]: any }) => {
const newConfig = { ...platformConfig, ...config };
const result = await savePlatformConfig(newConfig);
if (!result) return false;
updateClientConfig({ platform: newConfig });
return result;
};
const handleThemeChange = async (theme: Theme) => {
const updatedConfig = { ...platformConfig, theme };
const result = await savePlatformConfig(updatedConfig, "theme");
if (!result) return;
updateClientConfig({ platform: updatedConfig });
};
const settingsMenuItems: SettingsMenuItem[] = [
// General settings
{
key: SettingModalTab.BRANDING,
label: "Branding",
icon: <Trello size={16} />,
description: "Logo, colors, and brand identity",
},
{
key: SettingModalTab.TITLE_DESCRIPTION,
label: "Title & description",
icon: <Captions size={16} />,
description: "Configure your site title and description",
},
{
key: SettingModalTab.META_DATA,
label: "Meta data",
icon: <AppWindow size={16} />,
description: "Extra content for search engines and social accounts",
},
{
key: SettingModalTab.CUSTOM_DOMAIN,
label: "Domain",
icon: <GhostIcon size={16} />,
description: "Configure your custom domain settings",
},
{
key: SettingModalTab.PLATFORM_LANGUAGE,
label: "Platform Language",
icon: <GlobeIcon size={16} />,
description: "Configure platform language",
},
// Site
{
key: SettingModalTab.THEME,
label: "Theme",
icon: <Palette size={16} />,
description: "Visual theme and appearance settings",
},
{
key: SettingModalTab.NAVIGATION,
label: "Navigation",
icon: <SquareMenu size={16} />,
description: "Configure site navigation and menus",
},
{
key: SettingModalTab.TAGS_BAR,
label: "Tags Bar",
icon: <Tags size={16} />,
description: "Configure tags bar display",
},
{
key: SettingModalTab.FAQ,
label: "FAQ",
icon: <TableOfContents size={16} />,
description: "Configure FAQ",
},
// Business
{
key: SettingModalTab.PAYMENT,
label: "Payment",
icon: <CreditCard size={16} />,
description: "Configure payment channels",
},
{
key: SettingModalTab.XPACK_EXPLORE,
label: "XPack Explore",
icon: <Package size={16} />,
description: "Explore XPack features and integrations",
},
// Advanced
{
key: SettingModalTab.SMTP_SETTINGS,
label: "Email Configuration",
icon: <Mail size={16} />,
description: "Configure SMTP settings for email notifications",
},
{
key: SettingModalTab.EMAIL_LOGIN_SETTINGS,
label: "Email Login Settings",
icon: <LockIcon size={16} />,
description: "Configure email-based authentication",
},
{
key: SettingModalTab.GOOGLE_LOGIN_SETTINGS,
label: "Google Login Settings",
icon: <FcGoogle size={16} />,
description: "Configure Google OAuth integration",
},
{
key: SettingModalTab.CODE_INJECTION,
label: "Code injection",
icon: <Code size={16} />,
description: "Custom code injection and scripts",
},
// Account
{
key: SettingModalTab.CHANGE_PASSWORD,
label: "Password",
icon: <LockIcon size={16} />,
description: "Change your password",
},
];
// Hierarchical groups for the sidebar
const settingsGroups: SettingsGroup[] = useMemo(() => {
const mapByKey = Object.fromEntries(
settingsMenuItems.map((it) => [it.key, it])
);
const groupItems = (keys: SettingModalTab[]) =>
keys.map((k) => mapByKey[k]).filter(Boolean) as SettingsMenuItem[];
return [
{
key: "general-settings",
title: "General settings",
items: groupItems([
SettingModalTab.BRANDING,
SettingModalTab.TITLE_DESCRIPTION,
SettingModalTab.META_DATA,
SettingModalTab.CUSTOM_DOMAIN,
SettingModalTab.PLATFORM_LANGUAGE,
]),
},
{
key: "site",
title: "Site",
items: groupItems([
SettingModalTab.THEME,
SettingModalTab.NAVIGATION,
SettingModalTab.TAGS_BAR,
SettingModalTab.FAQ,
]),
},
{
key: "business",
title: "Business",
items: groupItems([
SettingModalTab.PAYMENT,
SettingModalTab.XPACK_EXPLORE,
]),
},
{
key: "advanced",
title: "Advanced",
items: groupItems([
SettingModalTab.SMTP_SETTINGS,
SettingModalTab.EMAIL_LOGIN_SETTINGS,
SettingModalTab.GOOGLE_LOGIN_SETTINGS,
SettingModalTab.CODE_INJECTION,
]),
},
{
key: "account",
title: "Account",
items: groupItems([SettingModalTab.CHANGE_PASSWORD]),
},
];
}, []);
// Filter keys by search (pure frontend)
const filteredKeys = useMemo(() => {
const q = searchQuery.trim().toLowerCase();
if (!q) return settingsMenuItems.map((it) => it.key);
return settingsMenuItems
.filter(
(it) =>
t(it.label).toLowerCase().includes(q) ||
t(it.description || "")
?.toLowerCase()
.includes(q)
)
.map((it) => it.key);
}, [searchQuery]);
// Optimized scroll to section function
const scrollToSection = useCallback((key: SettingModalTab) => {
const container = rightContentRef.current;
const el = titleRefs.current[key];
if (!container || !el) return;
// Prevent multiple rapid calls
if (scrollingByClickRef.current) return;
const containerRect = container.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
// scroll so that the title is aligned near the top of the container viewport
const TOP_OFFSET = 16; // small padding
const offset =
elRect.top - containerRect.top + container.scrollTop - TOP_OFFSET;
scrollingByClickRef.current = true;
setActiveSubTab(key);
// Use CSS-based scroll with better performance
const prevBehavior = container.style.scrollBehavior;
container.style.scrollBehavior = "smooth";
container.scrollTo({ top: Math.max(0, offset) });
// Reset scroll behavior and stop suppressing after animation completes
window.setTimeout(() => {
if (container) {
container.style.scrollBehavior = prevBehavior || "auto";
}
scrollingByClickRef.current = false;
}, 400);
}, []);
// Scroll-based scrollspy using rAF to avoid IO jitter
useEffect(() => {
const container = rightContentRef.current;
if (!container || !isOpen) return;
let ticking = false;
const computeActive = () => {
if (!container) return;
const keys = filteredKeys;
const rect = container.getBoundingClientRect();
const containerTop = rect.top;
const TOP_OFFSET = 16;
const scrollTop = container.scrollTop;
const scrollHeight = container.scrollHeight;
const containerHeight = container.clientHeight;
// Bottom stickiness
if (scrollTop + containerHeight >= scrollHeight - 2) {
const lastKey = keys[keys.length - 1];
if (lastKey && activeKeyRef.current !== lastKey) {
setActiveSubTab(lastKey);
}
return;
}
// Determine the last section whose title top is above the top + offset
let currentKey: SettingModalTab | null = null;
for (const k of keys) {
const el = titleRefs.current[k];
if (!el) continue;
const r = el.getBoundingClientRect();
if (r.top - containerTop <= TOP_OFFSET + 1) {
currentKey = k;
} else {
break;
}
}
if (!currentKey) {
const firstKey = keys[0];
if (firstKey && activeKeyRef.current !== firstKey) {
setActiveSubTab(firstKey);
}
return;
}
if (currentKey && activeKeyRef.current !== currentKey) {
setActiveSubTab(currentKey);
}
};
const onScroll = () => {
if (scrollingByClickRef.current) return;
if (!ticking) {
ticking = true;
requestAnimationFrame(() => {
computeActive();
ticking = false;
});
}
};
// Initial compute and bind listeners
computeActive();
container.addEventListener("scroll", onScroll, { passive: true });
return () => {
container.removeEventListener("scroll", onScroll);
};
}, [isOpen, filteredKeys]);
// When searching, auto-jump to first matched section
useEffect(() => {
if (!searchQuery.trim()) return;
if (filteredKeys.length > 0) {
const firstKey = filteredKeys[0];
if (firstKey !== activeSubTab) {
scrollToSection(firstKey);
}
}
}, [searchQuery]); // Only depend on searchQuery, not filteredKeys
return (
<Modal
isOpen={isOpen}
onClose={onClose}
size="full"
classNames={{
base: "h-screen !max-w-none !w-screen p-0",
body: "flex-1 overflow-hidden",
}}
isDismissable={false}
hideCloseButton={true}
>
<ModalContent>
<ModalHeader className="flex justify-between border-b border-default">
<h2 className="text-2xl font-bold">{t("System Settings")}</h2>
<Button onPress={onClose} isIconOnly size="sm" variant="light">
<XIcon size={24} className="text-gray-500" />
</Button>
</ModalHeader>
<ModalBody className="p-0">
<div className="flex h-full">
{/* Left Navigation */}
<SystemSettingsSidebar
activeKey={activeSubTab}
onSelect={scrollToSection}
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
groups={settingsGroups}
filteredKeys={filteredKeys}
/>
{/* Right Content: stacked sections with anchors */}
<div className="flex-1">
<SystemSettingsRightContent
filteredKeys={filteredKeys}
settingsMenuItems={settingsMenuItems}
platformConfig={platformConfig}
homepageConfig={homepageConfig}
onSaveEmbeddedHtml={saveEmbeddedHtmlConfig}
sectionRefs={sectionRefs}
titleRefs={titleRefs}
onSavePlatformConfig={handleSavePlatformConfig}
handleThemeChange={handleThemeChange}
uploadImage={uploadImage}
scrollContainerRef={rightContentRef}
saveNavigationConfig={saveNavigationConfig}
saveFaqConfig={saveFaqConfig}
saveLoginConfig={saveLoginConfig}
emailConfig={emailConfig}
loginConfig={loginConfig}
onSaveEmailConfig={saveEmailConfig}
emailSubmitLoading={emailLoading}
/>
</div>
</div>
</ModalBody>
</ModalContent>
</Modal>
);
};
export default SystemSettingsModal;
@@ -0,0 +1,251 @@
"use client";
import React, { useMemo } from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import {
EmbeddedHtmlConfig,
FaqItem,
LoginConfig,
PlatformConfig,
Theme,
TopNavigationItem,
} from "@/shared/types/system";
import { SettingsMenuItem } from "./SystemSettingsSidebar";
import TitleAndDescPanel, {
TitleAndDescPanelConfig,
} from "./system-setting/TitleAndDescPanel";
import MetaDataPanel from "./system-setting/MetaDataPanel";
import BrandPanel, { BrandPanelConfig } from "./system-setting/BrandPanel";
import { ThemeSelector } from "@/components/system-setting/ThemeSelector";
import { TopNavigationSettings } from "@/components/system-setting/TopNavigationSettings";
import { EmbeddedHtmlSettings } from "@/components/system-setting/EmbeddedHtmlSettings";
import { ExplorePanel } from "./system-setting/ExplorePanel";
import DomainPanel from "./system-setting/DomainPanel";
import PaymentChannelsContent from "@/components/console/PaymentChannelsContent";
import { HomepageConfig } from "@/services/homepageConfigService";
import { FaqSettings } from "@/components/system-setting/FaqSettings";
import { AdminConfigForm } from "./AdminConfigForm";
import { systemConfigService } from "@/services/systemConfigService";
import { md5Encrypt } from "@/shared/utils/crypto";
import { AdminConfig, EmailConfig } from "@/types/system";
import { LoginSettingsContent } from "./LoginSettingsContent";
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
import { LanguageSetting } from "@/components/system-setting/LanguageSetting";
import { TagsBarSetting } from "../system-setting/TagsBarSetting";
interface SystemSettingsRightContentProps {
filteredKeys: string[];
settingsMenuItems: SettingsMenuItem[];
platformConfig: PlatformConfig;
homepageConfig: HomepageConfig;
sectionRefs: React.MutableRefObject<Record<string, HTMLElement | null>>;
titleRefs: React.MutableRefObject<Record<string, HTMLElement | null>>; // New: refs for section titles
onSavePlatformConfig: (config: { [key: string]: any }) => Promise<boolean>;
onSaveEmbeddedHtml: (config: EmbeddedHtmlConfig) => Promise<boolean>;
handleThemeChange: (theme: Theme) => Promise<void>;
uploadImage: any;
scrollContainerRef?: React.RefObject<HTMLDivElement>;
saveNavigationConfig: (config: TopNavigationItem[]) => Promise<boolean>;
saveFaqConfig: (config: FaqItem[]) => Promise<boolean>;
saveLoginConfig: (config: LoginConfig) => Promise<boolean>;
emailConfig: EmailConfig;
loginConfig: LoginConfig;
onSaveEmailConfig: (config: EmailConfig) => Promise<boolean>;
emailSubmitLoading: boolean;
}
const SystemSettingsRightContent: React.FC<SystemSettingsRightContentProps> = ({
filteredKeys,
settingsMenuItems,
platformConfig,
homepageConfig,
onSaveEmbeddedHtml,
sectionRefs,
titleRefs, // New prop
onSavePlatformConfig,
handleThemeChange,
uploadImage,
scrollContainerRef,
saveNavigationConfig,
saveFaqConfig,
saveLoginConfig,
emailConfig,
loginConfig,
onSaveEmailConfig,
emailSubmitLoading,
}) => {
const { t } = useTranslation();
const menuItems = useMemo(() => {
return settingsMenuItems.filter((it) => filteredKeys.includes(it.key));
}, [settingsMenuItems, filteredKeys]);
const handleChangePassword = async (config: AdminConfig) => {
const result = await systemConfigService.updateSystemConfig(
{
account: {
...config,
password: md5Encrypt(config.password),
},
},
"password"
);
return result;
};
return (
<div
ref={scrollContainerRef}
className="flex-1 overflow-y-auto h-full pb-40 space-y-6"
style={{ scrollBehavior: "auto" }}
>
<div className="h-0" aria-hidden="true"></div>
{menuItems.map((section) => (
<>
<section
key={section.key}
ref={(el) => {
if (el) sectionRefs.current[section.key] = el;
}}
id={`section-${section.key}`}
className="px-6 py-6 scroll-mt-16 border-1 rounded-lg shadow-md max-w-2xl mx-auto"
>
<div className="mb-4">
<h2
className="text-xl font-semibold"
ref={(el) => {
if (el) titleRefs.current[section.key] = el;
}}
id={`title-${section.key}`}
>
{t(section.label)}
</h2>
<p className="text-sm text-default-500">
{t(section.description || "")}
</p>
</div>
{/* Content sections */}
{section.key === "title-description" && (
<TitleAndDescPanel
config={platformConfig as TitleAndDescPanelConfig}
onSave={onSavePlatformConfig}
/>
)}
{section.key === "meta-data" && (
<MetaDataPanel
metaData={platformConfig}
onSave={onSavePlatformConfig}
uploadImage={uploadImage}
platformConfig={platformConfig}
/>
)}
{section.key === "custom-domain" && (
<div className="space-y-4">
<DomainPanel
config={platformConfig}
onSave={onSavePlatformConfig}
/>
</div>
)}
{section.key === "platform-language" && (
<LanguageSetting
config={platformConfig}
onSave={onSavePlatformConfig}
/>
)}
{section.key === "branding" && (
<BrandPanel
config={platformConfig as BrandPanelConfig}
onSave={onSavePlatformConfig}
onUploadImage={uploadImage}
/>
)}
{section.key === "theme" && (
<ThemeSelector
value={platformConfig.theme || Theme.DEFAULT}
onChange={handleThemeChange}
/>
)}
{section.key === "smtp-settings" && (
<EmailConfigForm
config={emailConfig}
onSave={onSaveEmailConfig}
isLoading={emailSubmitLoading}
/>
)}
{section.key === "email-login-settings" && (
<LoginSettingsContent
loginConfig={loginConfig}
saveLoginConfig={saveLoginConfig}
emailConfig={emailConfig}
type="email"
/>
)}
{section.key === "google-login-settings" && (
<LoginSettingsContent
loginConfig={loginConfig}
saveLoginConfig={saveLoginConfig}
emailConfig={emailConfig}
type="google"
/>
)}
{section.key === "navigation" && (
<TopNavigationSettings
onSave={saveNavigationConfig}
config={homepageConfig.top_navigation}
labelPlacement="outside"
/>
)}
{section.key === "tagsBar" && (
<TagsBarSetting
isEnabled={!!platformConfig.tag_bar_display}
onSave={onSavePlatformConfig}
/>
)}
{section.key === "faq" && (
<FaqSettings
onSave={saveFaqConfig}
config={homepageConfig.faq}
labelPlacement="outside"
/>
)}
{section.key === "payment" && (
<PaymentChannelsContent labelPlacement="outside" />
)}
{section.key === "xpack-explore" && (
<ExplorePanel
isEnabled={!!platformConfig.is_showcased}
onSave={onSavePlatformConfig}
/>
)}
{section.key === "code-injection" && (
<EmbeddedHtmlSettings
onSave={onSaveEmbeddedHtml}
config={homepageConfig.embeded_html}
labelPlacement="outside"
/>
)}
{section.key === "change-password" && (
<AdminConfigForm onSave={handleChangePassword} />
)}
</section>
</>
))}
{/* Bottom spacer to allow last sections to scroll higher into view for better selection */}
<div className="h-40" aria-hidden="true" />
</div>
);
};
export default SystemSettingsRightContent;
@@ -0,0 +1,157 @@
"use client";
import React, { useMemo, useRef, useEffect } from "react";
import { Input, Button, ScrollShadow } from "@nextui-org/react";
import { Search } from "lucide-react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { SettingModalTab } from "./console.type";
export interface SettingsMenuItem {
key: SettingModalTab;
label: string;
description?: string;
icon?: React.ReactNode;
}
export interface SettingsGroup {
key: string;
title: string;
items: SettingsMenuItem[];
}
interface Props {
activeKey: SettingModalTab;
onSelect: (key: SettingModalTab) => void;
searchQuery: string;
onSearchChange: (val: string) => void;
groups: SettingsGroup[];
filteredKeys: SettingModalTab[]; // which item keys match the current search
}
const SystemSettingsSidebar: React.FC<Props> = ({
activeKey,
onSelect,
searchQuery,
onSearchChange,
groups,
filteredKeys,
}) => {
const { t } = useTranslation();
const sidebarScrollRef = useRef<HTMLDivElement | null>(null);
const activeItemRefs = useRef<Record<string, HTMLButtonElement | null>>({});
// filter groups based on filteredKeys
const visibleGroups = useMemo(() => {
const keySet = new Set(filteredKeys);
return groups
.map((g) => ({
...g,
items: g.items.filter((it) => keySet.has(it.key)),
}))
.filter((g) => g.items.length > 0);
}, [groups, filteredKeys]);
const hasResults = visibleGroups.length > 0;
// Auto-scroll to active item when activeKey changes
useEffect(() => {
const activeElement = activeItemRefs.current[activeKey];
const scrollContainer = sidebarScrollRef.current;
if (activeElement && scrollContainer) {
// Get the scroll container element (ScrollShadow wraps content)
const scrollElement =
(scrollContainer.querySelector(
'[data-scrollable="true"]'
) as HTMLElement) || scrollContainer;
const containerRect = scrollElement.getBoundingClientRect();
const elementRect = activeElement.getBoundingClientRect();
// Check if element is visible in container
const isElementVisible =
elementRect.top >= containerRect.top &&
elementRect.bottom <= containerRect.bottom;
if (!isElementVisible) {
// Calculate scroll position to center the active item
const containerHeight = containerRect.height;
const elementTop = activeElement.offsetTop;
const elementHeight = activeElement.offsetHeight;
const scrollTop = elementTop - containerHeight / 2 + elementHeight / 2;
scrollElement.scrollTo({
top: Math.max(0, scrollTop),
behavior: "smooth",
});
}
}
}, [activeKey]);
return (
<ScrollShadow
ref={sidebarScrollRef}
className="w-[300px] border-r border-divider bg-content1/50 scrollbar-thin"
>
<div className="p-4 space-y-4">
<Input
size="sm"
aria-label={t("Search settings")}
placeholder={t("Search settings")}
value={searchQuery}
onValueChange={onSearchChange}
startContent={<Search size={16} className="text-default-400" />}
isClearable
onClear={() => onSearchChange("")}
/>
{!hasResults ? (
<div className="text-xs text-default-400 px-1 py-2">
{t("No results")}
</div>
) : (
<nav className="space-y-6">
{visibleGroups.map((group) => (
<div key={group.key} className="space-y-1">
<div className="px-2 text-[11px] tracking-wide text-default-400">
{t(group.title)}
</div>
<div className="flex flex-col gap-2">
{group.items.map((item) => {
const isActive = activeKey === item.key;
return (
<Button
key={item.key}
ref={(el) => {
if (el) activeItemRefs.current[item.key] = el;
}}
variant={isActive ? "flat" : "light"}
color={isActive ? "primary" : "default"}
size="sm"
className={`w-full border-1 justify-start h-auto py-3 px-3 text-left rounded-md ${
isActive
? "bg-primary/10 border-primary/20"
: "hover:bg-default-100 border-transparent"
}`}
onPress={() => onSelect(item.key)}
startContent={item.icon}
>
<div className="flex flex-col items-start w-full">
<div className="font-medium text-sm">
{t(item.label)}
</div>
</div>
</Button>
);
})}
</div>
</div>
))}
</nav>
)}
</div>
</ScrollShadow>
);
};
export default SystemSettingsSidebar;
@@ -0,0 +1,18 @@
export enum SettingModalTab {
TITLE_DESCRIPTION = "title-description",
META_DATA = "meta-data",
CUSTOM_DOMAIN = "custom-domain",
BRANDING = "branding",
THEME = "theme",
PAYMENT = "payment",
CODE_INJECTION = "code-injection",
XPACK_EXPLORE = "xpack-explore",
NAVIGATION = "navigation",
TAGS_BAR = "tagsBar",
FAQ = "faq",
CHANGE_PASSWORD = "change-password",
EMAIL_LOGIN_SETTINGS = "email-login-settings",
GOOGLE_LOGIN_SETTINGS = "google-login-settings",
SMTP_SETTINGS = "smtp-settings",
PLATFORM_LANGUAGE = "platform-language",
}
@@ -0,0 +1,74 @@
"use client";
import React, { useState } from "react";
import { Input, Card, CardBody } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface CustomDomainPanelProps {
domain: string;
setDomain: (domain: string) => void;
onValidationChange?: (isValid: boolean) => void;
}
const CustomDomainPanel: React.FC<CustomDomainPanelProps> = ({
domain,
setDomain,
onValidationChange,
}) => {
const { t } = useTranslation();
const [validationError, setValidationError] = useState<string | undefined>();
// Validate domain URL
const validateDomain = (value: string): string | undefined => {
if (!value.trim()) {
return undefined; // Domain is optional
}
// Basic domain format validation ,like www.example.com
const domainRegex =
/^(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$/;
if (!domainRegex.test(value)) {
return t("Please enter a valid domain");
}
return undefined;
};
const handleBlur = () => {
const error = validateDomain(domain);
setValidationError(error);
// 通知父组件校验状态
onValidationChange?.(!error);
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setDomain(value);
// 实时校验
const error = validateDomain(value);
setValidationError(error);
onValidationChange?.(!error);
};
return (
<Card shadow="none">
<CardBody className="flex flex-col p-0">
<h3 className="font-semibold mb-2">
{"1. "}
{t("Enter the domain you want to use")}
</h3>
<Input
label={t("Domain")}
placeholder={t("Enter your full domain name (e.g., www.example.com)")}
value={domain}
onChange={handleChange}
onBlur={handleBlur}
isInvalid={!!validationError}
errorMessage={validationError}
/>
</CardBody>
</Card>
);
};
export default CustomDomainPanel;
@@ -0,0 +1,66 @@
"use client";
import React from "react";
import {
Card,
CardBody,
Table,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface DNSRecordsPanelProps {
cnameTarget: string; // e.g., subdomain.domainhost.com
apexATarget?: string; // optional A record IP for apex
}
type DnsRow = { key: string; type: string; host: string; value: string };
const DNSRecordsPanel: React.FC<DNSRecordsPanelProps> = ({
cnameTarget,
apexATarget,
}) => {
const { t } = useTranslation();
const rows: DnsRow[] = [
...(cnameTarget
? [{ key: "cname", type: "CNAME", host: "www", value: cnameTarget }]
: []),
...(apexATarget
? [{ key: "a-record", type: "A", host: "@", value: apexATarget }]
: []),
];
return (
<Card shadow="none">
<CardBody className="p-0 flex flex-col gap-2">
<h3 className="font-semibold mb-2">
{"2. "}
{t("Create your DNS records")}
</h3>
<Table aria-label={t("DNS Records Table")} shadow="none" removeWrapper>
<TableHeader>
<TableColumn>{t("Type")}</TableColumn>
<TableColumn>{t("Host")}</TableColumn>
<TableColumn>{t("Value")}</TableColumn>
</TableHeader>
<TableBody items={rows}>
{(item) => (
<TableRow key={item.key}>
<TableCell>{item.type}</TableCell>
<TableCell>{item.host}</TableCell>
<TableCell>{item.value}</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardBody>
</Card>
);
};
export default DNSRecordsPanel;
@@ -0,0 +1,92 @@
"use client";
import React, { useState } from "react";
import {
Button,
Modal,
ModalContent,
ModalBody,
ModalHeader,
Card,
CardBody,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import CustomDomainPanel from "./CustomDomainPanel";
import DNSRecordsPanel from "./DNSRecordsPanel";
export type DomainActivationPanelConfig = {
domain?: string;
subdomain?: string;
cname_a_ip?: string;
};
interface DomainActivationPanelProps {
config: DomainActivationPanelConfig;
onSave: (config: DomainActivationPanelConfig) => void;
isOpen: boolean;
onClose: () => void;
}
const DomainActivationPanel: React.FC<DomainActivationPanelProps> = ({
config,
onSave,
isOpen,
onClose,
}) => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const [domain, setDomain] = useState(config.domain || "");
const [isValidDomain, setIsValidDomain] = useState(false);
const handleActivate = async () => {
setIsLoading(true);
try {
await onSave({
domain,
});
onClose();
} finally {
setIsLoading(false);
}
};
return (
<>
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalContent>
<ModalHeader>{t("Set Custom Domain")}</ModalHeader>
<ModalBody className="flex flex-col gap-4">
<CustomDomainPanel
domain={domain}
setDomain={setDomain}
onValidationChange={setIsValidDomain}
/>
<DNSRecordsPanel
cnameTarget={`${config.subdomain || ""}${process.env.NEXT_PUBLIC_DOMAIN_HOST || ""}`}
apexATarget={config.cname_a_ip}
/>
<Card shadow="none">
<CardBody className="p-0 flex flex-col gap-2 pb-4">
<h3 className="font-semibold mb-2">
{"3. "}
{t("Activate your domain")}
</h3>
<Button
color="primary"
isDisabled={!domain || !isValidDomain}
isLoading={isLoading}
onPress={handleActivate}
size="sm"
>
{t("Activate")}
</Button>
</CardBody>
</Card>
</ModalBody>
</ModalContent>
</Modal>
</>
);
};
export default DomainActivationPanel;
@@ -0,0 +1,108 @@
"use client";
import React, { useEffect } from "react";
import { Input, Button } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import UploadImage from "@/components/common/UploadImage";
export type BrandPanelConfig = {
logo: string;
name: string;
};
const brandPanelSchema = z.object({
logo: z.string(),
name: z.string().min(1, "Name is required"),
});
interface BrandPanelProps {
config: BrandPanelConfig;
onSave: (config: BrandPanelConfig) => Promise<boolean>;
onUploadImage: (file: File, sha256?: string) => Promise<string>;
}
const BrandPanel: React.FC<BrandPanelProps> = ({
config,
onSave,
onUploadImage,
}) => {
const { t } = useTranslation();
const {
handleSubmit,
control,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<BrandPanelConfig>({
resolver: zodResolver(brandPanelSchema),
mode: "onBlur",
defaultValues: config,
});
useEffect(() => {
setValue("name", config.name);
setValue("logo", config.logo);
}, [config]);
return (
<div className="space-y-4">
<div className="flex flex-col gap-4">
<form onSubmit={handleSubmit(onSave)} className="flex flex-col gap-4">
<Controller
name="name"
control={control}
render={({ field }) => (
<>
<Input
{...field}
label={t("Your brand")}
placeholder={t("Enter your brand name")}
isInvalid={!!errors.name}
errorMessage={errors.name?.message}
labelPlacement="outside"
isRequired
/>
</>
)}
/>
<Controller
name="logo"
control={control}
render={({ field }) => (
<div className="flex flex-col gap-2">
<div>
<label className="text-sm font-medium text-foreground">
{t("Logo")}
</label>
<p className="text-xs text-gray-500">
{t("Support JPG, PNG, GIF, SVG. Max size 5MB")}
</p>
</div>
<UploadImage
onSave={onUploadImage}
setImageUrl={(imageUrl) => field.onChange(imageUrl)}
imageUrl={field.value}
/>
</div>
)}
/>
<Button
color="primary"
variant="solid"
type="submit"
isLoading={isSubmitting}
size="sm"
isDisabled={!isValid}
className="mt-2 w-fit"
>
{t("Save")}
</Button>
</form>
</div>
</div>
);
};
export default BrandPanel;
@@ -0,0 +1,70 @@
"use client";
import React, { useState, useEffect } from "react";
import { Button } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { EditIcon } from "lucide-react";
import DomainActivationPanel from "../custom-domain/DomainActivationPanel";
export type DomainPanelConfig = {
subdomain?: string;
domain?: string;
cname_a_ip?: string;
};
interface DomainPanelProps {
config: DomainPanelConfig;
onSave: (config: DomainPanelConfig) => Promise<boolean>;
}
const DomainPanel: React.FC<DomainPanelProps> = ({ config, onSave }) => {
const { t } = useTranslation();
const [formData, setFormData] = useState<DomainPanelConfig>(config);
const [showCustomDomainModal, setShowCustomDomainModal] = useState(false);
// when context config updated, sync to form
useEffect(() => {
setFormData(config);
}, [config]);
const handleCustomDomainSave = async (config: DomainPanelConfig) => {
const result = await onSave(config);
if (!result) return;
};
return (
<>
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{t("Custom Domain")}</span>
<span className="text-xs text-gray-500">
{formData.domain || t("Set your custom domain for the platform")}
</span>
</div>
<Button
size="sm"
onPress={() => setShowCustomDomainModal(true)}
isIconOnly
startContent={<EditIcon size={16} />}
variant="flat"
></Button>
</div>
</div>
{showCustomDomainModal && (
<DomainActivationPanel
config={{
subdomain: formData.subdomain,
domain: formData.domain,
cname_a_ip: config.cname_a_ip,
}}
onSave={handleCustomDomainSave}
isOpen={showCustomDomainModal}
onClose={() => setShowCustomDomainModal(false)}
/>
)}
</>
);
};
export default DomainPanel;
@@ -0,0 +1,51 @@
"use client";
import React from "react";
import { Switch } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
export type ExplorePanelConfig = {
is_showcased: boolean;
};
interface ExplorePanelProps {
isEnabled: boolean;
onSave: (config: ExplorePanelConfig) => void;
}
export const ExplorePanel: React.FC<ExplorePanelProps> = ({
isEnabled,
onSave,
}) => {
const { t } = useTranslation();
return (
<div className="space-y-4">
<div className="flex flex-col gap-4">
{/* showcase in xpack */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Featured in the XPack showcase")}
</span>
<span className="text-xs text-gray-500">
{t(
"Enable this option to feature your site in the XPack global showcase and reach users worldwide."
)}
</span>
</div>
<Switch
isSelected={isEnabled}
onValueChange={(value) => {
onSave({
is_showcased: value,
});
}}
color="primary"
size="sm"
/>
</div>
</div>
</div>
);
};
@@ -0,0 +1,159 @@
"use client";
import React, { useEffect } from "react";
import { Button, Card, CardBody, Input } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import UploadImage from "@/components/common/UploadImage";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlatformConfig } from "@/shared/types/system";
import { FaFacebook } from "react-icons/fa6";
export interface FacebookMetaData {
facebook_title: string;
facebook_description: string;
facebook_image_url?: string;
}
const formSchema = z.object({
facebook_title: z
.string()
.max(200, "Title is too long")
.optional()
.default(""),
facebook_description: z
.string()
.max(1000, "Description is too long")
.optional()
.default(""),
facebook_image_url: z.string().optional().or(z.literal("")).default(""),
});
type FormData = z.infer<typeof formSchema>;
interface MetaDataFacebookFormProps {
metaData: FacebookMetaData;
onSave: (metaData: FacebookMetaData) => Promise<boolean>;
onUploadImage: (file: File, sha256?: string) => Promise<string>;
platformConfig: PlatformConfig;
}
const MetaDataFacebookForm: React.FC<MetaDataFacebookFormProps> = ({
metaData,
onSave,
onUploadImage,
platformConfig,
}) => {
const { t } = useTranslation();
const {
control,
handleSubmit,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
mode: "onBlur",
defaultValues: metaData,
});
useEffect(() => {
if (!metaData) return;
setValue("facebook_title", metaData.facebook_title || "");
setValue("facebook_description", metaData.facebook_description || "");
setValue("facebook_image_url", metaData.facebook_image_url || "");
}, [metaData, setValue]);
const onSubmit = async (data: FormData) => {
await onSave(data);
};
return (
<>
<div className="max-w-2xl">
<div className="mb-2">
<div className="flex items-center gap-2">
<FaFacebook className="text-primary" size={40} />
<div className="flex flex-col">
<span className="font-semibold text-default-900">
{platformConfig.name}
</span>
<span className="text-default-400 text-xs">2h</span>
</div>
</div>
</div>
<div className="mb-2 h-3 w-full rounded-large bg-default-100"></div>
<div className="mb-4 h-3 w-3/5 rounded-large bg-default-100"></div>
</div>
<Card shadow="none" className="border-1 max-w-2xl">
<CardBody className="px-0 py-4">
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col gap-4 px-4"
>
<Controller
name="facebook_image_url"
control={control}
render={({ field }) => (
<UploadImage
onSave={onUploadImage}
imageUrl={field.value}
setImageUrl={(imageUrl) => {
field.onChange(imageUrl);
}}
className="h-[280px] w-full bg-default-100"
description={t("Upload Facebook Image")}
/>
)}
/>
<Controller
name="facebook_title"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Facebook Title")}
placeholder={platformConfig.headline || " "}
isInvalid={!!errors.facebook_title}
errorMessage={errors.facebook_title?.message}
labelPlacement="outside"
/>
)}
/>
<Controller
name="facebook_description"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Facebook Description")}
placeholder={platformConfig.subheadline || " "}
isInvalid={!!errors.facebook_description}
errorMessage={errors.facebook_description?.message}
labelPlacement="outside"
/>
)}
/>
<div className="flex justify-start mt-2">
<Button
type="submit"
color="primary"
size="sm"
className="w-fit"
isLoading={isSubmitting}
isDisabled={!isValid}
>
{t("Save")}
</Button>
</div>
</form>
</CardBody>
</Card>
</>
);
};
export default MetaDataFacebookForm;
@@ -0,0 +1,82 @@
"use client";
import React, { useEffect } from "react";
import { Tabs, Tab } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import MetaDataFacebookForm from "./MetaDataFacebookForm";
import MetaDataXForm from "./MetaDataXForm";
import MetaDataSearchForm from "./MetaDataSearchForm";
import { FacebookMetaData } from "./MetaDataFacebookForm";
import { SearchMetaData } from "./MetaDataSearchForm";
import { XMetaData } from "./MetaDataXForm";
import { PlatformConfig } from "@/shared/types/system";
interface MetaData {
website_title?: string;
meta_description?: string;
x_title?: string;
x_description?: string;
x_image_url?: string;
facebook_title?: string;
facebook_description?: string;
facebook_image_url?: string;
}
interface MetaDataPanelProps {
metaData: MetaData;
onSave: (metaData: MetaData) => Promise<boolean>;
uploadImage: (file: File, sha256?: string) => Promise<string>;
platformConfig: PlatformConfig;
}
const MetaDataPanel: React.FC<MetaDataPanelProps> = ({
metaData,
onSave,
uploadImage,
platformConfig,
}) => {
const { t } = useTranslation();
const handleSave = async (data: MetaData) => {
return await onSave({
...metaData,
...data,
});
};
return (
<Tabs
aria-label="Meta data options"
variant="solid"
className="w-full"
destroyInactiveTabPanel={false}
>
<Tab key="search" title={t("Search")} className="pb-0">
<MetaDataSearchForm
metaData={metaData as SearchMetaData}
onSave={handleSave}
platformConfig={platformConfig}
/>
</Tab>
<Tab key="x" title={t("X Card")} className="pb-0">
<MetaDataXForm
metaData={metaData as XMetaData}
onSave={handleSave}
onUploadImage={uploadImage}
platformConfig={platformConfig}
/>
</Tab>
<Tab key="facebook" title={t("Facebook Card")} className="pb-0">
<MetaDataFacebookForm
metaData={metaData as FacebookMetaData}
onSave={handleSave}
onUploadImage={uploadImage}
platformConfig={platformConfig}
/>
</Tab>
</Tabs>
);
};
export default MetaDataPanel;
@@ -0,0 +1,215 @@
"use client";
import React, { useEffect } from "react";
import { Button, Card, CardBody, CardFooter, Input } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlatformConfig } from "@/shared/types/system";
export interface SearchMetaData {
website_title: string;
meta_description: string;
}
const formSchema = z.object({
website_title: z.string().max(75, "Title is too long").optional().default(""),
meta_description: z
.string()
.max(156, "Description is too long")
.optional()
.or(z.literal(""))
.default(""),
});
type FormData = z.infer<typeof formSchema>;
interface MetaDataSearchFormProps {
metaData: SearchMetaData;
platformConfig: PlatformConfig;
onSave: (metaData: SearchMetaData) => Promise<boolean>;
}
const MetaDataSearchForm: React.FC<MetaDataSearchFormProps> = ({
metaData,
platformConfig,
onSave,
}) => {
const { t } = useTranslation();
const {
control,
handleSubmit,
setValue,
watch,
formState: { errors, isSubmitting, isValid },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
mode: "onBlur",
defaultValues: metaData,
});
useEffect(() => {
if (!metaData) return;
setValue("meta_description", metaData.meta_description || "");
setValue("website_title", metaData.website_title || "");
}, [metaData, setValue]);
const onSubmit = async (data: FormData) => {
await onSave(data);
};
const metaDescription = watch("meta_description");
const websiteTitle = watch("website_title");
return (
<Card shadow="none" className="border-1 max-w-2xl">
<CardBody className="px-0 py-4">
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col gap-4 px-4"
>
<Controller
name="website_title"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Meta Title")}
placeholder={platformConfig.headline || " "}
isInvalid={!!errors.website_title}
errorMessage={errors.website_title?.message}
labelPlacement="outside"
defaultValue={t("Recommended: 70 characters")}
/>
)}
/>
<Controller
name="meta_description"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("Meta Description")}
placeholder={platformConfig.subheadline || " "}
isInvalid={!!errors.meta_description}
errorMessage={errors.meta_description?.message}
labelPlacement="outside"
defaultValue={t("Recommended: 156 characters")}
/>
)}
/>
<div className="flex justify-start mt-2">
<Button
type="submit"
color="primary"
size="sm"
className="w-fit"
isLoading={isSubmitting}
isDisabled={!isValid}
>
{t("Save")}
</Button>
</div>
</form>
</CardBody>
<CardFooter className="p-0">
<div className="w-full bg-default-100">
<div className="mt-4 mb-2 text-grey-500 px-5 uppercase text-xs">
{t("Preview")}
</div>
<div className="mx-5 -mb-5 overflow-hidden rounded-b-xl bg-grey-50 pt-2 ">
<div className="rounded-t-lg bg-white px-5 py-3 shadow-lg mb-5">
<div className="mt-3 flex items-center">
<div>
<svg fill="none" viewBox="0 0 92 31" className="mr-7 h-7">
<title>google</title>
<path
d="M39.15 15.898c0 4.303-3.378 7.473-7.525 7.473s-7.526-3.17-7.526-7.473c0-4.334 3.38-7.474 7.526-7.474 4.147 0 7.526 3.14 7.526 7.474zm-3.294 0c0-2.69-1.958-4.529-4.231-4.529-2.273 0-4.231 1.84-4.231 4.529 0 2.662 1.958 4.528 4.231 4.528 2.273 0 4.231-1.87 4.231-4.528z"
fill="#EA4335"
></path>
<path
d="M55.386 15.898c0 4.303-3.379 7.473-7.526 7.473-4.146 0-7.526-3.17-7.526-7.473 0-4.33 3.38-7.474 7.526-7.474 4.147 0 7.526 3.14 7.526 7.474zm-3.294 0c0-2.69-1.959-4.529-4.232-4.529s-4.231 1.84-4.231 4.529c0 2.662 1.958 4.528 4.231 4.528 2.273 0 4.232-1.87 4.232-4.528z"
fill="#FBBC05"
></path>
<path
d="M70.945 8.875v13.418c0 5.52-3.267 7.774-7.13 7.774-3.636 0-5.825-2.423-6.65-4.404l2.868-1.19c.511 1.217 1.763 2.652 3.779 2.652 2.472 0 4.004-1.52 4.004-4.38V21.67h-.115c-.737.906-2.158 1.698-3.95 1.698-3.751 0-7.188-3.255-7.188-7.443 0-4.22 3.437-7.501 7.188-7.501 1.789 0 3.21.792 3.95 1.671h.115V8.88h3.129v-.004zm-2.895 7.05c0-2.632-1.763-4.556-4.005-4.556-2.273 0-4.177 1.924-4.177 4.556 0 2.604 1.904 4.501 4.177 4.501 2.242 0 4.005-1.897 4.005-4.501z"
fill="#4285F4"
></path>
<path
d="M76.103 1.01v21.903H72.89V1.011h3.213z"
fill="#34A853"
></path>
<path
d="M88.624 18.357l2.558 1.699c-.826 1.216-2.815 3.312-6.251 3.312-4.262 0-7.445-3.282-7.445-7.474 0-4.444 3.21-7.473 7.076-7.473 3.893 0 5.798 3.086 6.42 4.754l.341.85-10.028 4.137c.768 1.5 1.962 2.264 3.636 2.264 1.678 0 2.841-.822 3.693-2.069zm-7.87-2.688l6.703-2.774c-.368-.933-1.478-1.583-2.783-1.583-1.674 0-4.005 1.472-3.92 4.357z"
fill="#EA4335"
></path>
<path
d="M11.936 13.953v-3.17h10.726c.105.552.159 1.206.159 1.914 0 2.378-.653 5.32-2.757 7.416-2.046 2.123-4.66 3.255-8.124 3.255-6.42 0-11.818-5.21-11.818-11.605C.122 5.368 5.52.158 11.94.158c3.551 0 6.081 1.389 7.982 3.198l-2.246 2.237c-1.363-1.273-3.21-2.264-5.74-2.264-4.688 0-8.354 3.764-8.354 8.434s3.666 8.434 8.354 8.434c3.041 0 4.773-1.216 5.882-2.322.9-.896 1.492-2.176 1.725-3.925l-7.607.003z"
fill="#4285F4"
></path>
</svg>
</div>
<div className="grow">
<div className="flex w-full items-center justify-end rounded-full bg-white p-3 px-4 shadow dark:bg-grey-900">
<svg
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
stroke-width="1.5"
className="pointer-events-none size-4 stroke-[2px] text-blue-600"
>
<path
d="M0.750 9.812 A9.063 9.063 0 1 0 18.876 9.812 A9.063 9.063 0 1 0 0.750 9.812 Z"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
transform="translate(-3.056 4.62) rotate(-23.025)"
></path>
<path
d="M16.221 16.22L23.25 23.25"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
></path>
</svg>
</div>
</div>
</div>
<div className="mt-4 flex items-center gap-2 border-t border-grey-200 pt-4 dark:border-grey-900">
<div
className="flex size-7 items-center justify-center rounded-full bg-grey-200 dark:bg-grey-700"
style={{
backgroundImage: `url("${platformConfig.logo}")`,
backgroundSize: "contain",
}}
></div>
<div className="flex flex-col text-sm">
<span>{platformConfig.domain || window.location.host}</span>
<span className="-mt-0.5 inline-block text-xs text-grey-600">
https://
{platformConfig.domain || window.location.host}
</span>
</div>
</div>
<div className="mt-1 flex flex-col">
<span className="text-lg text-[#1a0dab] dark:text-blue">
{websiteTitle || platformConfig.headline}
</span>
<span className="text-sm text-grey-900 dark:text-grey-700">
{metaDescription || platformConfig.subheadline}
</span>
</div>
</div>
</div>
</div>
</CardFooter>
</Card>
);
};
export default MetaDataSearchForm;
@@ -0,0 +1,160 @@
"use client";
import React, { useEffect } from "react";
import { Button, Card, CardBody, Input } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import UploadImage from "@/components/common/UploadImage";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { PlatformConfig } from "@/shared/types/system";
import { FaXTwitter } from "react-icons/fa6";
export interface XMetaData {
x_title: string;
x_description: string;
x_image_url?: string;
}
const formSchema = z.object({
x_title: z.string().max(200, "Title is too long").optional().default(""),
x_description: z
.string()
.max(1000, "Description is too long")
.optional()
.or(z.literal(""))
.default(""),
x_image_url: z.string().optional().or(z.literal("")).default(""),
});
type FormData = z.infer<typeof formSchema>;
interface MetaDataXFormProps {
metaData: XMetaData;
onSave: (metaData: XMetaData) => Promise<boolean>;
onUploadImage: (file: File, sha256?: string) => Promise<string>;
platformConfig: PlatformConfig;
}
const MetaDataXForm: React.FC<MetaDataXFormProps> = ({
metaData,
onSave,
onUploadImage,
platformConfig,
}) => {
const { t } = useTranslation();
const {
control,
handleSubmit,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<FormData>({
resolver: zodResolver(formSchema),
mode: "onBlur",
defaultValues: metaData,
});
useEffect(() => {
if (!metaData) return;
setValue("x_title", metaData.x_title || "");
setValue("x_description", metaData.x_description || "");
setValue("x_image_url", metaData.x_image_url || "");
}, [metaData, setValue]);
const onSubmit = async (data: FormData) => {
await onSave(data);
};
return (
<>
<div className="flex items-start gap-2 w-full">
<FaXTwitter size={40} />
<div className="w-full">
<div className="max-w-2xl">
<div className="mb-2">
<div className="flex">
<span className="mr-1 font-semibold text-default-900">
{platformConfig.name}
</span>
<span className="text-default-400">· 2h</span>
</div>
</div>
<div className="mb-2 h-3 w-full rounded-large bg-default-100"></div>
<div className="mb-4 h-3 w-3/5 rounded-large bg-default-100"></div>
</div>
<Card shadow="none" className="border-1 max-w-2xl">
<CardBody className="px-0 py-4">
<form
onSubmit={handleSubmit(onSubmit)}
className="flex flex-col gap-4 px-4"
>
<Controller
name="x_image_url"
control={control}
render={({ field }) => (
<UploadImage
onSave={onUploadImage}
imageUrl={field.value}
setImageUrl={(imageUrl) => {
field.onChange(imageUrl);
}}
className="h-[280px] w-full bg-default-100"
description={t("Upload X Image")}
/>
)}
/>
<Controller
name="x_title"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("X Title")}
placeholder={platformConfig.headline || " "}
isInvalid={!!errors.x_title}
errorMessage={errors.x_title?.message}
labelPlacement="outside"
/>
)}
/>
<Controller
name="x_description"
control={control}
render={({ field }) => (
<Input
{...field}
label={t("X Description")}
placeholder={platformConfig.subheadline || " "}
isInvalid={!!errors.x_description}
errorMessage={errors.x_description?.message}
labelPlacement="outside"
/>
)}
/>
<div className="flex justify-start mt-2">
<Button
type="submit"
color="primary"
size="sm"
className="w-fit"
isLoading={isSubmitting}
isDisabled={!isValid}
>
{t("Save")}
</Button>
</div>
</form>
</CardBody>
</Card>
</div>
</div>
</>
);
};
export default MetaDataXForm;
@@ -0,0 +1,106 @@
"use client";
import React, { useEffect } from "react";
import { Input, Button } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { z } from "zod";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
export type TitleAndDescPanelConfig = {
headline: string;
subheadline: string;
};
const titleAndDescPanelSchema = z.object({
headline: z.string().min(1, "Title is required"),
subheadline: z.string(),
});
interface TitleAndDescPanelProps {
config: TitleAndDescPanelConfig;
onSave: (config: TitleAndDescPanelConfig) => Promise<boolean>;
}
const TitleAndDescPanel: React.FC<TitleAndDescPanelProps> = ({
config,
onSave,
}) => {
const { t } = useTranslation();
const {
handleSubmit,
control,
setValue,
formState: { errors, isSubmitting, isValid },
} = useForm<TitleAndDescPanelConfig>({
resolver: zodResolver(titleAndDescPanelSchema),
mode: "onBlur",
defaultValues: config,
});
useEffect(() => {
setValue("headline", config.headline);
setValue("subheadline", config.subheadline);
}, [config]);
return (
<div className="space-y-4">
<div className="flex flex-col gap-4">
<form onSubmit={handleSubmit(onSave)} className="flex flex-col gap-4">
<Controller
name="headline"
control={control}
render={({ field }) => (
<>
{/* homepage headline */}
<Input
{...field}
label={t("Site title")}
placeholder={t("Enter site title")}
description={t("Main title displayed on the home page")}
isInvalid={!!errors.headline}
errorMessage={errors.headline?.message}
labelPlacement="outside"
isRequired
/>
</>
)}
/>
<Controller
name="subheadline"
control={control}
render={({ field }) => (
<>
{/* homepage subheadline */}
<Input
{...field}
label={t("Site description")}
placeholder={t("Enter site description")}
description={t(
"Secondary description displayed below the main title"
)}
isInvalid={!!errors.subheadline}
errorMessage={errors.subheadline?.message}
labelPlacement="outside"
/>
</>
)}
/>
<Button
color="primary"
variant="solid"
type="submit"
isLoading={isSubmitting}
size="sm"
isDisabled={!isValid}
className="mt-2 w-fit"
>
{t("Save")}
</Button>
</form>
</div>
</div>
);
};
export default TitleAndDescPanel;
@@ -64,7 +64,12 @@ export const APIKeyModal = ({
if (!response.success) {
console.error("Error creating auth key:", response.error_message);
toast.error(t("Failed to create auth key"));
const errorMsg = response.error_message
if (errorMsg?.endsWith('already exists')) {
toast.error(t(errorMsg, { name: keyName }));
} else {
toast.error(t("Failed to create auth key"));
}
return;
}
@@ -79,7 +84,12 @@ export const APIKeyModal = ({
if (!response.success) {
console.error("Error updating auth key:", response.error_message);
toast.error(t("Failed to update auth key"));
const errorMsg = response.error_message
if (errorMsg?.endsWith('already exists')) {
toast.error(t(errorMsg, { name: keyName }));
} else {
toast.error(t("Failed to update auth key"));
}
return;
}
@@ -90,6 +100,7 @@ export const APIKeyModal = ({
toast.success(t("Auth key updated successfully"));
onClose();
}
setName('')
} catch (error) {
console.error("Error creating/updating auth key:", error);
toast.error(t("Failed to create/update auth key"));
@@ -0,0 +1,388 @@
"use client";
import React, { useState, useCallback, useRef, useEffect } from "react";
import {
Table,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
Button,
Pagination,
Tooltip,
Spinner,
Chip,
Dropdown,
DropdownTrigger,
DropdownMenu,
DropdownItem,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Calendar, HelpCircle, Filter } from "lucide-react";
import { fetchAPI } from "@/shared/rpc/common-function";
import i18n from "@/shared/lib/i18n";
import { toast } from "react-hot-toast";
import { fetchAdminAPI } from "@/rpc/admin-api";
export interface OrderItem {
id: string;
amount: string;
balance: string;
order_id: string;
// 支付类型,stripe默认值
payment_type: string;
// 支付状态,0=未支付,1=已支付,2=支付失败
payment_state: number;
description: string;
// 充值时间
create_at: string;
// 交易时间,确认订单时间,只有充值完成后才有
confirm_at: string;
// 订单类型,充值(recharge),消费(purchase),退款(refund),冲正(reversal)
order_type: string;
}
interface AccountBalanceTableProps {
userId?: string;
source?: "client" | "admin";
}
const AccountBalanceTable: React.FC<AccountBalanceTableProps> = ({ userId, source }) => {
const { t } = useTranslation();
const [items, setItems] = useState<OrderItem[]>([]);
const [loading, setLoading] = useState(false);
const [pagination, setPagination] = useState({
page: 1,
pageSize: 10,
total: 0,
});
const [selectedType, setSelectedType] = useState<string>("all");
const [selectedStatus, setSelectedStatus] = useState<string>("all");
const resourceGroupsParams = useRef({
page: 1,
pageSize: 10,
keyword: "",
orderType: "",
status: "",
});
const pages = Math.ceil(pagination.total / pagination.pageSize);
const currentPage = Number(pagination.page);
const fetchOrders = useCallback(
async (
page: number,
page_size: number,
order_type?: string,
status?: string
): Promise<{ data: OrderItem[]; total: number; page: number; page_size: number }> => {
try {
const params = new URLSearchParams({
page: page.toString(),
page_size: page_size.toString(),
});
if (order_type) params.append("order_type", order_type);
if (status) params.append("status", status);
if (userId) params.append("user_id", userId);
// 根据是否有 userId 来决定使用哪个 API
const apiUrl = userId
? `/api/order/list/by_user?${params.toString()}`
: `/api/user/order/list?${params.toString()}`;
const response = source === "client" ? await fetchAPI<OrderItem[]>(apiUrl) : await fetchAdminAPI<OrderItem[]>(apiUrl);
if (!response.success) {
toast.error(response.error_message || i18n.t("Failed to load orders"));
return {
data: [],
total: 0,
page,
page_size,
};
}
return {
data: response.data || [],
total: response.page?.total || 0,
page: response.page?.page || page,
page_size: response.page?.page_size || page_size,
};
} catch (error) {
console.error("Error fetching orders:", error);
return {
data: [],
total: 0,
page,
page_size,
};
}
},
[userId]
);
const loadOrders = useCallback(
async (
page: number = 1,
pageSize: number = 10,
keyword: string = "",
orderType: string = "",
status: string = ""
) => {
setLoading(true);
try {
const response = await fetchOrders(
page,
pageSize,
orderType || undefined,
status || undefined
);
setItems(response.data);
setPagination({
page: response.page,
pageSize: response.page_size,
total: response.total,
});
resourceGroupsParams.current = {
page: response.page,
pageSize: response.page_size,
keyword,
orderType,
status,
};
} catch (error) {
console.error(t("Failed to load orders"), error);
} finally {
setLoading(false);
}
},
[fetchOrders]
);
const formatDate = (dateString: string) => {
return (
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3 text-gray-500" />
<span className="text-sm text-gray-600">
{new Date(dateString).toLocaleString()}
</span>
</div>
);
};
// 格式化金额,带正负号和美元符号
const formatAmount = (amount: string | number): string => {
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
if (isNaN(numAmount)) return '$0.00';
const absAmount = Math.abs(numAmount).toFixed(2);
if (numAmount > 0) {
return `+$${absAmount}`;
} else if (numAmount < 0) {
return `-$${absAmount}`;
}
return `$${absAmount}`;
};
// 格式化余额,只显示美元符号,不带正负号
const formatBalance = (balance: string | number): string => {
const numBalance = typeof balance === 'string' ? parseFloat(balance) : balance;
if (isNaN(numBalance)) return '$0.00';
return `$${Math.abs(numBalance).toFixed(2)}`;
};
const getStatusColor = (status: number) => {
switch (status) {
case 1:
return "success";
case 2:
return "danger";
default:
return "warning";
}
};
const onPageChange = (page: number) => {
const { pageSize, orderType, status } = resourceGroupsParams.current;
loadOrders(page, pageSize, "", orderType, status);
};
const handleTypeChange = (value: string) => {
setSelectedType(value);
const orderType = value === "all" ? "" : value;
const { status } = resourceGroupsParams.current;
loadOrders(1, pagination.pageSize, "", orderType, status);
};
const handleStatusChange = (value: string) => {
setSelectedStatus(value);
const status = value === "all" ? "" : value;
const { orderType } = resourceGroupsParams.current;
loadOrders(1, pagination.pageSize, "", orderType, status);
};
useEffect(() => {
loadOrders(1, 10, "");
}, [loadOrders]);
return (
<div className="space-y-4">
<Table
aria-label="Orders table"
classNames={{
wrapper: "min-h-[400px]",
}}
removeWrapper
>
<TableHeader>
<TableColumn>
<div className="flex items-center gap-1">
<span>{t("Transaction Time")}</span>
</div>
</TableColumn>
<TableColumn>
<div className="flex items-center gap-2">
<span>{t("Type")}</span>
<Dropdown>
<DropdownTrigger>
<Button
isIconOnly
size="sm"
variant="light"
aria-label="Filter by type"
>
<Filter
className={`w-4 h-4 ${
selectedType !== "all" ? "text-primary" : ""
}`}
/>
</Button>
</DropdownTrigger>
<DropdownMenu
aria-label="Type filter"
selectionMode="single"
selectedKeys={[selectedType]}
onSelectionChange={(keys) => {
const selected = Array.from(keys)[0] as string;
handleTypeChange(selected);
}}
>
<DropdownItem key="all">{t("All")}</DropdownItem>
<DropdownItem key="recharge">{t("Recharge")}</DropdownItem>
<DropdownItem key="purchase">{t("Purchase")}</DropdownItem>
</DropdownMenu>
</Dropdown>
</div>
</TableColumn>
<TableColumn>{t("Description")}</TableColumn>
<TableColumn>{t("Amount")}</TableColumn>
<TableColumn>{t("Balance")}</TableColumn>
<TableColumn>
<div className="flex items-center gap-2">
<span>{t("Status")}</span>
<Dropdown>
<DropdownTrigger>
<Button
isIconOnly
size="sm"
variant="light"
aria-label="Filter by status"
>
<Filter
className={`w-4 h-4 ${
selectedStatus !== "all" ? "text-primary" : ""
}`}
/>
</Button>
</DropdownTrigger>
<DropdownMenu
aria-label="Status filter"
selectionMode="single"
selectedKeys={[selectedStatus]}
onSelectionChange={(keys) => {
const selected = Array.from(keys)[0] as string;
handleStatusChange(selected);
}}
>
<DropdownItem key="all">{t("All")}</DropdownItem>
<DropdownItem key="0">{t("Pending")}</DropdownItem>
<DropdownItem key="1">{t("Completed")}</DropdownItem>
<DropdownItem key="2">{t("Failed")}</DropdownItem>
</DropdownMenu>
</Dropdown>
</div>
</TableColumn>
</TableHeader>
<TableBody
items={items}
isLoading={loading}
loadingContent={<Spinner />}
emptyContent={t("No orders found")}
>
{(order) => (
<TableRow key={order.id}>
<TableCell>{formatDate(order.payment_state === 0 ? order.create_at : order.confirm_at)}</TableCell>
<TableCell>
<span
className={
order.order_type === "recharge"
? "text-green-500"
: "text-red-500"
}
>
{
order.order_type === "recharge" ? t("Recharge") : t("Purchase")
}
</span>
</TableCell>
<TableCell>{order.description}</TableCell>
<TableCell>
<span
className={
order.order_type === "recharge"
? "text-green-500"
: "text-red-500"
}
>
{formatAmount(order.amount)}
</span>
</TableCell>
<TableCell>{formatBalance(order.balance)}</TableCell>
<TableCell>
<Chip
className="capitalize"
color={getStatusColor(order.payment_state)}
size="sm"
variant="flat"
>
{t(
order.payment_state === 1
? "Completed"
: order.payment_state === 2
? "Failed"
: "Pending"
)}
</Chip>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{pages > 1 && (
<div className="flex w-full justify-center">
<Pagination
showControls
color="primary"
variant="light"
page={currentPage}
total={pages}
onChange={onPageChange}
/>
</div>
)}
</div>
);
};
export default AccountBalanceTable;
@@ -53,6 +53,10 @@ const OverviewPage: React.FC = () => {
useEffect(() => {
fetchApiKeys();
if (sessionStorage.getItem('create_new_authorization')) {
handleNewKey();
sessionStorage.removeItem('create_new_authorization');
}
}, []);
// create new auth key
+17 -8
View File
@@ -11,8 +11,9 @@ import { formatCurrency } from "@/shared/utils/currency";
// Import dashboard content components
import DashboardOverview from "@/components/dashboard/DashboardOverview";
import WalletManagement from "@/components/wallet/WalletManagement";
import UserAccountBalance from "@/components/dashboard/UserAccountBalance";
import { Home, Key, Wallet } from "lucide-react";
import { Avatar, Card, CardBody, Button, Divider } from "@nextui-org/react";
import { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react";
import { RechargeModal } from "@/shared/components/modal/RechargeModal";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ChangePasswordModal } from "@/components/common/ChangePasswordModal";
@@ -41,7 +42,7 @@ const DashboardContent: React.FC = () => {
const [isRechargeModalOpen, setIsRechargeModalOpen] = useState(false);
const getInitialTab = (): TabKey => {
const tabFromUrl = searchParams.get("tab") as TabKey;
if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET].includes(tabFromUrl)) {
if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET, TabKey.USER_ACCOUNT].includes(tabFromUrl)) {
return tabFromUrl;
}
return TabKey.OVERVIEW;
@@ -93,17 +94,17 @@ const DashboardContent: React.FC = () => {
},
];
const handleTabNavigate = (tab: TabKey) => {
setActiveTab(tab);
const handleTabNavigate = (tab: TabKey | string) => {
setActiveTab(tab as TabKey);
// update url params
if (tab === TabKey.OVERVIEW) {
// when switch to dashboard, clear all query params, only keep base path
router.push("/dashboard", { scroll: false });
router.push("/console", { scroll: false });
} else {
// other tabs set corresponding tab params
const params = new URLSearchParams();
params.set("tab", tab);
router.push(`/dashboard?${params.toString()}`, { scroll: false });
router.push(`/console?${params.toString()}`, { scroll: false });
}
};
@@ -158,8 +159,15 @@ const DashboardContent: React.FC = () => {
<Wallet size={16} />
<span>
{t("Balance: {{amount}}", {
amount: formatCurrency(user?.wallet?.balance || 0),
})}
amount: "",
}).replace("{{amount}}", "")}
<Link
href="#"
className="text-xs cursor-pointer"
onPress={() => handleTabNavigate(TabKey.USER_ACCOUNT)}
>
{formatCurrency(user?.wallet?.balance || 0)}
</Link>
</span>
</div>
@@ -187,6 +195,7 @@ const DashboardContent: React.FC = () => {
{activeTab === TabKey.WALLET && (
<WalletManagement onRecharge={() => setIsRechargeModalOpen(true)} />
)}
{activeTab === TabKey.USER_ACCOUNT && <UserAccountBalance />}
</div>
</div>
@@ -0,0 +1,23 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import AccountBalanceTable from "./AccountBalanceTable";
const UserAccountBalance: React.FC = () => {
const { t } = useTranslation();
return (
<DashboardDemoContent
title={t("Account Balance")}
description={t("View your balance and transaction history")}
>
<div className="space-y-6 w-full">
<AccountBalanceTable source="client" />
</div>
</DashboardDemoContent>
);
};
export default UserAccountBalance;
@@ -3,8 +3,6 @@
import React, { useEffect, useState } from "react";
import {
Switch,
AccordionItem,
Accordion,
Select,
SelectItem,
Button,
@@ -72,139 +70,115 @@ export const EmailConfigForm: React.FC<EmailConfigFormProps> = ({
const isEmailEnabled = formData.email?.is_enabled || false;
return (
<Accordion
variant="splitted"
itemClasses={{
base: "shadow-none border-1",
}}
defaultExpandedKeys={["email-login"]}
className="px-0"
>
<AccordionItem
key="email-login"
title={
<div className="flex items-center gap-3">
<div className="flex flex-col">
<h3 className="text-lg font-semibold">{t("Email Login")}</h3>
<p className="text-sm text-gray-500">
{t("Configure email-based authentication")}
</p>
</div>
</div>
}
>
<div className="space-y-4">
{/* enable email login */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Enable Email Login")}
</span>
<span className="text-xs text-gray-500">
{t("Allow users to sign in with email")}
</span>
</div>
<Switch
isSelected={isEmailEnabled}
onValueChange={handleToggleEnabled}
color="primary"
size="sm"
isDisabled={isLoading || (isCaptchaMode && !isEmailConfigured)}
/>
</div>
<div className="space-y-4">
{/* enable email login */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{t("Enable Email Login")}</span>
<span className="text-xs text-gray-500">
{t("Allow users to sign in with email")}
</span>
</div>
<Switch
isSelected={isEmailEnabled}
onValueChange={handleToggleEnabled}
color="primary"
size="sm"
isDisabled={isLoading || (isCaptchaMode && !isEmailConfigured)}
/>
</div>
{/* authentication mode selection */}
<div className="p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
{/* authentication mode selection */}
<div className="p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Authentication Mode")}
</span>
<span className="text-xs text-gray-500">
{t("Choose how users authenticate with email")}
</span>
</div>
<Select
selectedKeys={[formData.email?.mode || EmailMode.PASSWORD]}
onSelectionChange={(keys) => {
const mode = Array.from(keys)[0] as EmailMode;
handleModeChange(mode);
}}
size="sm"
isDisabled={isLoading || !isEmailEnabled}
renderValue={() => {
const selectedKey = formData.email?.mode || EmailMode.PASSWORD;
if (selectedKey === EmailMode.PASSWORD)
return t("Email/Password");
return t(
selectedKey === EmailMode.CAPTCHA
? "Email/Verification Code"
: "Email/Password"
);
}}
>
<SelectItem key={EmailMode.PASSWORD} value={EmailMode.PASSWORD}>
<div className="flex flex-col">
<span className="text-sm font-medium">
{t("Authentication Mode")}
{t("Email/Password")}
</span>
<span className="text-xs text-gray-500">
{t("Choose how users authenticate with email")}
{t("Traditional email and password authentication")}
</span>
</div>
<Select
selectedKeys={[formData.email?.mode || EmailMode.PASSWORD]}
onSelectionChange={(keys) => {
const mode = Array.from(keys)[0] as EmailMode;
handleModeChange(mode);
}}
size="sm"
isDisabled={isLoading || !isEmailEnabled}
renderValue={() => {
const selectedKey =
formData.email?.mode || EmailMode.PASSWORD;
if (selectedKey === EmailMode.PASSWORD)
return t("Email/Password");
return t(
selectedKey === EmailMode.CAPTCHA
? "Email/Verification Code"
: "Email/Password"
);
}}
>
<SelectItem key={EmailMode.PASSWORD} value={EmailMode.PASSWORD}>
<div className="flex flex-col">
<span className="text-sm font-medium">
{t("Email/Password")}
</span>
<span className="text-xs text-gray-500">
{t("Traditional email and password authentication")}
</span>
</div>
</SelectItem>
<SelectItem key={EmailMode.CAPTCHA} value={EmailMode.CAPTCHA}>
<div className="flex flex-col">
<span className="text-sm font-medium">
{t("Email/Verification Code")}
</span>
<span className="text-xs text-gray-500">
{t("Passwordless login with email verification code")}
</span>
</div>
</SelectItem>
</Select>
</div>
</div>
{/* email configuration hint - only show in captcha mode */}
{isEmailEnabled && isCaptchaMode && !isEmailConfigured && (
<Alert color="warning" variant="flat" className="mb-4">
<div className="flex gap-2">
<span>
{t(
"Email service is not configured. Please configure email settings first."
)}
</SelectItem>
<SelectItem key={EmailMode.CAPTCHA} value={EmailMode.CAPTCHA}>
<div className="flex flex-col">
<span className="text-sm font-medium">
{t("Email/Verification Code")}
</span>
<span className="text-xs text-gray-500">
{t("Passwordless login with email verification code")}
</span>
<Link
className="text-sm underline cursor-pointer"
onPress={() => {
onTabNavigate?.(TabKey.SYSTEM_SETTINGS, "email-admin");
}}
>
{t("Go to Settings")}
</Link>
</div>
</Alert>
)}
{/* save button - only show in enabled state */}
{isEmailEnabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
</SelectItem>
</Select>
</div>
</AccordionItem>
</Accordion>
</div>
{/* email configuration hint - only show in captcha mode */}
{isEmailEnabled && isCaptchaMode && !isEmailConfigured && (
<Alert color="warning" variant="flat" className="mb-4">
<div className="flex gap-2">
<span>
{t(
"SMTP is not configured. Please configure email settings first."
)}
</span>
{onTabNavigate ? (
<Link
className="text-sm underline cursor-pointer"
onPress={() => {
onTabNavigate?.(TabKey.SYSTEM_SETTINGS, "email-admin");
}}
>
{t("Go to Settings")}
</Link>
) : null}
</div>
</Alert>
)}
{/* save button - only show in enabled state */}
{isEmailEnabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
</div>
);
};
@@ -1,16 +1,10 @@
"use client";
import React, { useEffect, useState } from "react";
import {
Input,
Button,
Switch,
AccordionItem,
Accordion,
} from "@nextui-org/react";
import { Input, Button, Switch } from "@nextui-org/react";
import { Eye, EyeOff } from "lucide-react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { getGoogleRedirectUri } from "@/hooks/useLogin";
import { getGoogleRedirectUri } from "@/shared/hooks/useLogin";
import { GoogleAuthConfig } from "@/shared/types/system";
interface GoogleAuthConfigFormProps {
@@ -47,115 +41,94 @@ export const GoogleAuthConfigForm: React.FC<GoogleAuthConfigFormProps> = ({
const isFormValid = formData.client_id.trim() !== "";
return (
<Accordion
variant="splitted"
itemClasses={{
base: "shadow-none border-1",
}}
defaultExpandedKeys={["google-auth-config"]}
className="px-0"
>
<AccordionItem
key="google-auth-config"
title={
<div className="flex flex-col justify-between">
<h3 className="text-lg font-semibold">
{t("Google Login Settings")}
</h3>
<p className="text-sm text-gray-500">
{t("Configure Google OAuth integration")}
</p>
<>
<div className="space-y-4">
{/* enable google login */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Enable Google Login")}
</span>
<span className="text-xs text-gray-500">
{t("Allow users to sign in with Google")}
</span>
</div>
}
>
<div className="space-y-4">
{/* enable google login */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Enable Google Login")}
</span>
<span className="text-xs text-gray-500">
{t("Allow users to sign in with Google")}
</span>
</div>
<Switch
isSelected={formData.is_enabled}
onValueChange={(value) => {
onSave({
...formData,
is_enabled: value,
});
}}
color="primary"
size="sm"
/>
</div>
{/* Google Client ID */}
<Input
label={t("Google Client ID")}
placeholder={t("OAuth 2.0 Client ID from Google Cloud Console")}
value={formData.client_id}
onChange={(e) => handleInputChange("client_id", e.target.value)}
isRequired
isDisabled={!formData.is_enabled}
/>
{/* Google Client Secret */}
<Input
label={t("Google Client Secret")}
placeholder={t(
"OAuth 2.0 Client Secret (optional, for server-side verification)"
)}
value={formData.client_secret || ""}
onChange={(e) => handleInputChange("client_secret", e.target.value)}
type={showClientSecret ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowClientSecret(!showClientSecret)}
className="focus:outline-none"
disabled={!formData.is_enabled}
>
{showClientSecret ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
isDisabled={!formData.is_enabled}
/>
{/* Redirect URI */}
<Input
label={t("Redirect URI")}
placeholder="https://yourdomain.com/auth/google/callback"
description={t(
"Authorized redirect URI configured in Google Cloud Console"
)}
value={getGoogleRedirectUri()}
isDisabled={true}
<Switch
isSelected={formData.is_enabled}
onValueChange={(value) => {
onSave({
...formData,
is_enabled: value,
});
}}
color="primary"
size="sm"
/>
</div>
{/* Action Buttons */}
{formData.is_enabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
isDisabled={!isFormValid}
size="sm"
{/* Google Client ID */}
<Input
label={t("Google Client ID")}
placeholder={t("OAuth 2.0 Client ID from Google Cloud Console")}
value={formData.client_id}
onChange={(e) => handleInputChange("client_id", e.target.value)}
isRequired
isDisabled={!formData.is_enabled}
/>
{/* Google Client Secret */}
<Input
label={t("Google Client Secret")}
placeholder={t(
"OAuth 2.0 Client Secret (optional, for server-side verification)"
)}
value={formData.client_secret || ""}
onChange={(e) => handleInputChange("client_secret", e.target.value)}
type={showClientSecret ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowClientSecret(!showClientSecret)}
className="focus:outline-none"
disabled={!formData.is_enabled}
>
{t("Save")}
</Button>
</div>
)}
</AccordionItem>
</Accordion>
{showClientSecret ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
isDisabled={!formData.is_enabled}
/>
{/* Redirect URI */}
<Input
label={t("Redirect URI")}
placeholder="https://yourdomain.com/auth/google/callback"
description={t(
"Authorized redirect URI configured in Google Cloud Console"
)}
value={getGoogleRedirectUri()}
isDisabled={true}
/>
</div>
{/* Action Buttons */}
{formData.is_enabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
isDisabled={!isFormValid}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
</>
);
};
+47 -10
View File
@@ -4,12 +4,19 @@ import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { HeroSection } from "../../shared/components/marketplace/HeroSection";
import { ServiceListSection } from "@/shared/components/marketplace/ServiceListSection";
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
import { ServiceData } from "@/shared/types/marketplace";
import { fetchServices } from "@/services/marketplaceService";
import { Spinner } from "@nextui-org/react";
import { ThemeType } from "@/shared/types/system";
interface MarketplaceMainProps {
initialServices: ServiceData[];
availableTags: string[];
isTagBarDisplay: boolean;
selectedTag: string;
setSelectedTag: (tag: string) => void;
currentTheme: ThemeType;
initialTotal: number;
initialPage: number;
initialSearch: string;
@@ -19,6 +26,11 @@ interface MarketplaceMainProps {
export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
initialServices,
availableTags,
isTagBarDisplay,
selectedTag,
setSelectedTag,
currentTheme,
initialTotal,
initialPage,
initialSearch,
@@ -33,21 +45,23 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
const [total, setTotal] = useState(initialTotal);
const [loading, setLoading] = useState(false);
// load services data
const loadServices = async (page: number, search: string) => {
const loadServices = async (page: number, search: string, tag: string = "ALL") => {
try {
setLoading(true);
const result = await fetchServices({
page,
page_size: pageSize,
keyword: search,
// 如果需要,可以在这里添加tag参数传递给API
tag: tag !== "ALL" ? tag : undefined,
});
setServices(result.data.services);
setTotal(result.page.total);
setCurrentPage(page);
} catch (error) {
console.error('Failed to load services:', error);
console.error("Failed to load servers:", error);
} finally {
setLoading(false);
}
@@ -55,7 +69,7 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
// when search query changes, scroll to the top of the page
useEffect(() => {
window.scrollTo({ top: 0, behavior: 'smooth' });
window.scrollTo({ top: 0, behavior: "smooth" });
}, [currentPage, searchQuery]);
// update URL parameters
@@ -63,11 +77,11 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
const params = new URLSearchParams();
if (page > 1) {
params.set('page', page.toString());
params.set("page", page.toString());
}
if (search.trim()) {
params.set('search', search.trim());
params.set("search", search.trim());
}
const queryString = params.toString();
@@ -79,13 +93,20 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
// when page number changes, reload
const handlePageChange = (page: number) => {
updateURL(page, searchQuery);
loadServices(page, searchQuery);
loadServices(page, searchQuery, selectedTag);
};
// handle search submit
const handleSearch = () => {
updateURL(1, searchQuery);
loadServices(1, searchQuery);
loadServices(1, searchQuery, selectedTag);
};
// handle tag change
const handleTagChange = (tag: string) => {
setSelectedTag(tag);
setCurrentPage(1);
loadServices(1, searchQuery, tag);
};
// if there is an error, show error message
@@ -102,11 +123,27 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
{/* Hero Section */}
<HeroSection
searchQuery={searchQuery}
isTagBarDisplay={isTagBarDisplay}
onSearchChange={setSearchQuery}
onSearch={handleSearch}
/>
{/* filter section */}
{
isTagBarDisplay && (
<>
<TagFilter
theme={currentTheme}
tags={availableTags}
selectedTag={selectedTag}
onTagChange={handleTagChange}
maxWidthPercent={80}
/>
</>
)
}
{/* Service List Section */}
{/* Server List Section */}
{loading ? (
<div className="mx-auto h-[200px] flex items-center justify-center">
<Spinner />
@@ -122,4 +159,4 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
)}
</>
);
};
};
@@ -1,133 +0,0 @@
"use client";
import React from 'react';
import {
Input,
Select,
SelectItem,
Chip,
} from '@nextui-org/react';
import { useTranslation } from '@/shared/lib/useTranslation';
import { AuthMethod, MCPServiceFormData } from '@/types/mcp-service';
interface BasicInfoTabProps {
formData: MCPServiceFormData;
newTag: string;
setNewTag: (value: string) => void;
onInputChange: (field: keyof MCPServiceFormData, value: any) => void;
onAddTag: () => void;
onRemoveTag: (tag: string) => void;
}
export const BasicInfoTab: React.FC<BasicInfoTabProps> = ({
formData,
newTag,
setNewTag,
onInputChange,
onAddTag,
onRemoveTag
}) => {
const { t } = useTranslation();
return (
<div className="space-y-4">
<Input
label={t('Service Name')}
placeholder={t('Enter service name')}
value={formData.name}
onChange={(e) => onInputChange('name', e.target.value)}
isRequired
/>
<Input
label={t('Short Description')}
placeholder={t('Brief description of the service')}
value={formData.short_description || ''}
onChange={(e) => onInputChange('short_description', e.target.value)}
isRequired
/>
<Input
label={t('API Endpoint')}
placeholder="https://api.example.com/v1"
value={formData.base_url || ''}
onChange={(e) => onInputChange('base_url', e.target.value)}
isRequired
/>
<Select
label={t('Authentication Type')}
selectedKeys={formData.auth_method ? [formData.auth_method] : []}
onSelectionChange={(keys) => {
const selectedKey = Array.from(keys)[0] as string;
onInputChange('auth_method', selectedKey);
// clear auth config when switch auth type
onInputChange('auth_header', '');
onInputChange('auth_token', '');
}}
>
<SelectItem key="none" value="none">{t('None')}</SelectItem>
<SelectItem key="apikey" value="apikey">{t('API Key')}</SelectItem>
<SelectItem key="token" value="token">{t('Bearer Token')}</SelectItem>
</Select>
{/* auth config input fields */}
{formData.auth_method === AuthMethod.APIKey && (
<div className="space-y-4">
<Input
label={t('API Key Header Name')}
placeholder="X-API-Key"
value={formData.auth_header || ''}
onChange={(e) => onInputChange('auth_header', e.target.value)}
description={t('The header name for the API key (e.g., X-API-Key, Authorization)')}
/>
<Input
label={t('API Key Value')}
placeholder={t('Enter API key')}
type="password"
value={formData.auth_token || ''}
onChange={(e) => onInputChange('auth_token', e.target.value)}
autoComplete='new-password'
/>
</div>
)}
{formData.auth_method === AuthMethod.BearerToken && (
<Input
label={t('Bearer Token')}
placeholder={t('Enter bearer token')}
type="password"
value={formData.auth_token || ''}
onChange={(e) => onInputChange('auth_token', e.target.value)}
description={t('The bearer token for authentication')}
autoComplete='new-password'
/>
)}
{/* tag management */}
<div className="space-y-2">
<label className="text-sm font-medium">{t('Tags')}</label>
<div className="flex gap-2">
<Input
placeholder={t('Add tag')}
value={newTag}
onChange={(e) => setNewTag(e.target.value)}
onKeyUp={(e) => e.key === 'Enter' && onAddTag()}
/>
</div>
<div className="flex flex-wrap gap-2">
{(formData.tags || []).map((tag, index) => (
<Chip
key={index}
onClose={() => onRemoveTag(tag)}
variant="flat"
>
{tag}
</Chip>
))}
</div>
</div>
</div>
);
};
@@ -1,41 +1,54 @@
"use client";
import React, { useState, useCallback, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useState, useCallback, useEffect, useRef } from "react";
import { useSearchParams } from "next/navigation";
import { useMCPServicesList } from "@/hooks/useMCPServicesList";
import { MCPService, MCPServiceFormData, EnabledEnum } from "@/types/mcp-service";
import { MCPService, MCPServiceFormData } from "@/shared/types/mcp-service";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ServiceFiltersBar } from "./ServiceFiltersBar";
import { ServiceTable } from "./ServiceTable";
import { ServiceEditPage } from "./ServiceEditPage";
import { OpenAPIGeneratorModal } from "./OpenAPIGeneratorModal";
import { ServiceFiltersBar } from "@/shared/components/mcp-services/ServiceFiltersBar";
import { ServiceEditPage } from "@/components/mcp-services/ServiceEditPage";
import { DeleteConfirmModal } from "@/shared/components/modal/DeleteConfirmModal";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import { ServiceTable } from "@/shared/components/mcp-services/ServiceTable";
import { OpenAPIGeneratorModal } from "@/shared/components/mcp-services/OpenAPIGeneratorModal";
import { Input } from "@nextui-org/react";
import { Search } from "lucide-react";
type ViewMode = "list" | "edit" | "create";
export const MCPServicesManagement: React.FC = () => {
const { t } = useTranslation();
const router = useRouter();
const searchParams = useSearchParams();
const {
services,
loading,
pagination,
searchTerm,
setSearchTerm,
statusFilter,
setStatusFilter,
onPageChange,
createService,
updateService,
deleteService,
toggleServiceStatus,
parseOpenAPIDocument,
loadServices
loadServices,
setSearchTerm,
setStatusFilter,
} = useMCPServicesList();
const [addServiceType, setAddServiceType] = useState<string | null>(null);
// 搜索相关状态
const [searchValue, setSearchValue] = useState('');
const searchTimerRef = useRef<NodeJS.Timeout | null>(null);
// 清理定时器
useEffect(() => {
return () => {
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
};
}, []);
// Get initial state from URL
const getInitialViewMode = (): ViewMode => {
@@ -57,26 +70,29 @@ export const MCPServicesManagement: React.FC = () => {
);
// Update URL when view mode or service ID changes
const updateURL = useCallback((mode: ViewMode, serviceId?: string | null) => {
const params = new URLSearchParams(searchParams);
const updateURL = useCallback(
(mode: ViewMode, serviceId?: string | null) => {
const params = new URLSearchParams(searchParams);
// Always keep the tab parameter
params.set("tab", "mcp-services");
// Always keep the tab parameter
params.set("tab", "mcp-services");
if (mode === "list") {
params.delete("mode");
params.delete("serviceId");
} else {
params.set("mode", mode);
if (serviceId) {
params.set("serviceId", serviceId);
} else {
if (mode === "list") {
params.delete("mode");
params.delete("serviceId");
} else {
params.set("mode", mode);
if (serviceId) {
params.set("serviceId", serviceId);
} else {
params.delete("serviceId");
}
}
}
router.push(`/console?${params.toString()}`, { scroll: false });
}, [router, searchParams]);
window.history.pushState({}, "", `/admin/console?${params.toString()}`);
},
[searchParams]
);
// Sync state with URL on mount and URL changes
useEffect(() => {
@@ -94,29 +110,38 @@ export const MCPServicesManagement: React.FC = () => {
null
);
// Service CRUD operations
const handleCreateService = useCallback(() => {
setSelectedServiceId(null);
setViewMode("create");
updateURL("create");
}, [updateURL]);
// Server CRUD operations
const handleCreateService = (type: string) => {
setAddServiceType(type);
setIsOpenAPIModalOpen(true);
};
const handleEditService = useCallback((service: MCPService) => {
setSelectedServiceId(service.id);
setViewMode("edit");
updateURL("edit", service.id);
}, [updateURL]);
const handleEditService = useCallback(
(service: MCPService) => {
setSelectedServiceId(service.id);
setViewMode("edit");
updateURL("edit", service.id);
},
[updateURL]
);
const handleSaveService = useCallback(
async (formData: MCPServiceFormData) => {
async (formData: MCPServiceFormData, isDraft?: boolean) => {
try {
const result = selectedServiceId ? await updateService(selectedServiceId, formData) : await createService(formData);
if (!result) return
const result = selectedServiceId
? await updateService(selectedServiceId, formData)
: await createService(formData);
if (!result) return false;
if (isDraft) {
return true;
}
setViewMode("list");
setSelectedServiceId(null);
updateURL("list");
return true;
} catch (error) {
console.error("Failed to save service:", error);
console.error("Failed to save server:", error);
return false;
}
},
[selectedServiceId, updateService, createService, updateURL]
@@ -140,28 +165,22 @@ export const MCPServicesManagement: React.FC = () => {
setIsDeleteModalOpen(false);
setServiceToDelete(null);
} catch (error) {
console.error("Failed to delete service:", error);
console.error("Failed to delete server:", error);
}
}
}, [serviceToDelete, deleteService]);
const handleToggleStatus = useCallback(
async (service: MCPService) => {
async (serviceId: string) => {
try {
await toggleServiceStatus(service.id);
await toggleServiceStatus(serviceId);
} catch (error) {
console.error("Failed to toggle service status:", error);
console.error("Failed to toggle server status:", error);
}
},
[toggleServiceStatus]
);
// OpenAPI operations
const handleOpenAPIGenerate = useCallback(() => {
setIsOpenAPIModalOpen(true);
}, []);
const handleEditGeneratedService = useCallback(
async (serviceId: string) => {
try {
@@ -172,7 +191,7 @@ export const MCPServicesManagement: React.FC = () => {
setIsOpenAPIModalOpen(false);
loadServices(1);
} catch (error) {
console.error("Failed to navigate to generated service:", error);
console.error("Failed to navigate to generated server:", error);
}
},
[updateURL]
@@ -188,6 +207,26 @@ export const MCPServicesManagement: React.FC = () => {
setServiceToDelete(null);
}, []);
// 处理搜索 - 使用防抖
const handleSearchChange = useCallback((value: string) => {
setSearchValue(value);
// 清除之前的定时器
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
// 设置新的定时器,500ms 后触发搜索
searchTimerRef.current = setTimeout(() => {
setSearchTerm(value);
}, 500);
}, [setSearchTerm]);
// 处理状态筛选
const handleStatusFilterChange = useCallback((status: string) => {
setStatusFilter(status);
}, [setStatusFilter]);
// Render edit page if in edit/create mode
if (viewMode === "edit" || viewMode === "create") {
return (
@@ -196,31 +235,45 @@ export const MCPServicesManagement: React.FC = () => {
onSave={handleSaveService}
onCancel={handleCancelEdit}
loading={loading}
onUnpublish={handleToggleStatus}
onRefreshList={() => {
loadServices(1);
}}
/>
);
}
return (
<DashboardDemoContent
title="MCP Services"
description="Manage your MCP services, configure APIs, and monitor service status"
title={t("MCP")}
description={t(
"Manage your MCP servers, configure APIs, and monitor server status"
)}
>
<div className="space-y-6 w-full">
{/* comming soon:Filters and Actions */}
<ServiceFiltersBar
filters={{
search: searchTerm,
status: statusFilter,
}}
onFiltersChange={(filters) => {
setSearchTerm(filters.search);
setStatusFilter(filters.status);
}}
onAddService={handleCreateService}
onImportOpenAPI={handleOpenAPIGenerate}
/>
{/* Filters and Actions */}
<div className="flex justify-between items-center gap-4">
<ServiceFiltersBar onAddService={handleCreateService} />
{/* 搜索框 - 右侧 */}
<Input
isClearable
className="w-full sm:max-w-[400px]"
placeholder={t('Search by service name')}
startContent={<Search className="w-4 h-4" />}
value={searchValue}
onClear={() => {
setSearchValue('');
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
setSearchTerm('');
}}
onValueChange={handleSearchChange}
/>
</div>
{/* Services Table */}
{/* Servers Table */}
<ServiceTable
services={services}
loading={loading}
@@ -229,28 +282,31 @@ export const MCPServicesManagement: React.FC = () => {
onDelete={handleDeleteService}
onToggleStatus={handleToggleStatus}
onPageChange={onPageChange}
onStatusFilterChange={handleStatusFilterChange}
/>
{/* Modals */}
{
isOpenAPIModalOpen && (
<OpenAPIGeneratorModal
isOpen={true}
onClose={handleCloseOpenAPIModal}
onGenerate={parseOpenAPIDocument}
onEditGenerated={handleEditGeneratedService}
/>
)
}
{isOpenAPIModalOpen && (
<OpenAPIGeneratorModal
isOpen={true}
onClose={handleCloseOpenAPIModal}
onGenerate={parseOpenAPIDocument}
onEditGenerated={handleEditGeneratedService}
serverType={addServiceType || "openapi"}
/>
)}
<DeleteConfirmModal
isOpen={isDeleteModalOpen}
onClose={handleCloseDeleteModal}
onConfirm={handleConfirmDelete}
title={t('Confirm Delete')}
description={t('Are you sure you want to delete this "{{name}}" service?', {
name: serviceToDelete?.name || "",
})}
title={t("Confirm Delete")}
description={t(
'Are you sure you want to delete this "{{name}}" server?',
{
name: serviceToDelete?.name || "",
}
)}
/>
</div>
</DashboardDemoContent>
@@ -1,50 +1,108 @@
"use client";
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect } from "react";
import { Button, Tabs, Tab, Spinner } from "@nextui-org/react";
import { ChevronLeftIcon } from "lucide-react";
import { useTranslation } from "@/shared/lib/useTranslation";
import {
Button,
Tabs,
Tab,
Spinner,
} from '@nextui-org/react';
import { ChevronLeftIcon } from 'lucide-react';
import { useTranslation } from '@/shared/lib/useTranslation';
import { AuthMethod, MCPServiceFormData } from '@/types/mcp-service';
AuthMethod,
EnabledEnum,
MCPServiceFormData,
} from "@/shared/types/mcp-service";
import { useMCPServiceDetail } from "@/hooks/useMCPServiceDetail";
import { BasicInfoTab } from './BasicInfoTab';
import { PricingTab } from './PricingTab';
import { DescriptionTab } from './DescriptionTab';
import { ToolsTab } from './ToolsTab';
import { OpenAPIGeneratorModal } from './OpenAPIGeneratorModal';
import { ChargeType } from '@/shared/types/marketplace';
import { BasicInfoTab } from "@/shared/components/mcp-services/BasicInfoTab";
import { PricingTab } from "@/shared/components/mcp-services/PricingTab";
import { DescriptionTab } from "@/shared/components/mcp-services/DescriptionTab";
import { ToolsTab } from "@/shared/components/mcp-services/ToolsTab";
import { OpenAPIGeneratorModal } from "@/shared/components/mcp-services/OpenAPIGeneratorModal";
import { ChargeType } from "@/shared/types/marketplace";
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
import ResourceGroup from "@/shared/components/mcp-services/ResourceGroup";
const _DefaultFormData: MCPServiceFormData = {
id: '',
name: '',
short_description: '',
long_description: '',
base_url: '',
id: "",
name: "",
short_description: "",
long_description: "",
base_url: "",
auth_method: AuthMethod.None,
auth_header: '',
auth_token: '',
auth_header: "",
auth_token: "",
charge_type: ChargeType.Free,
price: '',
price: "",
enabled: 0,
tags: [],
apis: []
}
apis: [],
};
// Helper function to validate URL
const isValidUrl = (url: string) => {
if (!url) return false;
try {
const parsed = new URL(url);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
};
// Helper function to validate domain format
const isValidDomain = (url: string) => {
if (!url) return false;
try {
const parsed = new URL(url);
const hostname = parsed.hostname;
const domainRegex = /^(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$/;
return domainRegex.test(hostname);
} catch {
return false;
}
};
const validateServiceForm = (data: MCPServiceFormData, t: any) => {
const errors: Record<string, string> = {};
if (!data.slug_name?.trim()) {
errors.slug_name = t("Server ID is required");
} else if (data.slug_name.length > 255) {
errors.slug_name = t("Server ID must be less than 255 characters");
}
if (!data.name?.trim()) {
errors.name = t("Server name is required");
} else if (data.name.length > 255) {
errors.name = t("Server Name must be less than 255 characters");
}
if (!data.base_url?.trim()) {
errors.base_url = t("API Endpoint is required");
} else if (!isValidUrl(data.base_url)) {
errors.base_url = t("API Endpoint must be a valid HTTP/HTTPS URL");
} else if (!isValidDomain(data.base_url)) {
errors.base_url = t("API Endpoint must contain a valid domain name");
}
if (!data.short_description?.trim()) {
errors.short_description = t("Short description is required");
}
return errors;
};
interface ServiceEditPageProps {
serviceId?: string;
onSave: (data: MCPServiceFormData) => void;
onSave: (data: MCPServiceFormData, isDraft?: boolean) => void;
onCancel: () => void;
loading?: boolean;
onUnpublish?: (serviceId: string) => void;
onRefreshList?: () => void;
}
export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
const BaseServiceEditPage: React.FC<ServiceEditPageProps> = ({
serviceId,
onSave,
onCancel,
loading = false
loading = false,
}) => {
const { t } = useTranslation();
const isEditing = !!serviceId;
@@ -54,19 +112,24 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
serviceDetail: service,
detailLoading: dataLoading,
getServiceDetail,
clearServiceDetail
clearServiceDetail,
parseOpenAPIDocumentForUpdate,
fetchMCPResourceGroups,
deleteResourceGroup,
addServiceToGroup,
updateLoading,
} = useMCPServiceDetail();
const [isSaving, setIsSaving] = useState(false);
const [isDraft, setIsDraft] = useState(false);
// use services list hook for OpenAPI update
const { parseOpenAPIDocumentForUpdate, updateLoading } = useMCPServiceDetail();
const [formData, setFormData] = useState<MCPServiceFormData>(_DefaultFormData);
const [newTag, setNewTag] = useState('');
const [formData, setFormData] =
useState<MCPServiceFormData>(_DefaultFormData);
const [newTag, setNewTag] = useState("");
// OpenAPI modal state
const [isOpenAPIModalOpen, setIsOpenAPIModalOpen] = useState(false);
// get service detail
// get server detail
useEffect(() => {
if (serviceId) {
getServiceDetail(serviceId);
@@ -80,42 +143,70 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
// when service data loaded, fill form
useEffect(() => {
if (!serviceId || !service) return
if (!serviceId || !service) return;
setFormData({
...formData,
...service
...service,
});
}, [service, serviceId]);
const handleInputChange = (field: keyof MCPServiceFormData, value: any) => {
setFormData(prev => ({
setFormData((prev) => ({
...prev,
[field]: value
[field]: value,
}));
};
const handleAddTag = () => {
if (newTag.trim() && !(formData.tags || []).includes(newTag.trim())) {
setFormData(prev => ({
setFormData((prev) => ({
...prev,
tags: [...(prev.tags || []), newTag.trim()]
tags: [...(prev.tags || []), newTag.trim()],
}));
setNewTag('');
setNewTag("");
}
};
const handleRemoveTag = (tagToRemove: string) => {
setFormData(prev => ({
setFormData((prev) => ({
...prev,
tags: (prev.tags || []).filter(tag => tag !== tagToRemove)
tags: (prev.tags || []).filter((tag) => tag !== tagToRemove),
}));
};
const handleSubmit = () => {
onSave(formData);
const handleSubmit = async (enabled?: EnabledEnum) => {
// Check if slug_name has been modified
const isSlugNameChanged =
isEditing &&
service?.slug_name &&
formData.slug_name !== service.slug_name;
if (isSlugNameChanged) {
const confirmed = window.confirm(
t(
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?"
)
);
if (!confirmed) {
return;
}
}
// Proceed with save
setIsSaving(true);
const isDraft =
service?.enabled === EnabledEnum.Offline && enabled === undefined;
setIsDraft(isDraft);
await onSave(
{
...formData,
headers: formData.headers?.filter((header) => header.name !== ""),
...(enabled !== undefined ? { enabled } : {}),
},
isDraft
);
setIsSaving(false);
setIsDraft(false);
};
// OpenAPI update handlers
@@ -127,19 +218,26 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
setIsOpenAPIModalOpen(false);
};
const handleOpenAPIGenerate = async (url?: string, file?: File): Promise<{ service_id: string }> => {
const handleOpenAPIGenerate = async (
url?: string,
file?: File
): Promise<{ service_id: string }> => {
if (!serviceId) {
throw new Error('Service ID is required for update');
throw new Error("Server ID is required for update");
}
try {
const updatedService = await parseOpenAPIDocumentForUpdate(serviceId, url, file);
const updatedService = await parseOpenAPIDocumentForUpdate(
serviceId,
url,
file
);
// update form data
setFormData({
...formData,
...updatedService,
update_type: 'openapi'
update_type: "openapi",
});
// close modal
@@ -148,24 +246,46 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
// return service_id format to compatible with OpenAPIGeneratorModal
return { service_id: updatedService.id };
} catch (error) {
console.error('OpenAPI update failed:', error);
console.error("OpenAPI update failed:", error);
throw error;
}
};
// Helper function to validate price string
const isValidPrice = (priceStr: string | undefined): boolean => {
if (!priceStr || priceStr.trim() === "") {
return false;
}
const numValue = parseFloat(priceStr);
return !isNaN(numValue) && numValue >= 0;
};
const validationErrors = validateServiceForm(formData, t);
const isFormValid = () => {
const hasBasicInfo = formData.name.trim() && formData.short_description?.trim();
if (Object.keys(validationErrors).length > 0) {
return false;
}
// if free, no need to validate price
if (formData.charge_type === ChargeType.Free) {
return hasBasicInfo;
return true;
}
// if PerCall, validate price
if (formData.charge_type === ChargeType.PerCall) {
return isValidPrice(formData.price);
}
// if PerToken, validate both input and output token prices
if (formData.charge_type === ChargeType.PerToken) {
return (
isValidPrice(formData.input_token_price) &&
isValidPrice(formData.output_token_price)
);
}
// if paid, need to validate price
return hasBasicInfo &&
formData.price !== undefined &&
formData.price.trim() !== '';
return formData.price !== undefined && formData.price.trim() !== "";
};
return (
@@ -173,16 +293,11 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
{/* page title */}
<div className="flex items-center justify-between mb-6 px-8">
<div className="flex items-center gap-3">
<Button
isIconOnly
onPress={onCancel}
variant='flat'
size='sm'
>
<Button isIconOnly onPress={onCancel} variant="flat" size="sm">
<ChevronLeftIcon className="w-5 h-5" />
</Button>
<h1 className="text-2xl font-bold">
{isEditing ? t('Service Detail') : t('Create New Service')}
{isEditing ? t("Server Detail") : t("Create New Server")}
</h1>
</div>
<div className="flex items-center gap-2">
@@ -192,20 +307,39 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
onPress={handleOpenAPIUpdate}
isDisabled={loading || dataLoading || updateLoading}
isLoading={updateLoading}
size='sm'
size="sm"
>
{t('Update from OpenAPI')}
{t("Update from OpenAPI")}
</Button>
)}
<Button
color="primary"
onPress={handleSubmit}
isDisabled={!isFormValid() || loading || dataLoading || updateLoading}
isLoading={updateLoading}
size='sm'
onPress={() => handleSubmit()}
isDisabled={
!isFormValid() || loading || dataLoading || updateLoading
}
isLoading={
isSaving && (isDraft || service?.enabled !== EnabledEnum.Offline)
}
size="sm"
>
{t('Save')}
{service?.enabled === EnabledEnum.Offline
? t("Save Draft")
: t("Save")}
</Button>
{service?.enabled === EnabledEnum.Offline && (
<Button
color="success"
onPress={() => handleSubmit(EnabledEnum.Online)}
isDisabled={
!isFormValid() || loading || dataLoading || updateLoading
}
isLoading={isSaving && !isDraft}
size="sm"
>
{t("Publish")}
</Button>
)}
</div>
</div>
@@ -214,7 +348,7 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
<div className="flex-1 flex items-center justify-center">
<div className="flex flex-col items-center gap-4">
<Spinner size="lg" />
<p className="text-gray-600">{t('Loading service data...')}</p>
<p className="text-gray-600">{t("Loading server data...")}</p>
</div>
</div>
)}
@@ -222,17 +356,17 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
{/* form content */}
{!dataLoading && (
<Tabs
aria-label="Service edit tabs"
variant='bordered'
color='primary'
aria-label="Server edit tabs"
variant="bordered"
color="primary"
classNames={{
panel: "flex-1 overflow-y-auto px-8"
panel: "flex-1 overflow-y-auto px-8",
}}
className=' px-8'
className=" px-8"
>
<Tab key="basic" title={t('Basic Information')}>
<Tab key="basic" title={t("Basic Information")}>
<div className="pt-2 flex gap-4">
<div className='flex-1'>
<div className="flex-1">
<BasicInfoTab
formData={formData}
newTag={newTag}
@@ -240,9 +374,10 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
onInputChange={handleInputChange}
onAddTag={handleAddTag}
onRemoveTag={handleRemoveTag}
errors={validationErrors}
/>
</div>
<div className='w-[400px] max-w-[1/2]'>
<div className="w-[400px] max-w-[1/2]">
<PricingTab
formData={formData}
onInputChange={handleInputChange}
@@ -251,16 +386,13 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
</div>
</Tab>
<Tab key="tools" title={t('Tools Management')}>
<Tab key="tools" title={t("Tools Management")}>
<div className="pt-2">
<ToolsTab
formData={formData}
onInputChange={handleInputChange}
/>
<ToolsTab formData={formData} onInputChange={handleInputChange} />
</div>
</Tab>
<Tab key="description" title={t('Detailed Description')} >
<Tab key="description" title={t("Detailed Description")}>
<div className="pt-2 h-full">
<DescriptionTab
formData={formData}
@@ -268,20 +400,32 @@ export const ServiceEditPage: React.FC<ServiceEditPageProps> = ({
/>
</div>
</Tab>
<Tab key="ResourceGroups" title={t("Resource Groups")}>
<div className="pt-2 h-full">
<ResourceGroup
formData={formData}
deleteResourceGroup={deleteResourceGroup}
fetchMCPResourceGroups={fetchMCPResourceGroups}
addServiceToGroup={addServiceToGroup}
/>
</div>
</Tab>
</Tabs>
)}
{/* OpenAPI Generator Modal */}
{
isOpenAPIModalOpen && (
<OpenAPIGeneratorModal
isOpen={true}
onClose={handleCloseOpenAPIModal}
onGenerate={handleOpenAPIGenerate}
mode="update"
/>
)
}
{isOpenAPIModalOpen && (
<OpenAPIGeneratorModal
isOpen={true}
onClose={handleCloseOpenAPIModal}
onGenerate={handleOpenAPIGenerate}
mode="update"
/>
)}
</div>
);
};
};
export const ServiceEditPage = withComponentInjection(
"components/mcp-services/ServiceEditPage",
BaseServiceEditPage
);
@@ -1,80 +0,0 @@
"use client";
import React from "react";
import { Input, Select, SelectItem, Button } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ServiceFilters } from "@/types/mcp-service";
import { Search, Plus } from "lucide-react";
interface ServiceFiltersBarProps {
filters: ServiceFilters;
onFiltersChange: (filters: ServiceFilters) => void;
onAddService: () => void;
onImportOpenAPI?: () => void;
}
export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
filters,
onFiltersChange,
onImportOpenAPI,
}) => {
const { t } = useTranslation();
const handleSearchChange = (value: string) => {
onFiltersChange({ ...filters, search: value });
};
const handleStatusChange = (value: string) => {
onFiltersChange({ ...filters, status: value });
};
return (
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<Button
color="primary"
onPress={onImportOpenAPI}
startContent={<Plus size={16} />}
size="sm"
>
{t("Add Service")}
</Button>
{/* <Input
placeholder={t('Search services...')}
value={filters.search}
onValueChange={handleSearchChange}
startContent={<Search className="w-4 h-4 text-gray-400" />}
classNames={{
input: "text-sm",
inputWrapper: "h-10"
}}
/> */}
</div>
<div className="flex gap-2">
{/* <Select
placeholder={t('Filter by status')}
selectedKeys={filters.status ? [filters.status] : []}
onSelectionChange={(keys) => {
const value = Array.from(keys)[0] as string;
handleStatusChange(value || '');
}}
className="w-40"
classNames={{
trigger: "h-10"
}}
>
{[
{ key: "all", label: t('All Status') },
{ key: "enabled", label: t('Online') },
{ key: "disabled", label: t('Offline') }
].map((item) => (
<SelectItem key={item.key} value={item.key}>
{item.label}
</SelectItem>
))}
</Select> */}
</div>
</div>
);
};
@@ -1,77 +0,0 @@
"use client";
import React, { useCallback } from 'react';
import {
Input,
Table,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
} from '@nextui-org/react';
import { useTranslation } from '@/shared/lib/useTranslation';
import { MCPServiceAPIItem, MCPServiceFormData } from '@/types/mcp-service';
interface ToolsTabProps {
formData: MCPServiceFormData;
onInputChange: (field: keyof MCPServiceFormData, value: any) => void;
}
export const ToolsTab: React.FC<ToolsTabProps> = ({
formData,
onInputChange
}) => {
const { t } = useTranslation();
const handleToolChange = useCallback((index: number, field: keyof MCPServiceAPIItem, value: string) => {
onInputChange('apis', (formData.apis || []).map((api, i) =>
i === index ? { ...api, [field]: value } : api
));
}, [formData.apis, onInputChange]);
return (
<div className="space-y-4">
<Table
aria-label="APIs table"
removeWrapper
>
<TableHeader>
<TableColumn className='w-1/4'>{t('Tool Name')}</TableColumn>
<TableColumn className='w-1/4'>{t('Tool URL')}</TableColumn>
<TableColumn>{t('Description')}</TableColumn>
</TableHeader>
<TableBody emptyContent={t('No tools added yet. Add your first tool using the input above.')}>
{(formData.apis || []).map((tool, index) => (
<TableRow
key={`tool-${index}`}
>
<TableCell>
<Input
value={tool.name}
size="sm"
isDisabled
/>
</TableCell>
<TableCell>
<Input
value={tool.url}
size="sm"
isDisabled
/>
</TableCell>
<TableCell>
<Input
value={tool.description || ''}
onChange={(e) => handleToolChange(index, 'description', e.target.value)}
size="sm"
/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
};
@@ -18,6 +18,7 @@ interface StripeConfigFormProps {
onEnable: (channelId: string) => Promise<boolean>;
onDisable: (channelId: string) => Promise<boolean>;
isLoading?: boolean;
labelPlacement?: "outside" | "inside";
}
export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
@@ -26,6 +27,7 @@ export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
onEnable,
onDisable,
isLoading = false,
labelPlacement = "inside",
}) => {
const { t } = useTranslation();
const [formData, setFormData] = useState<StripeConfig>(config);
@@ -64,8 +66,117 @@ export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
onSave(formData);
};
const isFormValid =
formData.secret.trim() !== "" && formData.webhook_secret.trim() !== "";
const isFormValid =
formData?.secret?.trim() !== "" && formData?.webhook_secret?.trim() !== "";
const panelContent = () => {
return (
<>
<div
className={`flex flex-col gap-4 ${formData.is_enabled ? "" : "hidden"}`}
>
{/* Secret Key */}
<Input
label={t("Secret Key")}
placeholder={t("Enter Secret Key")}
description={t("Stripe secret key for server-side API calls")}
value={formData.secret}
onChange={(e) => handleInputChange("secret", e.target.value)}
type={showSecretKey ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowSecretKey(!showSecretKey)}
className="focus:outline-none"
>
{showSecretKey ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
isRequired
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
{/* Webhook Secret (Optional) */}
<Input
label={t("Webhook Secret")}
placeholder={t("Enter Webhook Secret")}
description={t(
"Webhook signing secret for verifying Stripe events"
)}
value={formData.webhook_secret || ""}
onChange={(e) =>
handleInputChange("webhook_secret", e.target.value)
}
type={showWebhookSecret ? "text" : "password"}
isRequired
endContent={
<button
type="button"
onClick={() => setShowWebhookSecret(!showWebhookSecret)}
className="focus:outline-none"
>
{showWebhookSecret ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
autoComplete="off"
isDisabled={!formData.is_enabled}
labelPlacement="outside"
/>
</div>
{/* Action Buttons */}
{formData.is_enabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
isDisabled={!isFormValid}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
</>
);
};
if (labelPlacement === "outside") {
return (
<div className="flex flex-col gap-4">
{/* Enable/Disable Toggle */}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Enable Stripe Payment")}
</span>
<span className="text-xs text-gray-500">
{t("Toggle to enable or disable Stripe payment interface")}
</span>
</div>
<Switch
isSelected={formData.is_enabled || false}
onValueChange={handleEnableDisable}
color="primary"
size="sm"
/>
</div>
{panelContent()}
</div>
);
}
return (
<Accordion
@@ -98,79 +209,7 @@ export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
</div>
}
>
<div className="space-y-4">
{/* Secret Key */}
<Input
label={t("Secret Key")}
placeholder="sk_test_... or sk_live_..."
description={t("Stripe secret key for server-side API calls")}
value={formData.secret}
onChange={(e) => handleInputChange("secret", e.target.value)}
type={showSecretKey ? "text" : "password"}
endContent={
<button
type="button"
onClick={() => setShowSecretKey(!showSecretKey)}
className="focus:outline-none"
>
{showSecretKey ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
isRequired
autoComplete="off"
isDisabled={!formData.is_enabled}
/>
{/* Webhook Secret (Optional) */}
<Input
label={t("Webhook Secret")}
placeholder="whsec_..."
description={t(
"Webhook signing secret for verifying Stripe events"
)}
value={formData.webhook_secret || ""}
onChange={(e) =>
handleInputChange("webhook_secret", e.target.value)
}
type={showWebhookSecret ? "text" : "password"}
isRequired
endContent={
<button
type="button"
onClick={() => setShowWebhookSecret(!showWebhookSecret)}
className="focus:outline-none"
>
{showWebhookSecret ? (
<EyeOff className="w-4 h-4 text-gray-400" />
) : (
<Eye className="w-4 h-4 text-gray-400" />
)}
</button>
}
autoComplete="off"
isDisabled={!formData.is_enabled}
/>
</div>
{/* Action Buttons */}
{formData.is_enabled && (
<div className="flex gap-3 py-4">
<Button
color="primary"
variant="solid"
onPress={handleSave}
isLoading={isLoading}
isDisabled={!isFormValid}
size="sm"
>
{t("Save")}
</Button>
</div>
)}
{panelContent()}
</AccordionItem>
</Accordion>
);
@@ -0,0 +1,175 @@
import {
Button,
Modal,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
Table,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
Chip,
Spinner,
} from "@nextui-org/react";
import { useState, useEffect, useCallback } from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ChargeType } from "@/shared/types/marketplace";
import { fetchSimpleMcpServices } from "@/api/resourceGroup.api";
import { Price } from "@/shared/components/marketplace/Price";
interface AddMcpServerModalProps {
isOpen: boolean;
onClose: () => void;
onSaveMcpServer: (serverIds: string[]) => Promise<void>;
id: string;
}
export interface SimpleMcpService {
id: string;
name: string;
base_url: string;
charge_type: ChargeType;
price: string;
enabled: boolean;
input_token_price?: string;
output_token_price?: string;
}
export const AddMcpServerModal: React.FC<AddMcpServerModalProps> = ({
isOpen,
onClose,
onSaveMcpServer,
id,
}) => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const [loading, setLoading] = useState(false);
const [services, setServices] = useState<SimpleMcpService[]>([]);
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
// 加载服务列表
const loadServices = useCallback(async (id: string) => {
setLoading(true);
try {
const response = await fetchSimpleMcpServices(id);
setServices(response);
} catch (error) {
console.error("Failed to load MCP services:", error);
} finally {
setLoading(false);
}
}, []);
// 当模态框打开时加载数据
useEffect(() => {
if (isOpen) {
setSelectedKeys(new Set());
loadServices(id);
}
}, [isOpen, loadServices]);
// 处理保存
const handleSave = async () => {
const serverIds = typeof selectedKeys === 'string' && selectedKeys === 'all' ? services.map((service) => service.id) : Array.from(selectedKeys);
if (serverIds.length === 0) {
return;
}
setIsLoading(true);
try {
await onSaveMcpServer(serverIds);
onClose();
} finally {
setIsLoading(false);
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="5xl" scrollBehavior="inside">
<ModalContent>
{() => (
<>
<ModalHeader className="flex flex-col gap-1">
{t("Add MCP Server")}
</ModalHeader>
<ModalBody>
<Table
aria-label="MCP services selection table"
selectionMode="multiple"
selectedKeys={selectedKeys}
onSelectionChange={(keys) => setSelectedKeys(keys as Set<string>)}
removeWrapper
classNames={{
wrapper: "min-h-[400px]",
}}
>
<TableHeader>
<TableColumn>{t("Service Name")}</TableColumn>
<TableColumn>{t("API Endpoint")}</TableColumn>
<TableColumn>{t("Status")}</TableColumn>
<TableColumn>{t("Pricing")}</TableColumn>
</TableHeader>
<TableBody
items={services}
isLoading={loading}
loadingContent={<Spinner />}
emptyContent={t("No MCP services available")}
>
{(service) => (
<TableRow key={service.id}>
<TableCell>
<span className="text-sm">{service.name}</span>
</TableCell>
<TableCell>
<span className="text-sm">{service.base_url}</span>
</TableCell>
<TableCell>
<Chip
className="capitalize"
color={service.enabled ? "success" : "danger"}
size="sm"
variant="flat"
>
{t(service.enabled ? "Published" : "Unpublished")}
</Chip>
</TableCell>
<TableCell>
<Price
price={service.price}
charge_type={service.charge_type}
input_token_price={service.input_token_price}
output_token_price={service.output_token_price}
/>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</ModalBody>
<ModalFooter>
<Button
color="danger"
variant="light"
onPress={onClose}
isDisabled={isLoading}
>
{t("Close")}
</Button>
<Button
color="primary"
onPress={handleSave}
isLoading={isLoading}
isDisabled={selectedKeys.size === 0}
>
{t("Add")}
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
);
};
@@ -0,0 +1,105 @@
import { Button, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Switch } from "@nextui-org/react"
import { useState, useEffect } from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface AddServerModalProps {
isOpen: boolean;
onClose: () => void;
name: string;
id: string;
onSaveServer: (name: string, isDefault: boolean) => Promise<void>;
type: "add" | "edit";
isDefault: boolean;
}
export const AddServerModal: React.FC<AddServerModalProps> = ({
isOpen,
onClose,
name,
id,
onSaveServer,
type,
isDefault,
}) => {
const { t } = useTranslation();
const [serverName, setServerName] = useState(name);
const [isEnabledState, setIsEnabledState] = useState(isDefault);
const [isLoading, setIsLoading] = useState(false);
// 当 name prop 或 isOpen 变化时,更新内部状态
useEffect(() => {
if (isOpen) {
setServerName(name);
setIsEnabledState(isDefault);
setIsLoading(false); // 重置 loading 状态
}
}, [name, isOpen, isDefault]);
// 处理保存
const handleSave = async () => {
setIsLoading(true);
try {
await onSaveServer(serverName, isEnabledState);
} finally {
setIsLoading(false);
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="2xl">
<ModalContent>
{() => (
<>
<ModalHeader className="flex flex-col gap-1">
{type === "add" ? t("Create New Resource Group") : t("Edit Resource Group")}
</ModalHeader>
<ModalBody>
{
!['allow-all', 'deny-all'].includes(id) && <>
<Input
label={t("Resource Group Name")}
value={serverName}
placeholder={t("Edit Resource Group Name")}
onChange={(e) => setServerName(e.target.value)}
maxLength={255}
/>
</>
}
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">
{t("Set as default")}
</span>
<span className="text-xs text-gray-500">
{t("Automatically bind default resource groups when adding users")}
</span>
</div>
<Switch
isSelected={isEnabledState || false}
onValueChange={setIsEnabledState}
color="primary"
size="sm"
/>
</div>
</ModalBody>
<ModalFooter>
<Button
color="danger"
variant="light"
onPress={onClose}
isDisabled={isLoading}
>
{t("Cancel")}
</Button>
<Button
color="primary"
onPress={handleSave}
isLoading={isLoading}
>
{t("Save")}
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
)
}
@@ -0,0 +1,94 @@
"use client";
import React, { useState } from "react";
import {
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Alert,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface DeleteServerModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void | Promise<void>;
title?: string | React.ReactNode;
description?: string | React.ReactNode;
alertDescription?: string;
customAlertContent?: React.ReactNode;
}
export const DeleteServerModal: React.FC<DeleteServerModalProps> = ({
isOpen,
onClose,
onConfirm,
title,
description,
alertDescription,
customAlertContent,
}) => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const handleConfirm = async () => {
setIsLoading(true);
try {
await onConfirm();
} finally {
setIsLoading(false);
}
};
const defaultTitle = t("Confirm Delete");
const defaultDescription = t("Are you sure you want to delete this item? This action cannot be undone.");
const defaultAlertDescription= t("This action cannot be undone.");
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalContent>
{() => (
<>
<ModalHeader className="flex flex-col gap-1">
{title || defaultTitle}
</ModalHeader>
<ModalBody>
<div className="space-y-4">
{/* Description */}
<div className="text-default-600">
{description || defaultDescription}
</div>
{/* Warning message */}
<Alert title={alertDescription || defaultAlertDescription} color="danger" classNames={{mainWrapper: "w-[calc(100%-60px)]"}}>
{customAlertContent && customAlertContent}
</Alert>
</div>
</ModalBody>
<ModalFooter>
<Button
color="default"
variant="light"
onPress={onClose}
isDisabled={isLoading}
>
{t("Cancel")}
</Button>
<Button
color="danger"
onPress={handleConfirm}
isLoading={isLoading}
>
{t("Remove")}
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal >
);
};
export default DeleteServerModal;
@@ -0,0 +1,162 @@
"use client";
import React, { useRef, useCallback, useEffect } from "react";
import { Button, Card, CardBody, CardHeader, Chip, Divider, Listbox, ListboxItem, Spinner } from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Plus } from "lucide-react";
// 资源组类型定义
export interface ResourceGroup {
id: string;
name: string;
description?: string;
isDefault?: boolean;
serviceCount?: number;
createdAt?: string;
}
interface GroupListProps {
groups: ResourceGroup[];
selectedGroup: ResourceGroup | null;
onSelectGroup: (group: ResourceGroup) => void;
onCreateGroup: () => void;
onLoadMore?: () => void;
hasMore?: boolean;
loading?: boolean;
shouldScrollToTop?: boolean;
onScrolledToTop?: () => void;
}
const GroupList: React.FC<GroupListProps> = ({
groups,
selectedGroup,
onSelectGroup,
onCreateGroup,
onLoadMore,
hasMore = false,
loading = false,
shouldScrollToTop = false,
onScrolledToTop,
}) => {
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement>(null);
const observerRef = useRef<IntersectionObserver | null>(null);
const loadMoreTriggerRef = useRef<HTMLDivElement>(null);
const hasLoadedMoreRef = useRef(false);
// 使用 IntersectionObserver 监听滚动到底部
const handleObserver = useCallback(
(entries: IntersectionObserverEntry[]) => {
const [target] = entries;
if (target.isIntersecting && hasMore && !loading && onLoadMore) {
hasLoadedMoreRef.current = true; // 标记已触发过加载更多
onLoadMore();
}
},
[hasMore, loading, onLoadMore]
);
useEffect(() => {
const element = loadMoreTriggerRef.current;
if (!element || !onLoadMore) return;
// 创建 IntersectionObserver
observerRef.current = new IntersectionObserver(handleObserver, {
root: scrollRef.current,
rootMargin: "100px", // 提前 100px 触发加载
threshold: 0.1,
});
observerRef.current.observe(element);
return () => {
if (observerRef.current && element) {
observerRef.current.unobserve(element);
}
};
}, [handleObserver, onLoadMore]);
// 监听 shouldScrollToTop 变化,滚动到顶部
useEffect(() => {
if (shouldScrollToTop && scrollRef.current) {
scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' });
// 通知父组件已完成滚动
onScrolledToTop?.();
}
}, [shouldScrollToTop, onScrolledToTop]);
return (
<div className="min-w-[300px] w-[300px] bg-default-100/50 h-full">
<Card shadow="none"
radius="none"
className="bg-transparent flex flex-col h-full">
<CardHeader className="flex justify-between items-center px-6 py-4">
<h2 className="text-xl font-semibold text-gray-900">{t("Group List")}</h2>
<Button
size="sm"
color="primary"
startContent={<Plus size={16} />}
onPress={onCreateGroup}
>
{t("New")}
</Button>
</CardHeader>
<Divider />
<CardBody className="flex-grow p-0">
<div ref={scrollRef} className="overflow-y-auto h-full px-4 py-4">
<Listbox
aria-label="Group list"
items={groups || []}
emptyContent={loading ? <></> : <div className="flex items-center justify-center h-full">{t("No groups found")}</div>}
selectionMode="single"
selectedKeys={selectedGroup ? [selectedGroup.id] : []}
onSelectionChange={(keys) => {
const selectedId = Array.from(keys)[0];
const selectedKey = (groups || []).find(
(k) => k.id === selectedId
);
if (selectedKey) onSelectGroup(selectedKey);
}}
itemClasses={{
title: "text-md font-medium",
base: "bg-white p-6 transition-colors border-1 data-[selected=true]:focus:bg-primary-50 data-[selected=true]:data-[hover=true]:bg-primary-50 data-[selected=true]:border-primary-500 data-[selected=true]:bg-primary-50 data-[hover=true]:bg-default/50 data-[selectable=true]:focus:bg-default/50 [&>span]:w-full",
}}
classNames={{
list: "gap-4",
}}
hideSelectedIcon
>
{(group) => (
<ListboxItem key={group.id} textValue={group.name}>
<div className="flex items-center gap-2 w-full overflow-hidden">
<span className="truncate flex-1 min-w-0">{group.name}</span>
{group.isDefault && (
<Chip size="sm" color="warning" variant="flat" className="shrink-0 ml-auto">
{t("Default")}
</Chip>
)}
</div>
</ListboxItem>
)}
</Listbox>
{/* 加载更多触发器 */}
{onLoadMore && (
<div ref={loadMoreTriggerRef} className="py-4 flex justify-center">
{loading && hasMore && (
<Spinner size="sm" color="primary" />
)}
{!hasMore && groups.length > 0 && hasLoadedMoreRef.current && (
<p className="text-sm text-default-400">{t("No more groups")}</p>
)}
</div>
)}
</div>
</CardBody>
</Card>
</div>
);
};
export default GroupList;
@@ -0,0 +1,252 @@
"use client";
import React, { useEffect, useState, useMemo } from "react";
import {
Button,
Card,
Chip,
Table,
TableHeader,
TableColumn,
TableBody,
TableRow,
TableCell,
Tooltip,
Spinner,
Divider,
CardHeader,
CardBody,
Pagination,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Plus, Trash2, Edit2 } from "lucide-react";
import { Price } from "@/shared/components/marketplace/Price";
import { ChargeType } from "@/shared/types/marketplace";
import { fetchResourceGroupDetail, ResourceGroupDetailResponse } from "@/api/resourceGroup.api";
import { useSearchParams } from "next/navigation";
// 组内服务类型定义
export interface GroupService {
id: string;
name: string;
base_url: string;
charge_type: ChargeType;
price: string;
enabled: boolean;
slug_name?: string;
input_token_price?: string;
output_token_price?: string;
}
interface GroupServiceTableProps {
groupId?: string; // 可选,因为可能从 URL 获取
services: GroupService[];
loading?: boolean;
pagination: {
page: number;
pageSize: number;
total: number;
};
onPageChange: (page: number) => void;
onAddService: () => void;
onRemoveService: (serviceId: string) => void;
onEditGroup: (groupId: string) => void;
onDeleteGroup: (groupId: string) => void;
refreshTrigger?: number; // 用于触发刷新
}
const GroupServiceTable: React.FC<GroupServiceTableProps> = ({
groupId: propGroupId,
services,
loading = false,
pagination,
onPageChange,
onAddService,
onRemoveService,
onEditGroup,
onDeleteGroup,
refreshTrigger,
}) => {
const { t } = useTranslation();
const searchParams = useSearchParams();
const pages = Math.ceil(pagination.total / pagination.pageSize);
const currentPage = pagination.page;
const [resourceGroupDetail, setResourceGroupDetail] = useState<ResourceGroupDetailResponse | null>(null);
// 优先使用 props 传入的 groupId,如果没有则从 URL 参数获取
const urlGroupId = searchParams.get('groupId');
const currentGroupId = propGroupId || urlGroupId || null;
// 使用 useMemo 计算 showOptions,确保响应式更新
const showOptions = useMemo(() => {
if (!resourceGroupDetail) return false;
return !['allow-all', 'deny-all'].includes(resourceGroupDetail.id);
}, [resourceGroupDetail]);
const getResourceGroup = async (groupId: string) => {
const response = await fetchResourceGroupDetail(groupId);
if (response) {
setResourceGroupDetail(response);
}
}
useEffect(() => {
if (currentGroupId) {
getResourceGroup(currentGroupId);
}
}, [currentGroupId, refreshTrigger]); // 当 refreshTrigger 变化时也会刷新
return (
<>
<Card className="flex-1" radius="none" shadow="sm">
<CardHeader className="px-6 py-4">
<div className="flex justify-between items-center w-full">
<h2 className="text-xl font-semibold text-gray-900 truncate" title={resourceGroupDetail?.name}>
{resourceGroupDetail?.name}
</h2>
<div className="flex gap-2 h-[32px]">
{currentGroupId && <>
<Button
isIconOnly
size="sm"
variant="bordered"
onPress={() => onEditGroup(currentGroupId)}
>
<Edit2 size={18} />
</Button></>
}
{showOptions && currentGroupId && <>
<Button
isIconOnly
size="sm"
variant="bordered"
color="danger"
onPress={() => onDeleteGroup(currentGroupId)}
>
<Trash2 size={18} />
</Button></>
}
</div>
</div>
</CardHeader>
<Divider />
<CardBody className="px-6 py-6">
{
showOptions && (<>
<div className="flex flex-col sm:flex-row gap-4 mb-6">
<div className="flex-1">
<Button
color="primary"
onPress={onAddService}
startContent={<Plus size={16} />}
size="sm"
>
{t("Add Server")}
</Button>
</div>
<div className="flex gap-2"></div>
</div>
</>)
}
<Table
key={`table-${showOptions}`}
aria-label="Group services table"
removeWrapper
classNames={{
wrapper: "min-h-[400px]",
}}
bottomContent={
pages > 1 ? (
<div className="flex w-full justify-center">
<Pagination
showControls
variant="light"
color="primary"
page={currentPage}
total={pages}
onChange={onPageChange}
/>
</div>
) : null
}
>
<TableHeader>
<TableColumn>{t("Service Name")}</TableColumn>
<TableColumn>{t("API Endpoint")}</TableColumn>
<TableColumn>{t("Status")}</TableColumn>
<TableColumn>{t("Pricing")}</TableColumn>
<TableColumn className={showOptions ? "w-20" : "hidden"}>{t("Actions")}</TableColumn>
</TableHeader>
<TableBody
items={services}
isLoading={loading}
loadingContent={<Spinner />}
emptyContent={t("No services in this group")}
>
{(service) => {
// 在渲染函数内部使用 showOptions,确保使用最新值
const cellClassName = showOptions ? "" : "hidden";
return (
<TableRow key={service.id}>
<TableCell>
<span className="text-sm">{service.name}</span>
</TableCell>
<TableCell>
<span className="text-sm">{service.base_url}</span>
</TableCell>
<TableCell>
<Chip
className="capitalize"
color={service.enabled ? "success" : "danger"}
size="sm"
variant="flat"
>
{t(service.enabled ? "Published" : "Unpublished")}
</Chip>
</TableCell>
<TableCell>
<div className="flex flex-col gap-1">
<Price
price={service.price}
charge_type={service.charge_type}
input_token_price={service.input_token_price}
output_token_price={service.output_token_price}
/>
</div>
</TableCell>
<TableCell className={cellClassName}>
<Tooltip
content={t("Remove")}
color="danger"
closeDelay={0}
disableAnimation
>
<Button
isIconOnly
size="sm"
variant="light"
color="danger"
onPress={() => onRemoveService(service.id)}
>
<Trash2 className="w-4 h-4" />
</Button>
</Tooltip>
</TableCell>
</TableRow>
);
}}
</TableBody>
</Table>
</CardBody>
</Card>
</>
);
};
export default GroupServiceTable;
@@ -0,0 +1,354 @@
"use client";
import React, { useState, useEffect } from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import GroupList, { ResourceGroup } from "./GroupList";
import GroupServiceTable, { GroupService } from "./GroupServiceTable";
import { AddServerModal } from "./AddServerModal";
import { DeleteServerModal } from "./DeleteServerModal";
import { Divider, Select, SelectItem } from "@nextui-org/react";
import { useResourceGroups } from "@/hooks/useResourceGroups";
import { AddMcpServerModal } from "./AddMcpServerModal";
import toast from "react-hot-toast";
const ResourceGroupManagement: React.FC = () => {
const { t } = useTranslation();
// 使用自定义 Hook 管理资源组
const {
groups,
simpleResourceGroups,
loadSimpleResourceGroups,
groupServices,
serviceTablePagination,
serviceTableParams,
loading,
servicesLoading,
hasMore,
shouldScrollToTop,
setShouldScrollToTop,
loadGroupServices,
loadMoreGroups,
handleServicePageChange,
handleAddServiceToGroup,
handleCreateGroup: createGroup,
handleUpdateGroup: updateGroup,
handleDeleteGroup: deleteGroup,
handleRemoveService: removeService,
} = useResourceGroups();
// 当前选中的资源组
const [selectedGroup, setSelectedGroup] = useState<ResourceGroup | null>(null);
// 删除组确认模态框
const [isDeleteGroupModalOpen, setIsDeleteGroupModalOpen] = useState(false);
const [groupToDelete, setGroupToDelete] = useState<ResourceGroup | null>(null);
const [transferToGroupId, setTransferToGroupId] = useState<string | null>(null);
const [simpleResourceGroupsLoading, setSimpleResourceGroupsLoading] = useState(false);
// 删除服务确认模态框
const [isDeleteServiceModalOpen, setIsDeleteServiceModalOpen] = useState(false);
const [serviceToDelete, setServiceToDelete] = useState<GroupService | null>(null);
// 创建/编辑组模态框
const [isGroupModalOpen, setIsGroupModalOpen] = useState(false);
const [editingGroup, setEditingGroup] = useState<ResourceGroup | null>(null);
// 添加 MCP 服务模态框
const [isAddMcpServerModalOpen, setIsAddMcpServerModalOpen] = useState(false);
// 刷新触发器,用于触发 GroupServiceTable 刷新
const [refreshTrigger, setRefreshTrigger] = useState(0);
const [newGroupId, setNewGroupId] = useState<string | null>(null);
/**
* 保存 MCP 服务
* @param serverIds 服务ID列表
* @returns 是否保存成功
*/
const handleSaveMcpServer = async (serverIds: string[]) => {
if (!selectedGroup) return;
const success = await handleAddServiceToGroup(selectedGroup.id, serverIds);
if (success) {
setIsAddMcpServerModalOpen(false);
await loadGroupServices(selectedGroup.id, 1, serviceTableParams.current.pageSize, serviceTableParams.current.keyword);
}
};
// 初始化选中第一个组,或在滚动到顶部时选中第一个
useEffect(() => {
if (groups.length > 0 && (shouldScrollToTop || !selectedGroup)) {
const index = shouldScrollToTop && newGroupId ? groups.findIndex((group) => group.id === newGroupId) : 0;
setSelectedGroup(groups[index]);
loadGroupServices(groups[index].id);
}
}, [groups, selectedGroup, loadGroupServices, shouldScrollToTop]);
// 选择组
const handleSelectGroup = (group: ResourceGroup) => {
setSelectedGroup(group);
loadGroupServices(group.id);
};
// 创建新组
const handleCreateGroup = () => {
setEditingGroup(null);
setIsGroupModalOpen(true);
};
// 保存组(创建或编辑)
const handleSaveGroup = async (name: string, isDefault: boolean) => {
// 去除首尾空格
const trimmedName = name.trim();
let success = false;
if (editingGroup) {
// 编辑现有组
success = await updateGroup(editingGroup.id, trimmedName, isDefault);
if (success && selectedGroup?.id === editingGroup.id) {
setSelectedGroup({ ...selectedGroup, name: trimmedName, isDefault });
// 触发 GroupServiceTable 刷新
setRefreshTrigger(prev => prev + 1);
}
} else {
// 创建新组
const newGroupId = await createGroup(trimmedName, isDefault);
success = !!newGroupId;
if (newGroupId) {
setNewGroupId(newGroupId);
}
}
if (success) {
setIsGroupModalOpen(false);
setEditingGroup(null);
}
};
// 编辑组
const handleEditGroup = (groupId: string) => {
const group = groups.find((g) => g.id === groupId);
if (group) {
setEditingGroup(group);
setIsGroupModalOpen(true);
}
};
// 删除组
const handleDeleteGroup = async (groupId: string) => {
const group = groups.find((g) => g.id === groupId);
if (group) {
setSimpleResourceGroupsLoading(true);
const simpleResourceGroups = await loadSimpleResourceGroups();
setTransferToGroupId(simpleResourceGroups.filter((group) => group.id !== groupId)[0].id);
setSimpleResourceGroupsLoading(false);
setGroupToDelete(group);
setIsDeleteGroupModalOpen(true);
}
};
// 确认删除组
const handleConfirmDeleteGroup = async () => {
if (groupToDelete && transferToGroupId) {
// 在删除前找到要选中的目标组
let targetGroup: ResourceGroup | null = null;
if (selectedGroup?.id === groupToDelete.id) {
const currentIndex = groups.findIndex((g) => g.id === groupToDelete.id);
if (currentIndex !== -1) {
// 优先选择上一个,如果没有上一个则选择下一个
if (currentIndex > 0) {
targetGroup = groups[currentIndex - 1];
} else if (currentIndex < groups.length - 1) {
targetGroup = groups[currentIndex + 1];
}
// 如果既没有上一个也没有下一个(只有一个元素),targetGroup 保持为 null
}
}
const success = await deleteGroup(groupToDelete.id, transferToGroupId);
if (success) {
// 等待列表刷新后选中目标组
setTimeout(() => {
if (groups.length === 0) {
// 删除后没有任何资源组了
setSelectedGroup(null);
} else if (targetGroup) {
// 在新列表中找到目标组(因为列表已经刷新了)
const newTarget = groups.find((g) => g.id === targetGroup.id);
if (newTarget) {
setSelectedGroup(newTarget);
loadGroupServices(newTarget.id);
} else {
// 如果目标组不存在了,选择第一个
setSelectedGroup(groups[0]);
loadGroupServices(groups[0].id);
}
} else if (selectedGroup?.id === groupToDelete.id) {
// 如果删除的是当前选中的组,且没有找到目标组(理论上不应该发生)
setSelectedGroup(groups[0]);
loadGroupServices(groups[0].id);
}
// 如果删除的不是当前选中的组,保持原有选中状态
}, 200);
setIsDeleteGroupModalOpen(false);
setGroupToDelete(null);
setTransferToGroupId(null);
}
}
};
// 添加服务到组
const handleAddService = () => {
setIsAddMcpServerModalOpen(true);
};
// 从组中移除服务
const handleRemoveService = (serviceId: string) => {
const service = groupServices.find((s) => s.id === serviceId);
if (service) {
setServiceToDelete(service);
setIsDeleteServiceModalOpen(true);
}
};
// 确认删除服务
const handleConfirmDeleteService = async () => {
if (serviceToDelete && selectedGroup) {
const success = await removeService(selectedGroup.id, serviceToDelete.id);
if (success) {
setIsDeleteServiceModalOpen(false);
setServiceToDelete(null);
await loadGroupServices(selectedGroup.id, 1, serviceTableParams.current.pageSize, serviceTableParams.current.keyword);
}
}
};
return (
<DashboardDemoContent
title={t("Resource Group")}
description={t("Manage your resource group. Each user has a resource group and can only access resources within their resource group")}
>
<div className="flex border-1 border-gray-200 rounded-lg items-stretch overflow-hidden h-full">
{/* 左侧组列表 */}
<GroupList
groups={groups}
selectedGroup={selectedGroup}
onSelectGroup={handleSelectGroup}
onCreateGroup={handleCreateGroup}
onLoadMore={loadMoreGroups}
hasMore={hasMore}
loading={loading}
shouldScrollToTop={shouldScrollToTop}
onScrolledToTop={() => setShouldScrollToTop(false)}
/>
<Divider orientation="vertical" className="h-auto" />
{/* 右侧服务列表 */}
{selectedGroup ? (
<GroupServiceTable
groupId={selectedGroup.id}
services={groupServices}
loading={servicesLoading}
pagination={serviceTablePagination}
onPageChange={(page) => handleServicePageChange(selectedGroup.id, page)}
onAddService={handleAddService}
onRemoveService={handleRemoveService}
onEditGroup={handleEditGroup}
onDeleteGroup={handleDeleteGroup}
refreshTrigger={refreshTrigger}
/>
) : (
<div className="flex-1 flex items-center justify-center text-default-400">
{t("Please select a group to view services")}
</div>
)}
</div>
{/* 删除资源组模态框 */}
<DeleteServerModal
isOpen={isDeleteGroupModalOpen}
onClose={() => {
setIsDeleteGroupModalOpen(false);
setGroupToDelete(null);
setTransferToGroupId(null);
}}
onConfirm={handleConfirmDeleteGroup}
title={t("Confirm Remove")}
description={t(
'Are you sure you want to remove this "{{name}}" Resource Group?',
{
name: groupToDelete?.name || "",
}
)}
alertDescription={t("The bound users have been transferred to the following resource group")}
customAlertContent={<div className="w-full mt-[10px]">
<Select
placeholder={t("Select resource group")}
isLoading={simpleResourceGroupsLoading}
selectedKeys={transferToGroupId ? [transferToGroupId] : simpleResourceGroups.length > 0 ? [simpleResourceGroups.filter((group) => group.id !== groupToDelete?.id)[0].id] : []}
onSelectionChange={(keys) => {
const selectedKey = Array.from(keys)[0] as string;
if (selectedKey) {
setTransferToGroupId(selectedKey);
}
}}
labelPlacement="outside"
>
{simpleResourceGroups.filter((group) => group.id !== groupToDelete?.id).map((group) => (
<SelectItem key={group.id} value={group.id}>
{group.name}
</SelectItem>
))}
</Select>
</div>}
/>
{/* 删除服务模态框 */}
<DeleteServerModal
isOpen={isDeleteServiceModalOpen}
onClose={() => {
setIsDeleteServiceModalOpen(false);
setServiceToDelete(null);
}}
onConfirm={handleConfirmDeleteService}
title={t("Confirm Remove")}
description={t(
'Are you sure you want to remove this "{{name}}" mcp server from "{{groupName}}" resource group?',
{
name: serviceToDelete?.name || "",
groupName: selectedGroup?.name || "",
}
)}
alertDescription={t("Users associated with this resource group will not be able to call the removed MCP server")}
/>
{/* 创建/编辑组模态框 */}
<AddServerModal
isOpen={isGroupModalOpen}
onClose={() => {
setIsGroupModalOpen(false);
setEditingGroup(null);
}}
name={editingGroup?.name || ""}
id={editingGroup?.id || ""}
isDefault={editingGroup?.isDefault || false}
onSaveServer={handleSaveGroup}
type={editingGroup ? "edit" : "add"}
/>
<AddMcpServerModal
id={selectedGroup?.id || ""}
isOpen={isAddMcpServerModalOpen}
onClose={() => {
setIsAddMcpServerModalOpen(false);
}}
onSaveMcpServer={handleSaveMcpServer}
/>
</DashboardDemoContent>
);
};
export default ResourceGroupManagement;
@@ -1,34 +1,77 @@
"use client";
import React from "react";
import React, { useState, useRef, useEffect } from "react";
import { RevenueTable } from "./RevenueTable";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import { useRevenueManagement } from "@/hooks/useRevenueManagement";
import { Input } from "@nextui-org/react";
import { Search } from "lucide-react";
import { useTranslation } from "@/shared/lib/useTranslation";
const RevenueManagement: React.FC = () => {
const { t } = useTranslation();
// use custom hook to manage revenue data
const {
records,
loading,
pagination,
setPage,
const {
records,
loading,
pagination,
setPage,
setSearch,
setPaymentType,
setSort
} = useRevenueManagement();
const [searchValue, setSearchValue] = useState('');
const searchTimerRef = useRef<NodeJS.Timeout | null>(null);
// 清理定时器
useEffect(() => {
return () => {
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
};
}, []);
// 处理搜索 - 使用防抖
const handleSearchChange = (value: string) => {
setSearchValue(value);
// 清除之前的定时器
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
// 设置新的定时器,500ms 后触发搜索
searchTimerRef.current = setTimeout(() => {
setSearch(value);
}, 500);
};
return (
<DashboardDemoContent
title="Revenue Management"
title="Revenue"
description="Monitor platform revenue and view user recharge history"
>
<div className="space-y-6 w-full">
{/* comming soon:Filters */}
{/* <RevenueFiltersBar
searchQuery={searchQuery}
onSearchChange={setSearch}
statusFilter={statusFilter}
onStatusChange={setStatus}
/> */}
{/* 搜索框 - 右上角 */}
<div className="flex justify-end items-center gap-4">
<Input
isClearable
className="w-full sm:max-w-[400px]"
placeholder={t('Search by email')}
startContent={<Search className="w-4 h-4" />}
value={searchValue}
onClear={() => {
setSearchValue('');
if (searchTimerRef.current) {
clearTimeout(searchTimerRef.current);
}
setSearch('');
}}
onValueChange={handleSearchChange}
/>
</div>
{/* Revenue Table */}
<RevenueTable
@@ -36,6 +79,8 @@ const RevenueManagement: React.FC = () => {
loading={loading}
pagination={pagination}
onPageChange={setPage}
onPaymentTypeChange={setPaymentType}
onSortChange={setSort}
/>
</div>
</DashboardDemoContent>
@@ -1,6 +1,6 @@
"use client";
import React from 'react';
import React, { useState } from 'react';
import {
Table,
TableHeader,
@@ -10,11 +10,17 @@ import {
TableCell,
Pagination,
Chip,
Spinner
Spinner,
Tooltip,
Dropdown,
DropdownTrigger,
DropdownMenu,
DropdownItem,
Button
} from '@nextui-org/react';
import { useTranslation } from '@/shared/lib/useTranslation';
import { PaymentState, RevenueRecord } from '@/types/revenue';
import { Calendar, CreditCard } from 'lucide-react';
import { Calendar, CreditCard, HelpCircle, Filter, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
import { formatCurrency } from '@/shared/utils/currency';
interface RevenueTableProps {
@@ -26,6 +32,8 @@ interface RevenueTableProps {
total: number;
};
onPageChange: (page: number) => void;
onPaymentTypeChange?: (paymentType: string) => void;
onSortChange?: (field: string | undefined, order: 'asc' | 'desc' | undefined) => void;
}
export const RevenueTable: React.FC<RevenueTableProps> = ({
@@ -33,8 +41,12 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
loading = false,
pagination,
onPageChange,
onPaymentTypeChange,
onSortChange,
}) => {
const { t } = useTranslation();
const [selectedPaymentType, setSelectedPaymentType] = useState('all');
const [sortState, setSortState] = useState<'none' | 'desc' | 'asc'>('none');
const pages = Math.ceil(pagination.total / pagination.pageSize);
const currentPage = pagination.page;
@@ -91,6 +103,35 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
);
};
// 处理付款方式筛选
const handlePaymentTypeChange = (type: string) => {
setSelectedPaymentType(type);
onPaymentTypeChange?.(type);
};
// 处理排序
const handleSortClick = () => {
let newSortState: 'none' | 'desc' | 'asc';
if (sortState === 'none') {
newSortState = 'desc';
onSortChange?.('amount', 'desc');
} else if (sortState === 'desc') {
newSortState = 'asc';
onSortChange?.('amount', 'asc');
} else {
newSortState = 'none';
onSortChange?.(undefined, undefined);
}
setSortState(newSortState);
};
// 获取排序图标
const getSortIcon = () => {
if (sortState === 'desc') return <ArrowDown className="w-4 h-4" />;
if (sortState === 'asc') return <ArrowUp className="w-4 h-4" />;
return <ArrowUpDown className="w-4 h-4" />;
};
if (loading) {
return (
<div className="flex justify-center items-center h-64">
@@ -121,9 +162,68 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
>
<TableHeader>
<TableColumn>{t('Account (Email)')}</TableColumn>
<TableColumn>{t('Recharge Amount')}</TableColumn>
<TableColumn>{t('Recharge Time')}</TableColumn>
<TableColumn>{t('Payment Method')}</TableColumn>
<TableColumn>
<div className="flex items-center gap-2">
<span>{t('Recharge Amount')}</span>
<Button
isIconOnly
size="sm"
variant="light"
onPress={handleSortClick}
className="min-w-unit-6 w-6 h-6"
>
{getSortIcon()}
</Button>
</div>
</TableColumn>
<TableColumn>
<div className="flex items-center gap-1">
<span>{t('Recharge Time')}</span>
<Tooltip
content={t("Current display time is UTC time")}
color="default"
closeDelay={0}
disableAnimation
>
<HelpCircle className="w-4 h-4" />
</Tooltip>
</div>
</TableColumn>
<TableColumn>
<div className="flex items-center gap-2">
<span>{t('Payment Method')}</span>
<Dropdown>
<DropdownTrigger>
<Button
isIconOnly
size="sm"
variant="light"
aria-label="Filter by payment method"
className="min-w-unit-6 w-6 h-6"
>
<Filter
className={`w-4 h-4 ${
selectedPaymentType !== 'all' ? 'text-primary' : ''
}`}
/>
</Button>
</DropdownTrigger>
<DropdownMenu
aria-label="Payment method filter"
selectionMode="single"
selectedKeys={[selectedPaymentType]}
onSelectionChange={(keys) => {
const selected = Array.from(keys)[0] as string;
handlePaymentTypeChange(selected);
}}
>
<DropdownItem key="all">{t('All')}</DropdownItem>
<DropdownItem key="stripe">Stripe</DropdownItem>
<DropdownItem key="platform">Platform</DropdownItem>
</DropdownMenu>
</Dropdown>
</div>
</TableColumn>
<TableColumn>{t('Transaction ID')}</TableColumn>
<TableColumn>{t('Status')}</TableColumn>
</TableHeader>
@@ -1,7 +1,7 @@
"use client";
import React, { useState, useEffect } from "react";
import { Button, AccordionItem, Accordion } from "@nextui-org/react";
import { Button } from "@nextui-org/react";
import MDEditor, { commands } from "@uiw/react-md-editor";
import { PlatformConfig } from "@/shared/types/system";
import { useTranslation } from "@/shared/lib/useTranslation";
@@ -53,7 +53,6 @@ export const AboutPageSettings: React.FC<AboutPageSettingsProps> = ({
preview="live"
hideToolbar={false}
visibleDragbar={false}
data-color-mode="light"
textareaProps={{
placeholder: t("Enter about page content (supports Markdown)"),
style: {
Loaded 100 of 314 files, more files were not shown because too many files have changed in this diff. Show more