Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b773063a0 | ||
|
|
f98ff6bf44 | ||
|
|
22aa1c34c7 | ||
|
|
680ae27dd1 | ||
|
|
4bb91c38ae | ||
|
|
6cdcb98dd5 | ||
|
|
d0e48f8ae2 | ||
|
|
3693d984c5 | ||
|
|
4782b2ee8f | ||
|
|
c2c64a2d29 | ||
|
|
2734841b2a | ||
|
|
86344c5bc0 | ||
|
|
a3ab01cc46 | ||
|
|
265ed78835 | ||
|
|
49627d2449 | ||
|
|
31e3b6b0a8 | ||
|
|
695580d844 | ||
|
|
9c7462f3ed | ||
|
|
4c03a25f9b | ||
|
|
cc2d66be11 | ||
|
|
754d8e596e | ||
|
|
97fdd892ed | ||
|
|
fc46e7b354 | ||
|
|
02fd02ceef | ||
|
|
ed1391fc84 | ||
|
|
4e57c9d0b1 | ||
|
|
a37d13604d | ||
|
|
19267e14c2 | ||
|
|
660c83e0c7 | ||
|
|
ea3174e0fe | ||
|
|
e01a0cb249 | ||
|
|
890d1d8bf3 | ||
|
|
b7197fb35d | ||
|
|
8751aa9ef6 | ||
|
|
35cb02a035 | ||
|
|
beba80a14c | ||
|
|
2c1b17a947 | ||
|
|
71322c2d9d | ||
|
|
d93a3f9af3 | ||
|
|
55457532cc | ||
|
|
9b953048b3 | ||
|
|
913006ba02 | ||
|
|
3a38426b13 | ||
|
|
e42e5ad752 | ||
|
|
c69ed103dc | ||
|
|
6cd52f0d92 | ||
|
|
be7033e9a2 | ||
|
|
8946be619d | ||
|
|
2262a7f49a | ||
|
|
11264d302d | ||
|
|
6a18812572 | ||
|
|
401b35cd10 | ||
|
|
f44102bdb7 | ||
|
|
29a779648d | ||
|
|
20eabea48f | ||
|
|
919285e716 | ||
|
|
01d1411d49 | ||
|
|
6cb7ca9902 | ||
|
|
3012d27aae | ||
|
|
dd3a784cb5 | ||
|
|
518d5f55c5 | ||
|
|
923496735e | ||
|
|
20903eeab5 | ||
|
|
4016bb9d52 | ||
|
|
bf9071122b | ||
|
|
3ff0b743a6 | ||
|
|
360e2cd20d | ||
|
|
e12f6c0db5 | ||
|
|
ec96465a96 | ||
|
|
920eb9154e | ||
|
|
a224445038 | ||
|
|
1c3e40d337 | ||
|
|
44d0768296 | ||
|
|
e9ae97762b | ||
|
|
26b8147f94 | ||
|
|
e4f97e1014 | ||
|
|
d3efa08da2 | ||
|
|
ede3d5c2a3 | ||
|
|
42665d13a7 | ||
|
|
c4bbf09a19 | ||
|
|
ba3a4fe2a2 | ||
|
|
496b9fa380 | ||
|
|
80b3118f3a | ||
|
|
c4f56df03b | ||
|
|
4d26a793a3 | ||
|
|
ac849ce4dd | ||
|
|
a9a83fa187 | ||
|
|
c2738813eb | ||
|
|
883ada7aac | ||
|
|
ad574f0162 | ||
|
|
5cc9e9910e | ||
|
|
d91c1c5369 | ||
|
|
f108551780 | ||
|
|
be19df6273 | ||
|
|
2eb02bb70f | ||
|
|
b548f2494d | ||
|
|
e1fdbdd026 | ||
|
|
7985c6ae2b | ||
|
|
fdfe2c63bc | ||
|
|
224a209fea |
No files matched your search
+1
-1
@@ -11,7 +11,7 @@ ADMIN_PORT=8001
|
||||
|
||||
# 调试配置
|
||||
DEBUG=false
|
||||
LOG_LEVEL=INFO
|
||||
LOG_LEVEL=DEBUG
|
||||
|
||||
# Redis 配置
|
||||
REDIS_HOST=xpack-redis
|
||||
|
||||
@@ -1,36 +1,37 @@
|
||||
# XPack 开源版本 - Copilot 编程指导
|
||||
# XPack Open Source Edition - Copilot Programming Guidelines
|
||||
|
||||
## 项目架构
|
||||
## Project Architecture
|
||||
|
||||
### 服务依赖
|
||||
- `admin_service` 和 `api_service` 相互独立,都依赖 `common`
|
||||
- 遵循分层架构:Controller → Service → Repository
|
||||
### Service Dependencies
|
||||
- `admin_service` and `api_service` are independent of each other, both depend on `common`
|
||||
- Follow layered architecture: Controller → Service → Repository
|
||||
|
||||
### 目录结构
|
||||
### Directory Structure
|
||||
```
|
||||
services/
|
||||
├── admin_service/ # 管理端服务
|
||||
├── api_service/ # API服务
|
||||
└── common/ # 公共模块
|
||||
├── admin_service/ # Admin service
|
||||
├── api_service/ # API service
|
||||
└── common/ # Common modules
|
||||
```
|
||||
|
||||
## 编码规范
|
||||
## Coding Standards
|
||||
|
||||
### 代码风格
|
||||
- 遵循 PEP 8,使用类型注解和 docstring
|
||||
- 命名:函数/变量用 `snake_case`,类用 `PascalCase`
|
||||
- 导入:优先使用 `services/common`,避免跨服务导入
|
||||
### Code Style
|
||||
- Follow PEP 8, use type annotations and docstrings
|
||||
- Naming: use `snake_case` for functions/variables, `PascalCase` for classes
|
||||
- Imports: prioritize `services/common`, avoid cross-service imports
|
||||
|
||||
### 日志要求
|
||||
- **必须使用英文**,使用 `services/common/logging_config.py`
|
||||
- 格式:`logger.info("Action completed: {context}")`
|
||||
- 避免敏感信息,包含必要上下文
|
||||
### Logging Requirements
|
||||
- **Must use English**, use `services/common/logging_config.py`
|
||||
- Format: `logger.info("Action completed: {context}")`
|
||||
- Avoid sensitive information, include necessary context
|
||||
|
||||
### 错误处理
|
||||
- 使用 `services/common/error_msg.py` 定义的错误消息
|
||||
- 统一异常处理和日志记录
|
||||
### Error Handling
|
||||
- Use error messages defined in `services/common/error_msg.py`
|
||||
- Unified exception handling and logging
|
||||
|
||||
## 开发建议
|
||||
- 有适当的日志记录(英文格式,统一格式)
|
||||
- 添加方法级别英文注释,需要简洁
|
||||
- 添加的注释一律使用英文
|
||||
## Development Guidelines
|
||||
- Think and analyze requirements first, wait for user confirmation before writing code
|
||||
- Include appropriate logging (English format, consistent style)
|
||||
- Add method-level English comments, keep them concise
|
||||
- All comments must be written in English
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Setup qshell
|
||||
uses: foxundermoon/setup-qshell@v5
|
||||
with:
|
||||
version: '2.9.0'
|
||||
version: '2.13.0'
|
||||
- name: build
|
||||
run: |
|
||||
cd scripts && ./docker_build.sh ${{ secrets.DOCKER_USERNAME }}
|
||||
|
||||
@@ -41,3 +41,4 @@ htmlcov/
|
||||
local_settings.py
|
||||
/.secrets
|
||||
/uploads/
|
||||
/.vercel/
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** ist der erste Open‑Source‑MCP‑Marktplatz der Welt – damit erstellen und verkaufen Sie Ihre MCP‑Services in wenigen Minuten.
|
||||
|
||||
<br>
|
||||
|
||||
✨ Was XPack bietet
|
||||
- ✅ **OpenAPI → MCP‑Servicekonfiguration per One‑Click**
|
||||
- 🧾 **SEO‑optimierte Startseite & Service‑Seiten**
|
||||
- 💳 **Integriertes Billing (pro Aufruf oder nach Token‑Verbrauch)**
|
||||
- 👥 **Benutzerkontenverwaltung**
|
||||
- 🛠 **Unterstützung für Stripe‑Zahlungen**
|
||||
- 🔐 **Anmeldung via E‑Mail & Google OAuth**
|
||||
|
||||
Alles ist Open Source unter **Apache 2.0** – bereit für den kommerziellen Einsatz.
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ Schnellstart
|
||||
😍 Die Bereitstellung ist extrem einfach. Mit **einem einzigen Befehl** ist Ihr MCP‑Marktplatz in 10 Minuten online.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 Funktionen
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ Systemanforderungen
|
||||
|
||||
### ✅ Empfohlene Hardware
|
||||
- **CPU**: 8 Kerne
|
||||
- **Arbeitsspeicher**: 16 GB
|
||||
- **Speicher**: 200 GB
|
||||
- **Betriebssystem**: Linux
|
||||
- **Architektur**: AMD64
|
||||
|
||||
### ✅ Mindestanforderungen
|
||||
- **CPU**: 2 Kerne
|
||||
- **Arbeitsspeicher**: 4 GB
|
||||
- **Speicher**: 200 GB
|
||||
- **Betriebssystem**: Linux / macOS
|
||||
- **Architektur**: AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 Laufzeitabhängigkeiten
|
||||
|
||||
Für **XPack‑MCP‑Market** werden folgende Dienste benötigt (selbst gehostet oder containerisiert):
|
||||
|
||||
| Komponente | Mindestversion |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
Stellen Sie sicher, dass diese Dienste verfügbar und korrekt konfiguriert sind, bevor Sie das Backend starten.
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 Bereitstellung
|
||||
|
||||
😍 So einfach: Mit **einem Befehl** ist Ihr MCP‑Marktplatz in 10 Minuten bereit.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Docker‑Compose‑Bereitstellung</h4></summary>
|
||||
|
||||
Für diese Methode benötigen Sie [Docker](https://docs.docker.com/engine/install/) und [Docker Compose](https://docs.docker.com/compose/install/standalone/).
|
||||
|
||||
1. `docker-compose.yml` bearbeiten
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. Konfiguration anpassen (Beispiel: [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml))
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. XPack‑MCP‑Market starten
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. Im Browser über Port 3000 öffnen
|
||||
* **Admin‑Login**: http://{IP}:3000/admin-signin
|
||||
* **Benutzer**: admin
|
||||
* **Passwort**: 123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Build</h4></summary>
|
||||
|
||||
1. Repository klonen
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. Projektordner öffnen
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### Frontend‑Build
|
||||
> Voraussetzungen:
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. Build‑Skript ausführen
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
Der Frontend‑Code wird nach `frontend/out` gebaut.
|
||||
|
||||
2. UI starten
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### Backend‑Build
|
||||
> Voraussetzungen:
|
||||
> - Python >= 3.11
|
||||
|
||||
#### Mit `uv` (empfohlen)
|
||||
1. Virtuelle Umgebung erstellen
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. Aktivieren
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. Abhängigkeiten installieren
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. Umgebungsdatei kopieren
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. Variablen anpassen
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. Admin‑Backend starten
|
||||
**Vordergrund**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**Hintergrund**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. API‑→‑MCP‑Service starten
|
||||
**Vordergrund**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**Hintergrund**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Docker‑Build
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 Screenshots
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 Lizenz
|
||||
XPack‑MCP‑Market steht unter der **Apache‑2.0‑Lizenz**.
|
||||
Details finden Sie in der Datei [LICENSE](./LICENSE).
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 Kontakt
|
||||
- 🌐 Website: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 E‑Mail: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord: [Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 Partner
|
||||
- [Cursor](https://www.cursor.com/): KI‑gestützter Code‑Editor mit Vorschlägen für die nächste Änderung, tiefem Codeverständnis und Bearbeitung in natürlicher Sprache – für mehr Produktivität.
|
||||
|
||||
- [Dify](https://dify.ai/): Führende agentische KI‑Plattform mit Workflows, RAG, Integrationen und Observability; unterstützt zahlreiche LLMs und Plugins.
|
||||
|
||||
- [Trae](https://www.trae.ai/): KI‑native IDE mit Chat‑Interface, die „The Real AI Engineer“ verkörpert – erleichtert Code‑Generierung und ‑Assistenz, steigert Qualität und Effizienz.
|
||||
|
||||
- [Windsurf](https://windsurf.com/): Neues IDE‑Konzept mit KI‑Features wie „Cascade“, „Windsurf Tab“ und „Memories“ für tiefes Codeverständnis und reibungslosen Flow.
|
||||
|
||||
- [Coze](https://www.coze.com/): Nächste Generation der No‑Code‑Plattform von ByteDance für KI‑Apps und Chatbots – mit Workflows, proprietären Daten, Plugins und Wissensbasen.
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): CLI‑Tool von Anthropic mit Claude Opus 4 direkt im Terminal; Datei‑/Projekt‑übergreifende Änderungen, Befehlsausführung, IDE‑Integration.
|
||||
|
||||
- [Flowith](https://flowith.io/): Canvas‑basierter KI‑Arbeitsraum für Produktivität und Deep Work mit Multi‑Thread‑Agenten.
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): Open‑Source‑Framework zum Aufbau allgemeiner KI‑Agenten; Multi‑Agent‑Fähigkeiten, LLM‑APIs und Browser‑Automatisierung integriert.
|
||||
|
||||
- [Fellou](https://fellou.ai/): „Agentic Browser“, der im Auftrag des Nutzers handelt – automatisiert Recherche und Erkenntnisse, mit Integrationen wie Notion/LinkedIn.
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): All‑in‑One‑KI‑Begleiter (AI Slides, Sheets, Chat) mit personalisierten Tools und AI Pods zur Inhaltsgenerierung aus vielfältigen Quellen.
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): Open‑Source‑Framework für Echtzeit, multimodale Sprach‑Agenten – inkl. Avatar, MCP‑Integration, Hardware‑Kommunikation und Bildschirmfreigabe‑Erkennung.
|
||||
|
||||
- [APIPark](https://apipark.com/): Open‑Source‑Entwicklerportal und All‑in‑One‑LLM‑Gateway – einheitliche APIs, Load‑Balancing, Traffic‑Kontrolle, semantischer Cache, Prompt‑Management und Data Masking.
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): Von OpenAI entwickelter KI‑Chatbot auf Basis großer Sprachmodelle – kontextbewusste Dialoge, Follow‑ups, Integrationen und Produktivitätsfunktionen.
|
||||
|
||||
- [LangChain](https://www.langchain.com/): Plattform für robuste Agenten‑/LLM‑Apps (LangGraph, LangSmith, LangGraph Platform) – Code‑Generierung, Automatisierung und AI Search.
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): Erster Full‑Stack, Open‑Source, agentischer KI‑Framework – inkl. integriertem Code‑Interpreter‑VM‑Sandbox für sichere Ausführung.
|
||||
|
||||
- [LobeChat](https://lobehub.com/): Persönliches LLM‑Produktivitätstool zum Aufbau persönlicher Agenten und Profi‑Teams; reiches Plugin‑Ökosystem, Wissensbasis, Bild/Audio‑Funktionen.
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): Weit verbreiteter, kostenloser Open‑Source‑Editor mit großer Erweiterbarkeit und KI‑Funktionen wie „Agent Mode“ und intelligenten Edit‑Vorschlägen.
|
||||
|
||||
- [XRoute](https://xroute.ai): Vereinheitlichte Schnittstelle für LLMs – bessere Preise, höhere Durchsätze, kein Abo nötig.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): Open‑Source‑Memory‑Framework für KI‑Companions.
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
|
||||
**XPack** es el primer marketplace MCP de código abierto del mundo: crea y vende tus propios servicios MCP en cuestión de minutos.
|
||||
|
||||
<br>
|
||||
|
||||
✨ Con XPack puedes:
|
||||
- ✅ **Generar con un clic la configuración OpenAPI → MCP**
|
||||
- 🧾 **Portada y páginas de servicio optimizadas para SEO**
|
||||
- 💳 **Facturación integrada (por llamada o por uso de tokens)**
|
||||
- 👥 **Gestión de cuentas de usuario**
|
||||
- 🛠 **Pagos con Stripe**
|
||||
- 🔐 **Inicio de sesión con correo y Google OAuth**
|
||||
|
||||
Todo es open source bajo **Apache 2.0**, listo para uso comercial.
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ Inicio rápido
|
||||
😍 Poner XPack en marcha es facilísimo. Con **un solo comando** tendrás tu marketplace MCP online en 10 minutos.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 Funcionalidades
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ Requisitos del sistema
|
||||
|
||||
### ✅ Hardware recomendado
|
||||
- **CPU**: 8 núcleos
|
||||
- **Memoria**: 16 GB
|
||||
- **Almacenamiento**: 200 GB
|
||||
- **Sistema operativo**: Linux
|
||||
- **Arquitectura**: AMD64
|
||||
|
||||
### ✅ Mínimos
|
||||
- **CPU**: 2 núcleos
|
||||
- **Memoria**: 4 GB
|
||||
- **Almacenamiento**: 200 GB
|
||||
- **Sistema operativo**: Linux / macOS
|
||||
- **Arquitectura**: AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 Dependencias de ejecución
|
||||
|
||||
**XPack-MCP-Market** requiere los siguientes servicios (autogestionados o en contenedores):
|
||||
|
||||
| Componente | Versión mínima |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
Asegúrate de que estos servicios estén disponibles y correctamente configurados antes de arrancar el backend.
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 Despliegue
|
||||
|
||||
😍 Así de simple: con **un comando** tendrás tu marketplace MCP listo en 10 minutos.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Despliegue con Docker-Compose</h4></summary>
|
||||
|
||||
Para este método, instala [Docker](https://docs.docker.com/engine/install/) y [Docker Compose](https://docs.docker.com/compose/install/standalone/).
|
||||
|
||||
1. Edita `docker-compose.yml`
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. Ajusta la configuración (archivo de referencia: [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml))
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. Arranca XPack-MCP-Market
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. Accede por el puerto 3000 en el navegador
|
||||
* **Inicio de sesión admin**: http://{IP}:3000/admin-signin
|
||||
* **Usuario**: admin
|
||||
* **Contraseña**: 123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Compilación (Build)</h4></summary>
|
||||
|
||||
1. Clona el repositorio
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. Entra al proyecto
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### Build del frontend
|
||||
> Requisitos:
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. Ejecuta el script de build
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
El código compilado quedará en `frontend/out`.
|
||||
|
||||
2. Inicia la interfaz
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### Build del backend
|
||||
> Requisitos:
|
||||
> - Python >= 3.11
|
||||
|
||||
#### Con `uv` (recomendado)
|
||||
1. Crea el entorno virtual
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. Actívalo
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. Instala dependencias
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. Copia el archivo de entorno
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. Edita las variables
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. Inicia el servicio de administración
|
||||
**Primer plano**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**Segundo plano**
|
||||
````
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. Inicia el servicio API → MCP
|
||||
**Primer plano**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**Segundo plano**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Build de Docker
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 Capturas
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 Licencia
|
||||
XPack-MCP-Market se publica bajo **Apache 2.0**.
|
||||
Consulta [LICENSE](./LICENSE) para más detalles.
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 Contacto
|
||||
- 🌐 Sitio web: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 Correo: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord: [Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 Socios
|
||||
- [Cursor](https://www.cursor.com/): editor de código con IA integrada en el flujo de trabajo; sugerencias contextuales, comprensión profunda del repositorio y edición en lenguaje natural.
|
||||
|
||||
- [Dify](https://dify.ai/): plataforma líder para desarrollo de IA agentica; cubre flujos de agentes, RAG, integraciones y observabilidad; compatible con múltiples LLMs y plugins.
|
||||
|
||||
- [Trae](https://www.trae.ai/): IDE nativo de IA que apunta a “The Real AI Engineer”; interfaz conversacional con generación y asistencia de código para mejorar calidad y eficiencia.
|
||||
|
||||
- [Windsurf](https://windsurf.com/): nuevo IDE impulsado por IA con “Cascade”, “Windsurf Tab” y “Memories” para un entendimiento profundo del código y un flujo continuo.
|
||||
|
||||
- [Coze](https://www.coze.com/): plataforma de ByteDance para crear apps y chatbots con IA sin código; workflows, datos propios, plugins y bases de conocimiento.
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): herramienta CLI de Anthropic que integra Claude Opus 4 en la terminal; edición multiarchivo, ejecución de comandos e integración con IDEs y test.
|
||||
|
||||
- [Flowith](https://flowith.io/): espacio de trabajo de creación con interfaz de lienzo y agentes avanzados; optimiza productividad y trabajo profundo.
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): framework open source para construir agentes generales; multiactor y con integración de APIs LLM y automatización de navegador.
|
||||
|
||||
- [Fellou](https://fellou.ai/): “navegador agéntico” que actúa por ti; automatiza la recolección de información y entrega de insights; integra con Notion/LinkedIn.
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): compañero de IA todo en uno (AI Slides, Sheets, Chat); herramientas personalizadas y AI Pods para generar contenido desde múltiples fuentes.
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): framework open source para agentes de voz multimodales en tiempo real; avatar, integración MCP, comunicación hardware y detección de pantalla.
|
||||
|
||||
- [APIPark](https://apipark.com/): portal de desarrolladores API open source y pasarela LLM todo en uno; API unificadas, balanceo de carga, control de tráfico, caché semántico, gestión de prompts y enmascaramiento de datos.
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): chatbot de OpenAI basado en LLMs; diálogo natural, comprensión de contexto, seguimiento de conversación e integración con múltiples plataformas.
|
||||
|
||||
- [LangChain](https://www.langchain.com/): plataforma para desarrollar agentes y apps LLM confiables (LangGraph, LangSmith, LangGraph Platform); generación de código, automatización y búsqueda con IA.
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): primer framework agentico full‑stack, open source; incluye sandbox VM del intérprete de código para ejecución segura.
|
||||
|
||||
- [LobeChat](https://lobehub.com/): herramienta de productividad LLM personal; permite crear agentes personales y equipos profesionales; plugins, base de conocimiento, visión y voz.
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): editor de código open source extensible, con funciones de IA como sugerencias inteligentes y “modo agente”.
|
||||
|
||||
- [XRoute](https://xroute.ai): interfaz unificada para LLMs; mejores precios, mejor throughput, sin suscripción.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): framework de memoria open source para compañeros de IA.
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** est le premier marketplace MCP open‑source au monde. Créez et vendez vos services MCP en quelques minutes.
|
||||
|
||||
<br>
|
||||
|
||||
✨ Avec XPack, vous pouvez :
|
||||
- ✅ **Générer en un clic la configuration OpenAPI → MCP**
|
||||
- 🧾 **Page d’accueil et pages service optimisées pour le SEO**
|
||||
- 💳 **Facturation intégrée (par appel ou à l’usage de jetons)**
|
||||
- 👥 **Gestion des comptes utilisateurs**
|
||||
- 🛠 **Prise en charge des paiements Stripe**
|
||||
- 🔐 **Connexion via e‑mail et Google OAuth**
|
||||
|
||||
Tout est open source sous **Apache 2.0**, prêt pour un usage commercial.
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ Démarrage rapide
|
||||
😍 Déployer XPack est ultra simple. **Une seule commande** suffit pour mettre votre marketplace MCP en ligne en 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 Fonctionnalités
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ Configuration système requise
|
||||
|
||||
### ✅ Configuration recommandée
|
||||
- **CPU** : 8 cœurs
|
||||
- **Mémoire** : 16 Go
|
||||
- **Stockage** : 200 Go
|
||||
- **Système** : Linux
|
||||
- **Architecture** : AMD64
|
||||
|
||||
### ✅ Configuration minimale
|
||||
- **CPU** : 2 cœurs
|
||||
- **Mémoire** : 4 Go
|
||||
- **Stockage** : 200 Go
|
||||
- **Système** : Linux / macOS
|
||||
- **Architecture** : AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 Dépendances d’exécution
|
||||
|
||||
**XPack‑MCP‑Market** nécessite les services suivants (auto‑hébergés ou en conteneur) :
|
||||
|
||||
| Composant | Version minimale |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
Assurez‑vous que ces services sont disponibles et correctement configurés avant de lancer le backend.
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 Déploiement
|
||||
|
||||
😍 Tellement simple : **une commande** pour déployer votre marketplace MCP en 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Déploiement avec Docker‑Compose</h4></summary>
|
||||
|
||||
Pour cette méthode, installez [Docker](https://docs.docker.com/engine/install/) et [Docker Compose](https://docs.docker.com/compose/install/standalone/).
|
||||
|
||||
1. Éditez `docker-compose.yml`
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. Modifiez la configuration (exemple de référence : [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml))
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. Démarrez XPack‑MCP‑Market
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. Accédez à l’interface sur le port 3000
|
||||
* **Connexion admin** : http://{IP}:3000/admin-signin
|
||||
* **Utilisateur** : admin
|
||||
* **Mot de passe** : 123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Build</h4></summary>
|
||||
|
||||
1. Clonez le dépôt
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. Ouvrez le projet
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### Build frontend
|
||||
> Prérequis :
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. Lancez le script de build
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
Le frontend compilé est disponible dans `frontend/out`.
|
||||
|
||||
2. Démarrez l’interface
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### Build backend
|
||||
> Prérequis :
|
||||
> - Python >= 3.11
|
||||
|
||||
#### Avec `uv` (recommandé)
|
||||
1. Créez l’environnement virtuel
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. Activez‑le
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. Installez les dépendances
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. Copiez le fichier d’environnement
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. Modifiez les variables
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. Démarrez le service d’administration
|
||||
**Premier plan**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**Arrière‑plan**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. Démarrez le service API → MCP
|
||||
**Premier plan**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**Arrière‑plan**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Build Docker
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 Captures d’écran
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 Licence
|
||||
XPack‑MCP‑Market est publié sous **Apache 2.0**.
|
||||
Pour plus d’informations, consultez le fichier [LICENSE](./LICENSE).
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 Contact
|
||||
- 🌐 Site web : [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 E‑mail : [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord : [Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 Partenaires
|
||||
- [Cursor](https://www.cursor.com/) : éditeur de code propulsé par l’IA, intégré au flux de travail, avec propositions d’édition, compréhension profonde du code et édition en langage naturel.
|
||||
|
||||
- [Dify](https://dify.ai/) : principale plateforme de développement d’IA agentique, couvrant workflows d’agents, RAG, intégrations et observabilité, avec prise en charge de nombreux LLM et plugins.
|
||||
|
||||
- [Trae](https://www.trae.ai/) : IDE natif IA visant “The Real AI Engineer”, interface conversationnelle, génération et assistance de code pour améliorer qualité et productivité.
|
||||
|
||||
- [Windsurf](https://windsurf.com/) : IDE nouvelle génération exploitant l’IA avec “Cascade”, “Windsurf Tab” et “Memories” pour une compréhension profonde et un flux ininterrompu.
|
||||
|
||||
- [Coze](https://www.coze.com/) : plateforme ByteDance pour créer des chatbots et apps IA sans code, avec workflows, données propriétaires, plugins, bases de connaissances et modèles prêts à l’emploi.
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code) : outil CLI d’Anthropic intégrant Claude Opus 4 dans le terminal, avec édition multi‑fichiers, exécution de commandes et intégration IDE/tests.
|
||||
|
||||
- [Flowith](https://flowith.io/) : espace de création basé sur un canvas multi‑fils, optimisé pour la productivité et le deep work via des agents avancés.
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus) : framework open‑source pour bâtir des agents IA généraux, multi‑agents, intégrable avec des API LLM et l’automatisation navigateur.
|
||||
|
||||
- [Fellou](https://fellou.ai/) : “navigateur agentique” qui agit pour l’utilisateur, automatisant la collecte d’infos et la synthèse, avec intégrations Notion/LinkedIn.
|
||||
|
||||
- [Genspark](https://www.genspark.ai/) : compagnon IA tout‑en‑un (AI Slides, Sheets, Chat), outils personnalisés et AI Pods pour générer du contenu à partir de multiples sources.
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework) : framework open‑source pour agents vocaux multimodaux en temps réel, avec avatar, intégration MCP, communication matérielle et détection d’écran.
|
||||
|
||||
- [APIPark](https://apipark.com/) : portail développeur API open‑source et passerelle LLM tout‑en‑un, avec API unifiées, répartition de charge, contrôle de trafic, cache sémantique, gestion de prompts et masquage de données.
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/) : chatbot d’OpenAI fondé sur des LLM, dialogues naturels, compréhension du contexte, intégrations variées et fonctions avancées de productivité.
|
||||
|
||||
- [LangChain](https://www.langchain.com/) : plateforme robuste pour développer agents et apps LLM (LangGraph, LangSmith, LangGraph Platform), pour génération de code, automatisation et recherche IA.
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/) : premier framework IA agentique full‑stack open‑source, avec bac à sable VM d’interpréteur de code pour une exécution sécurisée.
|
||||
|
||||
- [LobeChat](https://lobehub.com/) : outil de productivité LLM personnel, pour créer des agents personnels/équipes, avec vaste écosystème de plugins, base de connaissances et fonctions image/voix.
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/) : éditeur de code open‑source très populaire et extensible, compatible avec de nombreuses langues et doté de fonctions IA comme le “mode agent”.
|
||||
|
||||
- [XRoute](https://xroute.ai) : interface unifiée pour les LLM, meilleurs prix, meilleur débit, sans abonnement.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU) : framework mémoire open‑source pour compagnons IA.
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** は世界初のオープンソース MCP マーケットプレイスです。数分で自分の MCP サービスを作成して販売できます。
|
||||
|
||||
<br>
|
||||
|
||||
✨ XPack でできること
|
||||
- ✅ **OpenAPI → MCP サービス設定をワンクリック生成**
|
||||
- 🧾 **SEO に強いトップページ + MCP サービスページ**
|
||||
- 💳 **内蔵課金(リクエスト数 / トークン消費ベース)**
|
||||
- 👥 **ユーザーアカウント管理**
|
||||
- 🛠 **Stripe 決済対応**
|
||||
- 🔐 **Email & Google OAuth サインイン対応**
|
||||
|
||||
すべて **Apache 2.0** のオープンソース。商用利用も安心です。
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ クイックスタート
|
||||
😍 導入はとても簡単。**1 行のコマンド**で、10 分であなたの MCP マーケットを立ち上げられます。
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 機能
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ システム要件
|
||||
|
||||
### ✅ 推奨ハードウェア
|
||||
- **CPU**: 8 コア
|
||||
- **メモリ**: 16 GB
|
||||
- **ストレージ**: 200 GB
|
||||
- **OS**: Linux
|
||||
- **アーキテクチャ**: AMD64
|
||||
|
||||
### ✅ 最低要件
|
||||
- **CPU**: 2 コア
|
||||
- **メモリ**: 4 GB
|
||||
- **ストレージ**: 200 GB
|
||||
- **OS**: Linux / macOS
|
||||
- **アーキテクチャ**: AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 実行時依存関係
|
||||
|
||||
**XPack-MCP-Market** を実行するには、以下のサービス(セルフホストまたはコンテナ)が必要です。
|
||||
|
||||
| コンポーネント | 最低バージョン |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
これらのサービスが利用可能で、正しく設定されていることを確認してください。
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 デプロイ
|
||||
|
||||
😍 導入はとても簡単。**1 行のコマンド**で、10 分であなたの MCP マーケットを立ち上げられます。
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Docker-Compose デプロイ</h4></summary>
|
||||
|
||||
この方法でインストールするには、[Docker](https://docs.docker.com/engine/install/) と [Docker Compose](https://docs.docker.com/compose/install/standalone/) が必要です。
|
||||
|
||||
1. `docker-compose.yml` を編集
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. 設定を変更します。元のファイルは [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml) を参照してください。
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. XPack-MCP-Market を起動
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. ブラウザでポート 3000 にアクセス
|
||||
* **管理画面ログイン**: http://{IP}:3000/admin-signin
|
||||
* **管理ユーザー**: admin
|
||||
* **管理パスワード**: 123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 ビルド</h4></summary>
|
||||
|
||||
1. リポジトリをクローン
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. プロジェクトへ移動
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### フロントエンドビルド
|
||||
> 要件:
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. ビルドスクリプトを実行
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
ビルド後、フロントエンドは `frontend/out` に出力されます。
|
||||
|
||||
2. UI を起動
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### バックエンドビルド
|
||||
> 要件:
|
||||
> - Python >= 3.11
|
||||
|
||||
#### `uv` を使用(推奨)
|
||||
1. 仮想環境を作成
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. 仮想環境を有効化
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. 依存関係をインストール
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. 環境変数ファイルをコピー
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. 環境変数を編集
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. 管理用バックエンドサービスを起動
|
||||
**フォアグラウンド**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**バックグラウンド**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. API → MCP サービスを起動
|
||||
**フォアグラウンド**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**バックグラウンド**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Docker ビルド
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 スクリーンショット
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 ライセンス
|
||||
XPack-MCP-Market は **Apache 2.0** ライセンスで提供されています。
|
||||
詳細は [LICENSE](./LICENSE) をご覧ください。
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 お問い合わせ
|
||||
- 🌐 Website: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 Email: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord:[Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 パートナー
|
||||
- [Cursor](https://www.cursor.com/): Cursor は AI をエディタに統合し、次の編集候補、コードベースの深い理解、自然言語での編集などを提供する AI コードエディタです。開発効率を高めます。
|
||||
|
||||
- [Dify](https://dify.ai/): Dify はエージェンティック AI 開発プラットフォームのリーダーで、エージェントワークフロー、RAG、各種統合、可観測性など、AI アプリ構築に必要な一式を提供します。多数の LLM とプラグインに対応。
|
||||
|
||||
- [Trae](https://www.trae.ai/): Trae は「真の AI エンジニア」を体現することを目指した AI ネイティブ IDE。チャットベースの UI でコード生成や支援を行い、品質と生産性を向上させます。
|
||||
|
||||
- [Windsurf](https://windsurf.com/): Windsurf は AI を活用した新しい IDE。深いコード理解のための「Cascade」、賢い補完「Windsurf Tab」、コードベースの記憶「Memories」などを備え、開発の流れを途切れさせません。
|
||||
|
||||
- [Coze](https://www.coze.com/): Coze は ByteDance の次世代 AI アプリ/チャットボット開発プラットフォーム。ノーコードのビルダー、ワークフロー、独自データ接続、プラグイン/ナレッジベースで簡単に強力なボットを作成できます。
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): Claude Code は Anthropic の CLI ツール。ターミナルに Claude Opus 4 を組み込み、リポジトリ横断編集、コマンド実行、IDE 連携、テスト連携などを実現します。
|
||||
|
||||
- [Flowith](https://flowith.io/): Flowith はキャンバス型 UI の AI ワークスペース。マルチスレッドのエージェント体験で知識変換と深い作業に最適化し、従来のチャット型を越える体験を提供します。
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): OpenManus は汎用 AI エージェント構築のための OSS フレームワーク。複数エージェントに対応し、LLM API やブラウザ自動化ツールと統合可能です。
|
||||
|
||||
- [Fellou](https://fellou.ai/): Fellou は行動まで担う「エージェンティックブラウザ」。情報収集から洞察提示までを自動化し、Notion/LinkedIn などとも連携します。
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): Genspark は AI Slides / Sheets / Chat などを備えたオールインワンの AI コンパニオン。AI Pods による多様なコンテンツ生成が可能です。
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): TEN(The Embodied Narrator)はリアルタイム・マルチモーダル音声エージェントの OSS。アバター、MCP 連携、ハードウェア通信、画面共有検出などを備えます。
|
||||
|
||||
- [APIPark](https://apipark.com/): APIPark は OSS のエンタープライズ API デベロッパーポータルかつオールインワン LLM ゲートウェイ。統一 API、負荷分散、トラフィック制御、セマンティックキャッシュ、プロンプト管理、マスキング等で安全・安定運用を実現。
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): ChatGPT は OpenAI の対話型 AI。高度な言語理解と生成で、追質問対応や各種プラットフォーム統合を通じて生産性を高めます。
|
||||
|
||||
- [LangChain](https://www.langchain.com/): LangChain は堅牢なエージェント/LLM アプリ開発プラットフォーム。LangGraph / LangSmith / LangGraph Platform により、コード生成、自動化、AI 検索を横断的に支援します。
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): Lemon AI はフルスタックなオープンソース・エージェンティック AI フレームワーク。安全な実行のための組み込み Code Interpreter VM サンドボックスを備えます。
|
||||
|
||||
- [LobeChat](https://lobehub.com/): LobeHub の LobeChat は個人向け LLM 生産性ツール。個人エージェント/チーム構築、豊富なプラグイン、知識ベース、画像/音声対応などを提供します。
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): Visual Studio Code は拡張性が高い OSS エディタ。多言語対応と AI 機能(次の編集候補、エージェントモード等)を備えます。
|
||||
|
||||
- [XRoute](https://xroute.ai): 複数 LLM を単一インターフェースで扱えるゲートウェイ。より良い価格とスループット、サブスクリプション不要を提供します。
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU は AI コンパニオン向けのオープンソース記憶フレームワークです。
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** 는 세계 최초의 오픈 소스 MCP 마켓플레이스입니다. 몇 분 만에 나만의 MCP 서비스를 만들고 판매하세요.
|
||||
|
||||
<br>
|
||||
|
||||
✨ XPack으로 할 수 있는 일
|
||||
- ✅ **OpenAPI → MCP 서비스 설정을 원클릭으로 생성**
|
||||
- 🧾 **SEO 친화적 홈페이지 + 서비스 상세 페이지**
|
||||
- 💳 **내장 과금(요청 수 / 토큰 사용량 기준)**
|
||||
- 👥 **사용자 계정 관리**
|
||||
- 🛠 **Stripe 결제 지원**
|
||||
- 🔐 **이메일 & Google OAuth 로그인 지원**
|
||||
|
||||
모든 코드는 **Apache 2.0** 라이선스로 공개되어 있으며, 상업적 사용이 가능합니다.
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ 빠른 시작
|
||||
😍 정말 간단합니다. **한 줄 명령어**로 10분 만에 MCP 마켓을 배포할 수 있습니다.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 기능
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ 시스템 요구 사항
|
||||
|
||||
### ✅ 권장 하드웨어
|
||||
- **CPU**: 8코어
|
||||
- **메모리**: 16 GB
|
||||
- **스토리지**: 200 GB
|
||||
- **운영체제**: Linux
|
||||
- **아키텍처**: AMD64
|
||||
|
||||
### ✅ 최소 사양
|
||||
- **CPU**: 2코어
|
||||
- **메모리**: 4 GB
|
||||
- **스토리지**: 200 GB
|
||||
- **운영체제**: Linux / macOS
|
||||
- **아키텍처**: AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 런타임 의존성
|
||||
|
||||
**XPack-MCP-Market** 실행에는 다음 서비스가 필요합니다(셀프 호스팅 또는 컨테이너).
|
||||
|
||||
| 구성 요소 | 최소 버전 |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
실행 전에 위 서비스가 준비되어 있고 올바르게 설정되었는지 확인하세요.
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 배포
|
||||
|
||||
😍 **한 줄 명령어**로 10분 만에 MCP 마켓을 배포할 수 있습니다.
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 Docker-Compose 배포</h4></summary>
|
||||
|
||||
이 방법을 사용하려면 [Docker](https://docs.docker.com/engine/install/) 와 [Docker Compose](https://docs.docker.com/compose/install/standalone/) 가 필요합니다.
|
||||
|
||||
1. `docker-compose.yml` 편집
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. 설정 변경(원본 예시는 [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml) 참고)
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. XPack-MCP-Market 시작
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. 브라우저에서 3000 포트로 접속
|
||||
* **관리자 로그인 주소**: http://{IP}:3000/admin-signin
|
||||
* **관리자 계정**: admin
|
||||
* **관리자 비밀번호**: 123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 빌드</h4></summary>
|
||||
|
||||
1. 리포지토리 클론
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. 프로젝트 디렉토리로 이동
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### 프런트엔드 빌드
|
||||
> 요구 사항:
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. 빌드 스크립트 실행
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
빌드가 완료되면 `frontend/out` 디렉터리에 생성됩니다.
|
||||
|
||||
2. UI 서버 시작
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### 백엔드 빌드
|
||||
> 요구 사항:
|
||||
> - Python >= 3.11
|
||||
|
||||
#### `uv` 사용(권장)
|
||||
1. 가상 환경 생성
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. 가상 환경 활성화
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. 의존성 설치
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. 환경 변수 파일 복사
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. 환경 변수 편집
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. 관리자 백엔드 서비스 시작
|
||||
**포그라운드**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**백그라운드**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. API → MCP 서비스 시작
|
||||
**포그라운드**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**백그라운드**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Docker 빌드
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 스크린샷
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 라이선스
|
||||
XPack-MCP-Market 는 **Apache 2.0** 라이선스로 배포됩니다.
|
||||
자세한 내용은 [LICENSE](./LICENSE) 를 확인하세요.
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 문의
|
||||
- 🌐 Website: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 Email: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord: [Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 파트너
|
||||
- [Cursor](https://www.cursor.com/): Cursor는 AI를 에디터에 직접 통합하여 다음 편집 제안, 코드베이스 심층 이해, 자연어 편집 등을 제공하는 AI 코드 에디터입니다.
|
||||
|
||||
- [Dify](https://dify.ai/): Dify는 에이전틱 AI 개발 플랫폼으로, 에이전트 워크플로우, RAG, 통합, 가시성 등 AI 앱 구축에 필요한 모든 것을 제공합니다. 다양한 LLM과 플러그인을 지원합니다.
|
||||
|
||||
- [Trae](https://www.trae.ai/): Trae는 “The Real AI Engineer”를 표방하는 AI 네이티브 IDE로, 챗 기반 인터페이스로 코드 생성/도움을 제공하며 품질과 효율을 높입니다.
|
||||
|
||||
- [Windsurf](https://windsurf.com/): Windsurf는 AI 기반의 새로운 IDE입니다. 깊은 코드 이해를 위한 “Cascade”, 지능형 자동완성 “Windsurf Tab”, 코드 기억 “Memories” 등을 제공합니다.
|
||||
|
||||
- [Coze](https://www.coze.com/): Coze는 ByteDance의 차세대 AI 애플리케이션/챗봇 개발 플랫폼으로, 노코드 빌더와 워크플로우, 독자 데이터 연동, 플러그인·지식베이스로 손쉽게 강력한 봇을 만들 수 있습니다.
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): Claude Code는 터미널에 Claude Opus 4를 내장하는 CLI 도구로, 파일 편집/명령 실행/다중 파일 변경/IDE 통합을 지원합니다.
|
||||
|
||||
- [Flowith](https://flowith.io/): Flowith는 캔버스 기반 UI의 AI 작업 공간으로, 멀티 스레드형 에이전트 경험을 통해 지식 변환과 몰입 작업을 최적화합니다.
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): OpenManus는 범용 AI 에이전트 구축을 위한 오픈소스 프레임워크입니다. 다중 에이전트와 LLM/브라우저 자동화를 통합할 수 있습니다.
|
||||
|
||||
- [Fellou](https://fellou.ai/): Fellou는 사용자 대신 행동하는 “에이전틱 브라우저”로, 정보 수집부터 인사이트 제공까지 자동화하며 Notion/LinkedIn 등과도 연동됩니다.
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): Genspark는 AI Slides/Sheets/Chat을 포함한 올인원 AI 동반자 제품으로, AI Pods를 통해 다양한 소스에서 콘텐츠를 생성합니다.
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): TEN(The Embodied Narrator)은 실시간 멀티모달 음성 에이전트를 위한 오픈소스 프레임워크로, 아바타, MCP 연동, 하드웨어 통신, 화면 공유 감지 등을 제공합니다.
|
||||
|
||||
- [APIPark](https://apipark.com/): APIPark는 오픈소스 엔터프라이즈 API 개발자 포털이자 올인원 LLM 게이트웨이로, 통합 API 시그니처, 로드밸런싱, 트래픽 제어, 의미적 캐시, 프롬프트 관리, 데이터 마스킹 등을 지원합니다.
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): ChatGPT는 OpenAI가 개발한 대화형 AI로, 맥락 이해와 생성 능력을 바탕으로 후속 질문 처리와 다양한 플랫폼 통합을 지원합니다.
|
||||
|
||||
- [LangChain](https://www.langchain.com/): LangChain은 신뢰성 있는 에이전트/LLM 앱 개발 플랫폼으로, LangGraph/LangSmith/LangGraph Platform을 통해 코드 생성, 자동화, AI 검색을 지원합니다.
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): Lemon AI는 풀스택 오픈소스 에이전틱 AI 프레임워크로, 안전한 실행을 위한 내장 Code Interpreter VM 샌드박스를 제공합니다.
|
||||
|
||||
- [LobeChat](https://lobehub.com/): LobeChat은 개인 LLM 생산성 도구로, 개인 에이전트/전문 팀 구축, 플러그인 생태계, 지식 베이스, 이미지/음성 기능 등을 제공합니다.
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): Visual Studio Code는 확장성이 뛰어난 오픈소스 코드 에디터로, 다양한 언어를 지원하고 지능형 다음 편집 제안 및 “에이전트 모드” 같은 AI 기능을 갖추고 있습니다.
|
||||
|
||||
- [XRoute](https://xroute.ai): 여러 LLM을 단일 인터페이스로 제공하는 게이트웨이로, 더 나은 가격/처리량을 제공하며 구독이 필요 없습니다.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU는 AI 컴패니언을 위한 오픈소스 메모리 프레임워크입니다.
|
||||
+23
-11
@@ -4,22 +4,34 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** 是一款轻量级、开源的 MCP(Model Context Protocol)服务市场框架。
|
||||
它可以将任何符合 OpenAPI 规范的接口快速转换为 MCP 服务,并帮助你在数分钟内搭建自己的 API 商店。
|
||||
**XPack** 是全球首个开源 MCP 交易平台,帮助你在10分钟内快速搭建自己的 MCP 商店并立刻开始销售 MCP 服务。
|
||||
|
||||
<br>
|
||||
|
||||
✨ 使用 XPack,你可以:
|
||||
- ✅ **一键将 OpenAPI 转换为 MCP 服务配置**
|
||||
- 🧾 **自动生成 SEO 友好的主页和服务页**
|
||||
- 💳 **内置调用计费功能(支持按次收费)**
|
||||
- 👥 **用户账户体系与管理后台**
|
||||
- 🛠 **内置 Stripe 支付集成**
|
||||
- 🔐 **支持邮箱 & Google 登录认证**
|
||||
- ✅ 一键将 OpenAPI 转换为 MCP 服务并且为 MCP 定价
|
||||
- 🧾 自动生成 SEO 友好的主页和服务页
|
||||
- 💳 内置计费功能(支持按次、按Token收费)
|
||||
- 👥 管理注册用户、充值、交易记录等
|
||||
- 🛠 集成 Stripe 支付
|
||||
- 🔐 邮箱 & Google 登录认证
|
||||
- 📊 用户调用统计
|
||||
|
||||
本项目基于 **Apache 2.0 协议开源**,可放心用于商业用途。
|
||||
|
||||
@@ -27,10 +39,10 @@
|
||||
|
||||
# ✨ 快速开始
|
||||
|
||||
😍 只需一行命令,即可在 10 分钟内部署你的 MCP 服务市场:
|
||||
😍 只需一行命令,即可在 10 分钟内部署你的 MCP 交易平台:
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
该脚本会自动安装 MySQL、Redis、RabbitMQ,并启动 XPack 服务。
|
||||
@@ -83,7 +95,7 @@ XPack-MCP-Market 依赖以下服务(可容器化或自行安装):
|
||||
### 🟢 快速部署命令
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
支持系统包括:
|
||||
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
# XPack
|
||||

|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
|
||||
**XPack** 是全球首個開源的 MCP 市集,讓你在幾分鐘內就能建立並販售自己的 MCP 服務。
|
||||
|
||||
<br>
|
||||
|
||||
✨ 使用 XPack 你可以:
|
||||
- ✅ **一鍵將 OpenAPI 轉為 MCP 服務**
|
||||
- 🧾 **SEO 友善的首頁與服務頁**
|
||||
- 💳 **內建計費(按调用次數或 Token 使用量)**
|
||||
- 👥 **使用者帳號管理**
|
||||
- 🛠 **支援 Stripe 金流**
|
||||
- 🔐 **支援 Email 與 Google OAuth 登入**
|
||||
|
||||
所有原始碼皆採用 **Apache 2.0** 授權,商用無虞。
|
||||
|
||||
<br>
|
||||
|
||||
# ✨ 快速開始
|
||||
😍 部署非常簡單,以 **一行指令** 即可在 10 分鐘內架起你的 MCP 市集。
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
<br>
|
||||
|
||||
# 📸 功能
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
<br>
|
||||
|
||||
## 🖥️ 系統需求
|
||||
|
||||
### ✅ 建議硬體
|
||||
- **CPU**:8 核心
|
||||
- **記憶體**:16 GB
|
||||
- **儲存空間**:200 GB
|
||||
- **作業系統**:Linux
|
||||
- **架構**:AMD64
|
||||
|
||||
### ✅ 最低需求
|
||||
- **CPU**:2 核心
|
||||
- **記憶體**:4 GB
|
||||
- **儲存空間**:200 GB
|
||||
- **作業系統**:Linux / macOS
|
||||
- **架構**:AMD64 / ARM64
|
||||
|
||||
<br>
|
||||
|
||||
## 📦 執行相依
|
||||
|
||||
**XPack-MCP-Market** 需要以下服務(自架或容器化):
|
||||
|
||||
| 元件 | 最低版本 |
|
||||
|---|---|
|
||||
| **MySQL** | ≥ 5.7.x |
|
||||
| **Redis** | ≥ 6.2.x |
|
||||
| **RabbitMQ**| ≥ 4.0 |
|
||||
|
||||
請先確保上述服務已可用且設定正確,再啟動後端。
|
||||
|
||||
<br>
|
||||
|
||||
## 💿 部署
|
||||
|
||||
😍 就這麼簡單:用 **一行指令**,10 分鐘內完成部署。
|
||||
|
||||
```bash
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 以 Docker-Compose 部署</h4></summary>
|
||||
|
||||
使用此方法前,請先安裝 [Docker](https://docs.docker.com/engine/install/) 與 [Docker Compose](https://docs.docker.com/compose/install/standalone/)。
|
||||
|
||||
1. 編輯 `docker-compose.yml`
|
||||
```
|
||||
vi docker-compose.yml
|
||||
```
|
||||
<br>
|
||||
|
||||
2. 修改設定,可參考原始檔 [docker-compose.yml](https://github.com/xpack-ai/XPack-MCP-Market/blob/main/scripts/docker-compose.yml)
|
||||
```
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /var/lib/xpack/mysql:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "8002:8002"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
ports:
|
||||
- 6379:6379
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
container_name: xpack-rabbitmq
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
3. 啟動 XPack-MCP-Market
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
4. 瀏覽器透過 3000 埠連線
|
||||
* **管理員登入**:http://{IP}:3000/admin-signin
|
||||
* **帳號**:admin
|
||||
* **密碼**:123456789
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><h4>🔖 建置</h4></summary>
|
||||
|
||||
1. 取得原始碼
|
||||
```
|
||||
git clone https://github.com/xpack-ai/XPack-MCP-Market.git
|
||||
```
|
||||
2. 進入專案資料夾
|
||||
```
|
||||
cd XPack-MCP-Market
|
||||
```
|
||||
### 前端建置
|
||||
> 需求:
|
||||
> - Node >= 22.x
|
||||
> - Pnpm >= 10.x
|
||||
|
||||
1. 執行建置腳本
|
||||
```
|
||||
cd scripts && ./frontend_build.sh && cd ../
|
||||
```
|
||||
完成後產出於 `frontend/out`。
|
||||
|
||||
2. 啟動 UI
|
||||
```
|
||||
cd frontend/out && node server.js
|
||||
```
|
||||
### 後端建置
|
||||
> 需求:
|
||||
> - Python >= 3.11
|
||||
|
||||
#### 使用 `uv`(建議)
|
||||
1. 建立虛擬環境
|
||||
```
|
||||
uv venv
|
||||
```
|
||||
2. 啟用虛擬環境
|
||||
```
|
||||
source .venv/bin/activate
|
||||
```
|
||||
3. 安裝相依
|
||||
```
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
4. 複製環境變數檔
|
||||
```
|
||||
cp .env.example .env
|
||||
```
|
||||
5. 編輯環境變數
|
||||
```
|
||||
vi .env
|
||||
```
|
||||
6. 啟動管理後端服務
|
||||
**前景**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload
|
||||
```
|
||||
**背景**
|
||||
```
|
||||
uvicorn services.admin_service.main:app --host 0.0.0.0 --port 8001 --reload &
|
||||
```
|
||||
|
||||
7. 啟動 API → MCP 服務
|
||||
**前景**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload
|
||||
```
|
||||
**背景**
|
||||
```
|
||||
uvicorn services.api_service.main:app --host 0.0.0.0 --port 8002 --reload &
|
||||
```
|
||||
### Docker 建置
|
||||
```
|
||||
docker build -t xpack-mcp-market --build-arg APP=xpack-mcp-market --build-arg VERSION=1.0.0 -f ./scripts/Dockerfile ./
|
||||
```
|
||||
</details>
|
||||
|
||||
# 📸 螢幕截圖
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/5f71bfcf-c128-42ab-8077-3f2ede549f80" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/d7c0b40d-182e-47a6-bcdf-bd36970f5ee6" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/ae40f659-87ad-42d4-8379-b47a48eb6a29" />
|
||||
|
||||
<img width="1415" height="797" alt="image" src="https://github.com/user-attachments/assets/1049f4e5-ec3f-4520-8480-6d6432d6f5d2" />
|
||||
|
||||
<br>
|
||||
|
||||
# 🧾 授權
|
||||
XPack-MCP-Market 以 **Apache 2.0** 授權釋出。
|
||||
詳情請見 [LICENSE](./LICENSE)。
|
||||
|
||||
<br>
|
||||
|
||||
# 📬 聯絡方式
|
||||
- 🌐 Website: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 Email: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord:[Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 合作夥伴
|
||||
- [Cursor](https://www.cursor.com/): Cursor 是一款將 AI 深度整合進編輯器的工具,提供下一步編輯建議、對程式碼庫的深度理解與自然語言編輯,顯著提升生產力。
|
||||
|
||||
- [Dify](https://dify.ai/): Dify 為領先的代理式(Agentic)AI 開發平台,涵蓋代理流程、RAG、整合與可觀測性等完整能力,支援多種 LLM 與外掛。
|
||||
|
||||
- [Trae](https://www.trae.ai/): Trae 是 AI 原生 IDE,以對話式介面協助產生與改寫程式碼,提升品質與效率。
|
||||
|
||||
- [Windsurf](https://windsurf.com/): Windsurf 為新一代 AI IDE,具備「Cascade」深度理解、「Windsurf Tab」智慧補全與「Memories」程式碼記憶等功能。
|
||||
|
||||
- [Coze](https://www.coze.com/): Coze 是 ByteDance 推出的次世代 AI 應用/聊天機器人平台,透過無程式碼工作流、外掛與知識庫,輕鬆建立強大的 Bot。
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): Claude Code 是 Anthropic 的 CLI 工具,將 Claude Opus 4 直接帶到終端機,可跨檔案編輯、執行指令並與 IDE/測試整合。
|
||||
|
||||
- [Flowith](https://flowith.io/): Flowith 是以畫布為核心的 AI 工作空間,透過多執行緒代理體驗,優化知識轉換與深度工作。
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): OpenManus 是用於構建通用 AI 代理的開源框架,支援多代理與 LLM API、瀏覽器自動化整合。
|
||||
|
||||
- [Fellou](https://fellou.ai/): Fellou 是能主動代辦任務的「Agentic Browser」,自動化資料蒐集與洞察產出,並和 Notion/LinkedIn 等常用工具整合。
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): Genspark 是全方位 AI 夥伴(AI Slides、Sheets、Chat),以個人化工具與 AI Pods 從多來源生成內容。
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): TEN(The Embodied Narrator)為即時多模態語音代理的開源框架,支援虛擬分身、MCP 整合、硬體通訊與畫面偵測。
|
||||
|
||||
- [APIPark](https://apipark.com/): APIPark 是開源企業級 API 開發者入口與整合式 LLM 閘道,提供統一 API 介面、負載平衡、流量控制、語意快取、提示管理與資料遮罩。
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): ChatGPT 是 OpenAI 的對話式 AI,具備進階語言理解與生成能力,支援追問、情境保留與多平台整合。
|
||||
|
||||
- [LangChain](https://www.langchain.com/): LangChain 是開發可靠代理與 LLM 應用的平台,涵蓋 LangGraph、LangSmith 與 LangGraph Platform 等產品。
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): Lemon AI 是首個全端、開源的 Agentic AI 框架,內建 Code Interpreter VM 沙盒以確保安全執行。
|
||||
|
||||
- [LobeChat](https://lobehub.com/): LobeChat 為個人 LLM 生產力工具,支援個人/團隊代理、外掛生態、知識庫與影像/語音功能。
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): Visual Studio Code 是高延展性的開源編輯器,支援多語言並內建多項 AI 功能(如下一步編輯建議與代理模式)。
|
||||
|
||||
- [XRoute](https://xroute.ai): 提供統一介面的 LLM 閘道,具更佳價格與吞吐量,無需訂閱。
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU 是面向 AI 夥伴的開源記憶框架。
|
||||
@@ -3,19 +3,30 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="/README.md">English</a>
|
||||
|
|
||||
<a href="/README-fr.md">Français</a>
|
||||
|
|
||||
<a href="/README-de.md">Deutsch</a>
|
||||
|
|
||||
<a href="/README-es.md">Español</a>
|
||||
|
|
||||
<a href="/README-ja.md">日本語</a>
|
||||
|
|
||||
<a href="/README-ko.md">한국어</a>
|
||||
|
|
||||
<a href="/README-zh-tw.md">繁體中文</a>
|
||||
|
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**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.
|
||||
**XPack** is the world’s first open-source MCP marketplace, to quickly create and sell your own MCP services in just minutes.
|
||||
|
||||
<br>
|
||||
|
||||
✨ With XPack, you can:
|
||||
- ✅ **One-click OpenAPI → MCP service config**
|
||||
- 🧾 **SEO-friendly homepage + mcp service page**
|
||||
- 💳 **Built-in billing (per-call)**
|
||||
- 💳 **Built-in billing (per-call or token usage)**
|
||||
- 👥 **User account management**
|
||||
- 🛠 **Support Stripe Payment**
|
||||
- 🔐 **Support Email & Google OAuth Sign in**
|
||||
@@ -29,9 +40,12 @@ Everything is open-source and licensed under **Apache 2.0** — ready for commer
|
||||
😍 Deploying XPack is incredibly simple. With just one command line, you can deploy your MCP Market in 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=XHJXyvDevd8)
|
||||
|
||||
|
||||
<br>
|
||||
|
||||
|
||||
@@ -83,7 +97,7 @@ Ensure these services are available and properly configured before running the b
|
||||
😍 Deploying XPack is incredibly simple. With just one command line, you can deploy your MCP Market in 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
@@ -178,7 +192,7 @@ curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
|
||||
4. Access `XPack-MCP-Market` in your browser at port 3000
|
||||
|
||||
* **Admin User Login Address**: http://{IP}:3000/admin-signin
|
||||
* **Admin User Login Address**: http://{IP}:3000/admin
|
||||
* **Admin User**: admin
|
||||
* **Admin Password**: 123456789
|
||||
</details>
|
||||
@@ -281,3 +295,44 @@ For details, please see the [LICENSE](./LICENSE) file.
|
||||
- 🌐 Website: [https://xpack.ai](https://xpack.ai)
|
||||
- 📧 Email: [contact@xpack.com](mailto:contact@xpack.com)
|
||||
- 💬 Discord:[Link](https://discord.gg/cyZfcdCXkW)
|
||||
|
||||
<br>
|
||||
|
||||
# 🤝 Partner
|
||||
- [Cursor](https://www.cursor.com/): Cursor is an AI-powered code editor that integrates artificial intelligence directly into the coding workflow, offering features like intelligent next edit suggestions, deep codebase understanding for relevant answers, and natural language editing to streamline development tasks and boost developer productivity.
|
||||
|
||||
- [Dify](https://dify.ai/): Dify is a leading Agentic AI Development Platform that provides a comprehensive suite of tools for building and extending AI applications, offering everything needed for agentic workflows, RAG pipelines, integrations, and observability, while allowing users to amplify their applications with various global Large Language Models (LLMs) and versatile plugins.
|
||||
|
||||
- [Trae](https://www.trae.ai/): Trae is an AI-native Integrated Development Environment (IDE) product that aims to embody the concept of “The Real AI Engineer” through intelligent productivity, seamlessly integrating into the development process to enhance quality and efficiency, featuring a chat-based interaction interface and supporting code generation and assistance.
|
||||
|
||||
- [Windsurf](https://windsurf.com/): Windsurf is an AI code editor designed to provide a seamless and limitless flow for developers, introducing a new purpose-built IDE that leverages AI to enhance coding with features like "Cascade" for deep codebase understanding, "Windsurf Tab" for intelligent autocompletion, and "Memories" for remembering important aspects of the codebase.
|
||||
|
||||
- [Coze](https://www.coze.com/): Coze is a next-generation AI application and chatbot development platform by ByteDance, empowering users to easily create and deploy powerful AI chatbots across various platforms with a no-code bot builder, integrated workflow logic, access to proprietary data, and simplified creation through pre-built plugins, knowledge bases, and workflows.
|
||||
|
||||
- [Claude Code](https://www.anthropic.com/claude-code): Claude Code is a command-line AI tool by Anthropic that embeds the Claude Opus 4 model directly into the user’s terminal, providing deep codebase awareness, the ability to edit files and execute commands, and making coordinated changes across multiple files, all while integrating seamlessly with popular IDEs and leveraging existing test suites.
|
||||
|
||||
- [Flowith](https://flowith.io/): Flowith is an AI creation workspace designed to revolutionize productivity and deep work by transforming knowledge and streamlining tasks through a multi-thread interface powered by advanced AI agents, offering an intuitive canvas-based user experience unlike traditional chat-based AI tools, and including a 24/7 operational version for complex tasks.
|
||||
|
||||
- [OpenManus](https://github.com/FoundationAgents/OpenManus): OpenManus is an open-source framework dedicated to building general AI agents, aiming to provide a platform where users can create and deploy their own agents without an invite code, supporting multi-agent capabilities, and requiring configuration for Large Language Model (LLM) APIs while integrating with browser automation tools.
|
||||
|
||||
- [Fellou](https://fellou.ai/): Fellou is an innovative Agentic Browser designed to transcend traditional web browsing by actively performing actions on behalf of the user, automating the entire process of information gathering and insight delivery, and excelling in in-depth research with seamless integrations with popular tools like Notion and LinkedIn.
|
||||
|
||||
- [Genspark](https://www.genspark.ai/): Genspark is an ultimate all-in-one AI companion offering a comprehensive suite of tools like AI Slides, AI Sheets, and AI Chat, designed to enhance various aspects of productivity and content creation, with personalized tools and AI Pods for generating content from diverse sources.
|
||||
|
||||
- [TEN](https://github.com/TEN-framework/ten-framework): TEN (The Embodied Narrator) is an open-source framework for building real-time, multimodal conversational voice AI agents, including components like TEN Framework, TEN Turn Detection, TEN Agent, TMAN Designer, and TEN Portal, offering features like Real-time Avatar, seamless MCP integration, real-time hardware communication, and vision/screenshare detection.
|
||||
|
||||
- [APIPark](https://apipark.com/): APIPark is an open-source enterprise API developer portal and an all-in-one LLM gateway, providing fine-grained, visual management of LLMs in production environments with features like unified API signatures, load balancing, traffic control, intelligent semantic caching, flexible prompt management, and data masking, ensuring safer and more stable LLM calls.
|
||||
|
||||
- [ChatGPT](https://chatgpt.com/): ChatGPT is an AI chatbot developed by OpenAI, built upon large language models like GPT-3.5 and GPT-4, designed to generate human-like conversational dialogue, understand context, answer follow-up questions, and integrate with various platforms for enhanced productivity through advanced language understanding, generation, and multilingual capabilities.
|
||||
|
||||
- [LangChain](https://www.langchain.com/): LangChain is a robust platform engineered for the development of reliable agents and Large Language Model (LLM) applications, offering a comprehensive product suite that seamlessly integrates various tools across the entire application development lifecycle, including LangGraph, LangSmith, and the LangGraph Platform, with functionalities for code generation, automation, and AI Search.
|
||||
|
||||
- [LEMON AI](https://lemonai.cc/): Lemon AI is the first Full-stack, Open-source, Agentic AI framework, offering a fully local alternative to platforms like Manus & Genspark AI. It features an integrated Code Interpreter VM sandbox for safe execution.
|
||||
|
||||
- [LobeChat](https://lobehub.com/): LobeHub offers LobeChat, a personal LLM productivity tool designed to elevate the user experience beyond traditional chatbots by empowering individuals to build personal AI agents and professional teams, supporting a wide array of LLMs, offering a simple chat interface, visual recognition, voice interaction, a rich plugin ecosystem, and knowledge base functionalities.
|
||||
|
||||
- [VS Code](https://code.visualstudio.com/): Visual Studio Code (VS Code) is a widely popular, free, and open-source code editor by Microsoft, renowned for its extensibility and customization, supporting vast programming languages, and integrating AI capabilities like intelligent next edit suggestions and an advanced “agent mode” for complex tasks, with broad compatibility with various AI models.
|
||||
|
||||
- [XRoute](https://xroute.ai): The Unified Interface For LLMs, provides better prices, better throughput, and no subscription.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU is an open-source memory framework for AI companions
|
||||
@@ -42,10 +42,6 @@ const nextConfig = {
|
||||
key: "X-Content-Type-Options",
|
||||
value: "nosniff",
|
||||
},
|
||||
{
|
||||
key: "X-Frame-Options",
|
||||
value: "DENY",
|
||||
},
|
||||
{
|
||||
key: "X-XSS-Protection",
|
||||
value: "1; mode=block",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"Featured Packages": "Featured Packages",
|
||||
"Individual Tools": "Individual Tools",
|
||||
"Details": "Details",
|
||||
"Copy code": "Copy code",
|
||||
"excel": "Excel",
|
||||
"data": "Data",
|
||||
"analysis": "Analysis",
|
||||
@@ -198,6 +199,27 @@
|
||||
"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",
|
||||
"MCP Server Domain": "MCP Server Domain",
|
||||
"Enter MCP server domain (e.g., api.example.com)": "Enter MCP server domain (e.g., api.example.com)",
|
||||
"The domain for MCP server API calls": "The domain for MCP server API calls",
|
||||
"Featured in the XPack showcase": "Featured in the XPack showcase",
|
||||
"Enable this option to feature your site in the XPack global showcase and reach users worldwide.": "Enable this option to feature your site in the XPack global showcase and reach users worldwide.",
|
||||
"Please enter a platform domain before enabling showcase": "Please enter a platform domain before enabling showcase",
|
||||
"FAQ Management": "FAQ Management",
|
||||
"Configure frequently asked questions for your users": "Configure frequently asked questions for your users",
|
||||
"FAQ List": "FAQ List",
|
||||
"Edit questions and answers directly in the table below": "Edit questions and answers directly in the table below",
|
||||
"Save All": "Save All",
|
||||
"Order": "Order",
|
||||
"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",
|
||||
@@ -234,6 +256,8 @@
|
||||
"Failed to parse OpenAPI document": "Failed to parse OpenAPI document",
|
||||
"OpenAPI document parsed successfully": "OpenAPI document parsed successfully",
|
||||
"Please enter a valid URL": "Please enter a valid URL",
|
||||
"Please enter a valid URL with http:// or https://": "Please enter a valid URL with http:// or https://",
|
||||
"Please fix validation errors before saving": "Please fix validation errors before saving",
|
||||
"Please select a file": "Please select a file",
|
||||
"File uploaded successfully": "File uploaded successfully",
|
||||
"Failed to upload file": "Failed to upload file",
|
||||
@@ -306,6 +330,14 @@
|
||||
"All Roles": "All Roles",
|
||||
"Ban User": "Ban User",
|
||||
"Unban User": "Unban User",
|
||||
"Recharge User": "Recharge User",
|
||||
"Current Balance": "Current Balance",
|
||||
"User recharged successfully": "User recharged successfully",
|
||||
"Please enter a valid amount": "Please enter a valid amount",
|
||||
"Minimum recharge amount is $1": "Minimum recharge amount is $1",
|
||||
"User not selected": "User not selected",
|
||||
"Recharge failed": "Recharge failed",
|
||||
"Network error, please try again": "Network error, please try again",
|
||||
"Delete User": "Delete User",
|
||||
"View Profile": "View Profile",
|
||||
"Edit User": "Edit User",
|
||||
@@ -386,12 +418,20 @@
|
||||
"Failed to test Google auth": "Failed to test Google auth",
|
||||
"Failed to fetch Stripe config": "Failed to fetch Stripe config",
|
||||
"Failed to save Stripe config": "Failed to save Stripe config",
|
||||
"Failed to save Alipay config": "Failed to save Alipay config",
|
||||
"Failed to save WeChat config": "Failed to save WeChat config",
|
||||
"Stripe connection test failed": "Stripe connection test failed",
|
||||
"Stripe connection test successful": "Stripe connection test successful",
|
||||
"Alipay connection test successful": "Alipay connection test successful",
|
||||
"Alipay connection test failed": "Alipay connection test failed",
|
||||
"WeChat connection test successful": "WeChat connection test successful",
|
||||
"WeChat connection test failed": "WeChat connection test failed",
|
||||
"Connection test failed": "Connection test failed",
|
||||
"Unknown error": "Unknown error",
|
||||
"Secret Key cannot be empty": "Secret Key cannot be empty",
|
||||
"Stripe Configuration": "Stripe Configuration",
|
||||
"Alipay Configuration": "Alipay Configuration",
|
||||
"WeChat Configuration": "WeChat Configuration",
|
||||
"Google Login Settings": "Google Login Settings",
|
||||
"Enable Google Login": "Enable Google Login",
|
||||
"Administrator Account": "Administrator Account",
|
||||
@@ -533,8 +573,19 @@
|
||||
"Billing Mode": "Billing Mode",
|
||||
"Enable free quota": "Enable free quota",
|
||||
"Configure Stripe payment interface": "Configure Stripe payment interface",
|
||||
"Configure Alipay payment interface": "Configure Alipay payment interface",
|
||||
"Configure WeChat payment interface": "Configure WeChat payment interface",
|
||||
"Secret Key": "Secret Key",
|
||||
"Stripe secret key for server-side API calls": "Stripe secret key for server-side API calls",
|
||||
"App ID": "App ID",
|
||||
"Alipay App ID": "Alipay App ID",
|
||||
"App Private Key": "App Private Key",
|
||||
"Alipay App Private Key": "Alipay App Private Key",
|
||||
"Alipay Public Key": "Alipay Public Key",
|
||||
"Alipay public key for verification": "Alipay public key for verification",
|
||||
"WeChat App ID": "WeChat App ID",
|
||||
"Merchant ID": "Merchant ID",
|
||||
"WeChat Merchant ID": "WeChat Merchant ID",
|
||||
"Webhook Secret": "Webhook Secret",
|
||||
"Test Connection": "Test Connection",
|
||||
"Monitor platform revenue and view user recharge history": "Monitor platform revenue and view user recharge history",
|
||||
@@ -593,6 +644,7 @@
|
||||
"Confirm": "Confirm",
|
||||
"Recharge Account": "Recharge Account",
|
||||
"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}}",
|
||||
@@ -633,6 +685,12 @@
|
||||
"Total Revenue": "Total Revenue",
|
||||
"Failed to save stripe config": "Failed to save stripe config",
|
||||
"Stripe config saved successfully": "Stripe config saved successfully",
|
||||
"Alipay config saved successfully": "Alipay config saved successfully",
|
||||
"WeChat config saved successfully": "WeChat config saved successfully",
|
||||
"Failed to save {{channelName}} config": "Failed to save {{channelName}} config",
|
||||
"{{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",
|
||||
@@ -727,5 +785,92 @@
|
||||
"Theme changed successfully": "Theme changed successfully",
|
||||
"Failed to change theme": "Failed to change theme",
|
||||
"About page saved successfully": "About page saved successfully",
|
||||
"Failed to save about page": "Failed to save about page"
|
||||
"Failed to save about page": "Failed to save about page",
|
||||
"General": "General",
|
||||
"Homepage": "Homepage",
|
||||
"Homepage content and theme settings": "Homepage content and theme settings",
|
||||
"About Page": "About Page",
|
||||
"About page content configuration": "About page content configuration",
|
||||
"Email & Admin": "Email & Admin",
|
||||
"Email and administrator settings": "Email and administrator settings",
|
||||
"Embedded HTML": "Embedded HTML",
|
||||
"Configure custom HTML content for global injection": "Configure custom HTML content for global injection",
|
||||
"Enable Custom HTML": "Enable Custom HTML",
|
||||
"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.",
|
||||
"Usage Instructions": "Usage Instructions",
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts": "You can include Google Analytics, custom CSS, or any tracking scripts",
|
||||
"The HTML will be injected into the document head section": "The HTML will be injected into the document head section",
|
||||
"Make sure your code is valid to avoid breaking the application": "Make sure your code is valid to avoid breaking the application",
|
||||
"Changes take effect immediately after saving and enabling": "Changes take effect immediately after saving and enabling",
|
||||
"Welcome to Your Platform": "Welcome to Your Platform",
|
||||
"Let's set up your platform with some basic information": "Let's set up your platform with some basic information",
|
||||
"Information needed": "Information needed",
|
||||
"Fields marked with * are required": "Fields marked with * are required",
|
||||
"Website title is required": "Website title is required",
|
||||
"Headline is required": "Headline is required",
|
||||
"Subheadline is required": "Subheadline is required",
|
||||
"Please fill in all required fields": "Please fill in all required fields",
|
||||
"Setup failed. Please try again.": "Setup failed. Please try again.",
|
||||
"Complete Setup": "Complete Setup",
|
||||
"Platform setup completed successfully!": "Platform setup completed successfully!",
|
||||
"Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.": "Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.",
|
||||
"Please provide the following information. Do not worry, you can always change these settings later in the admin panel.": "Please provide the following information. Do not worry, you can always change these settings later in the admin panel.",
|
||||
"Failed to update homepage config": "Failed to update homepage config",
|
||||
"Homepage config updated successfully": "Homepage config updated successfully",
|
||||
"Failed to load homepage config": "Failed to load homepage config",
|
||||
"FAQ updated successfully": "FAQ updated successfully",
|
||||
"Navigation updated successfully": "Navigation updated successfully",
|
||||
"Embedded HTML updated successfully": "Embedded HTML updated successfully",
|
||||
"Payment channels updated successfully": "Payment channels updated successfully",
|
||||
"Manage frequently asked questions": "Manage frequently asked questions",
|
||||
"Add FAQ Item": "Add FAQ Item",
|
||||
"Remove FAQ Item": "Remove FAQ Item",
|
||||
"Top Navigation": "Top Navigation",
|
||||
"Manage top navigation links": "Manage top navigation links",
|
||||
"Title": "Title",
|
||||
"Link": "Link",
|
||||
"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",
|
||||
"Enable embedded HTML": "Enable embedded HTML",
|
||||
"HTML Content": "HTML Content",
|
||||
"Enter custom HTML code": "Enter custom HTML code",
|
||||
"Manage payment methods": "Manage payment methods",
|
||||
"Channel ID": "Channel ID",
|
||||
"Display Name": "Display Name",
|
||||
"Add Payment Channel": "Add Payment Channel",
|
||||
"Remove Payment Channel": "Remove Payment Channel",
|
||||
"Enter channel ID": "Enter channel ID",
|
||||
"Enter display name": "Enter display name",
|
||||
"Installation Status": "Installation Status",
|
||||
"First time installation": "First time installation",
|
||||
"System installed": "System installed",
|
||||
"Configure top navigation menu items and links": "Configure top navigation menu items and links",
|
||||
"Per Million Tokens": "Per Million Tokens",
|
||||
"Price per million tokens consumed": "Price per million tokens consumed",
|
||||
"Price per million tokens": "Price per million tokens",
|
||||
"Price per API call": "Price per API call",
|
||||
"Payment channel disabled successfully": "Payment channel disabled successfully",
|
||||
"Failed to disable payment channel": "Failed to disable payment channel",
|
||||
"Payment channel enabled successfully": "Payment channel enabled successfully",
|
||||
"Failed to enable payment channel": "Failed to enable payment channel",
|
||||
"Input Token Price": "Input Token Price",
|
||||
"Output Token Price": "Output Token Price",
|
||||
"Price per million input tokens": "Price per million input tokens",
|
||||
"Price per million output tokens": "Price per million output tokens",
|
||||
"Input": "Input",
|
||||
"Output": "Output",
|
||||
"1M tokens": "1M tokens",
|
||||
"Total Spending": "Total Spending"
|
||||
}
|
||||
@@ -40,6 +40,7 @@
|
||||
"Featured Packages": "精选工具包",
|
||||
"Individual Tools": "单个工具",
|
||||
"Details": "详情",
|
||||
"Copy code": "复制代码",
|
||||
"excel": "Excel",
|
||||
"data": "数据",
|
||||
"analysis": "分析",
|
||||
@@ -199,6 +200,27 @@
|
||||
"Tool name": "工具名称",
|
||||
"Tool description": "工具描述",
|
||||
"Take Offline": "下线",
|
||||
"Platform Domain": "平台域名",
|
||||
"Enter platform domain (e.g., example.com)": "输入平台域名(例如:example.com)",
|
||||
"The domain name of your platform": "您平台的域名",
|
||||
"MCP Server Domain": "MCP 服务器域名",
|
||||
"Enter MCP server domain (e.g., api.example.com)": "输入 MCP 服务器域名(例如:api.example.com)",
|
||||
"The domain for MCP server API calls": "用于 MCP 服务器 API 调用的域名",
|
||||
"Featured in the XPack showcase": "展示在 XPack 的全球案例榜单",
|
||||
"Enable this option to feature your site in the XPack global showcase and reach users worldwide.": "当开启选项,你的网站会展示在 XPack 的全球案例榜单来获得全球用户的关注。",
|
||||
"Please enter a platform domain before enabling showcase": "启用展示功能前请先输入平台域名",
|
||||
"FAQ Management": "FAQ管理",
|
||||
"Configure frequently asked questions for your users": "为您的用户配置常见问题",
|
||||
"FAQ List": "FAQ列表",
|
||||
"Edit questions and answers directly in the table below": "在下方表格中直接编辑问题和答案",
|
||||
"Save All": "保存全部",
|
||||
"Order": "排序",
|
||||
"Question": "问题",
|
||||
"Answer": "答案",
|
||||
"No FAQ items available.": "暂无FAQ项目。",
|
||||
"Enter question": "输入问题",
|
||||
"Enter answer": "输入答案",
|
||||
"Insert below": "在下方插入",
|
||||
"Bring Online": "上线",
|
||||
"Short Description": "简短描述",
|
||||
"Long Description": "详细描述",
|
||||
@@ -235,6 +257,8 @@
|
||||
"Failed to parse OpenAPI document": "解析 OpenAPI 文档失败",
|
||||
"OpenAPI document parsed successfully": "OpenAPI 文档解析成功",
|
||||
"Please enter a valid URL": "请输入有效的 URL",
|
||||
"Please enter a valid URL with http:// or https://": "请输入有效的 URL,需要包含 http:// 或 https://",
|
||||
"Please fix validation errors before saving": "请修复验证错误后再保存",
|
||||
"Please select a file": "请选择文件",
|
||||
"File uploaded successfully": "文件上传成功",
|
||||
"Failed to upload file": "文件上传失败",
|
||||
@@ -307,6 +331,14 @@
|
||||
"All Roles": "所有角色",
|
||||
"Ban User": "封禁用户",
|
||||
"Unban User": "解封用户",
|
||||
"Recharge User": "为用户充值",
|
||||
"Current Balance": "当前余额",
|
||||
"User recharged successfully": "用户充值成功",
|
||||
"Please enter a valid amount": "请输入有效金额",
|
||||
"Minimum recharge amount is $1": "最低充值金额为 $1",
|
||||
"User not selected": "未选择用户",
|
||||
"Recharge failed": "充值失败",
|
||||
"Network error, please try again": "网络错误,请重试",
|
||||
"Delete User": "删除用户",
|
||||
"View Profile": "查看资料",
|
||||
"Edit User": "编辑用户",
|
||||
@@ -387,12 +419,20 @@
|
||||
"Failed to test Google auth": "测试Google认证失败",
|
||||
"Failed to fetch Stripe config": "获取Stripe配置失败",
|
||||
"Failed to save Stripe config": "保存Stripe配置失败",
|
||||
"Failed to save Alipay config": "保存支付宝配置失败",
|
||||
"Failed to save WeChat config": "保存微信配置失败",
|
||||
"Stripe connection test failed": "Stripe连接测试失败",
|
||||
"Stripe connection test successful": "Stripe连接测试成功",
|
||||
"Alipay connection test successful": "支付宝连接测试成功",
|
||||
"Alipay connection test failed": "支付宝连接测试失败",
|
||||
"WeChat connection test successful": "微信连接测试成功",
|
||||
"WeChat connection test failed": "微信连接测试失败",
|
||||
"Connection test failed": "连接测试失败",
|
||||
"Unknown error": "未知错误",
|
||||
"Secret Key cannot be empty": "密钥不能为空",
|
||||
"Stripe Configuration": "Stripe配置",
|
||||
"Alipay Configuration": "支付宝配置",
|
||||
"WeChat Configuration": "微信配置",
|
||||
"Google Login Settings": "Google登录设置",
|
||||
"Enable Google Login": "启用Google登录",
|
||||
"Administrator Account": "管理员账户",
|
||||
@@ -535,6 +575,17 @@
|
||||
"Billing Mode": "计费模式",
|
||||
"Enable free quota": "启用免费配额",
|
||||
"Configure Stripe payment interface": "配置Stripe支付接口",
|
||||
"Configure Alipay payment interface": "配置支付宝支付接口",
|
||||
"Configure WeChat payment interface": "配置微信支付接口",
|
||||
"App ID": "应用ID",
|
||||
"Alipay App ID": "支付宝应用ID",
|
||||
"App Private Key": "应用私钥",
|
||||
"Alipay App Private Key": "支付宝应用私钥",
|
||||
"Alipay Public Key": "支付宝公钥",
|
||||
"Alipay public key for verification": "支付宝公钥用于验证",
|
||||
"WeChat App ID": "微信应用ID",
|
||||
"Merchant ID": "商户号",
|
||||
"WeChat Merchant ID": "微信商户号",
|
||||
"Secret Key": "密钥",
|
||||
"Stripe secret key for server-side API calls": "用于服务端API调用的Stripe密钥",
|
||||
"Webhook Secret": "Webhook密钥",
|
||||
@@ -594,7 +645,8 @@
|
||||
"WeChat Pay": "微信支付",
|
||||
"Confirm": "确认",
|
||||
"Recharge Account": "充值账户",
|
||||
"Funds will be added to your account balance": "资金将添加到您的账户余额",
|
||||
"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}}",
|
||||
@@ -609,6 +661,10 @@
|
||||
"Failed to toggle service status": "切换服务状态失败",
|
||||
"Stripe configuration saved successfully": "Stripe 配置保存成功",
|
||||
"Failed to save Stripe configuration": "保存 Stripe 配置失败",
|
||||
"Failed to save {{channelName}} config": "保存{{channelName}}配置失败",
|
||||
"{{channelName}} config saved successfully": "{{channelName}}配置保存成功",
|
||||
"{{channelName}} connection test failed": "{{channelName}}连接测试失败",
|
||||
"{{channelName}} connection test successful": "{{channelName}}连接测试成功",
|
||||
"System config updated successfully": "系统配置更新成功",
|
||||
"Failed to update system config": "更新系统配置失败",
|
||||
"Confirm Purchase": "确认购买",
|
||||
@@ -635,6 +691,8 @@
|
||||
"Total Revenue": "总收入",
|
||||
"Failed to save stripe config": "保存 Stripe 配置失败",
|
||||
"Stripe config saved successfully": "Stripe 配置保存成功",
|
||||
"Alipay config saved successfully": "支付宝配置保存成功",
|
||||
"WeChat config saved successfully": "微信配置保存成功",
|
||||
"Login successful": "登录成功",
|
||||
"Logged out successfully": "退出登录成功",
|
||||
"Configure email settings": "配置邮箱设置",
|
||||
@@ -729,5 +787,92 @@
|
||||
"Theme changed successfully": "主题切换成功",
|
||||
"Failed to change theme": "主题切换失败",
|
||||
"About page saved successfully": "关于页面保存成功",
|
||||
"Failed to save about page": "关于页面保存失败"
|
||||
"Failed to save about page": "关于页面保存失败",
|
||||
"General": "常规设置",
|
||||
"Homepage": "首页设置",
|
||||
"Homepage content and theme settings": "首页内容和主题设置",
|
||||
"About Page": "关于页面",
|
||||
"About page content configuration": "关于页面内容配置",
|
||||
"Email & Admin": "邮箱与管理员",
|
||||
"Email and administrator settings": "邮箱和管理员设置",
|
||||
"Embedded HTML": "嵌入式HTML",
|
||||
"Configure custom HTML content for global injection": "配置自定义HTML内容进行全局注入",
|
||||
"Enable Custom HTML": "启用自定义HTML",
|
||||
"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将在保存并启用后渲染。",
|
||||
"Usage Instructions": "使用说明",
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts": "您可以包含Google Analytics、自定义CSS或任何跟踪脚本",
|
||||
"The HTML will be injected into the document head section": "HTML将注入到文档头部分",
|
||||
"Make sure your code is valid to avoid breaking the application": "确保您的代码有效,以避免破坏应用程序",
|
||||
"Changes take effect immediately after saving and enabling": "更改在保存并启用后立即生效",
|
||||
"Welcome to Your Platform": "欢迎使用您的平台",
|
||||
"Let's set up your platform with some basic information": "让我们用一些基本信息来设置您的平台",
|
||||
"Fields marked with * are required": "标有 * 的字段为必填项",
|
||||
"Website title is required": "网站标题为必填项",
|
||||
"Headline is required": "标题为必填项",
|
||||
"Subheadline is required": "副标题为必填项",
|
||||
"Please fill in all required fields": "请填写所有必填字段",
|
||||
"Setup failed. Please try again.": "设置失败,请重试。",
|
||||
"Complete Setup": "完成设置",
|
||||
"Platform setup completed successfully!": "平台设置成功完成!",
|
||||
"Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.": "欢迎使用著名的五分钟平台设置流程!只需填写下面的信息,您就可以开始使用最具扩展性和功能强大的平台了。",
|
||||
"Information needed": "所需信息",
|
||||
"Please provide the following information. Do not worry, you can always change these settings later in the admin panel.": "请提供以下信息。不用担心,您随时可以在管理面板中更改这些设置。",
|
||||
"Failed to update homepage config": "更新主页配置失败",
|
||||
"Homepage config updated successfully": "主页配置更新成功",
|
||||
"Failed to load homepage config": "加载主页配置失败",
|
||||
"FAQ updated successfully": "常见问题更新成功",
|
||||
"Navigation updated successfully": "导航更新成功",
|
||||
"Embedded HTML updated successfully": "嵌入HTML更新成功",
|
||||
"Payment channels updated successfully": "支付渠道更新成功",
|
||||
"Manage frequently asked questions": "管理常见问题",
|
||||
"Add FAQ Item": "添加常见问题",
|
||||
"Remove FAQ Item": "删除常见问题",
|
||||
"Top Navigation": "顶部导航",
|
||||
"Manage top navigation links": "管理顶部导航链接",
|
||||
"Title": "标题",
|
||||
"Link": "链接",
|
||||
"Target": "目标",
|
||||
"Add Navigation Item": "添加导航项",
|
||||
"Remove Navigation Item": "删除导航项",
|
||||
"Enter title": "输入标题",
|
||||
"Enter link URL": "输入链接地址",
|
||||
"Same window": "当前窗口",
|
||||
"New window": "新窗口",
|
||||
"Custom HTML injection": "自定义HTML注入",
|
||||
"Enable embedded HTML": "启用嵌入HTML",
|
||||
"HTML Content": "HTML内容",
|
||||
"Enter custom HTML code": "输入自定义HTML代码",
|
||||
"Manage payment methods": "管理支付方式",
|
||||
"Channel ID": "渠道ID",
|
||||
"Display Name": "显示名称",
|
||||
"Add Payment Channel": "添加支付渠道",
|
||||
"Remove Payment Channel": "删除支付渠道",
|
||||
"Enter channel ID": "输入渠道ID",
|
||||
"Enter display name": "输入显示名称",
|
||||
"Installation Status": "安装状态",
|
||||
"First time installation": "首次安装",
|
||||
"System installed": "系统已安装",
|
||||
"Configure top navigation menu items and links": "配置顶部导航菜单项和链接",
|
||||
"Per Million Tokens": "每百万Token",
|
||||
"Price per million tokens consumed": "每百万Token消耗的价格",
|
||||
"Price per million tokens": "每百万Token价格",
|
||||
"Price per API call": "每次API调用价格",
|
||||
"Payment channel disabled successfully": "支付渠道禁用成功",
|
||||
"Failed to disable payment channel": "禁用支付渠道失败",
|
||||
"Payment channel enabled successfully": "支付渠道启用成功",
|
||||
"Failed to enable payment channel": "启用支付渠道失败",
|
||||
"Input Token Price": "输入Token价格",
|
||||
"Output Token Price": "输出Token价格",
|
||||
"Price per million input tokens": "每百万输入Token价格",
|
||||
"Price per million output tokens": "每百万输出Token价格",
|
||||
"Input": "输入",
|
||||
"Output": "输出",
|
||||
"1M tokens": "1M tokens",
|
||||
"Total Spending": "总支出"
|
||||
}
|
||||
@@ -32,6 +32,13 @@ 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>
|
||||
<ClientRootProviders initConfig={platformConfig}>
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import React, { Suspense } from "react";
|
||||
import { MarketplaceMain } from "@/components/marketplace/Main";
|
||||
import React from "react";
|
||||
import type { Metadata } from "next";
|
||||
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
|
||||
import { Navigation } from "@/shared/components/Navigation";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { fetchServices } from "@/services/marketplaceService";
|
||||
import type { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ThemeSelector } from "@/components/theme/ThemeSelector";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const title = await getDynamicTitle("Marketplace");
|
||||
const title = await getDynamicTitle();
|
||||
return createBaseMetadata(title);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useState } from "react";
|
||||
import { EmailConfigForm } from "@/components/login-setting/EmailConfigForm";
|
||||
import { GoogleAuthConfigForm } from "@/components/login-setting/GoogleAuthConfigForm";
|
||||
import { useSystemConfigManagement } from "@/hooks/useSystemConfigManagement";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { LoginConfig, GoogleAuthConfig } from "@/shared/types/system";
|
||||
import { TabKey } from "@/shared/types/dashboard";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { EmailConfig } from "@/types/system";
|
||||
|
||||
interface LoginSettingsContentProps {
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
loginConfig: LoginConfig;
|
||||
saveLoginConfig: (config: LoginConfig) => Promise<boolean>;
|
||||
emailConfig: EmailConfig;
|
||||
}
|
||||
|
||||
export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
onTabNavigate,
|
||||
loginConfig,
|
||||
saveLoginConfig,
|
||||
emailConfig,
|
||||
}) => {
|
||||
const [googleSubmitLoading, setGoogleSubmitLoading] = useState(false);
|
||||
const [emailSubmitLoading, setEmailSubmitLoading] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
const { updateClientConfig } = usePlatformConfig();
|
||||
|
||||
const {
|
||||
// login config
|
||||
loginConfig,
|
||||
loginLoading,
|
||||
saveLoginConfig,
|
||||
|
||||
// email config
|
||||
emailConfig,
|
||||
|
||||
// platform config
|
||||
platformConfig,
|
||||
} = useSystemConfigManagement();
|
||||
|
||||
// 验证至少有一种登录方式启用
|
||||
// check if at least one login method is enabled
|
||||
const validateLoginMethods = (config: LoginConfig): boolean => {
|
||||
const isGoogleEnabled =
|
||||
config.google?.is_enabled && config.google?.client_id;
|
||||
const isGoogleEnabled = config.google?.is_enabled;
|
||||
const isEmailEnabled = config.email?.is_enabled;
|
||||
|
||||
const enabledCount = [isGoogleEnabled, isEmailEnabled].filter(
|
||||
@@ -57,12 +51,13 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
setEmailSubmitLoading(true);
|
||||
const result = await saveLoginConfig(config);
|
||||
if (!result) return;
|
||||
updateClientConfig({
|
||||
platform: platformConfig,
|
||||
login: config,
|
||||
});
|
||||
setEmailSubmitLoading(false);
|
||||
};
|
||||
|
||||
// save google auth config
|
||||
@@ -76,22 +71,23 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
setGoogleSubmitLoading(true);
|
||||
const result = await saveLoginConfig(updatedLoginConfig);
|
||||
if (!result) return;
|
||||
updateClientConfig({
|
||||
platform: platformConfig,
|
||||
login: updatedLoginConfig,
|
||||
});
|
||||
setGoogleSubmitLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 w-full">
|
||||
<div className="space-y-4 w-full">
|
||||
{/* email config */}
|
||||
<EmailConfigForm
|
||||
config={loginConfig}
|
||||
emailConfig={emailConfig}
|
||||
onSave={handleSaveLoginConfig}
|
||||
isLoading={loginLoading}
|
||||
isLoading={emailSubmitLoading}
|
||||
onTabNavigate={onTabNavigate}
|
||||
/>
|
||||
|
||||
@@ -99,7 +95,7 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
<GoogleAuthConfigForm
|
||||
config={loginConfig.google}
|
||||
onSave={handleSaveGoogleAuthConfig}
|
||||
isLoading={loginLoading}
|
||||
isLoading={googleSubmitLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import React, { useEffect, useState, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAdminStore } from "@/store/admin";
|
||||
import DashboardSidebar from "@/shared/components/DashboardSidebar";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import ConsoleStats from "@/components/console/ConsoleStats";
|
||||
import PaymentChannelsContent from "@/components/console/PaymentChannelsContent";
|
||||
@@ -15,17 +14,14 @@ import { MCPServicesManagement } from "@/components/mcp-services/MCPServicesMana
|
||||
import UserManagement from "@/components/user-management/UserManagement";
|
||||
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
|
||||
import {
|
||||
Cog,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
Home,
|
||||
Settings,
|
||||
Users,
|
||||
LogIn,
|
||||
ServerIcon,
|
||||
} from "lucide-react";
|
||||
import { LoginSettingsContent } from "@/components/console/LoginSettingsContent";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { FaDiscord } from "react-icons/fa";
|
||||
import ConsoleSidebar from "./Sidebar";
|
||||
|
||||
const ConsoleContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -33,6 +29,8 @@ const ConsoleContent: React.FC = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const [admin_token] = useAdminStore((state) => [state.admin_token]);
|
||||
|
||||
const _DefaultSubTab = "general";
|
||||
|
||||
const getInitialTab = (): TabKey => {
|
||||
const tabFromUrl = searchParams.get("tab") as TabKey;
|
||||
if (
|
||||
@@ -51,49 +49,79 @@ const ConsoleContent: React.FC = () => {
|
||||
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 sidebarItems: SidebarItem[] = [
|
||||
{
|
||||
key: TabKey.CONSOLE,
|
||||
icon: <Home className="w-5 h-5" />,
|
||||
icon: <Home size={18} />,
|
||||
label: t("Dashboard"),
|
||||
description: t("Overview and analytics"),
|
||||
},
|
||||
{
|
||||
key: TabKey.MCP_SERVICES,
|
||||
icon: <Settings className="w-5 h-5" />,
|
||||
icon: <ServerIcon size={18} />,
|
||||
label: t("MCP Services"),
|
||||
description: t("Manage MCP services and API tools"),
|
||||
},
|
||||
{
|
||||
key: TabKey.USER_MANAGEMENT,
|
||||
icon: <Users className="w-5 h-5" />,
|
||||
icon: <Users size={18} />,
|
||||
label: t("User Management"),
|
||||
description: t("Manage registered users"),
|
||||
},
|
||||
{
|
||||
key: TabKey.REVENUE_MANAGEMENT,
|
||||
icon: <DollarSign className="w-5 h-5" />,
|
||||
icon: <DollarSign size={18} />,
|
||||
label: t("Revenue Management"),
|
||||
description: t("View user recharge history"),
|
||||
},
|
||||
{
|
||||
key: TabKey.PAYMENT_CHANNELS,
|
||||
icon: <CreditCard className="w-5 h-5" />,
|
||||
icon: <CreditCard size={18} />,
|
||||
label: t("Payment Channels"),
|
||||
description: t("Configure payment channels"),
|
||||
},
|
||||
{
|
||||
key: TabKey.LOGIN_SETTINGS,
|
||||
icon: <LogIn className="w-5 h-5" />,
|
||||
label: t("Login Settings"),
|
||||
description: t("Configure authentication methods"),
|
||||
},
|
||||
{
|
||||
key: TabKey.SYSTEM_SETTINGS,
|
||||
icon: <Cog className="w-5 h-5" />,
|
||||
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",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -104,8 +132,10 @@ const ConsoleContent: React.FC = () => {
|
||||
}
|
||||
}, [admin_token, router]);
|
||||
|
||||
const handleTabNavigate = (tab: TabKey) => {
|
||||
const handleTabNavigate = (tab: TabKey, subTab?: string) => {
|
||||
setActiveTab(tab);
|
||||
setActiveSubTab(subTab || _DefaultSubTab);
|
||||
|
||||
// update url params
|
||||
if (tab === TabKey.CONSOLE) {
|
||||
// when switch to dashboard, clear all query params, only keep base path
|
||||
@@ -114,6 +144,12 @@ const ConsoleContent: React.FC = () => {
|
||||
// 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 });
|
||||
}
|
||||
};
|
||||
@@ -151,23 +187,15 @@ const ConsoleContent: React.FC = () => {
|
||||
<PaymentChannelsContent />
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
case "login-settings":
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("Login Settings")}
|
||||
description={t("Configure authentication methods")}
|
||||
>
|
||||
<LoginSettingsContent onTabNavigate={handleTabNavigate} />
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
case "system-settings":
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("System Settings")}
|
||||
description={t("Platform basic configuration")}
|
||||
>
|
||||
<SystemSettingsContent />
|
||||
</DashboardDemoContent>
|
||||
<SystemSettingsContent
|
||||
activeSubTab={activeSubTab}
|
||||
subTab={sidebarItems
|
||||
.find((item) => item.key === activeTab)
|
||||
?.subItems?.find((item) => item.key === activeSubTab)}
|
||||
onTabNavigate={handleTabNavigate}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
@@ -185,25 +213,12 @@ const ConsoleContent: React.FC = () => {
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="flex">
|
||||
{/* Sidebar */}
|
||||
<DashboardSidebar
|
||||
<ConsoleSidebar
|
||||
activeTab={activeTab}
|
||||
activeSubTab={activeSubTab}
|
||||
onTabNavigate={handleTabNavigate}
|
||||
onLogout={handleLogout}
|
||||
sidebarItems={sidebarItems}
|
||||
bottomPanel={
|
||||
<Button
|
||||
variant="light"
|
||||
startContent={<FaDiscord className="w-5 h-5" />}
|
||||
className="w-full justify-start h-auto p-3"
|
||||
onPress={() => {
|
||||
window.open("https://discord.gg/cyZfcdCXkW", "_blank");
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<span className="font-medium">{t("Discord")}</span>
|
||||
</div>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
|
||||
@@ -1,46 +1,56 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import { StripeConfigForm } from './StripeConfigForm';
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import React from "react";
|
||||
import { StripeConfigForm } from "../payment/StripeConfigForm";
|
||||
import { AlipayConfigForm } from "../payment/AlipayConfigForm";
|
||||
import { WechatConfigForm } from "../payment/WechatConfigForm";
|
||||
import { usePaymentChannelManagement } from "@/hooks/usePaymentChannelManagement";
|
||||
import { StripeConfig } from "@/types/payment";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
export const PaymentChannelsContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
stripeConfig,
|
||||
isSaving,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
saveStripeConfig,
|
||||
testStripeConnection,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
enableChannel,
|
||||
disableChannel,
|
||||
} = usePaymentChannelManagement();
|
||||
|
||||
|
||||
// test stripe connection
|
||||
const handleTestStripeConnection = async (config: StripeConfig) => {
|
||||
const result = await testStripeConnection(config);
|
||||
|
||||
if (result.success) {
|
||||
toast.success(t("Stripe connection test successful"));
|
||||
} else {
|
||||
toast.error(result.message || t("Stripe connection test failed"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 w-full">
|
||||
{/* stripe configuration */}
|
||||
<StripeConfigForm
|
||||
config={stripeConfig}
|
||||
onSave={saveStripeConfig}
|
||||
onTest={handleTestStripeConnection}
|
||||
isLoading={isSaving}
|
||||
isTestLoading={false}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isStripeSaving}
|
||||
/>
|
||||
{/* coming soon */}
|
||||
{/* alipay configuration */}
|
||||
{/* <AlipayConfigForm
|
||||
config={alipayConfig}
|
||||
onSave={saveAlipayConfig}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isAlipaySaving}
|
||||
/> */}
|
||||
{/* coming soon */}
|
||||
{/* wechat configuration */}
|
||||
{/* <WechatConfigForm
|
||||
config={wechatConfig}
|
||||
onSave={saveWechatConfig}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isWechatSaving}
|
||||
/> */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PaymentChannelsContent;
|
||||
export default PaymentChannelsContent;
|
||||
@@ -0,0 +1,161 @@
|
||||
"use client";
|
||||
|
||||
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 { DashboardSidebarProps } from "@/shared/types/dashboard";
|
||||
import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { FaDiscord } from "react-icons/fa";
|
||||
|
||||
const ConsoleSidebar: React.FC<DashboardSidebarProps> = ({
|
||||
activeTab,
|
||||
activeSubTab,
|
||||
onTabNavigate,
|
||||
onLogout,
|
||||
sidebarItems,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleSubItemClick = (parentKey: string, subKey: string) => {
|
||||
onTabNavigate?.(parentKey as any, subKey);
|
||||
};
|
||||
|
||||
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"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div>
|
||||
<Divider className="my-2" />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Tooltip
|
||||
content={t("Discord")}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
placement="right"
|
||||
>
|
||||
<Button
|
||||
variant="light"
|
||||
startContent={<FaDiscord size={18} />}
|
||||
className="w-full h-auto p-4"
|
||||
onPress={() => {
|
||||
window.open("https://discord.gg/cyZfcdCXkW", "_blank");
|
||||
}}
|
||||
isIconOnly
|
||||
></Button>
|
||||
</Tooltip>
|
||||
|
||||
{/* Logout */}
|
||||
<Tooltip
|
||||
content={t("Log Out")}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
placement="right"
|
||||
>
|
||||
<Button
|
||||
variant="light"
|
||||
color="danger"
|
||||
startContent={<LogOut size={18} />}
|
||||
className="w-full h-auto p-4"
|
||||
onPress={onLogout}
|
||||
isIconOnly
|
||||
></Button>
|
||||
</Tooltip>
|
||||
</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>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConsoleSidebar;
|
||||
@@ -1,121 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Input, Button, AccordionItem, Accordion } from '@nextui-org/react';
|
||||
import { Eye, EyeOff } from 'lucide-react';
|
||||
import { StripeConfig } from '@/types/payment';
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface StripeConfigFormProps {
|
||||
config: StripeConfig;
|
||||
onSave: (config: StripeConfig) => void;
|
||||
onTest: (config: StripeConfig) => void;
|
||||
isLoading?: boolean;
|
||||
isTestLoading?: boolean;
|
||||
}
|
||||
|
||||
export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<StripeConfig>(config);
|
||||
const [showSecretKey, setShowSecretKey] = useState(false);
|
||||
const [showWebhookSecret, setShowWebhookSecret] = useState(false);
|
||||
useEffect(() => {
|
||||
console.log("config", config);
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof StripeConfig, value: string) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
|
||||
const isFormValid = formData.secret.trim() !== '' && formData.webhook_secret.trim() !== '';
|
||||
|
||||
return (
|
||||
<Accordion variant='splitted' itemClasses={{
|
||||
base: 'shadow-none border-1',
|
||||
}} defaultExpandedKeys={['stripe-config']} className='px-0'>
|
||||
<AccordionItem key="stripe-config" title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">{t('Stripe Configuration')}</h3>
|
||||
<p className="text-sm text-gray-500">{t('Configure Stripe payment interface')}</p>
|
||||
</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
|
||||
/>
|
||||
|
||||
{/* 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>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size='sm'
|
||||
>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -1,18 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { PlatformConfigForm } from "@/components/system-setting/PlatformConfigForm";
|
||||
import { AdminConfigForm } from "@/components/system-setting/AdminConfigForm";
|
||||
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
|
||||
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";
|
||||
|
||||
export const SystemSettingsContent: React.FC = () => {
|
||||
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,
|
||||
@@ -31,6 +46,10 @@ export const SystemSettingsContent: React.FC = () => {
|
||||
|
||||
// image upload
|
||||
uploadImage,
|
||||
|
||||
// login config
|
||||
loginConfig,
|
||||
saveLoginConfig,
|
||||
} = useSystemConfigManagement();
|
||||
|
||||
// save admin config
|
||||
@@ -77,33 +96,60 @@ export const SystemSettingsContent: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// 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 (
|
||||
<div className="space-y-6 w-full">
|
||||
{/* platform config */}
|
||||
<PlatformConfigForm
|
||||
config={platformConfig}
|
||||
onSave={handleSavePlatformConfig}
|
||||
onThemeChange={handleThemeChange}
|
||||
onAboutSave={handleAboutSave}
|
||||
isLoading={platformLoading}
|
||||
isAboutLoading={isAboutLoading}
|
||||
onImageUpload={uploadImage}
|
||||
/>
|
||||
|
||||
{/* admin config */}
|
||||
<AdminConfigForm
|
||||
config={adminConfig}
|
||||
onSave={handleSaveAdminConfig}
|
||||
isLoading={adminLoading}
|
||||
/>
|
||||
|
||||
{/* email config */}
|
||||
<EmailConfigForm
|
||||
config={emailConfig}
|
||||
onSave={handleSaveEmailConfig}
|
||||
isLoading={emailLoading}
|
||||
/>
|
||||
</div>
|
||||
<DashboardDemoContent
|
||||
title={t(subTab?.label || "System Settings")}
|
||||
description={t(subTab?.description || "Platform basic configuration")}
|
||||
>
|
||||
{renderSubTabContent()}
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ interface AuthKeyDetailsProps {
|
||||
interface ApiAnalyticsData {
|
||||
stats_day: string;
|
||||
call_tool_count: number;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
// Custom cursor to highlight the hovered bar with a lighter and narrower overlay
|
||||
@@ -76,7 +77,7 @@ const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await fetchAPI(
|
||||
`/api/stats/key_call_tool_count?apikey_id=${selectedApiKey.apikey_id}`,
|
||||
`/api/stats/key_call_tool?apikey_id=${selectedApiKey.apikey_id}`,
|
||||
{
|
||||
method: "GET",
|
||||
}
|
||||
@@ -86,7 +87,8 @@ const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
|
||||
const formattedData = response.data.days.map(
|
||||
(day: ApiAnalyticsData) => ({
|
||||
name: new Date(day.stats_day).toISOString().split("T")[0],
|
||||
value: day.call_tool_count,
|
||||
value: day.amount,
|
||||
count: day.call_tool_count,
|
||||
})
|
||||
);
|
||||
setAnalyticsData(formattedData);
|
||||
@@ -101,7 +103,7 @@ const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
|
||||
}, [selectedApiKey, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedApiKey?.apikey_id) return
|
||||
if (!selectedApiKey?.apikey_id) return;
|
||||
fetchAnalyticsData();
|
||||
}, [selectedApiKey?.apikey_id]);
|
||||
|
||||
@@ -163,7 +165,9 @@ const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 bg-gray-100 p-2 rounded relative justify-between">
|
||||
<span className="overflow-hidden text-ellipsis whitespace-nowrap">{getEncryptedKey(selectedApiKey.apikey)}</span>
|
||||
<span className="overflow-hidden text-ellipsis whitespace-nowrap">
|
||||
{getEncryptedKey(selectedApiKey.apikey)}
|
||||
</span>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -213,11 +217,14 @@ const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fontSize: 12, fill: "#666" }}
|
||||
allowDecimals={false}
|
||||
allowDecimals={true}
|
||||
/>
|
||||
<RechartsTooltip
|
||||
cursor={<CustomCursor />}
|
||||
formatter={(value: number) => [value, t("Times")]}
|
||||
formatter={(value: number) => [
|
||||
value,
|
||||
t("Total Spending"),
|
||||
]}
|
||||
contentStyle={{
|
||||
backgroundColor: "#fff",
|
||||
border: "1px solid #e5e7eb",
|
||||
|
||||
@@ -29,7 +29,7 @@ const DashboardContent: React.FC = () => {
|
||||
state.user_token,
|
||||
state.user,
|
||||
]);
|
||||
const { loginConfig } = usePlatformConfig();
|
||||
const { loginConfig, paymentChannels } = usePlatformConfig();
|
||||
|
||||
const [logOut, useGetUser] = useGlobalStore((state) => [
|
||||
state.logOut,
|
||||
@@ -163,14 +163,16 @@ const DashboardContent: React.FC = () => {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="bordered"
|
||||
onPress={handleRecharge}
|
||||
aria-label="Recharge wallet"
|
||||
size="sm"
|
||||
>
|
||||
{t("Recharge")}
|
||||
</Button>
|
||||
{paymentChannels.length > 0 && (
|
||||
<Button
|
||||
variant="bordered"
|
||||
onPress={handleRecharge}
|
||||
aria-label="Recharge wallet"
|
||||
size="sm"
|
||||
>
|
||||
{t("Recharge")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
@@ -21,7 +21,7 @@ interface EmailConfigFormProps {
|
||||
emailConfig: EmailConfig;
|
||||
onSave: (config: LoginConfig) => Promise<void>;
|
||||
isLoading?: boolean;
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
onTabNavigate?: (tab: TabKey, subTab?: string) => void;
|
||||
}
|
||||
|
||||
export const EmailConfigForm: React.FC<EmailConfigFormProps> = ({
|
||||
@@ -180,7 +180,7 @@ export const EmailConfigForm: React.FC<EmailConfigFormProps> = ({
|
||||
<Link
|
||||
className="text-sm underline cursor-pointer"
|
||||
onPress={() => {
|
||||
onTabNavigate?.(TabKey.SYSTEM_SETTINGS);
|
||||
onTabNavigate?.(TabKey.SYSTEM_SETTINGS, "email-admin");
|
||||
}}
|
||||
>
|
||||
{t("Go to Settings")}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Accordion, AccordionItem } from "@nextui-org/react";
|
||||
import { Plus } from "lucide-react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
|
||||
function FaqClient() {
|
||||
const { faqItems } = usePlatformConfig();
|
||||
const { t } = useTranslation();
|
||||
// Custom indicator component with plus sign that fades out when expanded
|
||||
const CustomIndicator = ({ isOpen }: { isOpen?: boolean }) => (
|
||||
<Plus
|
||||
className={`text-black transition-all duration-300 ${
|
||||
isOpen ? "rotate-0 opacity-0" : "rotate-0 opacity-100"
|
||||
}`}
|
||||
size={16}
|
||||
/>
|
||||
);
|
||||
if (faqItems.length === 0) return null;
|
||||
|
||||
return (
|
||||
<section className="py-12 sm:py-20 px-4 sm:px-6" id="faqs">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold mb-8 sm:mb-12 text-center">
|
||||
{t("FAQs")}
|
||||
</h2>
|
||||
{/**content */}
|
||||
<div className="relative bg-white rounded-lg">
|
||||
<Accordion variant="light">
|
||||
{faqItems.map((faq, index) => (
|
||||
<AccordionItem
|
||||
key={index}
|
||||
aria-label={faq.question}
|
||||
title={
|
||||
<span className="text-base sm:text-lg font-medium">
|
||||
{faq.question}
|
||||
</span>
|
||||
}
|
||||
className="pt-2 px-2"
|
||||
indicator={({ isOpen }) => <CustomIndicator isOpen={isOpen} />}
|
||||
>
|
||||
<div className="text-sm sm:text-base text-foreground-600 leading-relaxed space-y-2">
|
||||
{faq.answer}
|
||||
</div>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Faq() {
|
||||
return <FaqClient />;
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export const BasicInfoTab: React.FC<BasicInfoTabProps> = ({
|
||||
>
|
||||
<SelectItem key="none" value="none">{t('None')}</SelectItem>
|
||||
<SelectItem key="apikey" value="apikey">{t('API Key')}</SelectItem>
|
||||
<SelectItem key="bearer-token" value="bearer-token">{t('Bearer Token')}</SelectItem>
|
||||
<SelectItem key="token" value="token">{t('Bearer Token')}</SelectItem>
|
||||
</Select>
|
||||
|
||||
{/* auth config input fields */}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { MCPServiceFormData } from '@/types/mcp-service';
|
||||
import dynamic from 'next/dynamic';
|
||||
import React from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { MCPServiceFormData } from "@/types/mcp-service";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
// dynamic import MDEditor to avoid SSR problem
|
||||
const MDEditor = dynamic(
|
||||
() => import('@uiw/react-md-editor').then((mod) => mod.default),
|
||||
() => import("@uiw/react-md-editor").then((mod) => mod.default),
|
||||
{ ssr: false }
|
||||
);
|
||||
|
||||
@@ -18,29 +18,30 @@ interface DescriptionTabProps {
|
||||
|
||||
export const DescriptionTab: React.FC<DescriptionTabProps> = ({
|
||||
formData,
|
||||
onInputChange
|
||||
onInputChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleMarkdownChange = (value?: string) => {
|
||||
onInputChange('long_description', value || '');
|
||||
onInputChange("long_description", value || "");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4 h-full">
|
||||
<div className="w-full h-full">
|
||||
<MDEditor
|
||||
value={formData.long_description || ''}
|
||||
value={formData.long_description || ""}
|
||||
onChange={handleMarkdownChange}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={true}
|
||||
textareaProps={{
|
||||
placeholder: t('Detailed description of the service (supports Markdown)'),
|
||||
placeholder: t("Detailed description of the service"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.5,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
|
||||
},
|
||||
}}
|
||||
height="100%"
|
||||
@@ -49,4 +50,4 @@ export const DescriptionTab: React.FC<DescriptionTabProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,15 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
Input,
|
||||
Select,
|
||||
SelectItem,
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { MCPServiceFormData } from '@/types/mcp-service';
|
||||
import { getCurrencySymbol } from '@/shared/utils/currency';
|
||||
import { ChargeType } from '@/shared/types/marketplace';
|
||||
import React from "react";
|
||||
import { Input, Select, SelectItem } from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { MCPServiceFormData } from "@/types/mcp-service";
|
||||
import { getCurrencySymbol } from "@/shared/utils/currency";
|
||||
import { ChargeType } from "@/shared/types/marketplace";
|
||||
|
||||
interface PricingTabProps {
|
||||
formData: MCPServiceFormData;
|
||||
@@ -18,52 +14,111 @@ interface PricingTabProps {
|
||||
|
||||
export const PricingTab: React.FC<PricingTabProps> = ({
|
||||
formData,
|
||||
onInputChange
|
||||
onInputChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Select
|
||||
label={t('Charge Type')}
|
||||
label={t("Charge Type")}
|
||||
selectedKeys={formData.charge_type ? [formData.charge_type] : []}
|
||||
onSelectionChange={(keys) => {
|
||||
const selectedKey = Array.from(keys)[0] as string;
|
||||
onInputChange('charge_type', selectedKey);
|
||||
onInputChange("charge_type", selectedKey);
|
||||
}}
|
||||
renderValue={() => {
|
||||
const selectedKey = formData.charge_type || ChargeType.PerCall;
|
||||
if (selectedKey === ChargeType.Free) return t('Free');
|
||||
return t(selectedKey === ChargeType.PerCall ? 'Per Call' : 'Per Token');
|
||||
if (selectedKey === ChargeType.Free) return t("Free");
|
||||
return t(
|
||||
selectedKey === ChargeType.PerCall
|
||||
? "Per Call"
|
||||
: "Per Million Tokens"
|
||||
);
|
||||
}}
|
||||
>
|
||||
<SelectItem key="free" value={ChargeType.Free}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t('Free')}</span>
|
||||
<span className="text-xs text-gray-500">{t('No charge for API calls')}</span>
|
||||
<span>{t("Free")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("No charge for API calls")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem key="per_call" value={ChargeType.PerCall}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t('Per Call')}</span>
|
||||
<span className="text-xs text-gray-500">{t('Fixed price per API call')}</span>
|
||||
<span>{t("Per Call")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Fixed price per API call")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
|
||||
<SelectItem key="per_token" value={ChargeType.PerToken}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t("Per Million Tokens")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Price per million tokens consumed")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
|
||||
{formData.charge_type !== ChargeType.Free && (
|
||||
<Input
|
||||
label={t('Price')}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={formData.price || ''}
|
||||
onChange={(e) => onInputChange('price', e.target.value)}
|
||||
description={t('Price per unit (call or token)')}
|
||||
startContent={<span className="text-gray-500 leading-[20px]">{getCurrencySymbol()}</span>}
|
||||
/>
|
||||
<>
|
||||
{formData.charge_type === ChargeType.PerToken ? (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
label={t("Input Token Price")}
|
||||
value={formData.input_token_price || ""}
|
||||
onChange={(e) =>
|
||||
onInputChange("input_token_price", e.target.value)
|
||||
}
|
||||
placeholder={t("Price per million input tokens")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
label={t("Output Token Price")}
|
||||
value={formData.output_token_price || ""}
|
||||
onChange={(e) =>
|
||||
onInputChange("output_token_price", e.target.value)
|
||||
}
|
||||
placeholder={t("Price per million output tokens")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
label={t("Price")}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={formData.price || ""}
|
||||
onChange={(e) => onInputChange("price", e.target.value)}
|
||||
description={t("Price per API call")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
"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';
|
||||
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;
|
||||
@@ -16,7 +16,7 @@ interface ServiceFiltersBarProps {
|
||||
export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
filters,
|
||||
onFiltersChange,
|
||||
onImportOpenAPI
|
||||
onImportOpenAPI,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -24,20 +24,20 @@ export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
onFiltersChange({ ...filters, search: value });
|
||||
};
|
||||
|
||||
|
||||
const handleStatusChange = (value: string) => {
|
||||
onFiltersChange({ ...filters, status: value });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<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')}
|
||||
{t("Add Service")}
|
||||
</Button>
|
||||
{/* <Input
|
||||
placeholder={t('Search services...')}
|
||||
@@ -74,10 +74,7 @@ export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select> */}
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import React from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -12,19 +12,19 @@ import {
|
||||
Button,
|
||||
Tooltip,
|
||||
Pagination,
|
||||
Spinner
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { EnabledEnum, MCPService } from '@/types/mcp-service';
|
||||
Spinner,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { EnabledEnum, MCPService } from "@/types/mcp-service";
|
||||
import {
|
||||
Trash2,
|
||||
Zap,
|
||||
PencilIcon,
|
||||
CircleCheckIcon,
|
||||
BanIcon,
|
||||
} from 'lucide-react';
|
||||
import { ChargeType } from '@/shared/types/marketplace';
|
||||
import { Price } from '@/shared/components/marketplace/Price';
|
||||
} from "lucide-react";
|
||||
import { ChargeType } from "@/shared/types/marketplace";
|
||||
import { Price } from "@/shared/components/marketplace/Price";
|
||||
|
||||
interface ServiceTableProps {
|
||||
services: MCPService[];
|
||||
@@ -58,22 +58,29 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
const items = services;
|
||||
|
||||
const getStatusColor = (enabled: number) => {
|
||||
return enabled === EnabledEnum.Online ? 'success' : 'danger';
|
||||
return enabled === EnabledEnum.Online ? "success" : "danger";
|
||||
};
|
||||
|
||||
const handleEdit = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onEdit(service);
|
||||
},
|
||||
[onEdit]
|
||||
);
|
||||
|
||||
const handleEdit = React.useCallback((service: MCPService) => {
|
||||
onEdit(service);
|
||||
}, [onEdit]);
|
||||
|
||||
const handleDelete = React.useCallback((service: MCPService) => {
|
||||
onDelete(service);
|
||||
}, [onDelete]);
|
||||
|
||||
const handleToggleStatus = React.useCallback((service: MCPService) => {
|
||||
onToggleStatus(service);
|
||||
}, [onToggleStatus]);
|
||||
const handleDelete = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onDelete(service);
|
||||
},
|
||||
[onDelete]
|
||||
);
|
||||
|
||||
const handleToggleStatus = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onToggleStatus(service);
|
||||
},
|
||||
[onToggleStatus]
|
||||
);
|
||||
|
||||
if (loading && services.length === 0) {
|
||||
return (
|
||||
@@ -96,7 +103,7 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
<div className="flex w-full justify-center">
|
||||
<Pagination
|
||||
showControls
|
||||
variant='light'
|
||||
variant="light"
|
||||
color="primary"
|
||||
page={currentPage}
|
||||
total={pages}
|
||||
@@ -107,17 +114,17 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
}
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>{t('Service Name')}</TableColumn>
|
||||
<TableColumn>{t('API Endpoint')}</TableColumn>
|
||||
<TableColumn>{t('Status')}</TableColumn>
|
||||
<TableColumn>{t('Pricing')}</TableColumn>
|
||||
<TableColumn className='w-20'>{t('Actions')}</TableColumn>
|
||||
<TableColumn>{t("Service Name")}</TableColumn>
|
||||
<TableColumn>{t("API Endpoint")}</TableColumn>
|
||||
<TableColumn>{t("Status")}</TableColumn>
|
||||
<TableColumn>{t("Pricing")}</TableColumn>
|
||||
<TableColumn className="w-20">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
isLoading={loading}
|
||||
loadingContent={<Spinner />}
|
||||
emptyContent={t('No services found')}
|
||||
emptyContent={t("No services found")}
|
||||
>
|
||||
{(service) => (
|
||||
<TableRow key={service.id}>
|
||||
@@ -134,17 +141,22 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{t(service.enabled === 1 ? 'Online' : 'Offline')}
|
||||
{t(service.enabled === 1 ? "Online" : "Offline")}
|
||||
</Chip>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Price price={service.price} charge_type={service.charge_type} />
|
||||
<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>
|
||||
<div className="relative flex items-center gap-2">
|
||||
<Tooltip content={t('Edit')} closeDelay={0}>
|
||||
<Tooltip content={t("Edit")} closeDelay={0} disableAnimation>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -155,22 +167,40 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={service.enabled === EnabledEnum.Online ? t('Take Offline') : t('Bring Online')} closeDelay={0} >
|
||||
<Tooltip
|
||||
content={
|
||||
service.enabled === EnabledEnum.Online
|
||||
? t("Take Offline")
|
||||
: t("Bring Online")
|
||||
}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color={service.enabled === EnabledEnum.Online ? 'danger' : 'success'}
|
||||
color={
|
||||
service.enabled === EnabledEnum.Online
|
||||
? "danger"
|
||||
: "success"
|
||||
}
|
||||
onPress={() => handleToggleStatus(service)}
|
||||
>
|
||||
{service.enabled === EnabledEnum.Online ?
|
||||
<BanIcon className="w-4 h-4" /> :
|
||||
{service.enabled === EnabledEnum.Online ? (
|
||||
<BanIcon className="w-4 h-4" />
|
||||
) : (
|
||||
<CircleCheckIcon className="w-4 h-4" />
|
||||
}
|
||||
)}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={t('Delete Service')} color="danger" closeDelay={0}>
|
||||
<Tooltip
|
||||
content={t("Delete Service")}
|
||||
color="danger"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -189,4 +219,4 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -38,7 +38,8 @@ export const ToolsTab: React.FC<ToolsTabProps> = ({
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className='w-1/3'>{t('Tool Name')}</TableColumn>
|
||||
<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.')}>
|
||||
@@ -49,7 +50,13 @@ export const ToolsTab: React.FC<ToolsTabProps> = ({
|
||||
<TableCell>
|
||||
<Input
|
||||
value={tool.name}
|
||||
// onChange={(e) => handleToolChange(index, 'name', e.target.value)}
|
||||
size="sm"
|
||||
isDisabled
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={tool.url}
|
||||
size="sm"
|
||||
isDisabled
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { AlipayConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface AlipayConfigFormProps {
|
||||
config: AlipayConfig;
|
||||
onSave: (config: AlipayConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const AlipayConfigForm: React.FC<AlipayConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<AlipayConfig>(config);
|
||||
const [showAppPrivateKey, setShowAppPrivateKey] = useState(false);
|
||||
const [showAlipayPublicKey, setShowAlipayPublicKey] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof AlipayConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("alipay");
|
||||
} else {
|
||||
result = await onDisable("alipay");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.app_id.trim() !== "" &&
|
||||
formData.app_private_key.trim() !== "" &&
|
||||
formData.alipay_public_key.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["alipay-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="alipay-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Alipay Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure Alipay payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* App ID */}
|
||||
<Input
|
||||
label={t("App ID")}
|
||||
placeholder={t("Alipay App ID")}
|
||||
value={formData.app_id}
|
||||
onChange={(e) => handleInputChange("app_id", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* App Private Key */}
|
||||
<Input
|
||||
label={t("App Private Key")}
|
||||
placeholder={t("Alipay App Private Key")}
|
||||
value={formData.app_private_key}
|
||||
onChange={(e) =>
|
||||
handleInputChange("app_private_key", e.target.value)
|
||||
}
|
||||
type={showAppPrivateKey ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAppPrivateKey(!showAppPrivateKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showAppPrivateKey ? (
|
||||
<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}
|
||||
/>
|
||||
|
||||
{/* Alipay Public Key */}
|
||||
<Input
|
||||
label={t("Alipay Public Key")}
|
||||
placeholder={t("Alipay public key for verification")}
|
||||
value={formData.alipay_public_key || ""}
|
||||
onChange={(e) =>
|
||||
handleInputChange("alipay_public_key", e.target.value)
|
||||
}
|
||||
type={showAlipayPublicKey ? "text" : "password"}
|
||||
isRequired
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAlipayPublicKey(!showAlipayPublicKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showAlipayPublicKey ? (
|
||||
<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>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { StripeConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface StripeConfigFormProps {
|
||||
config: StripeConfig;
|
||||
onSave: (config: StripeConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<StripeConfig>(config);
|
||||
const [showSecretKey, setShowSecretKey] = useState(false);
|
||||
const [showWebhookSecret, setShowWebhookSecret] = useState(false);
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof StripeConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("stripe");
|
||||
} else {
|
||||
result = await onDisable("stripe");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.secret.trim() !== "" && formData.webhook_secret.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["stripe-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="stripe-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Stripe Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure Stripe payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</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>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { WechatConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface WechatConfigFormProps {
|
||||
config: WechatConfig;
|
||||
onSave: (config: WechatConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const WechatConfigForm: React.FC<WechatConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<WechatConfig>(config);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof WechatConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("wechat");
|
||||
} else {
|
||||
result = await onDisable("wechat");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.app_id.trim() !== "" && formData.mch_id.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["wechat-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="wechat-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("WeChat Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure WeChat payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* App ID */}
|
||||
<Input
|
||||
label={t("App ID")}
|
||||
placeholder={t("WeChat App ID")}
|
||||
value={formData.app_id}
|
||||
onChange={(e) => handleInputChange("app_id", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* Merchant ID */}
|
||||
<Input
|
||||
label={t("Merchant ID")}
|
||||
placeholder={t("WeChat Merchant ID")}
|
||||
value={formData.mch_id}
|
||||
onChange={(e) => handleInputChange("mch_id", e.target.value)}
|
||||
isRequired
|
||||
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>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Button, AccordionItem, Accordion } from "@nextui-org/react";
|
||||
import MDEditor, { commands } from "@uiw/react-md-editor";
|
||||
import { PlatformConfig } from "@/shared/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { calculateFileSha256 } from "@/shared/utils/crypto";
|
||||
import "@uiw/react-md-editor/markdown-editor.css";
|
||||
import "@uiw/react-markdown-preview/markdown.css";
|
||||
|
||||
interface AboutPageSettingsProps {
|
||||
config: PlatformConfig;
|
||||
onAboutSave: (aboutContent: string) => Promise<void>;
|
||||
onImageUpload?: (file: File, sha256?: string) => Promise<string>;
|
||||
isAboutLoading?: boolean;
|
||||
}
|
||||
|
||||
export const AboutPageSettings: React.FC<AboutPageSettingsProps> = ({
|
||||
config,
|
||||
onAboutSave,
|
||||
onImageUpload,
|
||||
isAboutLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [aboutContent, setAboutContent] = useState(config.about_page || "");
|
||||
|
||||
useEffect(() => {
|
||||
setAboutContent(config.about_page || "");
|
||||
}, [config.about_page]);
|
||||
|
||||
const handleAboutSave = async () => {
|
||||
await onAboutSave(aboutContent);
|
||||
};
|
||||
|
||||
const handleImageUpload = async (file: File): Promise<string> => {
|
||||
try {
|
||||
// 计算文件的 SHA256 哈希值
|
||||
const sha256 = await calculateFileSha256(file);
|
||||
return await onImageUpload!(file, sha256);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 justify-between h-full">
|
||||
<div className="flex-1">
|
||||
<MDEditor
|
||||
value={aboutContent}
|
||||
onChange={(value?: string) => setAboutContent(value || "")}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={false}
|
||||
data-color-mode="light"
|
||||
textareaProps={{
|
||||
placeholder: t("Enter about page content (supports Markdown)"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.6,
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
},
|
||||
}}
|
||||
height="100%"
|
||||
commands={[
|
||||
// 默认命令
|
||||
commands.bold,
|
||||
commands.italic,
|
||||
commands.strikethrough,
|
||||
commands.hr,
|
||||
commands.title,
|
||||
commands.divider,
|
||||
commands.link,
|
||||
commands.quote,
|
||||
commands.code,
|
||||
commands.codeBlock,
|
||||
commands.comment,
|
||||
commands.divider,
|
||||
commands.unorderedListCommand,
|
||||
commands.orderedListCommand,
|
||||
commands.checkedListCommand,
|
||||
commands.divider,
|
||||
// 自定义图片上传命令
|
||||
{
|
||||
name: "image-upload",
|
||||
keyCommand: "image-upload",
|
||||
buttonProps: {
|
||||
"aria-label": "Upload image",
|
||||
title: "Upload image",
|
||||
},
|
||||
icon: (
|
||||
<svg width="12" height="12" viewBox="0 0 20 20">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zM2 17l4.5-6 3.5 4.51 2.5-3.01L17 17H2z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
execute: (state, api) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
try {
|
||||
const dataUrl = await handleImageUpload(file);
|
||||
const imageMarkdown = ``;
|
||||
api.replaceSelection(imageMarkdown);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* About Save Button */}
|
||||
<div className="flex gap-3 pb-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleAboutSave}
|
||||
isLoading={isAboutLoading}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Input, Button, AccordionItem, Accordion } from '@nextui-org/react';
|
||||
import { Eye, EyeOff } from 'lucide-react';
|
||||
import { AdminConfig } from '@/types/system';
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Input, Button, AccordionItem, Accordion } from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { AdminConfig } from "@/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface AdminConfigFormProps {
|
||||
@@ -20,20 +20,20 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<AdminConfig>(config);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
useEffect(() => {
|
||||
setFormData({
|
||||
...config,
|
||||
password: '',
|
||||
password: "",
|
||||
});
|
||||
setConfirmPassword('');
|
||||
setConfirmPassword("");
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof AdminConfig, value: string) => {
|
||||
setFormData(prev => ({
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -42,41 +42,53 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.username.trim() !== '' &&
|
||||
formData.password.trim() !== '' &&
|
||||
formData.username.trim() !== "" &&
|
||||
formData.password?.trim() !== "" &&
|
||||
formData.password === confirmPassword &&
|
||||
formData.password.length >= 8;
|
||||
formData.password?.length >= 8;
|
||||
|
||||
const passwordsMatch = formData.password === confirmPassword;
|
||||
|
||||
return (
|
||||
<Accordion variant='splitted' itemClasses={{
|
||||
base: 'shadow-none border-1',
|
||||
}} defaultExpandedKeys={['admin-config']} className='px-0'>
|
||||
<AccordionItem key="admin-config" title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">{t('Administrator Account')}</h3>
|
||||
<p className="text-sm text-gray-500">{t('Configure administrator login credentials')}</p>
|
||||
</div>
|
||||
}>
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["admin-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="admin-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Administrator Account")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure administrator login credentials")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* admin username */}
|
||||
<Input
|
||||
label={t('Administrator Username')}
|
||||
placeholder={t('Enter administrator username')}
|
||||
description={t('Username for administrator login')}
|
||||
label={t("Administrator Username")}
|
||||
placeholder={t("Enter administrator username")}
|
||||
description={t("Username for administrator login")}
|
||||
value={formData.username}
|
||||
onChange={(e) => handleInputChange('username', e.target.value)}
|
||||
onChange={(e) => handleInputChange("username", e.target.value)}
|
||||
isRequired
|
||||
/>
|
||||
|
||||
{/* admin password */}
|
||||
<Input
|
||||
label={t('Administrator Password')}
|
||||
placeholder={t('Enter administrator password')}
|
||||
description={t('Password must be at least 8 characters long')}
|
||||
label={t("Administrator Password")}
|
||||
placeholder={t("Enter administrator password")}
|
||||
description={t("Password must be at least 8 characters long")}
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange('password', e.target.value)}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
type={showPassword ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
@@ -92,16 +104,24 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
</button>
|
||||
}
|
||||
isRequired
|
||||
autoComplete='new-password'
|
||||
color={formData.password.length > 0 && formData.password.length < 8 ? "danger" : "default"}
|
||||
errorMessage={formData.password.length > 0 && formData.password.length < 8 ? t('Password must be at least 8 characters') : ""}
|
||||
autoComplete="new-password"
|
||||
color={
|
||||
formData.password?.length > 0 && formData.password?.length < 8
|
||||
? "danger"
|
||||
: "default"
|
||||
}
|
||||
errorMessage={
|
||||
formData.password?.length > 0 && formData.password?.length < 8
|
||||
? t("Password must be at least 8 characters")
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
|
||||
{/* confirm password */}
|
||||
<Input
|
||||
label={t('Confirm Password')}
|
||||
placeholder={t('Confirm administrator password')}
|
||||
description={t('Re-enter the password to confirm')}
|
||||
label={t("Confirm Password")}
|
||||
placeholder={t("Confirm administrator password")}
|
||||
description={t("Re-enter the password to confirm")}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
@@ -118,10 +138,18 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
autoComplete='new-password'
|
||||
autoComplete="new-password"
|
||||
isRequired
|
||||
color={confirmPassword.length > 0 && !passwordsMatch ? "danger" : "default"}
|
||||
errorMessage={confirmPassword.length > 0 && !passwordsMatch ? t('Passwords do not match') : ""}
|
||||
color={
|
||||
confirmPassword?.length > 0 && !passwordsMatch
|
||||
? "danger"
|
||||
: "default"
|
||||
}
|
||||
errorMessage={
|
||||
confirmPassword?.length > 0 && !passwordsMatch
|
||||
? t("Passwords do not match")
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -133,12 +161,12 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size='sm'
|
||||
size="sm"
|
||||
>
|
||||
{t('Save')}
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { EmailConfigForm } from "./EmailConfigForm";
|
||||
import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { AdminConfigForm } from "./AdminConfigForm";
|
||||
|
||||
interface EmailAndAdminSettingsProps {
|
||||
emailConfig: EmailConfig;
|
||||
adminConfig: AdminConfig;
|
||||
onSaveEmailConfig: (config: EmailConfig) => void;
|
||||
onSaveAdminConfig: (config: AdminConfig) => void;
|
||||
isLoading?: boolean;
|
||||
isAdminLoading?: boolean;
|
||||
}
|
||||
|
||||
export const EmailAndAdminSettings: React.FC<EmailAndAdminSettingsProps> = ({
|
||||
emailConfig,
|
||||
adminConfig,
|
||||
onSaveEmailConfig,
|
||||
onSaveAdminConfig,
|
||||
isLoading = false,
|
||||
isAdminLoading = false,
|
||||
}) => {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<EmailConfigForm
|
||||
config={emailConfig}
|
||||
onSave={onSaveEmailConfig}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<AdminConfigForm
|
||||
config={adminConfig}
|
||||
onSave={onSaveAdminConfig}
|
||||
isLoading={isAdminLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Textarea,
|
||||
Button,
|
||||
Switch,
|
||||
Alert,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { EmbeddedHtmlConfig } from "@/shared/types/system";
|
||||
|
||||
interface EmbeddedHtmlSettingsProps {
|
||||
onSave?: (config: EmbeddedHtmlConfig) => void;
|
||||
config?: EmbeddedHtmlConfig;
|
||||
}
|
||||
|
||||
export const EmbeddedHtmlSettings: React.FC<EmbeddedHtmlSettingsProps> = ({
|
||||
onSave,
|
||||
config = { html: "", is_enabled: false },
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [htmlData, setHtmlData] = useState<EmbeddedHtmlConfig>(config);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
useEffect(() => {
|
||||
setHtmlData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(htmlData);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleHtmlChange = (value: string) => {
|
||||
setHtmlData((prev) => ({ ...prev, html: value }));
|
||||
};
|
||||
const handleToggleEnabled = async (enabled: boolean) => {
|
||||
const updatedConfig = {
|
||||
...htmlData,
|
||||
is_enabled: enabled,
|
||||
};
|
||||
// when toggle the switch, save directly, same as GoogleAuthConfigForm
|
||||
const result = await onSave?.(updatedConfig);
|
||||
if (result) {
|
||||
setHtmlData((prev) => ({ ...prev, is_enabled: enabled }));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["embedded-html"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="embedded-html"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("Embedded HTML")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure custom HTML content for global injection")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-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 Custom HTML")}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Toggle to enable or disable custom HTML injection")}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={htmlData.is_enabled}
|
||||
onValueChange={handleToggleEnabled}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* HTML Editor */}
|
||||
<div className="space-y-2">
|
||||
<Textarea
|
||||
placeholder={t(
|
||||
"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>"
|
||||
)}
|
||||
value={htmlData.html}
|
||||
onValueChange={handleHtmlChange}
|
||||
minRows={10}
|
||||
maxRows={20}
|
||||
description={t(
|
||||
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML."
|
||||
)}
|
||||
radius="sm"
|
||||
className="text-xs"
|
||||
isDisabled={!htmlData.is_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
{htmlData.is_enabled && (
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isSaving}
|
||||
isDisabled={!htmlData.html.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Usage Instructions */}
|
||||
<Alert
|
||||
color="primary"
|
||||
variant="flat"
|
||||
title={t("Usage Instructions")}
|
||||
description={
|
||||
<ul className="text-sm space-y-1 mt-2">
|
||||
<li>
|
||||
•{" "}
|
||||
{t(
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts"
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t("The HTML will be injected into the document head section")}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t(
|
||||
"Make sure your code is valid to avoid breaking the application"
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t("Changes take effect immediately after saving and enabling")}
|
||||
</li>
|
||||
</ul>
|
||||
}
|
||||
/>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Table,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
Button,
|
||||
Input,
|
||||
Textarea,
|
||||
Tooltip,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { GripVertical, Trash2, Plus } from "lucide-react";
|
||||
import { FaqItem } from "@/shared/types/system";
|
||||
|
||||
interface FaqSettingsProps {
|
||||
onSave?: (config: FaqItem[]) => void;
|
||||
config?: FaqItem[];
|
||||
}
|
||||
const defaultFaqs = [{ question: "", answer: "" }];
|
||||
export const FaqSettings: React.FC<FaqSettingsProps> = ({
|
||||
onSave,
|
||||
config = [],
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [faqs, setFaqs] = useState<FaqItem[]>(
|
||||
config && config.length > 0 ? config : defaultFaqs
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [focusedAnswer, setFocusedAnswer] = useState<number | null>(null);
|
||||
const draggedItem = useRef<number | null>(null);
|
||||
const draggedOverItem = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
setFaqs(config && config.length > 0 ? config : defaultFaqs);
|
||||
}, [config]);
|
||||
|
||||
const handleQuestionChange = (index: number, value: string) => {
|
||||
setFaqs((prev) =>
|
||||
prev.map((faq, idx) =>
|
||||
idx === index ? { ...faq, question: value } : faq
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleAnswerChange = (index: number, value: string) => {
|
||||
setFaqs((prev) =>
|
||||
prev.map((faq, idx) => (idx === index ? { ...faq, answer: value } : faq))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (index: number) => {
|
||||
setFaqs((prev) => {
|
||||
// Ensure at least one record remains
|
||||
if (prev.length <= 1) {
|
||||
return defaultFaqs;
|
||||
}
|
||||
return prev.filter((_, idx) => idx !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleInsertBelow = (index: number) => {
|
||||
setFaqs((prev) => {
|
||||
const newFaqs = [...prev];
|
||||
newFaqs.splice(index + 1, 0, {
|
||||
question: "",
|
||||
answer: "",
|
||||
});
|
||||
return newFaqs;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDragStart = (index: number) => {
|
||||
draggedItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnter = (index: number) => {
|
||||
draggedOverItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
if (draggedItem.current !== null && draggedOverItem.current !== null) {
|
||||
const draggedItemIndex = draggedItem.current;
|
||||
const draggedOverItemIndex = draggedOverItem.current;
|
||||
|
||||
if (draggedItemIndex !== draggedOverItemIndex) {
|
||||
setFaqs((prev) => {
|
||||
const newFaqs = [...prev];
|
||||
const draggedItemContent = newFaqs[draggedItemIndex];
|
||||
newFaqs.splice(draggedItemIndex, 1);
|
||||
newFaqs.splice(draggedOverItemIndex, 0, draggedItemContent);
|
||||
return newFaqs;
|
||||
});
|
||||
}
|
||||
}
|
||||
draggedItem.current = null;
|
||||
draggedOverItem.current = null;
|
||||
};
|
||||
|
||||
const handleSaveAll = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(faqs.filter((faq) => faq.question && faq.answer));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["faq"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="faq"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("FAQ Management")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure frequently asked questions for your users")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* FAQ Table */}
|
||||
<Table
|
||||
aria-label="FAQ management table"
|
||||
className="border-1 rounded-lg p-2"
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className="w-16">{t("Order")}</TableColumn>
|
||||
<TableColumn className="w-1/3">{t("Question")}</TableColumn>
|
||||
<TableColumn>{t("Answer")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody emptyContent={t("No FAQ items available.")}>
|
||||
{faqs.map((faq, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragEnter={() => handleDragEnter(index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="cursor-move"
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="w-4 h-4 text-gray-400" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={faq.question}
|
||||
onValueChange={(value) =>
|
||||
handleQuestionChange(index, value)
|
||||
}
|
||||
placeholder={t("Enter question")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="relative">
|
||||
<Input
|
||||
value={faq.answer}
|
||||
onValueChange={(value) =>
|
||||
handleAnswerChange(index, value)
|
||||
}
|
||||
onFocus={() => setFocusedAnswer(index)}
|
||||
placeholder={t("Enter answer")}
|
||||
size="sm"
|
||||
/>
|
||||
{focusedAnswer === index && (
|
||||
<div className="absolute top-0 left-0 right-0 z-50">
|
||||
<Textarea
|
||||
value={faq.answer}
|
||||
onValueChange={(value) =>
|
||||
handleAnswerChange(index, value)
|
||||
}
|
||||
placeholder={t("Enter answer")}
|
||||
size="sm"
|
||||
minRows={3}
|
||||
onBlur={() => setFocusedAnswer(null)}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={t("Insert below")}>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => handleInsertBelow(index)}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("Delete")} color="danger">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="danger"
|
||||
onPress={() => handleDelete(index)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="flex ">
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleSaveAll}
|
||||
isLoading={isSaving}
|
||||
isDisabled={faqs.length === 0}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { FaqSettings } from "./FaqSettings";
|
||||
import { TopNavigationSettings } from "./TopNavigationSettings";
|
||||
import { EmbeddedHtmlSettings } from "./EmbeddedHtmlSettings";
|
||||
import { useHomepageConfigManagement } from "@/hooks/useHomepageConfigManagement";
|
||||
|
||||
interface HomepageSettingsProps {
|
||||
// 预留接口,后续扩展
|
||||
}
|
||||
|
||||
export const HomepageSettings: React.FC<HomepageSettingsProps> = () => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
homepageConfig,
|
||||
error,
|
||||
saveFaqConfig,
|
||||
saveNavigationConfig,
|
||||
saveEmbeddedHtmlConfig,
|
||||
} = useHomepageConfigManagement();
|
||||
|
||||
// 显示错误提示
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
toast.error(t("Failed to load homepage config"));
|
||||
}
|
||||
}, [error, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* FAQ Management */}
|
||||
<FaqSettings onSave={saveFaqConfig} config={homepageConfig.faq} />
|
||||
|
||||
{/* Top Navigation */}
|
||||
<TopNavigationSettings
|
||||
onSave={saveNavigationConfig}
|
||||
config={homepageConfig.top_navigation}
|
||||
/>
|
||||
|
||||
{/* Embedded HTML */}
|
||||
<EmbeddedHtmlSettings
|
||||
onSave={saveEmbeddedHtmlConfig}
|
||||
config={homepageConfig.embeded_html}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { calculateFileSha256 } from "@/shared/utils/crypto";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
@@ -9,50 +8,113 @@ import {
|
||||
Accordion,
|
||||
Select,
|
||||
SelectItem,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import MDEditor, { commands } from "@uiw/react-md-editor";
|
||||
import { PlatformConfig, Theme } from "@/shared/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { SUPPORTED_LANGUAGES } from "@/shared/lib/i18n";
|
||||
import { ThemeSelector } from "./ThemeSelector";
|
||||
import "@uiw/react-md-editor/markdown-editor.css";
|
||||
import "@uiw/react-markdown-preview/markdown.css";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface PlatformConfigFormProps {
|
||||
config: PlatformConfig;
|
||||
onSave: (config: PlatformConfig) => void;
|
||||
onThemeChange?: (theme: Theme) => Promise<void>;
|
||||
onAboutSave?: (aboutContent: string) => Promise<void>;
|
||||
onImageUpload?: (file: File, sha256?: string) => Promise<string>;
|
||||
isLoading?: boolean;
|
||||
isAboutLoading?: boolean;
|
||||
}
|
||||
|
||||
export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onThemeChange,
|
||||
onAboutSave,
|
||||
onImageUpload,
|
||||
isLoading = false,
|
||||
isAboutLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<PlatformConfig>(config);
|
||||
const [validationErrors, setValidationErrors] = useState<{
|
||||
domain?: string;
|
||||
mcp_server_prefix?: string;
|
||||
}>({});
|
||||
|
||||
// when context config updated, sync to form
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof PlatformConfig, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
// URL validation function with strict regex
|
||||
const validateUrl = (url: string): boolean => {
|
||||
if (!url.trim()) return true; // Empty is valid (optional field)
|
||||
|
||||
// Strict regex for domain validation
|
||||
const domainRegex = /^https?:\/\/(?:[-\w.])+(?:\:[0-9]+)?(?:\/.*)?$/;
|
||||
|
||||
// First check with regex
|
||||
if (!domainRegex.test(url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Then validate with URL constructor for additional checks
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
return (
|
||||
(urlObj.protocol === "http:" || urlObj.protocol === "https:") &&
|
||||
urlObj.hostname.length > 0 &&
|
||||
urlObj.hostname.includes(".")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Validate field and update errors
|
||||
const validateField = (
|
||||
field: "domain" | "mcp_server_prefix",
|
||||
value: string
|
||||
) => {
|
||||
const isValid = validateUrl(value);
|
||||
setValidationErrors((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
[field]: isValid
|
||||
? undefined
|
||||
: t("Please enter a valid URL with http:// or https://"),
|
||||
}));
|
||||
return isValid;
|
||||
};
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof PlatformConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
// Validate URL fields
|
||||
if (field === "domain" || field === "mcp_server_prefix") {
|
||||
validateField(field, value as string);
|
||||
}
|
||||
|
||||
setFormData((prev) => {
|
||||
const newData = {
|
||||
...prev,
|
||||
[field]: value,
|
||||
};
|
||||
|
||||
return newData;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
// Validate all URL fields before saving
|
||||
const domainValid = validateField("domain", formData.domain || "");
|
||||
const mcpServerValid = validateField(
|
||||
"mcp_server_prefix",
|
||||
formData.mcp_server_prefix || ""
|
||||
);
|
||||
|
||||
if (!domainValid || !mcpServerValid) {
|
||||
toast.error(t("Please fix validation errors before saving"));
|
||||
return;
|
||||
}
|
||||
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
@@ -61,21 +123,6 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
onThemeChange?.(theme);
|
||||
};
|
||||
|
||||
const handleAboutSave = async () => {
|
||||
onAboutSave?.(formData.about_page || "");
|
||||
};
|
||||
|
||||
const handleImageUpload = async (file: File): Promise<string> => {
|
||||
try {
|
||||
// 计算文件的 SHA256 哈希值
|
||||
const sha256 = await calculateFileSha256(file);
|
||||
return await onImageUpload!(file, sha256);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Platform Information Accordion */}
|
||||
@@ -170,6 +217,56 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
{/* platform domain */}
|
||||
<Input
|
||||
label={t("Platform Domain")}
|
||||
placeholder={t(
|
||||
"Enter platform domain (e.g., https://example.com)"
|
||||
)}
|
||||
description={t("The domain name of your platform")}
|
||||
value={formData.domain || ""}
|
||||
onChange={(e) => handleInputChange("domain", e.target.value)}
|
||||
isInvalid={!!validationErrors.domain}
|
||||
errorMessage={validationErrors.domain}
|
||||
/>
|
||||
|
||||
{/* mcp server prefix */}
|
||||
<Input
|
||||
label={t("MCP Server Domain")}
|
||||
placeholder={t(
|
||||
"Enter MCP server domain (e.g., https://mcp.example.com)"
|
||||
)}
|
||||
description={t("The domain for MCP server API calls")}
|
||||
value={formData.mcp_server_prefix || ""}
|
||||
onChange={(e) =>
|
||||
handleInputChange("mcp_server_prefix", e.target.value)
|
||||
}
|
||||
isInvalid={!!validationErrors.mcp_server_prefix}
|
||||
errorMessage={validationErrors.mcp_server_prefix}
|
||||
/>
|
||||
|
||||
{/* 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={formData.is_showcased ?? false}
|
||||
onValueChange={(value) => {
|
||||
handleInputChange("is_showcased", value);
|
||||
}}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
@@ -187,120 +284,6 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* About Page Accordion */}
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["about-config"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="about-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("About Page Content")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure about page content")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<MDEditor
|
||||
value={formData.about_page || ""}
|
||||
onChange={(value?: string) =>
|
||||
handleInputChange("about_page", value || "")
|
||||
}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={false}
|
||||
data-color-mode="light"
|
||||
textareaProps={{
|
||||
placeholder: t("Enter about page content (supports Markdown)"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.6,
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
},
|
||||
}}
|
||||
height={300}
|
||||
commands={[
|
||||
// 默认命令
|
||||
commands.bold,
|
||||
commands.italic,
|
||||
commands.strikethrough,
|
||||
commands.hr,
|
||||
commands.title,
|
||||
commands.divider,
|
||||
commands.link,
|
||||
commands.quote,
|
||||
commands.code,
|
||||
commands.codeBlock,
|
||||
commands.comment,
|
||||
commands.divider,
|
||||
commands.unorderedListCommand,
|
||||
commands.orderedListCommand,
|
||||
commands.checkedListCommand,
|
||||
commands.divider,
|
||||
// 自定义图片上传命令
|
||||
{
|
||||
name: "image-upload",
|
||||
keyCommand: "image-upload",
|
||||
buttonProps: {
|
||||
"aria-label": "Upload image",
|
||||
title: "Upload image",
|
||||
},
|
||||
icon: (
|
||||
<svg width="12" height="12" viewBox="0 0 20 20">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zM2 17l4.5-6 3.5 4.51 2.5-3.01L17 17H2z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
execute: (state, api) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
try {
|
||||
const dataUrl = await handleImageUpload(file);
|
||||
const imageMarkdown = ``;
|
||||
api.replaceSelection(imageMarkdown);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* About Save Button */}
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleAboutSave}
|
||||
isLoading={isAboutLoading}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Theme Accordion */}
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Table,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
Button,
|
||||
Input,
|
||||
Tooltip,
|
||||
Select,
|
||||
SelectItem,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Plus, Trash2, GripVertical } from "lucide-react";
|
||||
import {
|
||||
TopNavigationItem,
|
||||
TopNavigationTargetEnum,
|
||||
} from "@/shared/types/system";
|
||||
|
||||
interface TopNavigationSettingsProps {
|
||||
onSave?: (config: TopNavigationItem[]) => void;
|
||||
config?: TopNavigationItem[];
|
||||
}
|
||||
const defaultNavigationItems = [
|
||||
{ title: "", link: "", target: TopNavigationTargetEnum.BLANK },
|
||||
];
|
||||
export const TopNavigationSettings: React.FC<TopNavigationSettingsProps> = ({
|
||||
onSave,
|
||||
config = [],
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [navigationItems, setNavigationItems] = useState<TopNavigationItem[]>(
|
||||
config && config.length > 0 ? config : defaultNavigationItems
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const draggedItem = useRef<number | null>(null);
|
||||
const draggedOverItem = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
setNavigationItems(
|
||||
config && config.length > 0 ? config : defaultNavigationItems
|
||||
);
|
||||
}, [config]);
|
||||
|
||||
const handleTitleChange = (index: number, value: string) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) =>
|
||||
idx === index ? { ...item, title: value } : item
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleHrefChange = (index: number, value: string) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) => (idx === index ? { ...item, link: value } : item))
|
||||
);
|
||||
};
|
||||
|
||||
const handleTargetChange = (
|
||||
index: number,
|
||||
target: TopNavigationTargetEnum
|
||||
) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) => (idx === index ? { ...item, target } : item))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (index: number) => {
|
||||
setNavigationItems((prev) => {
|
||||
// Ensure at least one record remains
|
||||
if (prev.length <= 1) {
|
||||
return defaultNavigationItems;
|
||||
}
|
||||
return prev.filter((_, idx) => idx !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleInsertBelow = (index: number) => {
|
||||
setNavigationItems((prev) => {
|
||||
const newItem: TopNavigationItem = {
|
||||
title: "",
|
||||
link: "",
|
||||
target: TopNavigationTargetEnum.BLANK,
|
||||
};
|
||||
const newItems = [...prev];
|
||||
newItems.splice(index + 1, 0, newItem);
|
||||
return newItems;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDragStart = (index: number) => {
|
||||
draggedItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnter = (index: number) => {
|
||||
draggedOverItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
if (draggedItem.current !== null && draggedOverItem.current !== null) {
|
||||
const draggedItemIndex = draggedItem.current;
|
||||
const draggedOverItemIndex = draggedOverItem.current;
|
||||
|
||||
if (draggedItemIndex !== draggedOverItemIndex) {
|
||||
setNavigationItems((prev) => {
|
||||
const newItems = [...prev];
|
||||
const draggedItemContent = newItems[draggedItemIndex];
|
||||
newItems.splice(draggedItemIndex, 1);
|
||||
newItems.splice(draggedOverItemIndex, 0, draggedItemContent);
|
||||
return newItems;
|
||||
});
|
||||
}
|
||||
}
|
||||
draggedItem.current = null;
|
||||
draggedOverItem.current = null;
|
||||
};
|
||||
|
||||
const handleSaveAll = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(navigationItems.filter((item) => item.title && item.link));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["top-navigation"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="top-navigation"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("Top Navigation")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure top navigation menu items and links")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Navigation Table */}
|
||||
<Table
|
||||
aria-label="Navigation items management table"
|
||||
className="border-1 rounded-lg p-2"
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className="w-16">{t("Order")}</TableColumn>
|
||||
<TableColumn className="w-1/4">{t("Title")}</TableColumn>
|
||||
<TableColumn className="w-1/3">{t("Link")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Target")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody emptyContent={t("No navigation items available.")}>
|
||||
{navigationItems.map((item, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragEnter={() => handleDragEnter(index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="cursor-move"
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="w-4 h-4 text-gray-400" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={item.title}
|
||||
onValueChange={(value) => handleTitleChange(index, value)}
|
||||
placeholder={t("Enter title")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={item.link}
|
||||
onValueChange={(value) => handleHrefChange(index, value)}
|
||||
placeholder={t("Enter link URL")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
selectedKeys={[item.target]}
|
||||
onSelectionChange={(keys) => {
|
||||
const target = Array.from(keys)[0] as
|
||||
| TopNavigationTargetEnum.SELF
|
||||
| TopNavigationTargetEnum.BLANK;
|
||||
handleTargetChange(index, target);
|
||||
}}
|
||||
size="sm"
|
||||
className="min-w-24"
|
||||
>
|
||||
<SelectItem
|
||||
key={TopNavigationTargetEnum.SELF}
|
||||
value={TopNavigationTargetEnum.SELF}
|
||||
>
|
||||
{t("Same Tab")}
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
key={TopNavigationTargetEnum.BLANK}
|
||||
value={TopNavigationTargetEnum.BLANK}
|
||||
>
|
||||
{t("New Tab")}
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={t("Insert below")}>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => handleInsertBelow(index)}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("Delete")} color="danger">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="danger"
|
||||
onPress={() => handleDelete(index)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="flex">
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleSaveAll}
|
||||
isLoading={isSaving}
|
||||
isDisabled={navigationItems.length === 0}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -13,24 +13,40 @@ import { NavigationItems } from "@/components/theme/Theme.const";
|
||||
import { AboutContent } from "@/components/about/AboutContent";
|
||||
|
||||
export const AboutThemeSelector: React.FC = () => {
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...(platformConfig.about_page
|
||||
? [
|
||||
{
|
||||
label: "About",
|
||||
href: "/about",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
|
||||
// Render the About page based on the current theme
|
||||
switch (currentTheme) {
|
||||
case Theme.MODERN:
|
||||
return <ModernAbout navItems={NavigationItems} />;
|
||||
return <ModernAbout navItems={navigationItems} />;
|
||||
case Theme.CLASSIC:
|
||||
return <ClassicAbout navItems={NavigationItems} />;
|
||||
return <ClassicAbout navItems={navigationItems} />;
|
||||
case Theme.CREATIVE:
|
||||
return <CreativeAbout navItems={NavigationItems} />;
|
||||
return <CreativeAbout navItems={navigationItems} />;
|
||||
case Theme.TEMU:
|
||||
return <TemuAbout navItems={NavigationItems} />;
|
||||
return <TemuAbout navItems={navigationItems} />;
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1 max-w-7xl mx-auto px-4 py-8">
|
||||
<AboutContent />
|
||||
</main>
|
||||
|
||||
@@ -12,6 +12,9 @@ import { ProductDetailClient } from "@/shared/components/marketplace/ProductDeta
|
||||
import { Navigation } from "@/shared/components/Navigation";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { NavigationItems } from "./Theme.const";
|
||||
import { copyToClipboard } from "@/shared/utils/clipboard";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface ProductDetailThemeSelectorProps {
|
||||
product: ServiceData;
|
||||
@@ -24,13 +27,78 @@ interface ProductDetailThemeSelectorProps {
|
||||
export const ProductDetailThemeSelector: React.FC<
|
||||
ProductDetailThemeSelectorProps
|
||||
> = ({ product, breadcrumbs }) => {
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const [url, setUrl] = useState<string>(process.env.NEXT_PUBLIC_MCP_URL || "");
|
||||
const mcpServerPrefix =
|
||||
platformConfig.mcp_server_prefix || process.env.NEXT_PUBLIC_MCP_URL || "";
|
||||
const [url, setUrl] = useState<string>("");
|
||||
const [mcpName, setMcpName] = useState<string>("");
|
||||
const { t } = useTranslation();
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...(platformConfig.about_page
|
||||
? [
|
||||
{
|
||||
label: "About",
|
||||
href: "/about",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
useEffect(() => {
|
||||
if (url || !product.slug_name) return;
|
||||
setUrl(`${window.location.origin}/mcp/${product.slug_name}`);
|
||||
setUrl(
|
||||
`${
|
||||
mcpServerPrefix ||
|
||||
`${window.location.protocol}//${window.location.hostname}:8002`
|
||||
}/mcp/${product.slug_name}`
|
||||
);
|
||||
}, [product.slug_name]);
|
||||
function sanitizeMCPServerName(rawName: string | undefined): string {
|
||||
if (!rawName) return "xpack-mcp-service";
|
||||
|
||||
// Lower-case & replace invalid chars with hyphen
|
||||
let name = rawName
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-_]+/g, "-");
|
||||
|
||||
// Collapse multiple hyphens
|
||||
name = name.replace(/-+/g, "-");
|
||||
|
||||
// Trim leading/trailing hyphens
|
||||
name = name.replace(/^-+/, "").replace(/-+$/, "");
|
||||
|
||||
return name || "mcp-service";
|
||||
}
|
||||
useEffect(() => {
|
||||
setMcpName(sanitizeMCPServerName(product.name));
|
||||
}, [product.name]);
|
||||
const getCodeContent = () => {
|
||||
return `{
|
||||
"mcpServers": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey={Your-${platformConfig?.name}-API-Key}"
|
||||
}
|
||||
}
|
||||
}`;
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const result = await copyToClipboard(getCodeContent());
|
||||
if (result.success) {
|
||||
toast.success(t("Copied to clipboard"));
|
||||
} else {
|
||||
toast.error(t("Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
//Render the About page based on the current theme
|
||||
switch (currentTheme) {
|
||||
@@ -40,7 +108,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.CLASSIC:
|
||||
@@ -49,7 +119,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.CREATIVE:
|
||||
@@ -58,7 +130,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.TEMU:
|
||||
@@ -67,16 +141,22 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1">
|
||||
<ProductDetailClient product={product} />
|
||||
<ProductDetailClient
|
||||
product={product}
|
||||
mcpName={mcpName}
|
||||
url={url}
|
||||
/>
|
||||
</main>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -5,8 +5,4 @@ export const NavigationItems: NavigationItem[] = [
|
||||
label: "Home",
|
||||
href: "/",
|
||||
},
|
||||
{
|
||||
label: "About",
|
||||
href: "/about",
|
||||
},
|
||||
];
|
||||
@@ -14,6 +14,7 @@ import { Navigation } from "@/shared/components/Navigation";
|
||||
import { MarketplaceMain } from "../marketplace/Main";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { NavigationItems } from "./Theme.const";
|
||||
import { Faq } from "../marketplace/Faq";
|
||||
|
||||
interface ThemeSelectorProps {
|
||||
initialServices: ServiceData[];
|
||||
@@ -33,8 +34,24 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
error,
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...(platformConfig.about_page
|
||||
? [
|
||||
{
|
||||
label: "About",
|
||||
href: "/about",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
|
||||
// state management for services, search query, pagination, and loading state
|
||||
const [searchQuery, setSearchQuery] = useState(initialSearch);
|
||||
@@ -122,7 +139,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.CLASSIC:
|
||||
@@ -139,7 +156,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.CREATIVE:
|
||||
@@ -156,7 +173,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.TEMU:
|
||||
@@ -173,14 +190,14 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1">
|
||||
<MarketplaceMain
|
||||
initialServices={services}
|
||||
@@ -190,6 +207,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
pageSize={pageSize}
|
||||
error={error}
|
||||
/>
|
||||
<Faq />
|
||||
</main>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { FileText, Wrench, Cog } from "lucide-react";
|
||||
import { FileText, Wrench, Cog, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import Link from "next/link";
|
||||
@@ -21,16 +21,18 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -83,7 +85,7 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-lg mb-4">
|
||||
<p className="text-sm mb-4">
|
||||
{product.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
@@ -93,10 +95,12 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Price section */}
|
||||
{product.charge_type && (
|
||||
<div className="flex gap-2 items-center">
|
||||
<b className="text-xs">{t("Price")}:</b>
|
||||
<b className="text-md">{t("Price")}:</b>
|
||||
<Price
|
||||
price={product.price}
|
||||
charge_type={product.charge_type}
|
||||
input_token_price={product.input_token_price}
|
||||
output_token_price={product.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -209,20 +213,28 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove"":"all",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -163,13 +164,14 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="bg-gray-50 py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card className="group h-[200px] hover:shadow-lg transition-shadow duration-200 cursor-pointer border border-gray-200 bg-white rounded-sm shadow-sm">
|
||||
<Card className="group h-[200px] w-full hover:shadow-lg transition-shadow duration-200 cursor-pointer border border-gray-200 bg-white rounded-sm shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
@@ -211,6 +213,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -245,6 +249,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Faq />
|
||||
</div>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -43,7 +43,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
<div className="flex items-center justify-between max-w-7xl mx-auto">
|
||||
<div className="flex space-x-6">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { Sparkles, Zap, Settings2 } from "lucide-react";
|
||||
import { Sparkles, Zap, Settings2, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +20,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -41,151 +43,190 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-pink-50 via-orange-50 to-yellow-50 relative overflow-hidden">
|
||||
<div className="min-h-screen bg-gradient-to-br from-pink-50 via-orange-50 to-yellow-50 relative overflow-hidden flex flex-col justify-between">
|
||||
<Navigation items={navItems} />
|
||||
{/* Creative Background */}
|
||||
<div className="absolute inset-0">
|
||||
{/* Artistic decorative elements */}
|
||||
<div className="absolute top-20 left-20 w-32 h-32 bg-gradient-to-br from-pink-200/30 to-orange-200/30 rounded-full blur-2xl" />
|
||||
<div className="absolute top-40 right-32 w-24 h-24 bg-gradient-to-br from-orange-200/40 to-yellow-200/40 rounded-2xl rotate-45 blur-xl" />
|
||||
<div className="absolute bottom-32 left-1/4 w-40 h-40 bg-gradient-to-br from-yellow-200/25 to-pink-200/25 rounded-full blur-3xl" />
|
||||
<div className="absolute bottom-20 right-20 w-28 h-28 bg-gradient-to-br from-pink-200/35 to-red-200/35 rounded-2xl rotate-12 blur-xl" />
|
||||
<div className="flex-1 relative">
|
||||
<div className="absolute inset-0">
|
||||
{/* Artistic decorative elements */}
|
||||
<div className="absolute top-20 left-20 w-32 h-32 bg-gradient-to-br from-pink-200/30 to-orange-200/30 rounded-full blur-2xl" />
|
||||
<div className="absolute top-40 right-32 w-24 h-24 bg-gradient-to-br from-orange-200/40 to-yellow-200/40 rounded-2xl rotate-45 blur-xl" />
|
||||
<div className="absolute bottom-32 left-1/4 w-40 h-40 bg-gradient-to-br from-yellow-200/25 to-pink-200/25 rounded-full blur-3xl" />
|
||||
<div className="absolute bottom-20 right-20 w-28 h-28 bg-gradient-to-br from-pink-200/35 to-red-200/35 rounded-2xl rotate-12 blur-xl" />
|
||||
|
||||
{/* Additional artistic elements */}
|
||||
<div className="absolute top-1/3 left-1/3 w-20 h-20 bg-gradient-to-br from-orange-300/20 to-yellow-300/20 rounded-full blur-xl" />
|
||||
<div className="absolute top-2/3 right-1/3 w-16 h-16 bg-gradient-to-br from-pink-300/25 to-orange-300/25 rounded-lg rotate-45 blur-lg" />
|
||||
</div>
|
||||
|
||||
<div className="relative z-10">
|
||||
{/* Creative Product Header */}
|
||||
<div className="pt-24">
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-pink-200/50">
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
</div>
|
||||
</div>
|
||||
{/* Additional artistic elements */}
|
||||
<div className="absolute top-1/3 left-1/3 w-20 h-20 bg-gradient-to-br from-orange-300/20 to-yellow-300/20 rounded-full blur-xl" />
|
||||
<div className="absolute top-2/3 right-1/3 w-16 h-16 bg-gradient-to-br from-pink-300/25 to-orange-300/25 rounded-lg rotate-45 blur-lg" />
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/5 via-transparent to-orange-500/5" />
|
||||
<CardBody className="p-0 relative">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="secondary"
|
||||
className="px-6 pt-6"
|
||||
classNames={{
|
||||
tabList:
|
||||
"gap-6 w-full relative rounded-none p-0 border-b border-pink-200/50",
|
||||
cursor:
|
||||
"w-full bg-gradient-to-r from-pink-500 via-red-500 to-orange-500",
|
||||
tab: "max-w-fit px-0 h-12",
|
||||
tabContent:
|
||||
"group-data-[selected=true]:text-pink-600 font-semibold",
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
key="overview"
|
||||
title={
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>{t("Overview")}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
<ProductOverview product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<Zap className="w-4 h-4" />
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip
|
||||
size="sm"
|
||||
className="h-4 text-xs bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 text-white shadow-lg"
|
||||
>
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
<ProductTools product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</CardBody>
|
||||
</Card>
|
||||
<div className="relative z-10">
|
||||
{/* Creative Product Header */}
|
||||
<div className="pt-24">
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-pink-200/50">
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-orange-500/5 via-transparent to-pink-500/5" />
|
||||
<CardBody className="relative">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 rounded-lg">
|
||||
<Settings2 className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg bg-gradient-to-r from-pink-600 to-orange-600 bg-clip-text text-transparent">
|
||||
{t("Configuration")}
|
||||
</h3>
|
||||
</div>
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
{/* Main Content */}
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/5 via-transparent to-orange-500/5" />
|
||||
<CardBody className="p-0 relative">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="secondary"
|
||||
className="px-6 pt-6"
|
||||
classNames={{
|
||||
tabList:
|
||||
"gap-6 w-full relative rounded-none p-0 border-b border-pink-200/50",
|
||||
cursor:
|
||||
"w-full bg-gradient-to-r from-pink-500 via-red-500 to-orange-500",
|
||||
tab: "max-w-fit px-0 h-12",
|
||||
tabContent:
|
||||
"group-data-[selected=true]:text-pink-600 font-semibold",
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
key="overview"
|
||||
title={
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>{t("Overview")}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
<div className="p-6 pt-4">
|
||||
<ProductOverview product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<Zap className="w-4 h-4" />
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip
|
||||
size="sm"
|
||||
className="h-4 text-xs bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 text-white shadow-lg"
|
||||
>
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
{product.tools.length > 0 ? (
|
||||
product.tools.map((tool, index) => (
|
||||
<Card
|
||||
radius="sm"
|
||||
key={`${product.service_id}-tool-${index}`}
|
||||
shadow="none"
|
||||
className="border-1"
|
||||
>
|
||||
<CardBody>
|
||||
<h4 className="font-semibold text-sm mb-2 text-pink-600">
|
||||
{tool.name}
|
||||
</h4>
|
||||
<p className="text-sm mb-3">
|
||||
{tool.description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Card>
|
||||
<CardBody>
|
||||
<p className="text-center">
|
||||
{t("No tools available in this service.")}
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-orange-500/5 via-transparent to-pink-500/5" />
|
||||
<CardBody className="relative">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 rounded-lg">
|
||||
<Settings2 className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg bg-gradient-to-r from-pink-600 to-orange-600 bg-clip-text text-transparent">
|
||||
{t("Configuration")}
|
||||
</h3>
|
||||
</div>
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove"":"all",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
}
|
||||
}
|
||||
}`}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</Card>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</Card>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Footer />
|
||||
<div>
|
||||
<Footer />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -69,17 +70,17 @@ export const Home: React.FC<HomeProps> = ({
|
||||
|
||||
{/* Creative Background decorative elements */}
|
||||
<div className="absolute inset-0 overflow-hidden pointer-events-none z-50">
|
||||
{/* 主要装饰圆圈 */}
|
||||
{/* main decorative circles */}
|
||||
<div className="absolute top-1/4 left-1/4 w-64 h-64 bg-gradient-to-r from-pink-400/15 to-orange-400/15 rounded-full blur-3xl animate-pulse"></div>
|
||||
<div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-gradient-to-r from-orange-400/10 to-yellow-400/10 rounded-full blur-3xl"></div>
|
||||
|
||||
{/* 小装饰圆圈 */}
|
||||
{/* small decorative circles */}
|
||||
<div className="absolute top-10 right-20 w-16 h-16 bg-gradient-to-br from-pink-400/20 to-red-500/20 rounded-full transform rotate-12"></div>
|
||||
<div className="absolute top-32 left-16 w-12 h-12 bg-gradient-to-br from-orange-400/25 to-yellow-400/25 rounded-full transform -rotate-12"></div>
|
||||
<div className="absolute bottom-20 left-1/3 w-20 h-20 bg-gradient-to-br from-yellow-400/15 to-pink-400/15 rounded-full transform rotate-6"></div>
|
||||
<div className="absolute bottom-32 right-16 w-14 h-14 bg-gradient-to-br from-purple-400/20 to-pink-400/20 rounded-full transform -rotate-6"></div>
|
||||
|
||||
{/* 微小装饰点 */}
|
||||
{/* small decorative points */}
|
||||
<div className="absolute top-1/3 right-1/3 w-4 h-4 bg-pink-400/30 rounded-full"></div>
|
||||
<div className="absolute top-2/3 left-1/5 w-3 h-3 bg-orange-400/40 rounded-full"></div>
|
||||
<div className="absolute bottom-1/3 right-1/5 w-5 h-5 bg-yellow-400/25 rounded-full"></div>
|
||||
@@ -129,7 +130,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
placeholder={
|
||||
searchSuggestions.length > 0
|
||||
? t(searchSuggestions[0])
|
||||
: t("✨ 发现神奇的服务...")
|
||||
: t("✨ Discover amazing services...")
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
@@ -170,9 +171,6 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="bg-white/90 backdrop-blur-xl p-8 rounded-2xl shadow-lg border border-pink-200/50">
|
||||
<div className="flex items-center gap-4">
|
||||
<Spinner size="lg" color="secondary" />
|
||||
<span className="text-gray-700 text-lg font-bold">
|
||||
✨ 加载魔法中...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -180,7 +178,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="relative z-10">
|
||||
<div className="relative mx-auto px-6 py-16 max-w-8xl">
|
||||
{/* Creative Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service, index) => {
|
||||
const gradientBorders = [
|
||||
"border-pink-200/50",
|
||||
@@ -211,7 +209,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="block group"
|
||||
className="block group w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card
|
||||
className={`
|
||||
@@ -220,11 +218,11 @@ export const Home: React.FC<HomeProps> = ({
|
||||
hover:scale-105 hover:shadow-xl
|
||||
transition-all duration-300 ease-out
|
||||
group-hover:bg-white/90 relative
|
||||
h-[200px]
|
||||
h-[200px] w-full
|
||||
`}
|
||||
>
|
||||
<CardBody className="p-6">
|
||||
{/* 创意图标 */}
|
||||
{/* creative icon */}
|
||||
<div
|
||||
className={` absolute -top-2 -left-2
|
||||
w-8 h-8 ${iconGradients[index % 6]}
|
||||
@@ -233,17 +231,18 @@ export const Home: React.FC<HomeProps> = ({
|
||||
`}
|
||||
></div>
|
||||
|
||||
{/* 服务标题 */}
|
||||
{/* service title */}
|
||||
<div className="text-lg font-bold text-gray-800 mb-2 group-hover:text-gray-900 transition-colors">
|
||||
{service.name}
|
||||
</div>
|
||||
|
||||
{/* 服务描述 */}
|
||||
<div className="text-sm text-gray-600 group-hover:text-gray-700 transition-colors flex-1">
|
||||
{service.short_description || "探索精彩服务"}
|
||||
{/* service description */}
|
||||
<div className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</div>
|
||||
|
||||
{/* 装饰性元素 */}
|
||||
{/* decorative elements */}
|
||||
<div className="absolute top-2 right-2 w-3 h-3 bg-gradient-to-r from-pink-400/30 to-orange-400/30 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
|
||||
</CardBody>
|
||||
|
||||
@@ -265,6 +264,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -317,6 +318,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
`}</style>
|
||||
</div>
|
||||
)}
|
||||
<Faq />
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -52,7 +52,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</div>
|
||||
<div className="hidden lg:flex gap-6 justify-center">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { Monitor, Code, Settings } from "lucide-react";
|
||||
import { Monitor, Code, Settings, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +21,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -137,20 +140,28 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove"":"all",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -106,7 +107,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
{/* Modern Search Bar */}
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="bg-white p-1 rounded-xl shadow-sm border border-gray-100">
|
||||
<div className="flex">
|
||||
<div className="flex gap-1">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
size="lg"
|
||||
@@ -141,97 +142,103 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Service List Section */}
|
||||
{loading ? (
|
||||
<div className="mx-auto h-[200px] flex items-center justify-center">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md">
|
||||
<Spinner size="lg" color="primary" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
>
|
||||
<Card className="group h-[200px] hover:shadow-lg transition-all duration-200 cursor-pointer bg-white border border-gray-100 rounded-xl shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Zap className="w-4 h-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-gray-900 text-base mb-1 truncate group-hover:text-blue-600 transition-colors">
|
||||
{service.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
|
||||
{/* Footer */}
|
||||
<CardFooter className="pt-0 px-4 pb-4">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
{/* Tools count */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-blue-600 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{t("{{count}} Tools", {
|
||||
count: service.tools.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="flex flex-col items-end">
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
<section>
|
||||
{/* Service List Section */}
|
||||
{loading ? (
|
||||
<div className="mx-auto h-[200px] flex items-center justify-center">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md">
|
||||
<Spinner size="lg" color="primary" />
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center">
|
||||
<Pagination
|
||||
total={totalPages}
|
||||
page={currentPage}
|
||||
onChange={onPageChange}
|
||||
showControls
|
||||
color="primary"
|
||||
variant="light"
|
||||
size="lg"
|
||||
classNames={{
|
||||
wrapper: "gap-2",
|
||||
item: "w-10 h-10 text-sm font-medium",
|
||||
cursor:
|
||||
"bg-gradient-to-r from-blue-500 to-indigo-600 shadow-sm",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<div className="py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card className="group h-[200px] w-full hover:shadow-lg transition-all duration-200 cursor-pointer bg-white border border-gray-100 rounded-xl shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Zap className="w-4 h-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-gray-900 text-base mb-1 truncate group-hover:text-blue-600 transition-colors">
|
||||
{service.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
|
||||
{/* Footer */}
|
||||
<CardFooter className="pt-0 px-4 pb-4">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
{/* Tools count */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-blue-600 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{t("{{count}} Tools", {
|
||||
count: service.tools.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="flex flex-col items-end">
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center">
|
||||
<Pagination
|
||||
total={totalPages}
|
||||
page={currentPage}
|
||||
onChange={onPageChange}
|
||||
showControls
|
||||
color="primary"
|
||||
variant="light"
|
||||
size="lg"
|
||||
classNames={{
|
||||
wrapper: "gap-2",
|
||||
item: "w-10 h-10 text-sm font-medium",
|
||||
cursor:
|
||||
"bg-gradient-to-r from-blue-500 to-indigo-600 shadow-sm",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<Faq />
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
@@ -48,7 +48,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</div>
|
||||
<div className="hidden lg:flex gap-6 justify-center">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { FileText, Wrench, Cog } from "lucide-react";
|
||||
import { FileText, Wrench, Cog, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +20,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -158,20 +160,28 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove"":"all",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -188,6 +189,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</CardFooter>
|
||||
@@ -212,6 +215,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Faq />
|
||||
</div>
|
||||
|
||||
<Footer />
|
||||
|
||||
@@ -52,7 +52,9 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
<div className="hidden lg:flex gap-8 justify-center ml-8">
|
||||
{items?.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-gray-700 hover:text-orange-500 font-medium transition-colors"
|
||||
>
|
||||
{t(item.label)}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
ModalContent,
|
||||
ModalHeader,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
Button,
|
||||
Input,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
|
||||
interface AdminRechargeModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
user: User | null;
|
||||
onRecharge: (id: string, amount: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
user,
|
||||
onRecharge,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [amount, setAmount] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value;
|
||||
// 只允许输入数字和小数点
|
||||
if (/^\d*\.?\d*$/.test(value) || value === "") {
|
||||
setAmount(value);
|
||||
setError("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRecharge = async () => {
|
||||
const numAmount = parseFloat(amount);
|
||||
if (isNaN(numAmount) || numAmount <= 0) {
|
||||
setError(t("Please enter a valid amount"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (numAmount < 1) {
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
setError(t("User not selected"));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const success = await onRecharge(user.id, numAmount);
|
||||
|
||||
if (success) {
|
||||
handleClose();
|
||||
}
|
||||
} catch (error) {
|
||||
setError(t("Network error, please try again"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAmount("");
|
||||
setError("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={handleClose} size="sm">
|
||||
<ModalContent>
|
||||
{() => (
|
||||
<>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
{t("Recharge User")}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
{user && (
|
||||
<div className="mb-4 p-3 bg-gray-50 rounded-lg">
|
||||
<p className="text-sm text-gray-600">
|
||||
{t("User")}: {user.email}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{t("Current Balance")}: ${user.balance.toFixed(2)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<Input
|
||||
autoFocus
|
||||
label={t("Recharge Amount")}
|
||||
placeholder="0.00"
|
||||
value={amount}
|
||||
onChange={handleAmountChange}
|
||||
startContent={
|
||||
<div className="pointer-events-none flex items-center">
|
||||
<span className="text-default-400 text-small">$</span>
|
||||
</div>
|
||||
}
|
||||
isInvalid={!!error}
|
||||
errorMessage={error}
|
||||
type="number"
|
||||
/>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button color="danger" variant="light" onPress={handleClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleRecharge}
|
||||
isLoading={loading}
|
||||
isDisabled={!amount || !!error}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</>
|
||||
)}
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -12,8 +12,14 @@ const UserManagement: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// use custom hook to manage user data
|
||||
const { users, loading, pagination, handleDeleteUser, setPage } =
|
||||
useUserManagement();
|
||||
const {
|
||||
users,
|
||||
loading,
|
||||
pagination,
|
||||
handleDeleteUser,
|
||||
setPage,
|
||||
handleRechargeUser,
|
||||
} = useUserManagement();
|
||||
|
||||
// Modal states
|
||||
const [deleteModal, setDeleteModal] = useState({
|
||||
@@ -47,6 +53,13 @@ const UserManagement: React.FC = () => {
|
||||
setDeleteModal({ isOpen: false, user: null });
|
||||
}, []);
|
||||
|
||||
const handleRecharge = useCallback(
|
||||
async (id: string, amount: number): Promise<boolean> => {
|
||||
return await handleRechargeUser(id, amount);
|
||||
},
|
||||
[handleRechargeUser]
|
||||
);
|
||||
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("User Management")}
|
||||
@@ -59,6 +72,7 @@ const UserManagement: React.FC = () => {
|
||||
users={users}
|
||||
loading={loading}
|
||||
onDelete={handleDeleteUserClick}
|
||||
onRecharge={handleRecharge}
|
||||
pagination={pagination}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import React from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -11,16 +11,18 @@ import {
|
||||
Button,
|
||||
Pagination,
|
||||
Tooltip,
|
||||
Spinner
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { User } from '@/types/user';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
Spinner,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
import { Trash2, CreditCard } from "lucide-react";
|
||||
import { AdminRechargeModal } from "@/components/user-management/AdminRechargeModal";
|
||||
|
||||
interface UserTableProps {
|
||||
users: User[];
|
||||
loading?: boolean;
|
||||
onDelete: (user: User) => void;
|
||||
onRecharge: (id: string, amount: number) => Promise<boolean>;
|
||||
pagination: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
@@ -33,6 +35,7 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
users,
|
||||
loading = false,
|
||||
onDelete,
|
||||
onRecharge,
|
||||
pagination,
|
||||
onPageChange,
|
||||
}) => {
|
||||
@@ -45,10 +48,25 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
// 直接显示传入的用户数据(已经是当前页的数据)
|
||||
const items = users;
|
||||
|
||||
const [isRechargeModalOpen, setIsRechargeModalOpen] = React.useState(false);
|
||||
const [selectedUser, setSelectedUser] = React.useState<User | null>(null);
|
||||
|
||||
const handleDelete = React.useCallback((user: User) => {
|
||||
onDelete(user);
|
||||
}, [onDelete]);
|
||||
const handleDelete = React.useCallback(
|
||||
(user: User) => {
|
||||
onDelete(user);
|
||||
},
|
||||
[onDelete]
|
||||
);
|
||||
|
||||
const handleRecharge = React.useCallback((user: User) => {
|
||||
setSelectedUser(user);
|
||||
setIsRechargeModalOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRechargeClose = React.useCallback(() => {
|
||||
setIsRechargeModalOpen(false);
|
||||
setSelectedUser(null);
|
||||
}, []);
|
||||
|
||||
if (loading && users.length === 0) {
|
||||
return (
|
||||
@@ -68,33 +86,50 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>{t('Email')}</TableColumn>
|
||||
<TableColumn>{t('Register Date')}</TableColumn>
|
||||
<TableColumn>{t('Balance')}</TableColumn>
|
||||
<TableColumn>{t('Actions')}</TableColumn>
|
||||
<TableColumn>{t("Email")}</TableColumn>
|
||||
<TableColumn>{t("Register Date")}</TableColumn>
|
||||
<TableColumn>{t("Balance")}</TableColumn>
|
||||
<TableColumn>{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
isLoading={loading}
|
||||
loadingContent={<Spinner />}
|
||||
emptyContent={t('No users found')}
|
||||
emptyContent={t("No users found")}
|
||||
>
|
||||
{(user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<span className="text-sm">{user.email}</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{user.created_at || '-'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{user.balance.toFixed(2) || "-"}
|
||||
</TableCell>
|
||||
<TableCell>{user.created_at || "-"}</TableCell>
|
||||
<TableCell>{user.balance.toFixed(2) || "-"}</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<div className="relative flex items-center gap-2">
|
||||
<Tooltip
|
||||
content={t("Recharge User")}
|
||||
color="primary"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="primary"
|
||||
onPress={() => handleRecharge(user)}
|
||||
>
|
||||
<CreditCard className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={t('Delete User')} color="danger" closeDelay={0}>
|
||||
<Tooltip
|
||||
content={t("Delete User")}
|
||||
color="danger"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -124,6 +159,14 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Admin Recharge Modal */}
|
||||
<AdminRechargeModal
|
||||
isOpen={isRechargeModalOpen}
|
||||
onClose={handleRechargeClose}
|
||||
user={selectedUser}
|
||||
onRecharge={onRecharge}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { HomepageConfig } from "@/services/homepageConfigService";
|
||||
import {
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
} from "@/shared/types/system";
|
||||
import { homepageConfigService } from "@/services/homepageConfigService";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { revalidatePlatformConfig } from "@/app/actions/revalidate";
|
||||
|
||||
export const useHomepageConfigManagement = () => {
|
||||
const { updateClientConfig } = usePlatformConfig();
|
||||
|
||||
// homepage config state
|
||||
const [homepageConfig, setHomepageConfig] = useState<HomepageConfig>({
|
||||
faq: [],
|
||||
top_navigation: [],
|
||||
embeded_html: {
|
||||
is_enabled: false,
|
||||
html: "",
|
||||
},
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// load homepage config
|
||||
const loadHomepageConfig = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const config = await homepageConfigService.getHomepageConfig();
|
||||
setHomepageConfig(config);
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to load homepage config";
|
||||
setError(errorMessage);
|
||||
console.error("Failed to load homepage config:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save homepage config
|
||||
const saveHomepageConfig = useCallback(
|
||||
async (config: {
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
}): Promise<boolean> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await homepageConfigService.updateHomepageConfig(config);
|
||||
if (result) {
|
||||
updateClientConfig(config);
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save homepage config";
|
||||
setError(errorMessage);
|
||||
console.error("Failed to save homepage config:", err);
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// save FAQ data
|
||||
const saveFaqConfig = useCallback(
|
||||
async (faqs: FaqItem[]): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ faq: faqs });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// save navigation data
|
||||
const saveNavigationConfig = useCallback(
|
||||
async (navigationItems: TopNavigationItem[]): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ top_navigation: navigationItems });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// save embedded HTML data
|
||||
const saveEmbeddedHtmlConfig = useCallback(
|
||||
async (htmlData: EmbeddedHtmlConfig): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ embeded_html: htmlData });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// clear error
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
// load config on init
|
||||
useEffect(() => {
|
||||
loadHomepageConfig();
|
||||
}, [loadHomepageConfig]);
|
||||
|
||||
return {
|
||||
// state
|
||||
homepageConfig,
|
||||
loading,
|
||||
error,
|
||||
|
||||
// actions
|
||||
loadHomepageConfig,
|
||||
saveHomepageConfig,
|
||||
saveFaqConfig,
|
||||
saveNavigationConfig,
|
||||
saveEmbeddedHtmlConfig,
|
||||
clearError,
|
||||
};
|
||||
};
|
||||
@@ -2,22 +2,41 @@ import { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
PaymentChannelApiItem,
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
PaymentChannelTestResult,
|
||||
} from "@/types/payment";
|
||||
import { paymentChannelService } from "@/services/paymentChannelService";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { revalidatePlatformConfig } from "@/app/actions/revalidate";
|
||||
|
||||
export const usePaymentChannelManagement = () => {
|
||||
const { updateClientConfig, paymentChannels } = usePlatformConfig();
|
||||
const [channels, setChannels] = useState<PaymentChannelApiItem[]>([]);
|
||||
const [stripeConfig, setStripeConfig] = useState<StripeConfig>({
|
||||
secret: "",
|
||||
webhook_secret: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [alipayConfig, setAlipayConfig] = useState<AlipayConfig>({
|
||||
app_id: "",
|
||||
app_private_key: "",
|
||||
alipay_public_key: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [wechatConfig, setWechatConfig] = useState<WechatConfig>({
|
||||
app_id: "",
|
||||
mch_id: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [testResult, setTestResult] = useState<PaymentChannelTestResult | null>(
|
||||
null
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [isWechatSaving, setIsWechatSaving] = useState(false);
|
||||
const [isStripeSaving, setIsStripeSaving] = useState(false);
|
||||
const [isAlipaySaving, setIsAlipaySaving] = useState(false);
|
||||
|
||||
// get payment channel list
|
||||
const fetchChannels = useCallback(async () => {
|
||||
@@ -29,12 +48,35 @@ export const usePaymentChannelManagement = () => {
|
||||
|
||||
setChannels(response.data);
|
||||
|
||||
// find stripe channel and get config
|
||||
// find channels and get configs
|
||||
const stripeChannel = response.data.find(
|
||||
(channel) => channel.id === "stripe"
|
||||
);
|
||||
if (stripeChannel) {
|
||||
setStripeConfig(stripeChannel.config);
|
||||
setStripeConfig({
|
||||
...stripeChannel.config,
|
||||
is_enabled: stripeChannel.is_enabled,
|
||||
} as StripeConfig);
|
||||
}
|
||||
|
||||
const alipayChannel = response.data.find(
|
||||
(channel) => channel.id === "alipay"
|
||||
);
|
||||
if (alipayChannel) {
|
||||
setAlipayConfig({
|
||||
...alipayChannel.config,
|
||||
is_enabled: alipayChannel.is_enabled,
|
||||
} as AlipayConfig);
|
||||
}
|
||||
|
||||
const wechatChannel = response.data.find(
|
||||
(channel) => channel.id === "wechat"
|
||||
);
|
||||
if (wechatChannel) {
|
||||
setWechatConfig({
|
||||
...wechatChannel.config,
|
||||
is_enabled: wechatChannel.is_enabled,
|
||||
} as WechatConfig);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(
|
||||
@@ -48,9 +90,103 @@ export const usePaymentChannelManagement = () => {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// test alipay connection
|
||||
const testAlipayConnection = useCallback(async (config: AlipayConfig) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.testAlipayConnection(config);
|
||||
setTestResult(result);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to test alipay connection";
|
||||
const failedResult: PaymentChannelTestResult = {
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
};
|
||||
setTestResult(failedResult);
|
||||
setError(errorMessage);
|
||||
return failedResult;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// test wechat connection
|
||||
const testWechatConnection = useCallback(async (config: WechatConfig) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.testWechatConnection(config);
|
||||
setTestResult(result);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to test wechat connection";
|
||||
const failedResult: PaymentChannelTestResult = {
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
};
|
||||
setTestResult(failedResult);
|
||||
setError(errorMessage);
|
||||
return failedResult;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save alipay config
|
||||
const saveAlipayConfig = useCallback(async (config: AlipayConfig) => {
|
||||
setIsAlipaySaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.saveAlipayConfig(config);
|
||||
if (result) {
|
||||
setAlipayConfig(config);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save alipay config";
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsAlipaySaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save wechat config
|
||||
const saveWechatConfig = useCallback(async (config: WechatConfig) => {
|
||||
setIsWechatSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.saveWechatConfig(config);
|
||||
if (result) {
|
||||
setWechatConfig(config);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save wechat config";
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsWechatSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save stripe config
|
||||
const saveStripeConfig = useCallback(async (config: StripeConfig) => {
|
||||
setIsSaving(true);
|
||||
setIsStripeSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
@@ -67,7 +203,7 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
setIsStripeSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -102,16 +238,25 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await paymentChannelService.enablePaymentChannel(channelId);
|
||||
await fetchChannels(); // re-fetch list
|
||||
return { success: true };
|
||||
const result =
|
||||
await paymentChannelService.enablePaymentChannel(channelId);
|
||||
if (result) {
|
||||
updateClientConfig({
|
||||
payment_channels: [
|
||||
...paymentChannels,
|
||||
{ id: channelId, name: channelId },
|
||||
],
|
||||
});
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Failed to enable payment channel";
|
||||
setError(errorMessage);
|
||||
return { success: false, message: errorMessage };
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -126,16 +271,24 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await paymentChannelService.disablePaymentChannel(channelId);
|
||||
await fetchChannels(); // re-fetch list
|
||||
return { success: true };
|
||||
const result =
|
||||
await paymentChannelService.disablePaymentChannel(channelId);
|
||||
if (result) {
|
||||
updateClientConfig({
|
||||
payment_channels: paymentChannels.filter(
|
||||
(channel) => channel.id !== channelId
|
||||
),
|
||||
});
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Failed to disable payment channel";
|
||||
setError(errorMessage);
|
||||
return { success: false, message: errorMessage };
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -161,13 +314,21 @@ export const usePaymentChannelManagement = () => {
|
||||
return {
|
||||
channels,
|
||||
stripeConfig,
|
||||
isSaving,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
loading,
|
||||
error,
|
||||
testResult,
|
||||
fetchChannels,
|
||||
saveStripeConfig,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
testStripeConnection,
|
||||
testAlipayConnection,
|
||||
testWechatConnection,
|
||||
enableChannel,
|
||||
disableChannel,
|
||||
clearTestResult,
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { PlatformConfig, LoginConfig, EmailMode } from "@/shared/types/system";
|
||||
import {
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
EmailMode,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel
|
||||
} from "@/shared/types/system";
|
||||
import { systemConfigService } from "@/services/systemConfigService";
|
||||
import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { md5Encrypt } from "@/shared/utils/crypto";
|
||||
@@ -49,6 +57,29 @@ export const useSystemConfigManagement = () => {
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState<string | null>(null);
|
||||
|
||||
// faq config
|
||||
const [faqItems, setFaqItems] = useState<FaqItem[]>([]);
|
||||
const [faqLoading, setFaqLoading] = useState(false);
|
||||
const [faqError, setFaqError] = useState<string | null>(null);
|
||||
|
||||
// top navigation config
|
||||
const [topNavigation, setTopNavigation] = useState<TopNavigationItem[]>([]);
|
||||
const [navigationLoading, setNavigationLoading] = useState(false);
|
||||
const [navigationError, setNavigationError] = useState<string | null>(null);
|
||||
|
||||
// embedded html config
|
||||
const [embeddedHtml, setEmbeddedHtml] = useState<EmbeddedHtmlConfig | null>(null);
|
||||
const [embeddedHtmlLoading, setEmbeddedHtmlLoading] = useState(false);
|
||||
const [embeddedHtmlError, setEmbeddedHtmlError] = useState<string | null>(null);
|
||||
|
||||
// payment channels config
|
||||
const [paymentChannels, setPaymentChannels] = useState<PaymentChannel[]>([]);
|
||||
const [paymentLoading, setPaymentLoading] = useState(false);
|
||||
const [paymentError, setPaymentError] = useState<string | null>(null);
|
||||
|
||||
// installation status
|
||||
const [isInstalled, setIsInstalled] = useState<boolean>(false);
|
||||
|
||||
// global loading
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
@@ -80,6 +111,11 @@ export const useSystemConfigManagement = () => {
|
||||
mode: EmailMode.PASSWORD,
|
||||
},
|
||||
});
|
||||
setFaqItems(response.faq || []);
|
||||
setTopNavigation(response.top_navigation || []);
|
||||
setEmbeddedHtml(response.embeded_html || null);
|
||||
setPaymentChannels(response.payment_channels || []);
|
||||
setIsInstalled(response.is_installed || false);
|
||||
} catch (error) {
|
||||
console.error("Failed to load configurations:", error);
|
||||
} finally {
|
||||
@@ -160,11 +196,71 @@ export const useSystemConfigManagement = () => {
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save faq config
|
||||
const saveFaqConfig = useCallback(async (items: FaqItem[]) => {
|
||||
setFaqLoading(true);
|
||||
setFaqError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
faq: items,
|
||||
}, "faq");
|
||||
if (result) {
|
||||
setFaqItems(items);
|
||||
}
|
||||
setFaqLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save top navigation config
|
||||
const saveTopNavigationConfig = useCallback(async (items: TopNavigationItem[]) => {
|
||||
setNavigationLoading(true);
|
||||
setNavigationError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
top_navigation: items,
|
||||
}, "navigation");
|
||||
if (result) {
|
||||
setTopNavigation(items);
|
||||
}
|
||||
setNavigationLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save embedded html config
|
||||
const saveEmbeddedHtmlConfig = useCallback(async (config: EmbeddedHtmlConfig) => {
|
||||
setEmbeddedHtmlLoading(true);
|
||||
setEmbeddedHtmlError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
embeded_html: config,
|
||||
}, "embedded_html");
|
||||
if (result) {
|
||||
setEmbeddedHtml(config);
|
||||
}
|
||||
setEmbeddedHtmlLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save payment channels config
|
||||
const savePaymentChannelsConfig = useCallback(async (channels: PaymentChannel[]) => {
|
||||
setPaymentLoading(true);
|
||||
setPaymentError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
payment_channels: channels,
|
||||
}, "payment");
|
||||
if (result) {
|
||||
setPaymentChannels(channels);
|
||||
}
|
||||
setPaymentLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// clear errors
|
||||
const clearPlatformError = useCallback(() => setPlatformError(null), []);
|
||||
const clearAdminError = useCallback(() => setAdminError(null), []);
|
||||
const clearEmailError = useCallback(() => setEmailError(null), []);
|
||||
const clearLoginError = useCallback(() => setLoginError(null), []);
|
||||
const clearFaqError = useCallback(() => setFaqError(null), []);
|
||||
const clearNavigationError = useCallback(() => setNavigationError(null), []);
|
||||
const clearEmbeddedHtmlError = useCallback(() => setEmbeddedHtmlError(null), []);
|
||||
const clearPaymentError = useCallback(() => setPaymentError(null), []);
|
||||
|
||||
// load configs on init
|
||||
useEffect(() => {
|
||||
@@ -217,6 +313,42 @@ export const useSystemConfigManagement = () => {
|
||||
saveLoginConfig,
|
||||
clearLoginError,
|
||||
|
||||
// faq config
|
||||
faqItems,
|
||||
setFaqItems,
|
||||
faqLoading,
|
||||
faqError,
|
||||
saveFaqConfig,
|
||||
clearFaqError,
|
||||
|
||||
// top navigation config
|
||||
topNavigation,
|
||||
setTopNavigation,
|
||||
navigationLoading,
|
||||
navigationError,
|
||||
saveTopNavigationConfig,
|
||||
clearNavigationError,
|
||||
|
||||
// embedded html config
|
||||
embeddedHtml,
|
||||
setEmbeddedHtml,
|
||||
embeddedHtmlLoading,
|
||||
embeddedHtmlError,
|
||||
saveEmbeddedHtmlConfig,
|
||||
clearEmbeddedHtmlError,
|
||||
|
||||
// payment channels config
|
||||
paymentChannels,
|
||||
setPaymentChannels,
|
||||
paymentLoading,
|
||||
paymentError,
|
||||
savePaymentChannelsConfig,
|
||||
clearPaymentError,
|
||||
|
||||
// installation status
|
||||
isInstalled,
|
||||
setIsInstalled,
|
||||
|
||||
// image upload
|
||||
uploadImage,
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { User } from "@/types/user";
|
||||
import { getUserList, deleteUser } from "@/services/userService";
|
||||
import { getUserList, deleteUser, rechargeUser } from "@/services/userService";
|
||||
|
||||
interface PaginationInfo {
|
||||
page: number;
|
||||
@@ -67,6 +67,28 @@ export const useUserManagement = () => {
|
||||
},
|
||||
[fetchUsers]
|
||||
);
|
||||
const handleRechargeUser = async (
|
||||
userId: string,
|
||||
amount: number
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const result = await rechargeUser(userId, amount);
|
||||
if (result) {
|
||||
// after recharge, fetch users again
|
||||
setUsers((prevUsers: User[]) =>
|
||||
prevUsers.map((user: User) =>
|
||||
user.id === userId
|
||||
? { ...user, balance: user.balance + amount }
|
||||
: user
|
||||
)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Recharge user failed");
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const setSearch = useCallback((search: string) => {
|
||||
setSearchQuery(search);
|
||||
@@ -88,6 +110,7 @@ export const useUserManagement = () => {
|
||||
|
||||
return {
|
||||
users,
|
||||
handleRechargeUser,
|
||||
loading,
|
||||
error,
|
||||
searchQuery,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import {
|
||||
EmbeddedHtmlConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
} from "@/shared/types/system";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
export interface HomepageConfig {
|
||||
faq: FaqItem[];
|
||||
top_navigation: TopNavigationItem[];
|
||||
embeded_html: EmbeddedHtmlConfig;
|
||||
}
|
||||
|
||||
export class HomepageConfigService {
|
||||
// get homepage config
|
||||
async getHomepageConfig(): Promise<HomepageConfig> {
|
||||
const response = await fetchAdminAPI<HomepageConfig>(
|
||||
"/api/sysconfig/homepage",
|
||||
{
|
||||
method: "GET",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to fetch homepage config"
|
||||
);
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// update homepage config
|
||||
async updateHomepageConfig(config: {
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
}): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/sysconfig/homepage", {
|
||||
method: "PUT",
|
||||
body: config as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to update homepage config")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Homepage config updated successfully"));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export const homepageConfigService = new HomepageConfigService();
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
PaymentChannelApiItem,
|
||||
PaymentChannelListResponse,
|
||||
PaymentChannelTestResult,
|
||||
@@ -52,50 +54,74 @@ export class PaymentChannelService {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// Save Stripe configuration
|
||||
async saveStripeConfig(config: StripeConfig): Promise<boolean> {
|
||||
const response = await fetchAdminAPI<StripeConfig>(
|
||||
"/api/payment_channel/info",
|
||||
{
|
||||
method: "PUT",
|
||||
body: {
|
||||
id: "stripe",
|
||||
config: config,
|
||||
} as unknown as BodyInit,
|
||||
}
|
||||
);
|
||||
// Generic method to save payment channel configuration
|
||||
async savePaymentChannelConfig<T>(
|
||||
channelId: string,
|
||||
config: T,
|
||||
channelName: string
|
||||
): Promise<boolean> {
|
||||
const response = await fetchAdminAPI<T>("/api/payment_channel/info", {
|
||||
method: "PUT",
|
||||
body: {
|
||||
id: channelId,
|
||||
config: {
|
||||
...config,
|
||||
is_enabled: undefined,
|
||||
},
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to save Stripe config")
|
||||
response.error_message ||
|
||||
i18n.t("Failed to save {{channelName}} config", { channelName })
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Stripe config saved successfully"));
|
||||
toast.success(
|
||||
i18n.t("{{channelName}} config saved successfully", { channelName })
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Test Stripe connection
|
||||
async testStripeConnection(
|
||||
config: StripeConfig
|
||||
// Save Stripe configuration
|
||||
async saveStripeConfig(config: StripeConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("stripe", config, "Stripe");
|
||||
}
|
||||
|
||||
// Generic method to test payment channel connection
|
||||
async testPaymentChannelConnection<T>(
|
||||
channelId: string,
|
||||
config: T,
|
||||
channelName: string
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
try {
|
||||
const response = await fetchAdminAPI<any>("/api/payment_channel/info", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(config),
|
||||
const response = await fetchAdminAPI<any>("/api/payment_channel/test", {
|
||||
method: "POST",
|
||||
body: {
|
||||
id: channelId,
|
||||
config: {
|
||||
...config,
|
||||
is_enabled: undefined,
|
||||
},
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: response.error_message || "Stripe connection test failed",
|
||||
message:
|
||||
response.error_message ||
|
||||
i18n.t("{{channelName}} connection test failed", { channelName }),
|
||||
details: response.data,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Stripe connection test successful",
|
||||
message: i18n.t("{{channelName}} connection test successful", {
|
||||
channelName,
|
||||
}),
|
||||
details: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -106,36 +132,73 @@ export class PaymentChannelService {
|
||||
}
|
||||
}
|
||||
|
||||
// Test Stripe connection
|
||||
async testStripeConnection(
|
||||
config: StripeConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("stripe", config, "Stripe");
|
||||
}
|
||||
|
||||
// enable payment channel
|
||||
async enablePaymentChannel(id: string): Promise<void> {
|
||||
async enablePaymentChannel(id: string): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/payment_channel/enable", {
|
||||
method: "POST",
|
||||
method: "PUT",
|
||||
body: {
|
||||
id,
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to enable payment channel"
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to enable payment channel")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Payment channel enabled successfully"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// disable payment channel
|
||||
async disablePaymentChannel(id: string): Promise<void> {
|
||||
async disablePaymentChannel(id: string): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/payment_channel/disable", {
|
||||
method: "POST",
|
||||
method: "PUT",
|
||||
body: {
|
||||
id,
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to disable payment channel"
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to disable payment channel")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Payment channel disabled successfully"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Save Alipay configuration
|
||||
async saveAlipayConfig(config: AlipayConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("alipay", config, "Alipay");
|
||||
}
|
||||
|
||||
// Save WeChat configuration
|
||||
async saveWechatConfig(config: WechatConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("wechat", config, "WeChat");
|
||||
}
|
||||
|
||||
// Test Alipay connection
|
||||
async testAlipayConnection(
|
||||
config: AlipayConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("alipay", config, "Alipay");
|
||||
}
|
||||
|
||||
// Test WeChat connection
|
||||
async testWechatConnection(
|
||||
config: WechatConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("wechat", config, "WeChat");
|
||||
}
|
||||
|
||||
// validate stripe config
|
||||
|
||||
@@ -37,10 +37,26 @@ export class PlatformConfigService {
|
||||
console.error(response.error_message);
|
||||
return {
|
||||
platform: _DefaultPlatformConfig,
|
||||
login: undefined,
|
||||
faq: [],
|
||||
top_navigation: [],
|
||||
embeded_html: undefined,
|
||||
payment_channels: [],
|
||||
is_installed: false,
|
||||
};
|
||||
}
|
||||
|
||||
return response.data;
|
||||
// 确保返回的数据结构正确
|
||||
const data = response.data;
|
||||
return {
|
||||
platform: data.platform || _DefaultPlatformConfig,
|
||||
login: data.login,
|
||||
faq: data.faq || [],
|
||||
top_navigation: data.top_navigation || [],
|
||||
embeded_html: data.embeded_html,
|
||||
payment_channels: data.payment_channels || [],
|
||||
is_installed: data.is_installed || false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { PlatformConfig, LoginConfig } from "@/shared/types/system";
|
||||
import {
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel
|
||||
} from "@/shared/types/system";
|
||||
import { AdminConfig, EmailConfig, SystemConfigApiData } from "@/types/system";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
@@ -29,8 +36,13 @@ export class SystemConfigService {
|
||||
account?: AdminConfig;
|
||||
email?: EmailConfig;
|
||||
login?: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
},
|
||||
key?: "theme" | "about"
|
||||
key?: "theme" | "about" | "faq" | "navigation" | "embedded_html" | "payment"
|
||||
): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/sysconfig/info", {
|
||||
method: "PUT",
|
||||
@@ -50,6 +62,18 @@ export class SystemConfigService {
|
||||
case "about":
|
||||
toast.success(i18n.t("About page saved successfully"));
|
||||
break;
|
||||
case "faq":
|
||||
toast.success(i18n.t("FAQ updated successfully"));
|
||||
break;
|
||||
case "navigation":
|
||||
toast.success(i18n.t("Navigation updated successfully"));
|
||||
break;
|
||||
case "embedded_html":
|
||||
toast.success(i18n.t("Embedded HTML updated successfully"));
|
||||
break;
|
||||
case "payment":
|
||||
toast.success(i18n.t("Payment channels updated successfully"));
|
||||
break;
|
||||
default: {
|
||||
toast.success(i18n.t("System config updated successfully"));
|
||||
break;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { User } from "@/types/user";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import toast from "react-hot-toast";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { md5Encrypt, sha256Encrypt } from "@/shared/utils/crypto";
|
||||
|
||||
// user list API response interface (according to API document xpack-response-array format)
|
||||
export interface UserListApiResponse extends ApiArrayResponse<User> {}
|
||||
@@ -63,3 +64,42 @@ export const deleteUser = async (userId: string): Promise<boolean> => {
|
||||
toast.success(i18n.t("User deleted successfully"));
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* recharge user balance
|
||||
*/
|
||||
export const rechargeUser = async (
|
||||
userId: string,
|
||||
amount: number
|
||||
): Promise<boolean> => {
|
||||
// Create request body
|
||||
const body = {
|
||||
user_id: userId,
|
||||
balance: amount,
|
||||
type: "incr",
|
||||
};
|
||||
|
||||
// Generate timestamp
|
||||
const timestamp = Date.now().toString();
|
||||
|
||||
// Generate signature: sha256(md5((x-xpack-timestamp){body}))
|
||||
// For this implementation, we're using a simplified approach
|
||||
// In a real implementation, you would use actual crypto functions
|
||||
const bodyString = JSON.stringify(body);
|
||||
const signature = sha256Encrypt(md5Encrypt(`${timestamp}${bodyString}`));
|
||||
const response = await fetchAdminAPI(`/api/user_manager/balance/recharge`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"x-xpack-timestamp": timestamp,
|
||||
"x-xpack-sign": signature,
|
||||
},
|
||||
body: body as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to recharge user"));
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("User recharged successfully"));
|
||||
return true;
|
||||
};
|
||||
@@ -9,9 +9,16 @@ import React from "react";
|
||||
interface PriceProps {
|
||||
price?: string;
|
||||
charge_type?: ChargeType;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
}
|
||||
|
||||
export const Price: React.FC<PriceProps> = ({ price, charge_type }) => {
|
||||
export const Price: React.FC<PriceProps> = ({
|
||||
price,
|
||||
charge_type,
|
||||
input_token_price,
|
||||
output_token_price,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
if (!charge_type) {
|
||||
return null;
|
||||
@@ -37,13 +44,24 @@ export const Price: React.FC<PriceProps> = ({ price, charge_type }) => {
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
const inputPrice = parseFloat(input_token_price || "0");
|
||||
const outputPrice = parseFloat(output_token_price || "0");
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Zap className="w-3 h-3 text-blue-600" />
|
||||
<span className="text-sm font-medium text-blue-600">
|
||||
${priceText.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("token")}</span>
|
||||
<div className="flex flex-col gap-1 text-xs ">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Input")}:</span>
|
||||
<span className="font-medium text-green-600">
|
||||
${inputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Output")}:</span>
|
||||
<span className="font-medium text-blue-600">
|
||||
${outputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,13 +14,17 @@ interface ProductDetailClientProps {
|
||||
product: ServiceData;
|
||||
breadcrumbs?: {
|
||||
link: string;
|
||||
name: string
|
||||
name: string;
|
||||
}[];
|
||||
mcpName?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export const ProductDetailClient: React.FC<ProductDetailClientProps> = ({
|
||||
product,
|
||||
breadcrumbs
|
||||
breadcrumbs,
|
||||
mcpName,
|
||||
url,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -28,52 +32,58 @@ export const ProductDetailClient: React.FC<ProductDetailClientProps> = ({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col mx-auto p-6 max-w-7xl">
|
||||
{product ? (<>
|
||||
<ProductHeader
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
/>
|
||||
{product ? (
|
||||
<>
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="primary"
|
||||
>
|
||||
<Tab key="overview" title={t("Overview")}>
|
||||
<ProductOverview product={product} />
|
||||
</Tab>
|
||||
<Tab key="tools" title={<div className="flex gap-2 items-center">
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip size="sm" className="h-4 text-xs"> {product.tools.length}</Chip>
|
||||
</div>}>
|
||||
<ProductTools product={product} />
|
||||
</Tab>
|
||||
</Tabs>
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="primary"
|
||||
>
|
||||
<Tab key="overview" title={t("Overview")}>
|
||||
<ProductOverview product={product} />
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip size="sm" className="h-4 text-xs">
|
||||
{" "}
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ProductTools product={product} />
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<ServerConfig mcpName={mcpName} url={url} />
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<ServerConfig product={product} />
|
||||
</div>
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 && (
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (<ProductNotFound />)}
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<ProductNotFound />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -63,7 +63,7 @@ export const ProductHeader: React.FC<ProductHeaderProps> = ({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-lg mb-4">
|
||||
<p className="text-sm mb-4">
|
||||
{product.short_description || t("No description available")}
|
||||
</p>
|
||||
</div>
|
||||
@@ -72,8 +72,13 @@ export const ProductHeader: React.FC<ProductHeaderProps> = ({
|
||||
{/* Price section */}
|
||||
{product.charge_type && (
|
||||
<div className="flex gap-2 items-center">
|
||||
<b className="text-xs">{t("Price")}:</b>
|
||||
<Price price={product.price} charge_type={product.charge_type} />
|
||||
<b className="text-md">{t("Price")}:</b>
|
||||
<Price
|
||||
price={product.price}
|
||||
charge_type={product.charge_type}
|
||||
input_token_price={product.input_token_price}
|
||||
output_token_price={product.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
|
||||
@@ -1,28 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { Card, Chip } from "@nextui-org/react";
|
||||
import React from "react";
|
||||
import { Card, Chip, Button } from "@nextui-org/react";
|
||||
import { FlipButton } from "@/shared/components/FlipButton";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { Copy } from "lucide-react";
|
||||
import { copyToClipboard } from "@/shared/utils/clipboard";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface ServerConfigProps {
|
||||
product: ServiceData;
|
||||
mcpName?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
|
||||
|
||||
export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
mcpName,
|
||||
url = process.env.NEXT_PUBLIC_MCP_URL,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { handleLogin } = useAuth();
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const [url, setUrl] = useState<string>(process.env.NEXT_PUBLIC_MCP_URL || "");
|
||||
useEffect(() => {
|
||||
if (url || !product.slug_name) return
|
||||
setUrl(`${window.location.origin}/mcp/${product.slug_name}`);
|
||||
}, [product.slug_name]);
|
||||
|
||||
const getCodeContent = () => {
|
||||
return `{
|
||||
"mcpServers": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey={Your-${platformConfig?.name}-API-Key}"
|
||||
}
|
||||
}
|
||||
}`;
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const result = await copyToClipboard(getCodeContent());
|
||||
if (result.success) {
|
||||
toast.success(t("Copied to clipboard"));
|
||||
} else {
|
||||
toast.error(t("Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0 mt-12">
|
||||
@@ -37,16 +57,28 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip className="mb-2 text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={handleCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove"":"all",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
@@ -59,4 +91,4 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -17,7 +17,10 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ service }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Link href={`/marketplace/${service.service_id}`}>
|
||||
<Link
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card
|
||||
className="group w-full h-[180px] hover:border-primary-500 transition-all duration-300 border-1"
|
||||
shadow="none"
|
||||
@@ -48,7 +51,12 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ service }) => {
|
||||
{t("{{count}} Tools", { count: service.tools.length })}
|
||||
</Chip>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Price price={service.price} charge_type={service.charge_type} />
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
|
||||
@@ -25,7 +25,7 @@ export const ServiceListSection: React.FC<ServiceListSectionProps> = ({
|
||||
return (
|
||||
<div className="mx-auto px-6 py-12 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-12">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<ServiceCard key={service.service_id} service={service} />
|
||||
))}
|
||||
@@ -46,4 +46,4 @@ export const ServiceListSection: React.FC<ServiceListSectionProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
ModalContent,
|
||||
@@ -7,11 +7,14 @@ import {
|
||||
ModalFooter,
|
||||
Button,
|
||||
Input,
|
||||
RadioGroup,
|
||||
Radio,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import toast from "react-hot-toast";
|
||||
import { ConfirmPurchaseModal } from "./ConfirmPurchaseModal";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
|
||||
interface RechargeModalProps {
|
||||
isOpen: boolean;
|
||||
@@ -23,13 +26,16 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
onClose,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { paymentChannels } = usePlatformConfig();
|
||||
const [amount, setAmount] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
const [selectedPaymentChannel, setSelectedPaymentChannel] = useState<string>(
|
||||
paymentChannels[0]?.id || ""
|
||||
);
|
||||
|
||||
const [paymentId, setPaymentId] = useState("");
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
|
||||
|
||||
const handlePurchase = async () => {
|
||||
const numAmount = parseFloat(amount);
|
||||
if (isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -41,10 +47,17 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedPaymentChannel) {
|
||||
setError(t("Please select a payment method"));
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetchAPI("/api/payment/create_payment_link", {
|
||||
method: "POST",
|
||||
body: {
|
||||
amount: numAmount,
|
||||
payment_channel: selectedPaymentChannel,
|
||||
success_url: window.location.origin + "/pay_success",
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
@@ -93,6 +106,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
const handleClose = () => {
|
||||
setAmount("");
|
||||
setError("");
|
||||
setSelectedPaymentChannel(paymentChannels[0]?.id || "");
|
||||
onClose();
|
||||
};
|
||||
|
||||
@@ -119,23 +133,54 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
}
|
||||
type="text"
|
||||
variant="bordered"
|
||||
isInvalid={!!error}
|
||||
errorMessage={error}
|
||||
isInvalid={!!error && !error.includes("payment method")}
|
||||
errorMessage={
|
||||
error && !error.includes("payment method") ? error : ""
|
||||
}
|
||||
labelPlacement="outside"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
handlePurchase();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-default-500">
|
||||
{t("Funds will be added to your account balance")}
|
||||
</p>
|
||||
{/**coming soon : select payment channel*/}
|
||||
|
||||
{/* {paymentChannels.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-default-700">
|
||||
{t("Payment Method")}
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={selectedPaymentChannel}
|
||||
onValueChange={setSelectedPaymentChannel}
|
||||
isInvalid={!!error && error.includes("payment method")}
|
||||
errorMessage={
|
||||
error && error.includes("payment method") ? error : ""
|
||||
}
|
||||
orientation="horizontal"
|
||||
description={t(
|
||||
"Funds will be added to your account balance"
|
||||
)}
|
||||
>
|
||||
{paymentChannels.map((channel) => (
|
||||
<Radio key={channel.id} value={channel.id}>
|
||||
{channel.name}
|
||||
</Radio>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
)} */}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onPress={handleClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button color="primary" onPress={handlePurchase}>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handlePurchase}
|
||||
isDisabled={!selectedPaymentChannel || !amount}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
@@ -144,7 +189,6 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
|
||||
|
||||
{/**Confirm Purchase Modal */}
|
||||
<ConfirmPurchaseModal
|
||||
isOpen={isConfirmOpen}
|
||||
@@ -154,4 +198,4 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
PlatformConfigResponse,
|
||||
Theme,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel,
|
||||
} from "@/shared/types/system";
|
||||
export const _DefaultPlatformConfig: PlatformConfig = {
|
||||
name: "XPack",
|
||||
@@ -17,10 +21,18 @@ export const _DefaultPlatformConfig: PlatformConfig = {
|
||||
subheadline:
|
||||
"Open‑source MCP marketplace — publish or consume APIs in minutes.",
|
||||
theme: Theme.DEFAULT,
|
||||
domain: "",
|
||||
is_showcased: false,
|
||||
mcp_server_prefix: "",
|
||||
};
|
||||
interface PlatformConfigContextType {
|
||||
platformConfig: PlatformConfig;
|
||||
loginConfig: LoginConfig | null;
|
||||
faqItems: FaqItem[];
|
||||
topNavigation: TopNavigationItem[];
|
||||
embeddedHtml: EmbeddedHtmlConfig | null;
|
||||
paymentChannels: PaymentChannel[];
|
||||
isInstalled: boolean;
|
||||
updateClientConfig: (config: PlatformConfigResponse) => void;
|
||||
}
|
||||
|
||||
@@ -43,13 +55,41 @@ export const PlatformConfigProvider: React.FC<PlatformConfigProviderProps> = ({
|
||||
const [loginConfig, setLoginConfig] = useState<LoginConfig | null>(
|
||||
initConfig?.login || null
|
||||
);
|
||||
const [faqItems, setFaqItems] = useState<FaqItem[]>(initConfig?.faq || []);
|
||||
const [topNavigation, setTopNavigation] = useState<TopNavigationItem[]>(
|
||||
initConfig?.top_navigation || []
|
||||
);
|
||||
const [embeddedHtml, setEmbeddedHtml] = useState<EmbeddedHtmlConfig | null>(
|
||||
initConfig?.embeded_html || null
|
||||
);
|
||||
const [paymentChannels, setPaymentChannels] = useState<PaymentChannel[]>(
|
||||
initConfig?.payment_channels || []
|
||||
);
|
||||
const [isInstalled, setIsInstalled] = useState<boolean>(
|
||||
initConfig?.is_installed || false
|
||||
);
|
||||
|
||||
const updateClientConfig = (config: PlatformConfigResponse) => {
|
||||
if (config.platform) setPlatformConfig(config.platform);
|
||||
if (config.login) setLoginConfig(config.login);
|
||||
if (config.faq) setFaqItems(config.faq);
|
||||
if (config.top_navigation) setTopNavigation(config.top_navigation);
|
||||
if (config.embeded_html) setEmbeddedHtml(config.embeded_html);
|
||||
if (config.payment_channels) setPaymentChannels(config.payment_channels);
|
||||
if (config.is_installed !== undefined) setIsInstalled(config.is_installed);
|
||||
};
|
||||
return (
|
||||
<PlatformConfigContext.Provider
|
||||
value={{ platformConfig, loginConfig, updateClientConfig }}
|
||||
value={{
|
||||
platformConfig,
|
||||
loginConfig,
|
||||
faqItems,
|
||||
topNavigation,
|
||||
embeddedHtml,
|
||||
paymentChannels,
|
||||
isInstalled,
|
||||
updateClientConfig,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PlatformConfigContext.Provider>
|
||||
|
||||
@@ -54,12 +54,11 @@ export const fetchAPI = async <T = any>(
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("API fetch error:", error);
|
||||
return {
|
||||
success: false,
|
||||
code: "ERROR",
|
||||
error_message: error instanceof Error ? error.message : "Unknown error",
|
||||
data: null as T,
|
||||
};
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
console.log("Request aborted:", url);
|
||||
} else {
|
||||
console.error("Fetch error:", error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -11,16 +11,28 @@ export enum TabKey {
|
||||
ACCOUNT = "account",
|
||||
}
|
||||
|
||||
export interface SidebarSubItem {
|
||||
key: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface SidebarItem {
|
||||
key: TabKey;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
description: string;
|
||||
subItems?: SidebarSubItem[];
|
||||
}
|
||||
|
||||
export interface SidebarItemWithActive extends SidebarItem {
|
||||
isExpanded?: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardSidebarProps {
|
||||
activeTab: TabKey;
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
activeSubTab?: string;
|
||||
onTabNavigate?: (tab: TabKey, subTab?: string) => void;
|
||||
onLogout: () => void;
|
||||
bottomPanel?: React.ReactNode;
|
||||
sidebarItems: SidebarItem[];
|
||||
|
||||
@@ -8,6 +8,8 @@ export interface ServiceData {
|
||||
tags?: string[];
|
||||
price?: string;
|
||||
charge_type?: ChargeType;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
}
|
||||
|
||||
export interface ToolData {
|
||||
|
||||
@@ -21,12 +21,48 @@ export interface PlatformConfig {
|
||||
subheadline?: string; // homepage subheadline
|
||||
theme?: Theme; // platform theme for homepage and marketplace templates
|
||||
about_page?: string; // about page content (markdown)
|
||||
domain?: string; // platform domain
|
||||
is_showcased?: boolean; // whether to showcase in xpack official case list
|
||||
mcp_server_prefix?: string; // MCP server domain prefix for API calls
|
||||
}
|
||||
|
||||
export type ThemeType = Theme;
|
||||
// FAQ item
|
||||
export interface FaqItem {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
export enum TopNavigationTargetEnum {
|
||||
SELF = "_self",
|
||||
BLANK = "_blank",
|
||||
}
|
||||
// Top navigation item
|
||||
export interface TopNavigationItem {
|
||||
title: string;
|
||||
link: string;
|
||||
target: TopNavigationTargetEnum;
|
||||
}
|
||||
|
||||
// Embedded HTML config
|
||||
export interface EmbeddedHtmlConfig {
|
||||
is_enabled: boolean;
|
||||
html: string;
|
||||
}
|
||||
|
||||
// Payment channel
|
||||
export interface PaymentChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface PlatformConfigResponse {
|
||||
platform: PlatformConfig;
|
||||
platform?: PlatformConfig;
|
||||
login?: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
}
|
||||
|
||||
// google auth config
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface BaseMCPService {
|
||||
long_description?: string;
|
||||
charge_type: ChargeType;
|
||||
price?: string;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
apis: MCPServiceAPIItem[];
|
||||
tags?: string[];
|
||||
}
|
||||
@@ -34,6 +36,7 @@ export interface MCPServiceAPIItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
// form data interface, used to create and edit service
|
||||
@@ -48,6 +51,8 @@ export interface MCPServiceFormData {
|
||||
auth_token?: string;
|
||||
charge_type: ChargeType;
|
||||
price?: string;
|
||||
input_token_price?: string; // Price for input tokens when charge_type is PerToken
|
||||
output_token_price?: string; // Price for output tokens when charge_type is PerToken
|
||||
enabled: EnabledEnum; // API requires string type
|
||||
apis: MCPServiceAPIItem[];
|
||||
tags?: string[];
|
||||
@@ -89,41 +94,6 @@ export interface ServiceDeleteRequest {
|
||||
id: string;
|
||||
}
|
||||
|
||||
// predefined auth methods
|
||||
export const AUTH_METHODS = [
|
||||
{ value: "free", label: "free" },
|
||||
{ value: "apikey", label: "API key" },
|
||||
] as const;
|
||||
|
||||
// predefined charge types
|
||||
export const CHARGE_TYPES = [
|
||||
{ value: "free", label: "free" },
|
||||
{ value: "per_call", label: "per call" },
|
||||
{ value: "per_token", label: "per token" },
|
||||
] as const;
|
||||
|
||||
// predefined service categories
|
||||
export const SERVICE_CATEGORIES = [
|
||||
"Web Services",
|
||||
"Database",
|
||||
"AI/ML",
|
||||
"Authentication",
|
||||
"Payment",
|
||||
"Communication",
|
||||
"Analytics",
|
||||
"Storage",
|
||||
"Security",
|
||||
"Development Tools",
|
||||
"Financial",
|
||||
"Logistics & Transportation",
|
||||
"E-commerce",
|
||||
"Social Media",
|
||||
"Content Management",
|
||||
"Other",
|
||||
] as const;
|
||||
|
||||
export type ServiceCategory = (typeof SERVICE_CATEGORIES)[number];
|
||||
|
||||
// tool function: convert frontend form data to API data
|
||||
export function convertFormToAPI(
|
||||
formData: MCPServiceFormData
|
||||
@@ -138,6 +108,8 @@ export function convertFormToAPI(
|
||||
auth_token: formData.auth_token,
|
||||
charge_type: formData.charge_type,
|
||||
price: formData.price,
|
||||
input_token_price: formData.input_token_price,
|
||||
output_token_price: formData.output_token_price,
|
||||
enabled: formData.enabled,
|
||||
apis: formData.apis,
|
||||
tags: formData.tags,
|
||||
|
||||
@@ -1,18 +1,37 @@
|
||||
// payment channel type
|
||||
export type PaymentChannelType = "stripe";
|
||||
export type PaymentChannelType = "stripe" | "alipay" | "wechat";
|
||||
|
||||
// stripe config - admin need to configure
|
||||
export interface StripeConfig {
|
||||
secret: string;
|
||||
webhook_secret: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// alipay config - admin need to configure
|
||||
export interface AlipayConfig {
|
||||
app_id: string;
|
||||
app_private_key: string;
|
||||
alipay_public_key: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// wechat config - admin need to configure
|
||||
export interface WechatConfig {
|
||||
app_id: string;
|
||||
mch_id: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// union type for all payment configs
|
||||
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig;
|
||||
|
||||
// API return payment channel item structure
|
||||
export interface PaymentChannelApiItem {
|
||||
id: PaymentChannelType;
|
||||
name: string;
|
||||
is_enabled: boolean;
|
||||
config: StripeConfig;
|
||||
config: PaymentConfig;
|
||||
update_time: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
GoogleAuthConfig,
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel,
|
||||
} from "@/shared/types/system";
|
||||
|
||||
// API return system config data structure
|
||||
@@ -12,6 +16,11 @@ export interface SystemConfigApiData {
|
||||
account: AdminConfig;
|
||||
email: EmailConfig;
|
||||
login: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
}
|
||||
// admin config
|
||||
export interface AdminConfig {
|
||||
|
||||
+2
-1
@@ -13,4 +13,5 @@ PyYAML>=6.0
|
||||
python-multipart
|
||||
google-auth>=2.0.0
|
||||
google-auth-oauthlib>=1.0.0
|
||||
fastapi_mcp
|
||||
fastapi_mcp
|
||||
alipay-sdk-python>=3.0.0
|
||||
@@ -17,7 +17,7 @@ echo "login qiniu..."
|
||||
qshell account ${AccessKey} ${SecretKey} ${QINIU_NAME}
|
||||
|
||||
echo "qshell rput ${QINIU_BUCKET} \"xpack/images/${Tar}\" ${Tar}"
|
||||
qshell rput ${QINIU_BUCKET} "xpack/images/${Tar}" ${Tar}
|
||||
qshell rput --overwrite ${QINIU_BUCKET} "xpack/images/${Tar}" ${Tar}
|
||||
|
||||
rm -f ${Tar}
|
||||
docker rmi -f ${ImageName}:${Version}
|
||||
@@ -926,8 +926,8 @@ print_xpack_mcp_market_info() {
|
||||
webPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT})
|
||||
echo_pass "XPack MCP Market has run successfully."
|
||||
echo_info "The Web UI access information is as follows:"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${webPort}/admin-signin"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin-signin"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${webPort}/admin"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin"
|
||||
echo_info "Inital Username: admin"
|
||||
echo_info "Inital Password: 123456789"
|
||||
echo ""
|
||||
@@ -1027,7 +1027,7 @@ operate() {
|
||||
echo_logo
|
||||
echo_split
|
||||
echo_question "Hello, Welcome to use XPack MCP Market! What do you want to do?"
|
||||
echo_point "1. Install XPack MCP Market"
|
||||
echo_point "1. Install or Update XPack MCP Market"
|
||||
echo_point "2. Print system information"
|
||||
echo_point "3. Uninstall XPack MCP Market"
|
||||
echo_point "4. Exit"
|
||||
|
||||
+247
-46
@@ -1,9 +1,10 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
import mysql.connector
|
||||
from typing import Optional
|
||||
from typing import Optional, List, Tuple, Union
|
||||
|
||||
# 加载环境变量
|
||||
load_dotenv()
|
||||
@@ -16,77 +17,277 @@ class DBConfig:
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "123456")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB", "xpack")
|
||||
|
||||
def execute_sql_file(file_path: str, db_config: Optional[DBConfig] = None) -> None:
|
||||
"""执行 SQL 文件
|
||||
|
||||
def get_db_connection(db_config: Optional[DBConfig] = None):
|
||||
"""获取数据库连接
|
||||
|
||||
Args:
|
||||
file_path: SQL 文件路径
|
||||
db_config: 数据库配置,如果为 None 则使用默认配置
|
||||
|
||||
Returns:
|
||||
数据库连接对象
|
||||
"""
|
||||
if db_config is None:
|
||||
db_config = DBConfig()
|
||||
print(db_config.MYSQL_HOST, db_config.MYSQL_PORT, db_config.MYSQL_USER, db_config.MYSQL_PASSWORD, db_config.MYSQL_DB)
|
||||
# 连接数据库
|
||||
conn = mysql.connector.connect(
|
||||
|
||||
return mysql.connector.connect(
|
||||
host=db_config.MYSQL_HOST,
|
||||
port=db_config.MYSQL_PORT,
|
||||
user=db_config.MYSQL_USER,
|
||||
password=db_config.MYSQL_PASSWORD,
|
||||
database=db_config.MYSQL_DB
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
|
||||
def get_current_version(db_config: Optional[DBConfig] = None) -> Optional[str]:
|
||||
"""查询sys_config表中的version值
|
||||
|
||||
Args:
|
||||
db_config: 数据库配置
|
||||
|
||||
Returns:
|
||||
当前版本号,如果不存在则返回None
|
||||
"""
|
||||
try:
|
||||
conn = get_db_connection(db_config)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 查询version配置
|
||||
cursor.execute("SELECT value FROM sys_config WHERE `key` = 'version'")
|
||||
result = cursor.fetchone()
|
||||
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
if result and len(result) > 0:
|
||||
# 将元组的第一个元素转换为字符串并返回
|
||||
return str(result['value'] if isinstance(result, dict) else result[0])
|
||||
return None
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
# 如果表不存在或其他数据库错误,返回None
|
||||
print(f"查询版本信息失败: {err}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"查询版本信息出错: {e}")
|
||||
return None
|
||||
|
||||
def execute_sql_file(file_path: str, db_config: Optional[DBConfig] = None) -> bool:
|
||||
"""执行 SQL 文件
|
||||
|
||||
Args:
|
||||
file_path: SQL 文件路径
|
||||
db_config: 数据库配置,如果为 None 则使用默认配置
|
||||
|
||||
Returns:
|
||||
执行是否成功
|
||||
"""
|
||||
if db_config is None:
|
||||
db_config = DBConfig()
|
||||
|
||||
sql = ""
|
||||
try:
|
||||
# 读取 SQL 文件
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
sql_content = f.read()
|
||||
|
||||
# 设置字符集
|
||||
cursor.execute('SET NAMES utf8mb4')
|
||||
conn = get_db_connection(db_config)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 禁用外键检查
|
||||
cursor.execute('SET FOREIGN_KEY_CHECKS = 0')
|
||||
|
||||
# 执行 SQL 语句
|
||||
for statement in sql_content.split(';'):
|
||||
if statement.strip():
|
||||
sql = statement
|
||||
cursor.execute(statement)
|
||||
|
||||
# 启用外键检查
|
||||
|
||||
# 读取SQL文件
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
content = file.read()
|
||||
|
||||
# 移除多行注释 /* ... */
|
||||
import re
|
||||
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
|
||||
|
||||
# 按分号分割语句
|
||||
statements = content.split(';')
|
||||
statement_count = 0
|
||||
|
||||
for statement in statements:
|
||||
# 清理语句:移除空行和注释行
|
||||
lines = statement.strip().split('\n')
|
||||
cleaned_lines = []
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('--'):
|
||||
cleaned_lines.append(line)
|
||||
|
||||
if not cleaned_lines:
|
||||
continue
|
||||
|
||||
sql = '\n'.join(cleaned_lines)
|
||||
statement_count += 1
|
||||
|
||||
# 跳过SET语句,单独处理
|
||||
if sql.upper().startswith('SET '):
|
||||
print(f"执行第{statement_count}个语句: {sql}")
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
print(f" -> 成功")
|
||||
except mysql.connector.Error as e:
|
||||
print(f" -> SET语句执行错误: {e}")
|
||||
# SET语句失败不影响后续执行
|
||||
continue
|
||||
|
||||
# 添加调试信息
|
||||
if sql.upper().startswith('CREATE TABLE'):
|
||||
table_match = re.search(r'CREATE TABLE.*?`(\w+)`', sql, re.IGNORECASE)
|
||||
table_name = table_match.group(1) if table_match else 'unknown'
|
||||
print(f"执行第{statement_count}个语句: 创建表 {table_name}")
|
||||
elif sql.upper().startswith('INSERT INTO'):
|
||||
table_match = re.search(r'INSERT INTO.*?`(\w+)`', sql, re.IGNORECASE)
|
||||
table_name = table_match.group(1) if table_match else 'unknown'
|
||||
print(f"执行第{statement_count}个语句: 插入数据到表 {table_name}")
|
||||
else:
|
||||
print(f"执行第{statement_count}个语句: {sql[:50]}...")
|
||||
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
print(f" -> 成功")
|
||||
except mysql.connector.Error as e:
|
||||
if "Duplicate column name" in str(e):
|
||||
print(f" -> 忽略重复列错误: {e}")
|
||||
continue
|
||||
else:
|
||||
print(f" -> 执行错误: {e}")
|
||||
print(f" -> 语句内容: {sql}")
|
||||
raise
|
||||
|
||||
# 恢复外键检查
|
||||
cursor.execute('SET FOREIGN_KEY_CHECKS = 1')
|
||||
# 提交事务
|
||||
conn.commit()
|
||||
print(f"成功执行 SQL 文件: {file_path}")
|
||||
except FileNotFoundError:
|
||||
print(f"错误: SQL 文件不存在: {file_path}")
|
||||
sys.exit(1)
|
||||
except mysql.connector.Error as err:
|
||||
# 输出语句
|
||||
print(f"数据库错误: {err}, 语句: {sql}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"执行出错: {e}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
# 关闭连接
|
||||
print(f"成功执行 SQL 文件: {file_path},共执行 {statement_count} 个语句")
|
||||
|
||||
cursor.close()
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
except FileNotFoundError:
|
||||
print(f"错误: SQL 文件不存在: {file_path}")
|
||||
return False
|
||||
except mysql.connector.Error as err:
|
||||
print(f"数据库错误: {err}")
|
||||
if sql:
|
||||
print(f"出错的SQL语句: {sql}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"未知错误: {e}")
|
||||
return False
|
||||
|
||||
def get_version_files(sql_dir: Path) -> List[Tuple[str, Path]]:
|
||||
"""获取所有版本SQL文件并按版本号排序
|
||||
|
||||
Args:
|
||||
sql_dir: SQL文件目录
|
||||
|
||||
Returns:
|
||||
排序后的版本文件列表,格式为[(版本号, 文件路径), ...]
|
||||
"""
|
||||
version_files = []
|
||||
|
||||
# 查找所有version-*.sql文件
|
||||
for file_path in sql_dir.glob("version-*.sql"):
|
||||
# 提取版本号
|
||||
match = re.match(r'version-(.+)\.sql', file_path.name)
|
||||
if match:
|
||||
version_str = match.group(1)
|
||||
version_files.append((version_str, file_path))
|
||||
|
||||
# 按版本号排序(简单的字符串排序)
|
||||
version_files.sort(key=lambda x: x[0])
|
||||
|
||||
return version_files
|
||||
|
||||
def should_apply_version(current_version: Optional[str], target_version: str) -> bool:
|
||||
"""判断是否需要应用指定版本的更新
|
||||
|
||||
Args:
|
||||
current_version: 当前版本号
|
||||
target_version: 目标版本号
|
||||
|
||||
Returns:
|
||||
是否需要应用更新
|
||||
"""
|
||||
if current_version is None:
|
||||
return True
|
||||
|
||||
# 简单的字符串比较
|
||||
return target_version > current_version
|
||||
|
||||
def main():
|
||||
"""主函数:实现版本化数据库迁移策略"""
|
||||
print("开始数据库初始化和迁移...")
|
||||
|
||||
# 获取项目根目录
|
||||
project_root = Path(__file__).parent
|
||||
sql_dir = project_root / 'sql'
|
||||
|
||||
# SQL 文件路径(优先使用 scripts/resource/db.sql,如果不存在则使用 docs/db.sql)
|
||||
sql_paths = [
|
||||
project_root / 'sql' / 'init.sql'
|
||||
]
|
||||
print(sql_paths)
|
||||
sql_file = next((path for path in sql_paths if path.exists()), None)
|
||||
if not sql_file:
|
||||
print("错误: 未找到 init.sql 文件")
|
||||
if not sql_dir.exists():
|
||||
print(f"错误: SQL目录不存在: {sql_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
execute_sql_file(str(sql_file))
|
||||
|
||||
# 步骤1: 查询sys_config,获取当key=version的值
|
||||
print("步骤1: 查询当前数据库版本...")
|
||||
current_version = get_current_version()
|
||||
|
||||
# 步骤2: 当不存在该key时,执行init.sql
|
||||
if current_version is None:
|
||||
print("步骤2: 未找到版本信息,执行初始化SQL...")
|
||||
init_sql_file = sql_dir / 'init.sql'
|
||||
|
||||
if not init_sql_file.exists():
|
||||
print(f"错误: 初始化SQL文件不存在: {init_sql_file}")
|
||||
sys.exit(1)
|
||||
|
||||
if not execute_sql_file(str(init_sql_file)):
|
||||
print("初始化SQL执行失败")
|
||||
sys.exit(1)
|
||||
|
||||
# 重新查询版本信息
|
||||
current_version = get_current_version()
|
||||
print(f"初始化完成,当前版本: {current_version}")
|
||||
else:
|
||||
print(f"当前数据库版本: {current_version}")
|
||||
|
||||
# 步骤3: 获取对应的版本号
|
||||
# 步骤4: 依次读取sql下的version-*.sql文件,执行更新sql,直到所有sql执行完成
|
||||
print("步骤3-4: 检查并执行版本更新...")
|
||||
|
||||
# 获取所有版本文件
|
||||
version_files = get_version_files(sql_dir)
|
||||
|
||||
if not version_files:
|
||||
print("未找到版本更新文件,数据库已是最新版本")
|
||||
return
|
||||
|
||||
print(f"找到 {len(version_files)} 个版本更新文件")
|
||||
|
||||
# 依次执行需要的版本更新
|
||||
updated_count = 0
|
||||
for version_str, file_path in version_files:
|
||||
if should_apply_version(current_version, version_str):
|
||||
print(f"执行版本更新: {version_str} ({file_path.name})")
|
||||
|
||||
if execute_sql_file(str(file_path)):
|
||||
print(f"版本 {version_str} 更新成功")
|
||||
current_version = version_str
|
||||
updated_count += 1
|
||||
else:
|
||||
print(f"版本 {version_str} 更新失败,停止后续更新")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(f"跳过版本 {version_str}(已应用或版本较低)")
|
||||
|
||||
if updated_count > 0:
|
||||
print(f"数据库迁移完成,共应用了 {updated_count} 个版本更新")
|
||||
# 验证最终版本
|
||||
final_version = get_current_version()
|
||||
print(f"最终数据库版本: {final_version}")
|
||||
else:
|
||||
print("数据库已是最新版本,无需更新")
|
||||
|
||||
print("数据库初始化和迁移流程完成!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -275,15 +275,7 @@ UNIQUE KEY `uk_key` (`key`) USING BTREE COMMENT '配置键名唯一索引'
|
||||
|
||||
INSERT INTO `user` (`id`, `name`, `email`, `password`, `is_active`, `is_deleted`, `register_type`, `role_id`, `created_at`, `updated_at`)
|
||||
VALUES ('admin', 'admin', 'admin@xpack.com', '25f9e794323b453885f5181f1b624d0b', 1, 0, 'inner', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`name` = VALUES(`name`),
|
||||
`email` = VALUES(`email`),
|
||||
`password` = VALUES(`password`),
|
||||
`is_active` = VALUES(`is_active`),
|
||||
`is_deleted` = VALUES(`is_deleted`),
|
||||
`register_type` = VALUES(`register_type`),
|
||||
`role_id` = VALUES(`role_id`),
|
||||
`updated_at` = CURRENT_TIMESTAMP;
|
||||
ON DUPLICATE KEY UPDATE `register_type` = VALUES(`register_type`);
|
||||
|
||||
INSERT INTO `user_wallet` (`id`, `user_id`, `balance`, `frozen_balance`, `created_at`, `updated_at`)
|
||||
SELECT UUID(), 'admin', 0.00, 0.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
@@ -293,4 +285,8 @@ INSERT INTO `payment_channel` (`id`, `name`, `status`, `config`, `updated_at`)
|
||||
SELECT 'stripe', 'Stripe', 1, '{\"secret\": \"\", \"webhook_secret\": \"\"}', '2025-07-17 06:42:55'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `payment_channel` WHERE `id` = 'stripe');
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '0.2.2', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- mcp_call_log
|
||||
ALTER TABLE `mcp_call_log` DROP COLUMN `apikey`;
|
||||
ALTER TABLE `mcp_call_log` ADD COLUMN `apikey_id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'apikey_id' AFTER `wallet_history_id`;
|
||||
|
||||
-- mcp_service
|
||||
ALTER TABLE `mcp_service` ADD COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'input token price' AFTER `price`;
|
||||
ALTER TABLE `mcp_service` ADD COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'output token price' AFTER `price`;
|
||||
|
||||
-- temp_mcp_service
|
||||
ALTER TABLE `temp_mcp_service` ADD COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'input token price' AFTER `price`;
|
||||
ALTER TABLE `temp_mcp_service` ADD COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'output token price' AFTER `price`;
|
||||
|
||||
-- user_wallet
|
||||
ALTER TABLE `user_wallet` MODIFY COLUMN `balance` decimal(16, 6) NOT NULL COMMENT 'Wallet balance' AFTER `user_id`;
|
||||
ALTER TABLE `user_wallet` MODIFY COLUMN `frozen_balance` decimal(16, 6) NOT NULL COMMENT 'Frozen balance' AFTER `balance`;
|
||||
|
||||
-- user_wallet_history
|
||||
ALTER TABLE `user_wallet_history` MODIFY COLUMN `amount` decimal(16, 6) NOT NULL COMMENT 'Change amount' AFTER `payment_method`;
|
||||
ALTER TABLE `user_wallet_history` MODIFY COLUMN `balance_after` decimal(16, 6) NOT NULL COMMENT 'Balance after change' AFTER `amount`;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '1.0.0', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-is_showcased','is_showcased', '1', 'Is showcase', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-login_google_enable','login_google_enable', '1', 'Login google enable', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-login_email_enable','login_email_enable', '1', 'Login email enable', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-login_email_mode','email_mode', 'password', 'Login email mode', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '1.0.1', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"version": "v0.1",
|
||||
"releaseDate": "2025-07-20",
|
||||
"version": "v1.0",
|
||||
"releaseDate": "2025-07-30",
|
||||
"description": "This is the latest release of the application.",
|
||||
"downloads": {
|
||||
"program": {
|
||||
"xpack_mcp_market": {
|
||||
"version": "v0.1.0",
|
||||
"version": "v1.0.1",
|
||||
"docker": "xpackai/xpack-mcp-market",
|
||||
"tar": "xpack-mcp-market.tar.gz",
|
||||
"url": "https://public.eolinker.com/xpack/images/xpack-mcp-market.${VERSION}.${ARCH}.tar.gz"
|
||||
|
||||
@@ -20,4 +20,12 @@ KEY_EMAIL_SMTP_PASSWORD = "email_smtp_password"
|
||||
KEY_EMAIL_SMTP_SENDER = "email_smtp_sender"
|
||||
KEY_LOGIN_EMAIL_ENABLE = "login_email_enable"
|
||||
KEY_LOGIN_EMAIL_MODE = "login_email_mode"
|
||||
KEY_DOMAIN = "domain"
|
||||
KEY_IS_SHOWCASED = "is_showcased"
|
||||
KEY_MCP_SERVER_PREFIX = "mcp_server_prefix"
|
||||
|
||||
KEY_FAQ = "faq"
|
||||
KEY_TOP_NAVIGATION = "top_navigation"
|
||||
KEY_EMBEDED_HTML = "embedded_html"
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import threading
|
||||
import time
|
||||
import logging
|
||||
from typing import Callable
|
||||
|
||||
import os
|
||||
from services.common.config import Config
|
||||
from services.common.database import get_db
|
||||
from services.admin_service.services.billing_message_handler import BillingMessageHandler
|
||||
@@ -20,7 +20,7 @@ class BillingMessageConsumer:
|
||||
"""Billing message consumer"""
|
||||
|
||||
def __init__(self):
|
||||
self.queue_name = "billing.api.calls"
|
||||
self.queue_name = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
self.connection = None
|
||||
self.channel = None
|
||||
self.consuming = False
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends
|
||||
import json
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
@@ -19,19 +20,26 @@ from services.admin_service.constants.sys_config_key import (
|
||||
KEY_LOGIN_GOOGLE_ENABLE,
|
||||
KEY_LOGIN_EMAIL_ENABLE,
|
||||
KEY_LOGIN_EMAIL_MODE,
|
||||
KEY_FAQ,
|
||||
KEY_EMBEDED_HTML,
|
||||
KEY_TOP_NAVIGATION,
|
||||
KEY_MCP_SERVER_PREFIX
|
||||
)
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/config", summary="Get configuration (no login required)", tags=["common"])
|
||||
def get_config(db: Session = Depends(get_db)):
|
||||
def get_config(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get platform configuration settings without authentication."""
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
payment_channel_service = PaymentChannelService(db)
|
||||
|
||||
# Get platform config
|
||||
platform_name = sys_config_service.get_value_by_key(KEY_PLATFORM_NAME) or "XPack"
|
||||
@@ -54,7 +62,24 @@ def get_config(db: Session = Depends(get_db)):
|
||||
# Convert to boolean
|
||||
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
|
||||
email_mode = sys_config_service.get_value_by_key(KEY_LOGIN_EMAIL_MODE) or "password"
|
||||
|
||||
mcp_server_prefix = sys_config_service.get_value_by_key(KEY_MCP_SERVER_PREFIX) or ""
|
||||
|
||||
# Get homepage config
|
||||
faq = sys_config_service.get_value_by_key(KEY_FAQ) or "[]"
|
||||
embeded_html = sys_config_service.get_value_by_key(KEY_EMBEDED_HTML,True) or "{}"
|
||||
top_navigation = sys_config_service.get_value_by_key(KEY_TOP_NAVIGATION) or "[]"
|
||||
try:
|
||||
faq = json.loads(faq)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
try:
|
||||
embeded_html = json.loads(embeded_html)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Embeded HTML配置格式错误")
|
||||
try:
|
||||
top_navigation = json.loads(top_navigation)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
# Build response data
|
||||
config_data = {
|
||||
"login": {
|
||||
@@ -70,10 +95,48 @@ def get_config(db: Session = Depends(get_db)):
|
||||
"language": language,
|
||||
"theme": theme,
|
||||
"about_page": about_page,
|
||||
"mcp_server_prefix": mcp_server_prefix,
|
||||
},
|
||||
"faq": faq,
|
||||
"embeded_html": embeded_html,
|
||||
"top_navigation": top_navigation,
|
||||
"payment_channels": [{"id": item.id, "name": item.name} for item in payment_channel_service.available_list()],
|
||||
}
|
||||
|
||||
return ResponseUtils.success(data=config_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get config: {str(e)}")
|
||||
return ResponseUtils.error(message="Failed to get configuration")
|
||||
|
||||
@router.get("/homepage", summary="Get homepage configuration (no login required)", tags=["common"])
|
||||
def get_homepage_config(db: Session = Depends(get_db)):
|
||||
"""Get homepage configuration settings without authentication."""
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
|
||||
# Get homepage config
|
||||
faq = sys_config_service.get_value_by_key(KEY_FAQ) or "[]"
|
||||
embeded_html = sys_config_service.get_value_by_key(KEY_EMBEDED_HTML,True) or "{}"
|
||||
top_navigation = sys_config_service.get_value_by_key(KEY_TOP_NAVIGATION) or "[]"
|
||||
try:
|
||||
faq = json.loads(faq)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
try:
|
||||
embeded_html = json.loads(embeded_html)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Embeded HTML配置格式错误")
|
||||
try:
|
||||
top_navigation = json.loads(top_navigation)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
config_data = {
|
||||
"faq": faq,
|
||||
"embeded_html": embeded_html,
|
||||
"top_navigation": top_navigation,
|
||||
}
|
||||
return ResponseUtils.success(data=config_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get homepage config: {str(e)}")
|
||||
return ResponseUtils.error(message="Failed to get configuration")
|
||||
@@ -12,6 +12,8 @@ from services.common.utils.cache_utils import CacheUtils
|
||||
from services.common.redis_keys import RedisKeys
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
from services.common.models.mcp_service import ChargeType
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -199,7 +201,9 @@ def get_mcp_service_list(
|
||||
"auth_header": service.auth_header,
|
||||
"auth_token": service.auth_token,
|
||||
"charge_type": service.charge_type.value if service.charge_type else None,
|
||||
"price": float(service.price) if service.price else 0.0,
|
||||
"price": str(float(service.price)) if service.price and service.charge_type == ChargeType.PER_CALL else "0.00",
|
||||
"input_token_price": str(float(service.input_token_price)) if service.input_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
"output_token_price": str(float(service.output_token_price)) if service.output_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
"enabled": service.enabled,
|
||||
"tags": parse_tags_to_array(service.tags),
|
||||
"created_at": str(service.created_at) if service.created_at else None,
|
||||
|
||||
@@ -26,7 +26,7 @@ def get_user_order_list(
|
||||
):
|
||||
"""Get paginated list of user order history."""
|
||||
offset = (page - 1) * page_size
|
||||
total, orders = user_wallet_history_service.success_order_list(offset, page_size)
|
||||
total, orders = user_wallet_history_service.success_deposit_order_list(offset, page_size)
|
||||
if not orders:
|
||||
return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size)
|
||||
result = []
|
||||
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user