Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
feat: aitoearn-2.1 (#487)
Sakura608536db7ef9
diff --git a/DOCKER_DEPLOYMENT_CN.md b/DOCKER_DEPLOYMENT_CN.mdindex 51741925..ffcdadc6 100644--- a/DOCKER_DEPLOYMENT_CN.md+++ b/DOCKER_DEPLOYMENT_CN.md@@ -95,19 +95,16 @@ NEXT_PUBLIC_API_URL: https://your-domain.com/api### 3. 配置应用配置文件-`config/` 目录包含应用配置文件,以只读卷挂载到容器中:+配置文件位于各应用的 `config/` 子目录中,以只读卷挂载到容器中:| 文件 | 挂载到 | 说明 ||------|--------|------|-| `config/aitoearn-ai.config.js` | aitoearn-ai:/app/config.js | AI 服务配置(AI 模型定义、存储配置) |-| `config/aitoearn-server.config.js` | aitoearn-server:/app/config.js | 后端配置(OAuth 回调、邮件、存储配置) |-| `config/gcs-placeholder.json` | aitoearn-ai:/app/config/gcs-placeholder.json | Google Cloud 凭证占位文件 |+| `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` | aitoearn-ai:/app/config.js | AI 服务配置(AI 模型定义、存储配置) |+| `project/aitoearn-backend/apps/aitoearn-server/config/config.js` | aitoearn-server:/app/config.js | 后端配置(OAuth 回调、邮件、存储配置) |这些配置文件从 `process.env`(由 docker-compose.yml 设置)读取环境变量,同时包含一些硬编码配置(存储端点、AI 模型列表等)。-**如需修改 RustFS 凭证或切换到外部 S3/OSS**,需同时更新两个 config.js 文件中的 `assets` 配置部分。--**如需使用真实 Gemini 服务**,将 `config/gcs-placeholder.json` 替换为实际的 Google Cloud 服务账号凭证文件。+**如需修改 RustFS 凭证或切换到外部 S3/OSS**,需同时更新两个 config.js 文件中的 `assets` 配置部分,或通过 `ASSETS_CONFIG` 环境变量覆盖(见下文)。### 4. 启动服务@@ -148,6 +145,7 @@ docker compose ps| `JWT_SECRET` | aitoearn-ai, aitoearn-server | JWT 签名密钥 | `change-this-jwt-secret` || `INTERNAL_TOKEN` | aitoearn-ai, aitoearn-server | 内部服务通信 token | `change-this-secret-token` || `APP_DOMAIN` | aitoearn-server | 应用域名(用于 OAuth 回调地址) | `localhost` |+| `ASSETS_CONFIG` | aitoearn-ai, aitoearn-server | 资源存储配置(JSON 格式,见上文) | 内置 RustFS 配置 || `NEXT_PUBLIC_API_URL` | aitoearn-web | 前端 API 地址(浏览器端访问) | `http://localhost:8080/api` |### 内部服务通信@@ -180,25 +178,23 @@ Docker Compose 内置了 [RustFS](https://github.com/rustfs/rustfs) 作为 S3- 默认账号:`rustfsadmin`- 默认密码:`rustfsadmin`-如需修改 RustFS 凭证,需要同时更新以下三处:+如需修改 RustFS 凭证,需要同时更新以下位置:1. `docker-compose.yml` 中 `rustfs` 服务的 `RUSTFS_ACCESS_KEY` 和 `RUSTFS_SECRET_KEY`2. `docker-compose.yml` 中 `rustfs-init` 服务的 `entrypoint` 命令(`mc alias set` 中的凭证)-3. `config/aitoearn-ai.config.js` 和 `config/aitoearn-server.config.js` 中 `assets` 配置的 `accessKeyId` 和 `secretAccessKey`--**生产环境**如使用 AWS S3 或阿里云 OSS,更新两个 config.js 文件中的 `assets` 配置:--```javascript-// config.js 中的 assets 配置示例(AWS S3)-assets: {- provider: 's3',- region: 'ap-southeast-1',- bucketName: 'your-bucket',- endpoint: 'https://s3.ap-southeast-1.amazonaws.com',- accessKeyId: 'xxx',- secretAccessKey: 'xxx',- cdnEndpoint: 'https://your-cdn.com',-}+3. `docker-compose.yml` 中 `aitoearn-ai` 和 `aitoearn-server` 服务的 `ASSETS_CONFIG` 环境变量++**`ASSETS_CONFIG` 环境变量**(JSON 格式)用于配置资源存储,在 `aitoearn-ai` 和 `aitoearn-server` 两个服务中都需要设置:++```yaml+ASSETS_CONFIG: '{"provider":"s3","region":"us-east-1","bucketName":"aitoearn","endpoint":"http://rustfs.local:9000","publicEndpoint":"http://localhost:9000","cdnEndpoint":"http://localhost:8080/oss","accessKeyId":"rustfsadmin","secretAccessKey":"rustfsadmin","forcePathStyle":true}'+```++**生产环境**如使用 AWS S3 或阿里云 OSS,更新 `ASSETS_CONFIG` 或两个 config.js 文件中的 `assets` 配置:++```yaml+# docker-compose.yml 中(AWS S3 示例)+ASSETS_CONFIG: '{"provider":"s3","region":"ap-southeast-1","bucketName":"your-bucket","endpoint":"https://s3.ap-southeast-1.amazonaws.com","accessKeyId":"xxx","secretAccessKey":"xxx","cdnEndpoint":"https://your-cdn.com"}'```### AI 服务配置@@ -238,13 +234,17 @@ OPENAI_API_KEY: sk-your-new-api-key| `GEMINI_LOCATION` | Google Gemini | 默认 `us-central1` || `AI_PROXY_URL` | AI 代理 | 可选,用于代理访问 AI API |-`GEMINI_KEY_PAIRS` 格式为 JSON 数组:+`GEMINI_KEY_PAIRS` 格式为 JSON 数组,默认为 `'[]'`(空数组):```yaml-GEMINI_KEY_PAIRS: '[{"projectId":"your-gcp-project-id","apiKey":"your-gemini-api-key","keyFile":"/app/config/gcs-placeholder.json","bucket":"your-bucket"}]'+# 默认值(不使用 Gemini)+GEMINI_KEY_PAIRS: '[]'++# 配置 Gemini 示例+GEMINI_KEY_PAIRS: '[{"projectId":"your-gcp-project-id","apiKey":"your-gemini-api-key","bucket":"your-bucket"}]'```-AI 模型的具体定义(可用模型列表、定价等)在 `config/aitoearn-ai.config.js` 中配置。+AI 模型的具体定义(可用模型列表、定价等)在 `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` 中配置。### 第三方平台 OAuth 配置(可选)@@ -277,13 +277,41 @@ AI 模型的具体定义(可用模型列表、定价等)在 `config/aitoearn| `MAIL_USER` / `MAIL_PASS` | aitoearn-server | 邮件服务(AWS SES SMTP) | AWS Console → SES → SMTP || `ALI_SMS_ACCESS_KEY_ID` 等 4 项 | aitoearn-server | 阿里云短信 | https://dysms.console.aliyun.com || `ALI_GREEN_ACCESS_KEY_ID/SECRET` | aitoearn-server | 阿里云内容安全 | https://yundun.console.aliyun.com |-| `NEW_API_URL` / `NEW_API_TOKEN` | aitoearn-server | 内部 API 中转服务 | 自行部署 new-api |++### 自动登录配置(可选)++如需在 aitoearn-server 启动时自动初始化管理员 token,可通过 docker-compose 的 `command` 读取 token 文件并设置为 `AUTO_LOGIN_TOKEN` 环境变量:++```yaml+aitoearn-server:+ command: >+ sh -c 'export AUTO_LOGIN_TOKEN=$$(cat /run/secrets/auto-login-token 2>/dev/null || echo ""); exec node main.js'+```++> 注意:之前的 `AUTO_LOGIN_TOKEN_PATH` 环境变量已被移除,改为在启动命令中直接读取文件内容。++### 镜像拉取策略++Docker Compose 中所有应用服务镜像使用 `pull_policy: always`,确保每次 `docker compose up` 都拉取最新镜像:++```yaml+services:+ aitoearn-web:+ image: aitoearn/web:latest+ pull_policy: always+ aitoearn-server:+ image: aitoearn/server:latest+ pull_policy: always+ aitoearn-ai:+ image: aitoearn/ai:latest+ pull_policy: always+```## 配置文件参考-以下是 `config/` 目录中配置文件的完整说明。这些文件以只读卷挂载到容器中,修改后需重启对应服务。+以下是各应用配置文件的完整说明。这些文件以只读卷挂载到容器中,修改后需重启对应服务。-### config/aitoearn-ai.config.js+### project/aitoearn-backend/apps/aitoearn-ai/config/config.jsAI 服务的完整配置文件,挂载到 `aitoearn-ai:/app/config.js`。@@ -426,7 +454,7 @@ AI 服务的完整配置文件,挂载到 `aitoearn-ai:/app/config.js`。----### config/aitoearn-server.config.js+### project/aitoearn-backend/apps/aitoearn-server/config/config.js后端服务的完整配置文件,挂载到 `aitoearn-server:/app/config.js`。@@ -486,7 +514,7 @@ AI 服务的完整配置文件,挂载到 `aitoearn-ai:/app/config.js`。#### 资源存储(assets)-与 aitoearn-ai.config.js 中的 `assets` 配置相同,两处需保持一致。+与 aitoearn-ai config.js 中的 `assets` 配置相同,两处需保持一致。也可通过 `ASSETS_CONFIG` 环境变量统一覆盖。#### 邮件配置(mail)@@ -517,20 +545,26 @@ AI 服务的完整配置文件,挂载到 `aitoearn-ai:/app/config.js`。| `aiClient.baseUrl` | 访问 AI 服务的地址 | 环境变量 `AI_URL` || `aiClient.token` | 服务通信 token | 环境变量 `INTERNAL_TOKEN` |-#### New API 中转服务+#### Relay 配置(可选)-| 配置项 | 说明 | 来源 |-|--------|------|------|-| `newApi.baseUrl` | New API 服务地址 | 环境变量 `NEW_API_URL` |-| `newApi.token` | New API 访问 token | 环境变量 `NEW_API_TOKEN` |+Relay 允许自部署实例通过官方 AiToEarn 中继服务器连接社交媒体平台账号,无需自行配置各平台的 OAuth 凭据。----+**配置步骤:**-### config/gcs-placeholder.json+1. 在 [https://aitoearn.ai](https://aitoearn.ai) 的 **设置 → API Key** 中创建一个 API Key。+2. 在 `docker-compose.yml` 的 `aitoearn-server` 服务中配置:-Google Cloud 服务账号凭证占位文件。Gemini 服务需要此文件来访问 Google Cloud API。+| 变量 | 说明 | 默认值 |+|------|------|--------|+| `RELAY_SERVER_URL` | Relay 服务器地址 | `https://aitoearn.ai/api` |+| `RELAY_API_KEY` | 你的 API Key(第 1 步创建) | 无 |+| `RELAY_CALLBACK_URL` | 本地回调地址,用于接收中继结果 | `http://127.0.0.1:8080/api/plat/relay-callback` |-默认包含占位值,如需使用真实 Gemini 服务,替换为从 Google Cloud Console 下载的服务账号 JSON 密钥文件。+```yaml+RELAY_SERVER_URL: https://aitoearn.ai/api+RELAY_API_KEY: 你的API-Key+RELAY_CALLBACK_URL: http://127.0.0.1:8080/api/plat/relay-callback+```## 常用命令@@ -630,19 +664,18 @@ bash scripts/build.sh> 前置要求:需要安装 Node.js 和 pnpm,并在 `project/aitoearn-backend` 目录下执行过 `pnpm install`。-### Q: config/ 目录下的配置文件有什么作用?+### Q: 配置文件有什么作用?-`config/` 目录包含两个应用配置文件和一个凭证占位文件:+各应用的 `config/` 子目录包含应用配置文件:-- **aitoearn-ai.config.js**: AI 服务的详细配置,包含 AI 模型定义(可用模型列表、定价)、存储配置、Gemini 设置等-- **aitoearn-server.config.js**: 后端服务配置,包含 OAuth 回调地址模式、邮件传输设置、存储配置等-- **gcs-placeholder.json**: Google Cloud 服务账号凭证占位文件,使用 Gemini 时需替换为真实凭证+- **project/aitoearn-backend/apps/aitoearn-ai/config/config.js**: AI 服务的详细配置,包含 AI 模型定义(可用模型列表、定价)、存储配置、Gemini 设置等+- **project/aitoearn-backend/apps/aitoearn-server/config/config.js**: 后端服务配置,包含 OAuth 回调地址模式、邮件传输设置、存储配置等这些文件以只读卷挂载到容器中,修改后需重启对应服务:`docker compose restart aitoearn-ai aitoearn-server`### Q: 如何修改或添加 AI 模型?-编辑 `config/aitoearn-ai.config.js` 中的 `ai.models` 部分,可以修改可用模型列表、定价和模型参数。修改后重启 AI 服务:+编辑 `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` 中的 `ai.models` 部分,可以修改可用模型列表、定价和模型参数。修改后重启 AI 服务:```bashdocker compose restart aitoearn-ai@@ -675,7 +708,7 @@ lsof -i :63791. 确认 `docker-compose.yml` 中 `OPENAI_API_KEY` 和 `OPENAI_BASE_URL` 已正确配置2. 推荐部署 [new-api](https://github.com/Calcium-Ion/new-api) 中转服务统一管理所有 AI 模型3. 默认的 `sk-placeholder` 仅作为占位值,不会调通任何 AI 服务-4. AI 模型的配置在 `config/aitoearn-ai.config.js` 中,确认模型定义与你的 API 服务匹配+4. AI 模型的配置在 `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` 中,确认模型定义与你的 API 服务匹配### Q: 如何更新到最新版本?diff --git a/DOCKER_DEPLOYMENT_EN.md b/DOCKER_DEPLOYMENT_EN.mdindex 0c805b0e..1e47800e 100644--- a/DOCKER_DEPLOYMENT_EN.md+++ b/DOCKER_DEPLOYMENT_EN.md@@ -95,19 +95,16 @@ NEXT_PUBLIC_API_URL: https://your-domain.com/api### 3. Configure Application Config Files-The `config/` directory contains application configuration files mounted as read-only volumes into containers:+Configuration files are located in each application's `config/` subdirectory, mounted as read-only volumes into containers:| File | Mounted to | Description ||------|------------|-------------|-| `config/aitoearn-ai.config.js` | aitoearn-ai:/app/config.js | AI service config (AI model definitions, storage) |-| `config/aitoearn-server.config.js` | aitoearn-server:/app/config.js | Backend config (OAuth callbacks, email, storage) |-| `config/gcs-placeholder.json` | aitoearn-ai:/app/config/gcs-placeholder.json | Google Cloud credentials placeholder |+| `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` | aitoearn-ai:/app/config.js | AI service config (AI model definitions, storage) |+| `project/aitoearn-backend/apps/aitoearn-server/config/config.js` | aitoearn-server:/app/config.js | Backend config (OAuth callbacks, email, storage) |These config files read environment variables from `process.env` (set by docker-compose.yml) and also contain hardcoded configuration (storage endpoints, AI model lists, etc.).-**To change RustFS credentials or switch to external S3/OSS**, update the `assets` configuration in both config.js files.--**To use real Gemini services**, replace `config/gcs-placeholder.json` with actual Google Cloud service account credentials.+**To change RustFS credentials or switch to external S3/OSS**, update the `assets` configuration in both config.js files, or override via the `ASSETS_CONFIG` environment variable (see below).### 4. Start Services@@ -148,6 +145,7 @@ All variables below are configured in the `environment` section of each service| `JWT_SECRET` | aitoearn-ai, aitoearn-server | JWT signing secret | `change-this-jwt-secret` || `INTERNAL_TOKEN` | aitoearn-ai, aitoearn-server | Inter-service auth token | `change-this-secret-token` || `APP_DOMAIN` | aitoearn-server | Application domain (for OAuth callbacks) | `localhost` |+| `ASSETS_CONFIG` | aitoearn-ai, aitoearn-server | Asset storage config (JSON format, see above) | Built-in RustFS config || `NEXT_PUBLIC_API_URL` | aitoearn-web | Frontend API URL (browser-facing) | `http://localhost:8080/api` |### Internal Service Communication@@ -180,25 +178,23 @@ On startup, the `aitoearn` bucket is automatically created. Application services- Default username: `rustfsadmin`- Default password: `rustfsadmin`-To change RustFS credentials, update all three locations:+To change RustFS credentials, update these locations:1. `docker-compose.yml` — `rustfs` service: `RUSTFS_ACCESS_KEY` and `RUSTFS_SECRET_KEY`2. `docker-compose.yml` — `rustfs-init` service: credentials in the `mc alias set` command-3. `config/aitoearn-ai.config.js` and `config/aitoearn-server.config.js` — `accessKeyId` and `secretAccessKey` in the `assets` config--**For production** with AWS S3 or other providers, update the `assets` config in both config.js files:--```javascript-// Example assets config for AWS S3 in config.js-assets: {- provider: 's3',- region: 'ap-southeast-1',- bucketName: 'your-bucket',- endpoint: 'https://s3.ap-southeast-1.amazonaws.com',- accessKeyId: 'xxx',- secretAccessKey: 'xxx',- cdnEndpoint: 'https://your-cdn.com',-}+3. `docker-compose.yml` — `ASSETS_CONFIG` environment variable in both `aitoearn-ai` and `aitoearn-server` services++**`ASSETS_CONFIG` environment variable** (JSON format) configures asset storage. Required in both `aitoearn-ai` and `aitoearn-server` services:++```yaml+ASSETS_CONFIG: '{"provider":"s3","region":"us-east-1","bucketName":"aitoearn","endpoint":"http://rustfs.local:9000","publicEndpoint":"http://localhost:9000","cdnEndpoint":"http://localhost:8080/oss","accessKeyId":"rustfsadmin","secretAccessKey":"rustfsadmin","forcePathStyle":true}'+```++**For production** with AWS S3 or other providers, update `ASSETS_CONFIG` or the `assets` config in both config.js files:++```yaml+# In docker-compose.yml (AWS S3 example)+ASSETS_CONFIG: '{"provider":"s3","region":"ap-southeast-1","bucketName":"your-bucket","endpoint":"https://s3.ap-southeast-1.amazonaws.com","accessKeyId":"xxx","secretAccessKey":"xxx","cdnEndpoint":"https://your-cdn.com"}'```### AI Services@@ -238,13 +234,17 @@ All supported AI services (configured in the `aitoearn-ai` service):| `GEMINI_LOCATION` | Google Gemini | Default: `us-central1` || `AI_PROXY_URL` | AI Proxy | Optional, for proxied AI API access |-`GEMINI_KEY_PAIRS` format (JSON array):+`GEMINI_KEY_PAIRS` format (JSON array), defaults to `'[]'` (empty array):```yaml-GEMINI_KEY_PAIRS: '[{"projectId":"your-gcp-project-id","apiKey":"your-gemini-api-key","keyFile":"/app/config/gcs-placeholder.json","bucket":"your-bucket"}]'+# Default (Gemini disabled)+GEMINI_KEY_PAIRS: '[]'++# Example with Gemini configured+GEMINI_KEY_PAIRS: '[{"projectId":"your-gcp-project-id","apiKey":"your-gemini-api-key","bucket":"your-bucket"}]'```-AI model definitions (available models, pricing, etc.) are configured in `config/aitoearn-ai.config.js`.+AI model definitions (available models, pricing, etc.) are configured in `project/aitoearn-backend/apps/aitoearn-ai/config/config.js`.### Third-party OAuth (Optional)@@ -277,13 +277,41 @@ Configure social media OAuth credentials as needed in the `aitoearn-server` serv| `MAIL_USER` / `MAIL_PASS` | aitoearn-server | Email (AWS SES SMTP) | AWS Console → SES → SMTP || `ALI_SMS_*` (4 vars) | aitoearn-server | Aliyun SMS | https://dysms.console.aliyun.com || `ALI_GREEN_ACCESS_KEY_ID/SECRET` | aitoearn-server | Aliyun Content Safety | https://yundun.console.aliyun.com |-| `NEW_API_URL` / `NEW_API_TOKEN` | aitoearn-server | Internal API relay service | Self-deploy new-api |++### Auto-Login Configuration (Optional)++To automatically initialize an admin token when aitoearn-server starts, use the docker-compose `command` to read a token file and set it as the `AUTO_LOGIN_TOKEN` environment variable:++```yaml+aitoearn-server:+ command: >+ sh -c 'export AUTO_LOGIN_TOKEN=$$(cat /run/secrets/auto-login-token 2>/dev/null || echo ""); exec node main.js'+```++> Note: The previous `AUTO_LOGIN_TOKEN_PATH` environment variable has been removed. The file contents are now read directly in the startup command.++### Image Pull Policy++All application service images in Docker Compose use `pull_policy: always` to ensure the latest images are pulled on every `docker compose up`:++```yaml+services:+ aitoearn-web:+ image: aitoearn/web:latest+ pull_policy: always+ aitoearn-server:+ image: aitoearn/server:latest+ pull_policy: always+ aitoearn-ai:+ image: aitoearn/ai:latest+ pull_policy: always+```## Config Files Reference-The `config/` directory contains configuration files mounted as read-only volumes into containers. Restart the corresponding service after making changes.+Each application has its own configuration file, mounted as read-only volumes into containers. Restart the corresponding service after making changes.-### config/aitoearn-ai.config.js+### project/aitoearn-backend/apps/aitoearn-ai/config/config.jsComplete configuration for the AI service, mounted to `aitoearn-ai:/app/config.js`.@@ -426,7 +454,7 @@ Pricing is per resolution (1K/2K/4K), all default to `0`.----### config/aitoearn-server.config.js+### project/aitoearn-backend/apps/aitoearn-server/config/config.jsComplete configuration for the backend service, mounted to `aitoearn-server:/app/config.js`.@@ -486,7 +514,7 @@ Same config structure as aitoearn-ai.config.js, read from environment variables.#### Assets Storage-Same as `assets` in aitoearn-ai.config.js. Both must be kept in sync.+Same as `assets` in the aitoearn-ai config.js. Both must be kept in sync. Can also be overridden via the `ASSETS_CONFIG` environment variable.#### Email Configuration (mail)@@ -517,20 +545,26 @@ To switch email providers (e.g., SendGrid, Mailgun), modify the `mail.transport`| `aiClient.baseUrl` | URL to reach AI service | Env var `AI_URL` || `aiClient.token` | Service communication token | Env var `INTERNAL_TOKEN` |-#### New API Relay Service+#### Relay Configuration (Optional)-| Config | Description | Source |-|--------|-------------|--------|-| `newApi.baseUrl` | New API service URL | Env var `NEW_API_URL` |-| `newApi.token` | New API access token | Env var `NEW_API_TOKEN` |+Relay allows self-hosted instances to connect social media platform accounts via the official AiToEarn relay server, without needing to configure OAuth credentials for each platform.----+**Setup:**-### config/gcs-placeholder.json+1. Go to **Settings → API Key** at [https://aitoearn.ai](https://aitoearn.ai) and create an API Key.+2. Configure in the `aitoearn-server` service of `docker-compose.yml`:-Google Cloud service account credentials placeholder file. Required by Gemini service to access Google Cloud APIs.+| Variable | Description | Default |+|----------|-------------|---------|+| `RELAY_SERVER_URL` | Relay server URL | `https://aitoearn.ai/api` |+| `RELAY_API_KEY` | Your API Key (created in step 1) | None |+| `RELAY_CALLBACK_URL` | Local callback URL for receiving relay results | `http://127.0.0.1:8080/api/plat/relay-callback` |-Contains placeholder values by default. To use real Gemini services, replace with an actual service account JSON key file downloaded from Google Cloud Console.+```yaml+RELAY_SERVER_URL: https://aitoearn.ai/api+RELAY_API_KEY: your-api-key+RELAY_CALLBACK_URL: http://127.0.0.1:8080/api/plat/relay-callback+```## Common Commands@@ -630,19 +664,18 @@ After building, start services normally with `docker compose up -d`.> Prerequisites: Node.js and pnpm must be installed, and `pnpm install` must have been run in `project/aitoearn-backend`.-### Q: What are the config/ files for?+### Q: What are the config files for?-The `config/` directory contains two application config files and a credentials placeholder:+Each application has its own config file in its `config/` subdirectory:-- **aitoearn-ai.config.js**: Detailed AI service configuration including AI model definitions (available models, pricing), storage config, and Gemini settings-- **aitoearn-server.config.js**: Backend service configuration including OAuth callback URL patterns, email transport settings, and storage config-- **gcs-placeholder.json**: Google Cloud service account credentials placeholder — replace with real credentials for production Gemini usage+- **project/aitoearn-backend/apps/aitoearn-ai/config/config.js**: Detailed AI service configuration including AI model definitions (available models, pricing), storage config, and Gemini settings+- **project/aitoearn-backend/apps/aitoearn-server/config/config.js**: Backend service configuration including OAuth callback URL patterns, email transport settings, and storage configThese files are mounted as read-only volumes. After editing, restart the relevant services: `docker compose restart aitoearn-ai aitoearn-server`### Q: How to add or change AI models?-Edit the `ai.models` section in `config/aitoearn-ai.config.js` to modify the available model list, pricing, and model parameters. Then restart the AI service:+Edit the `ai.models` section in `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` to modify the available model list, pricing, and model parameters. Then restart the AI service:```bashdocker compose restart aitoearn-ai@@ -675,7 +708,7 @@ lsof -i :63791. Verify `OPENAI_API_KEY` and `OPENAI_BASE_URL` are correctly configured in `docker-compose.yml`2. Recommended: deploy [new-api](https://github.com/Calcium-Ion/new-api) relay service to manage all AI models3. The default `sk-placeholder` is just a placeholder — no AI service will work until real keys are set-4. AI model configuration is in `config/aitoearn-ai.config.js` — ensure model definitions match your API service+4. AI model configuration is in `project/aitoearn-backend/apps/aitoearn-ai/config/config.js` — ensure model definitions match your API service### Q: How to update to the latest version?diff --git a/README.md b/README.mdindex 64952d4f..ddbfe45e 100644--- a/README.md+++ b/README.md@@ -201,9 +201,12 @@ You can still use Docker for MongoDB/Redis, or configure your own services in th```bashcd project/aitoearn-backendpnpm install-npx nx serve aitoearn-ai+# Copy config files for local development+cp apps/aitoearn-ai/config/config.js apps/aitoearn-ai/config/local.config.js+cp apps/aitoearn-server/config/config.js apps/aitoearn-server/config/local.config.js+pnpm nx serve aitoearn-ai# in another terminal-npx nx serve aitoearn-server+pnpm nx serve aitoearn-server```#### 2. Start the frontend `aitoearn-web`@@ -242,9 +245,63 @@ The Electron project provides a desktop client for AiToEarn.</details>## MCP Service-https://www.modelscope.cn/mcp/servers/whh826219822/aitoearn-https://www.npmjs.com/~aitoearn?activeTab=packages+AiToEarn provides MCP (Model Context Protocol) server endpoints that allow AI assistants (such as Claude, Cursor, etc.) to interact with your AiToEarn instance programmatically — including publishing content, managing accounts, and more.++### Endpoints++AiToEarn exposes two MCP transport protocols:++| Transport | Endpoint | Description |+|-----------|----------|-------------|+| **HTTP** | `{baseUrl}/api/unified/mcp` | Recommended. Stateless HTTP-based MCP transport |+| **SSE** | `{baseUrl}/api/unified/sse` | Server-Sent Events transport for long-lived connections |++### Quick Setup++1. Go to **Settings → API Key** in the AiToEarn web interface and create an API Key.+2. Configure your AI assistant's MCP client to connect to one of the endpoints above, passing your API Key via the `x-api-key` header.++**Example for Claude Desktop** (`claude_desktop_config.json`):++```json+{+ "mcpServers": {+ "aitoearn": {+ "type": "http",+ "url": "https://aitoearn.ai/api/unified/mcp",+ "headers": {+ "x-api-key": "your-api-key"+ }+ }+ }+}+```++> For self-hosted instances, replace the URL with your own (e.g., `http://localhost:8080/api/unified/mcp`).++## Relay Service++Relay enables self-hosted AiToEarn instances to connect social media platform accounts via the official AiToEarn relay server (`https://aitoearn.ai`), without needing to configure OAuth credentials for each platform yourself.++### How It Works++1. Your self-hosted instance sends OAuth requests through the relay server.+2. Users authorize on the platform via the relay server's OAuth credentials.+3. The relay server forwards the authorization result back to your instance via the callback URL.++### Setup++1. Go to **Settings → API Key** on [https://aitoearn.ai](https://aitoearn.ai) and create an API Key.+2. Configure the following environment variables in your `docker-compose.yml` under the `aitoearn-server` service:++```yaml+RELAY_SERVER_URL: https://aitoearn.ai/api+RELAY_API_KEY: your-api-key+RELAY_CALLBACK_URL: http://127.0.0.1:8080/api/plat/relay-callback+```++3. Restart the service: `docker compose restart aitoearn-server`## Contacthttps://t.me/harryyyy2025diff --git a/README_CN.md b/README_CN.mdindex be9bd5c5..f5d08a00 100644--- a/README_CN.md+++ b/README_CN.md@@ -186,9 +186,12 @@ Docker 成功启动后,您可以通过以下地址访问服务:```bashcd project/aitoearn-backendpnpm install-npx nx serve aitoearn-ai+# 复制配置文件用于本地开发+cp apps/aitoearn-ai/config/config.js apps/aitoearn-ai/config/local.config.js+cp apps/aitoearn-server/config/config.js apps/aitoearn-server/config/local.config.js+pnpm nx serve aitoearn-ai# 在另一个终端-npx nx serve aitoearn-server+pnpm nx serve aitoearn-server```#### 2. 启动前端 `aitoearn-web`@@ -230,8 +233,62 @@ Electron 项目为 AiToEarn 提供桌面客户端。## MCP 服务-- [ModelScope MCP Servers](https://www.modelscope.cn/mcp/servers/whh826219822/aitoearn)-- [NPM Packages](https://www.npmjs.com/~aitoearn?activeTab=packages)+AiToEarn 提供 MCP(Model Context Protocol)服务端点,让 AI 助手(如 Claude、Cursor 等)能够以编程方式与您的 AiToEarn 实例交互——包括发布内容、管理账号等。++### 端点++AiToEarn 支持两种 MCP 传输协议:++| 传输方式 | 端点 | 说明 |+|---------|------|------|+| **HTTP** | `{baseUrl}/api/unified/mcp` | 推荐。基于 HTTP 的无状态 MCP 传输 |+| **SSE** | `{baseUrl}/api/unified/sse` | 基于 Server-Sent Events 的长连接传输 |++### 快速配置++1. 在 AiToEarn Web 界面中进入 **设置 → API Key**,创建一个 API Key。+2. 在你的 AI 助手中配置 MCP 客户端连接到上述端点,通过 `x-api-key` header 传入你的 API Key。++**以 Claude Desktop 为例**(`claude_desktop_config.json`):++```json+{+ "mcpServers": {+ "aitoearn": {+ "type": "http",+ "url": "https://aitoearn.ai/api/unified/mcp",+ "headers": {+ "x-api-key": "你的API-Key"+ }+ }+ }+}+```++> 如果是自部署实例,将 URL 替换为你自己的地址(如 `http://localhost:8080/api/unified/mcp`)。++## Relay 中继服务++Relay 允许自部署的 AiToEarn 实例通过官方中继服务器(`https://aitoearn.ai`)连接社交媒体平台账号,无需自行配置各平台的 OAuth 凭据。++### 工作原理++1. 您的自部署实例通过中继服务器发送 OAuth 请求。+2. 用户通过中继服务器的 OAuth 凭据在平台上授权。+3. 中继服务器通过回调 URL 将授权结果转发回您的实例。++### 配置步骤++1. 在 [https://aitoearn.ai](https://aitoearn.ai) 的 **设置 → API Key** 中创建一个 API Key。+2. 在 `docker-compose.yml` 的 `aitoearn-server` 服务中配置以下环境变量:++```yaml+RELAY_SERVER_URL: https://aitoearn.ai/api+RELAY_API_KEY: 你的API-Key+RELAY_CALLBACK_URL: http://127.0.0.1:8080/api/plat/relay-callback+```++3. 重启服务:`docker compose restart aitoearn-server`## 高级设置diff --git a/config/aitoearn-ai.config.js b/config/aitoearn-ai.config.jsdeleted file mode 100644index da745147..00000000--- a/config/aitoearn-ai.config.js+++ /dev/null@@ -1,461 +0,0 @@-const {- REDIS_HOST,- REDIS_PORT,- REDIS_PASSWORD,-} = process.env--const {- MONGODB_HOST,- MONGODB_PORT,- MONGODB_USERNAME,- MONGODB_PASSWORD,-} = process.env--const {- JWT_SECRET,- INTERNAL_TOKEN,-} = process.env--const {- VOLCENGINE_API_KEY,- VOLCENGINE_ACCESS_KEY_ID,- VOLCENGINE_SECRET_ACCESS_KEY,- VOLCENGINE_VOD_SPACE_NAME,- OPENAI_API_KEY,- OPENAI_BASE_URL,- ANTHROPIC_BASE_URL,- ANTHROPIC_API_KEY,- GROK_API_KEY,- AICSO_API_KEY,- AICSO_BASE_URL,-} = process.env--const {- GEMINI_KEY_PAIRS,- GEMINI_LOCATION,- AI_PROXY_URL,-} = process.env--const {- SERVER_URL,-} = process.env--function parseGeminiKeyPairs() {- if (!GEMINI_KEY_PAIRS) {- throw new Error('GEMINI_KEY_PAIRS 环境变量必须配置')- }-- try {- return JSON.parse(GEMINI_KEY_PAIRS)- }- catch (e) {- console.error('解析 GEMINI_KEY_PAIRS 失败:', e)- throw new Error('GEMINI_KEY_PAIRS 格式错误')- }-}--module.exports = {- port: 3010,- logger: {- console: {- enable: true,- level: 'debug',- pretty: false,- },- },- redis: {- host: REDIS_HOST,- port: Number(REDIS_PORT),- username: 'default',- password: REDIS_PASSWORD,- },- redlock: {- redis: {- host: REDIS_HOST,- port: Number(REDIS_PORT),- username: 'default',- password: REDIS_PASSWORD,- },- },- mongodb: {- uri: `mongodb://${MONGODB_USERNAME}:${encodeURIComponent(MONGODB_PASSWORD)}@${MONGODB_HOST}:${MONGODB_PORT}/?authSource=admin&directConnection=true`,- dbName: 'aitoearn',- },- auth: {- secret: JWT_SECRET,- expiresIn: 7 * 24 * 60 * 60,- internalToken: INTERNAL_TOKEN,- },- serverClient: {- baseUrl: SERVER_URL,- token: INTERNAL_TOKEN,- },- assets: {- provider: 's3',- region: 'us-east-1',- bucketName: 'aitoearn',- endpoint: 'http://rustfs.local:9000',- accessKeyId: 'rustfsadmin',- secretAccessKey: 'rustfsadmin',- },- ai: {- volcengine: {- baseUrl: 'https://ark.cn-beijing.volces.com/',- apiKey: VOLCENGINE_API_KEY,- accessKeyId: VOLCENGINE_ACCESS_KEY_ID,- secretAccessKey: VOLCENGINE_SECRET_ACCESS_KEY,- spaceName: VOLCENGINE_VOD_SPACE_NAME,- playbackBaseUrl: 'http://vod.assets.aitoearn.ai',- urlAuthPrimaryKey: 'd8eea018341d4e9687ead69bea628271',- },- openai: {- baseUrl: AI_PROXY_URL ? `${AI_PROXY_URL}/${OPENAI_BASE_URL}` : OPENAI_BASE_URL,- apiKey: OPENAI_API_KEY,- },- grok: {- baseUrl: 'https://api.x.ai',- apiKey: GROK_API_KEY,- ...(AI_PROXY_URL && { proxyUrl: AI_PROXY_URL }),- },- anthropic: {- baseUrl: AI_PROXY_URL ? `${AI_PROXY_URL}/${ANTHROPIC_BASE_URL}` : ANTHROPIC_BASE_URL,- apiKey: ANTHROPIC_API_KEY,- },- gemini: {- keyPairs: parseGeminiKeyPairs(),- location: GEMINI_LOCATION || 'us-central1',- apiKey: OPENAI_API_KEY,- baseUrl: OPENAI_BASE_URL.replace(/\/v1$/, ''),- ...(AI_PROXY_URL && { proxyUrl: AI_PROXY_URL }),- },- aicso: {- apiKey: AICSO_API_KEY,- ...(AICSO_BASE_URL && { baseUrl: AICSO_BASE_URL }),- },- aideo: {- vCreative: {- basePrice: 0, // AI editing base price (cents/minute, 720P)- },- vision: {- basePrice: 0, // Video understanding base price (cents/minute)- },- highlight: {- basePrice: 0, // Highlight smart editing base price (cents/minute)- },- aiTranslation: {- facialTranslation: 0, // Facial translation price (cents/minute) - the only supported translation type- },- erase: {- basePrice: 0, // AI subtitle removal base price (cents/minute)- },- videoEdit: {- basePrice: 0, // Video editing base price (cents/minute, 720P)- },- dramaRecap: {- basePrice: 0, // Drama recap base price (cents/minute)- },- styleTransfer: {- basePrice: 0, // Video style transfer base price (cents/minute)- },- },- models: {- chat: [- {- name: 'gemini-3.1-pro-preview',- description: 'Gemini 3.1 Pro Preview',- inputModalities: ['text', 'image', 'audio', 'video'],- outputModalities: ['text'],- pricing: {- tiers: [- {- maxInputTokens: 200000,- input: { text: '0', image: '0', video: '0', audio: '0' },- output: { text: '0' },- },- {- input: { text: '0', image: '0', video: '0', audio: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'gemini-3-flash-preview',- description: 'Gemini 3 Flash Preview',- inputModalities: ['text', 'image', 'audio', 'video'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0', video: '0', audio: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'gpt-5.1-all',- description: 'GPT 5.1',- inputModalities: ['text', 'image'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'gpt-5',- description: 'GPT 5',- inputModalities: ['text', 'image'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'gemini-3.1-flash-image-preview',- description: 'Nano Banana 2',- inputModalities: ['text', 'image'],- outputModalities: ['image'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0', image: '0' },- },- ],- },- },- {- name: 'gemini-3-pro-image-preview',- description: 'Nano Banana Pro',- inputModalities: ['text', 'image'],- outputModalities: ['image'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0', image: '0' },- },- ],- },- },- {- name: 'claude-opus-4-5-20251101',- description: 'Claude Opus 4.5',- inputModalities: ['text', 'image'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'claude-opus-4-6',- description: 'Claude Opus 4.6',- inputModalities: ['text', 'image'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'claude-sonnet-4-5-20250929',- description: 'Claude Sonnet 4.5',- inputModalities: ['text', 'image'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0' },- output: { text: '0' },- },- ],- },- },- {- name: 'gemini-2.5-flash',- description: 'Gemini 2.5 Flash',- inputModalities: ['text', 'image', 'audio', 'video'],- outputModalities: ['text'],- pricing: {- tiers: [- {- input: { text: '0', image: '0', video: '0', audio: '0' },- output: { text: '0' },- },- ],- },- },- ],- image: {- generation: [- {- name: 'gpt-image-1.5',- description: 'gpt-image-1.5',- sizes: ['1024x1024', '1536x1024', '1024x1536', 'auto'],- qualities: ['high', 'medium', 'low'],- styles: [],- pricing: '0',- },- ],- edit: [- {- name: 'gpt-image-1.5',- description: 'gpt-image-1.5',- sizes: ['1024x1024', '1536x1024', '1024x1536', 'auto'],- qualities: ['high', 'medium', 'low'],- styles: [],- pricing: '0',- maxInputImages: 16,- },- ],- },- video: {- generation: [- {- name: 'grok-imagine-video',- description: 'Grok Video',- channel: 'grok',- modes: ['text2video', 'image2video', 'video2video'],- resolutions: ['720p'],- durations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],- maxInputImages: 1,- aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'],- defaults: {- duration: 8,- aspectRatio: '9:16',- },- pricing: [- { duration: 1, price: 0 },- { duration: 2, price: 0 },- { duration: 3, price: 0 },- { duration: 4, price: 0 },- { duration: 5, price: 0 },- { duration: 6, price: 0 },- { duration: 7, price: 0 },- { duration: 8, price: 0 },- { duration: 9, price: 0 },- { duration: 10, price: 0 },- { duration: 11, price: 0 },- { duration: 12, price: 0 },- { duration: 13, price: 0 },- { duration: 14, price: 0 },- { duration: 15, price: 0 },- { mode: 'video2video', duration: 1, price: 0 },- { mode: 'video2video', duration: 2, price: 0 },- { mode: 'video2video', duration: 3, price: 0 },- { mode: 'video2video', duration: 4, price: 0 },- { mode: 'video2video', duration: 5, price: 0 },- { mode: 'video2video', duration: 6, price: 0 },- { mode: 'video2video', duration: 7, price: 0 },- { mode: 'video2video', duration: 8, price: 0 },- ],- },- {- name: 'grok-video-3-15s',- description: 'Grok Video 15s',- channel: 'aicso-grok',- modes: ['text2video', 'image2video'],- resolutions: ['720p'],- durations: [15],- maxInputImages: 1,- aspectRatios: ['2:3', '3:2', '1:1'],- tags: ['限时'],- defaults: {- duration: 15,- aspectRatio: '9:16',- },- pricing: [- { duration: 15, price: 0 },- ],- },- {- name: 'veo3.1-components-4k',- description: 'Veo 3.1 4K',- channel: 'aicso-veo',- modes: ['text2video', 'image2video'],- resolutions: ['4k'],- durations: [8],- maxInputImages: 3,- aspectRatios: ['9:16', '16:9', '1:1'],- tags: ['限时'],- defaults: {- duration: 8,- aspectRatio: '9:16',- },- pricing: [- { duration: 8, price: 0 },- ],- },- {- name: 'veo3.1-components',- description: 'Veo 3.1',- channel: 'aicso-veo',- modes: ['text2video', 'image2video'],- resolutions: ['720p'],- durations: [8],- maxInputImages: 3,- aspectRatios: ['9:16', '16:9', '1:1'],- tags: ['限时'],- defaults: {- duration: 8,- aspectRatio: '9:16',- },- pricing: [- { duration: 8, price: 0 },- ],- },- ],- },- },- draftGeneration: {- imageModels: [- {- model: 'gemini-3.1-flash-image-preview',- displayName: 'NanoBanana 2',- supportedAspectRatios: ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9'],- maxInputImages: 14,- pricing: [- { resolution: '1K', pricePerImage: 0 },- { resolution: '2K', pricePerImage: 0 },- { resolution: '4K', pricePerImage: 0 },- ],- },- {- model: 'gemini-3-pro-image-preview',- displayName: 'NanoBanana Pro',- supportedAspectRatios: ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9'],- maxInputImages: 14,- pricing: [- { resolution: '1K', pricePerImage: 0 },- { resolution: '2K', pricePerImage: 0 },- { resolution: '4K', pricePerImage: 0 },- ],- },- ],- },- },- agent: {- baseUrl: AI_PROXY_URL ? `${AI_PROXY_URL}/${OPENAI_BASE_URL}/messages` : `${OPENAI_BASE_URL}/messages`,- apiKey: OPENAI_API_KEY,- },-}diff --git a/config/aitoearn-server.config.js b/config/aitoearn-server.config.jsdeleted file mode 100644index c5cdc079..00000000--- a/config/aitoearn-server.config.js+++ /dev/null@@ -1,296 +0,0 @@-const {- REDIS_HOST,- REDIS_PORT,- REDIS_PASSWORD,-} = process.env--const {- MONGODB_HOST,- MONGODB_PORT,- MONGODB_USERNAME,- MONGODB_PASSWORD,-} = process.env--const {- AI_URL,-} = process.env--const {- JWT_SECRET,- INTERNAL_TOKEN,-} = process.env--const {- NODE_ENV,- APP_DOMAIN,-} = process.env--const {- MAIL_USER,- MAIL_PASS,-} = process.env--const {- NEW_API_URL,- NEW_API_TOKEN,-} = process.env--const {- BILIBILI_CLIENT_ID,- BILIBILI_CLIENT_SECRET,- GOOGLE_CLIENT_ID,- GOOGLE_CLIENT_SECRET,- KWAI_CLIENT_ID,- KWAI_CLIENT_SECRET,- PINTEREST_CLIENT_ID,- PINTEREST_CLIENT_SECRET,- PINTEREST_TEST_AUTHORIZATION,- TIKTOK_CLIENT_ID,- TIKTOK_CLIENT_SECRET,- TWITTER_CLIENT_ID,- TWITTER_CLIENT_SECRET,- FACEBOOK_CLIENT_ID,- FACEBOOK_CLIENT_SECRET,- FACEBOOK_CONFIG_ID,- THREADS_CLIENT_ID,- THREADS_CLIENT_SECRET,- INSTAGRAM_CLIENT_ID,- INSTAGRAM_CLIENT_SECRET,- LINKEDIN_CLIENT_ID,- LINKEDIN_CLIENT_SECRET,- YOUTUBE_CLIENT_ID,- YOUTUBE_CLIENT_SECRET,- WXPLAT_APP_ID,- WXPLAT_APP_SECRET,- WXPLAT_ENCODING_AES_KEY,- DOYIN_CLIENT_ID,- DOYIN_CLIENT_SECRET,-} = process.env--const {- ALI_SMS_ACCESS_KEY_ID,- ALI_SMS_ACCESS_KEY_SECRET,- ALI_SMS_SIGN_NAME,- ALI_SMS_TEMPLATE_CODE,-} = process.env--module.exports = {- // 应用基础- appDomain: APP_DOMAIN,- port: 3002,- environment: NODE_ENV,- enableBadRequestDetails: true,-- // 认证- auth: {- secret: JWT_SECRET,- internalToken: INTERNAL_TOKEN,- },-- // 日志- logger: {- console: {- enable: true,- level: 'debug',- pretty: false,- },- },-- // 数据库- mongodb: {- uri: `mongodb://${MONGODB_USERNAME}:${encodeURIComponent(MONGODB_PASSWORD)}@${MONGODB_HOST}:${MONGODB_PORT}/?authSource=admin&directConnection=true`,- dbName: 'aitoearn',- },-- // 缓存/队列- redis: {- host: REDIS_HOST,- port: Number(REDIS_PORT),- username: 'default',- password: REDIS_PASSWORD,- },- redlock: {- redis: {- host: REDIS_HOST,- port: Number(REDIS_PORT),- username: 'default',- password: REDIS_PASSWORD,- },- },-- // Channel- channel: {- channelDb: {- uri: `mongodb://${MONGODB_USERNAME}:${encodeURIComponent(MONGODB_PASSWORD)}@${MONGODB_HOST}:${MONGODB_PORT}/?authSource=admin&directConnection=true`,- dbName: 'aitoearn_channel',- },- moreApi: {- platApiUri: 'https://platapi.yikart.cn',- xhsCreatorUri: 'http://39.106.41.190:7008',- },- shortLink: {- baseUrl: `https://${APP_DOMAIN}/api/shortLink/`,- },- bilibili: {- id: BILIBILI_CLIENT_ID,- secret: BILIBILI_CLIENT_SECRET,- authBackHost: `https://${APP_DOMAIN}/api/plat/bilibili/auth/back`,- },- google: {- id: GOOGLE_CLIENT_ID,- secret: GOOGLE_CLIENT_SECRET,- authBackHost: '',- },- googleBusiness: {- clientId: '',- clientSecret: '',- redirectUri: `https://${APP_DOMAIN}/api/plat/google-business/auth/callback`,- },- kwai: {- id: KWAI_CLIENT_ID,- secret: KWAI_CLIENT_SECRET,- authBackHost: `https://${APP_DOMAIN}/api/plat/kwai/auth/back`,- },- pinterest: {- id: PINTEREST_CLIENT_ID,- secret: PINTEREST_CLIENT_SECRET,- authBackHost: `https://${APP_DOMAIN}/api/plat/pinterest/authWebhook`,- baseUrl: 'https://api.pinterest.com',- test_authorization: PINTEREST_TEST_AUTHORIZATION,- },- tiktok: {- clientId: TIKTOK_CLIENT_ID,- clientSecret: TIKTOK_CLIENT_SECRET,- redirectUri: `https://${APP_DOMAIN}/api/plat/tiktok/auth/back`,- promotionRedirectUri: `https://${APP_DOMAIN}/api/plat/tiktok/auth/redirect`,- scopes: [- 'user.info.basic',- 'user.info.profile',- 'video.upload',- 'video.publish',- ],- promotionBaseUrl: `https://${APP_DOMAIN}/promo`,- },- twitter: {- clientId: TWITTER_CLIENT_ID,- clientSecret: TWITTER_CLIENT_SECRET,- redirectUri: `https://${APP_DOMAIN}/api/plat/twitter/auth/back`,- },- oauth: {- facebook: {- clientId: FACEBOOK_CLIENT_ID,- clientSecret: FACEBOOK_CLIENT_SECRET,- configId: FACEBOOK_CONFIG_ID,- redirectUri: `https://${APP_DOMAIN}/api/plat/meta/auth/back`,- scopes: [- 'public_profile',- 'pages_show_list',- 'pages_manage_posts',- 'pages_read_engagement',- 'pages_read_user_content',- 'pages_manage_engagement',- 'read_insights',- ],- },- threads: {- clientId: THREADS_CLIENT_ID,- clientSecret: THREADS_CLIENT_SECRET,- redirectUri: `https://${APP_DOMAIN}/api/plat/meta/auth/back`,- scopes: [- 'threads_basic',- 'threads_content_publish',- 'threads_read_replies',- 'threads_manage_replies',- 'threads_manage_insights',- 'threads_location_tagging',- ],- },- instagram: {- clientId: INSTAGRAM_CLIENT_ID,- clientSecret: INSTAGRAM_CLIENT_SECRET,- redirectUri: `https://${APP_DOMAIN}/api/plat/meta/auth/back`,- promotionRedirectUri: `https://${APP_DOMAIN}/api/plat/meta/auth/redirect`,- promotionBaseUrl: `https://${APP_DOMAIN}/promo`,- scopes: [- 'instagram_business_basic',- 'instagram_business_manage_comments',- 'instagram_business_content_publish',- ],- },- linkedin: {- clientId: LINKEDIN_CLIENT_ID,- clientSecret: LINKEDIN_CLIENT_SECRET,- redirectUri: `https://${APP_DOMAIN}/api/plat/meta/auth/back`,- scopes: ['openid', 'profile', 'email', 'w_member_social'],- },- },- wxPlat: {- id: WXPLAT_APP_ID,- secret: WXPLAT_APP_SECRET,- token: 'aitoearn',- encodingAESKey: WXPLAT_ENCODING_AES_KEY,- authBackHost: `https://${APP_DOMAIN}/platcallback`,- },- myWxPlat: {- id: 'dev',- secret: 'f1a36f23d027c969d6c6969423d72eda',- hostUrl: `https://wxplat.${APP_DOMAIN}`,- },- youtube: {- id: YOUTUBE_CLIENT_ID,- secret: YOUTUBE_CLIENT_SECRET,- authBackHost: `https://${APP_DOMAIN}/api/plat/youtube/auth/callback`,- },- douyin: {- id: DOYIN_CLIENT_ID,- secret: DOYIN_CLIENT_SECRET,- authBackHost: `https://${APP_DOMAIN}/api/plat/douyin/auth/back`,- },- },-- // 外部服务- assets: {- provider: 's3',- region: 'us-east-1',- bucketName: 'aitoearn',- endpoint: 'http://rustfs.local:9000',- signEndpoint: 'http://localhost:9000',- cdnEndpoint: 'http://localhost:8080/oss',- accessKeyId: 'rustfsadmin',- secretAccessKey: 'rustfsadmin',- },- mail: {- transport: {- host: 'email-smtp.ap-southeast-1.amazonaws.com',- port: 587,- secure: false,- auth: {- user: MAIL_USER,- pass: MAIL_PASS,- },- },- defaults: {- from: '[email protected]',- },- },- aliSms: {- accessKeyId: ALI_SMS_ACCESS_KEY_ID,- accessKeySecret: ALI_SMS_ACCESS_KEY_SECRET,- signName: ALI_SMS_SIGN_NAME,- templateCode: ALI_SMS_TEMPLATE_CODE,- },-- // 内部服务通信- aiClient: {- baseUrl: AI_URL,- token: INTERNAL_TOKEN,- },-- // 业务- credits: {- },- newApi: {- baseUrl: NEW_API_URL,- token: NEW_API_TOKEN,- },-}diff --git a/config/gcs-placeholder.json b/config/gcs-placeholder.jsondeleted file mode 100644index 33032e26..00000000--- a/config/gcs-placeholder.json+++ /dev/null@@ -1,10 +0,0 @@-{- "type": "service_account",- "project_id": "placeholder",- "private_key_id": "placeholder",- "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIBogIBAAJBALRiMLAHudeSA/x3hB2f+2NRkJLA4WviRkCnoQF2Rq6OBdwegyXH\nd6CMonUBFZ7CqXMIjVMFKUWIFMLLfwY2RusCAwEAAQJAE3vSMiWRbqxuPnXJaFI5\nfxMGGCjYJKUBqPiQHfa5bvF2qHCzmJQl6k6RI/VBIajXFDCOhBJZJnO6s3WMHQIQ\naQIhAOOjrp4hhWCufRhBFbX/4ZGHfoKxBFJsJFR7oi8OyDNnAiEA0MjU1GFE1Xyj\ncdJHB98FKKE0V3MuZbGCydDqS6C0h68CIGlFzBHLfO79E0r+8cGEzdL6tHFJymyK\nS+h8GVFled1vAiEAoS5FbN2vaFIBIAnJxb7VoGjE6mXYDiGbkmPzXMVLZskCIBBl\nF4BuL0bwjJsk/HN0tgZaLBRubMIy/VyBqOXnBbCJ\n-----END RSA PRIVATE KEY-----\n",- "client_email": "[email protected]",- "client_id": "000000000000000000000",- "auth_uri": "https://accounts.google.com/o/oauth2/auth",- "token_uri": "https://oauth2.googleapis.com/token"-}diff --git a/docker-compose.yml b/docker-compose.ymlindex 44249fde..18c95cc8 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -3,6 +3,7 @@ services:image: mongo:latestcontainer_name: aitoearn-mongodbrestart: unless-stopped+ entrypoint: ["bash", "-c", "openssl rand -base64 756 > /data/mongodb-keyfile && chmod 400 /data/mongodb-keyfile && chown mongodb:mongodb /data/mongodb-keyfile && exec docker-entrypoint.sh mongod --replSet rs0 --keyFile /data/mongodb-keyfile"]environment:MONGO_INITDB_ROOT_USERNAME: adminMONGO_INITDB_ROOT_PASSWORD: password@@ -14,12 +15,23 @@ services:networks:- aitoearn-networkhealthcheck:- test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/test --quiet+ test: mongosh --quiet --eval "try { rs.status().ok } catch(e) { 0 }"interval: 10stimeout: 5s- retries: 5+ retries: 10start_period: 40s+ mongodb-rs-init:+ image: mongo:latest+ container_name: aitoearn-mongodb-rs-init+ depends_on:+ mongodb:+ condition: service_started+ entrypoint: ["/bin/sh", "-c", "sleep 5 && mongosh mongodb://admin:password@mongodb:27017/?authSource=admin --eval \"try { rs.initiate({_id:'rs0', members:[{_id:0, host:'mongodb:27017'}]}) } catch(e) { if (e.codeName!=='AlreadyInitialized') throw e }\""]+ restart: "no"+ networks:+ - aitoearn-network+redis:image: redis:latestcontainer_name: aitoearn-redis@@ -99,6 +111,7 @@ services:aitoearn-ai:image: aitoearn/aitoearn-ai:latest+ pull_policy: alwayscontainer_name: aitoearn-airestart: unless-stoppeddepends_on:@@ -107,8 +120,7 @@ services:redis:condition: service_healthyvolumes:- - ./config/aitoearn-ai.config.js:/app/config.js:ro- - ./config/gcs-placeholder.json:/app/config/gcs-placeholder.json:ro+ - ./project/aitoearn-backend/apps/aitoearn-ai/config/config.js:/app/config.js:ronetworks:- aitoearn-networkenvironment:@@ -130,6 +142,8 @@ services:SERVER_URL: http://aitoearn-server:3002+ ASSETS_CONFIG: '{"provider":"s3","region":"us-east-1","bucketName":"aitoearn","endpoint":"http://rustfs.local:9000","publicEndpoint":"http://127.0.0.1:9000","cdnEndpoint":"http://127.0.0.1:8080/oss","accessKeyId":"rustfsadmin","secretAccessKey":"rustfsadmin","forcePathStyle":true}'+# AI ServicesOPENAI_API_KEY: sk-placeholderOPENAI_BASE_URL: https://api.openai.com/v1@@ -142,7 +156,7 @@ services:GROK_API_KEY: ""AICSO_API_KEY: ""AICSO_BASE_URL: ""- GEMINI_KEY_PAIRS: '[{"projectId":"placeholder","apiKey":"placeholder","keyFile":"/app/config/gcs-placeholder.json","bucket":"placeholder"}]'+ GEMINI_KEY_PAIRS: '[]'GEMINI_LOCATION: us-central1AI_PROXY_URL: ""healthcheck:@@ -154,6 +168,7 @@ services:aitoearn-server:image: aitoearn/aitoearn-server:latest+ pull_policy: alwayscontainer_name: aitoearn-serverrestart: unless-stoppeddepends_on:@@ -164,7 +179,7 @@ services:aitoearn-ai:condition: service_healthyvolumes:- - ./config/aitoearn-server.config.js:/app/config.js:ro+ - ./project/aitoearn-backend/apps/aitoearn-server/config/config.js:/app/config.js:ronetworks:- aitoearn-networkenvironment:@@ -178,11 +193,6 @@ services:MONGODB_USERNAME: adminMONGODB_PASSWORD: password- STATISTICS_DB_HOST: mongodb- STATISTICS_DB_PORT: 27017- STATISTICS_DB_USERNAME: admin- STATISTICS_DB_PASSWORD: password-REDIS_HOST: redisREDIS_PORT: 6379REDIS_PASSWORD: password@@ -192,13 +202,11 @@ services:JWT_SECRET: change-this-jwt-secretINTERNAL_TOKEN: change-this-secret-token+ ASSETS_CONFIG: '{"provider":"s3","region":"us-east-1","bucketName":"aitoearn","endpoint":"http://rustfs.local:9000","publicEndpoint":"http://127.0.0.1:9000","cdnEndpoint":"http://127.0.0.1:8080/oss","accessKeyId":"rustfsadmin","secretAccessKey":"rustfsadmin","forcePathStyle":true}'+MAIL_USER: ""MAIL_PASS: ""- # AI Services- OPENAI_API_KEY: sk-placeholder- OPENAI_BASE_URL: https://api.openai.com/v1-# Third-party OAuthBILIBILI_CLIENT_ID: ""BILIBILI_CLIENT_SECRET: ""@@ -208,7 +216,6 @@ services:KWAI_CLIENT_SECRET: ""PINTEREST_CLIENT_ID: ""PINTEREST_CLIENT_SECRET: ""- PINTEREST_TEST_AUTHORIZATION: ""TIKTOK_CLIENT_ID: ""TIKTOK_CLIENT_SECRET: ""TWITTER_CLIENT_ID: ""@@ -236,13 +243,10 @@ services:ALI_SMS_SIGN_NAME: ""ALI_SMS_TEMPLATE_CODE: ""- # Aliyun Content Safety- ALI_GREEN_ACCESS_KEY_ID: ""- ALI_GREEN_ACCESS_KEY_SECRET: ""-- # New API- NEW_API_URL: ""- NEW_API_TOKEN: ""+ # Relay (optional)+ RELAY_SERVER_URL: https://aitoearn.ai/api+ RELAY_API_KEY: ""+ RELAY_CALLBACK_URL: http://127.0.0.1:8080/api/plat/relay-callbackhealthcheck:test: ["CMD", "node", "-e", "require('http').get('http://localhost:3002/health', (r) => { process.exit(r.statusCode === 200 ? 0 : 1) })"]interval: 30s@@ -252,6 +256,7 @@ services:aitoearn-web:image: aitoearn/aitoearn-web:latest+ pull_policy: alwayscontainer_name: aitoearn-webrestart: unless-stoppeddepends_on:@@ -261,10 +266,10 @@ services:- init-data:/data/init:ronetworks:- aitoearn-network+ command: ["/bin/sh", "-c", "AUTO_LOGIN_TOKEN=$$(cat /data/init/token.txt 2>/dev/null || echo '') exec node server.js"]environment:NODE_ENV: productionNEXT_TELEMETRY_DISABLED: 1- AUTO_LOGIN_TOKEN_PATH: /data/init/token.txtnginx:image: nginx:alpine@@ -285,7 +290,7 @@ services:networks:- aitoearn-networkhealthcheck:- test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/_nhealth"]+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1/_nhealth"]interval: 10stimeout: 5sretries: 3diff --git a/project/aitoearn-backend/.claude/rules/performance.md b/project/aitoearn-backend/.claude/rules/ai-workflow.mdsimilarity index 97%rename from project/aitoearn-backend/.claude/rules/performance.mdrename to project/aitoearn-backend/.claude/rules/ai-workflow.mdindex f7ef93bb..48e101e0 100644--- a/project/aitoearn-backend/.claude/rules/performance.md+++ b/project/aitoearn-backend/.claude/rules/ai-workflow.md@@ -1,4 +1,4 @@-# Performance Optimization+# AI Workflow and Model Selection## Model Selection Strategydiff --git a/project/aitoearn-backend/.claude/rules/coding-style.md b/project/aitoearn-backend/.claude/rules/coding-style.mdindex 2399d164..831c2e36 100644--- a/project/aitoearn-backend/.claude/rules/coding-style.md+++ b/project/aitoearn-backend/.claude/rules/coding-style.md@@ -30,18 +30,26 @@ MANY SMALL FILES > FEW LARGE FILES:## Error Handling-ALWAYS handle errors comprehensively:+Business errors use `AppException + ResponseCode`, handled by the global exception filter. Do NOT wrap business logic with try-catch.```typescript+// WRONG: try-catch + console + throw new Errortry {- const result = await riskyOperation()- return result+ const order = await this.orderService.getById(id)} catch (error) {- console.error('Operation failed:', error)- throw new Error('Detailed user-friendly message')+ console.error('Failed:', error) // ❌ console prohibited+ throw new Error('Order not found') // ❌ use AppException+}++// CORRECT: Let the framework handle exceptions+const order = await this.orderRepository.getById(id)+if (!order) {+ throw new AppException(ResponseCode.OrderNotFound)}```+Only use try-catch for infrastructure-level operations (external API calls, file I/O), and log with `this.logger.error()` instead of `console`.+## Input ValidationALWAYS validate user input:@@ -65,6 +73,6 @@ Before marking work complete:- [ ] Files are focused (<800 lines)- [ ] No deep nesting (>4 levels)- [ ] Proper error handling-- [ ] No console.log statements+- [ ] No console usage (use Logger instance)- [ ] No hardcoded values- [ ] No mutation (immutable patterns used)diff --git a/project/aitoearn-backend/.claude/rules/git-workflow.md b/project/aitoearn-backend/.claude/rules/git-workflow.mdindex a32d0bc3..2817b53f 100644--- a/project/aitoearn-backend/.claude/rules/git-workflow.md+++ b/project/aitoearn-backend/.claude/rules/git-workflow.md@@ -1,5 +1,11 @@# Git Workflow+## Branch Naming++Format: `<type>/<description>`, e.g., `feat/user-auth`, `fix/login-bug`, `refactor/rename-files`++Types: feat, fix, refactor, docs, test, chore, perf, ci+## Commit Message Format```@@ -12,14 +18,22 @@ Types: feat, fix, refactor, docs, test, chore, perf, ciNote: Attribution disabled globally via ~/.claude/settings.json.+## Merge Strategy++- Feature branches must be rebased onto target branch before merging: `git rebase <target-branch>`+- Use squash merge to combine all commits into one: `git merge --squash <feature-branch>` (then `git commit`)+- Merge commits are prohibited; keep commit history linear and clean+## Pull Request WorkflowWhen creating PRs:1. Analyze full commit history (not just latest commit)2. Use `git diff [base-branch]...HEAD` to see all changes-3. Draft comprehensive PR summary+3. Draft comprehensive PR summary following the PR template (`.github/pull_request_template.md`)4. Include test plan with TODOs5. Push with `-u` flag if new branch+6. Wait for Gemini code review, read review comments and fix any issues raised+7. After fixing review comments, resolve the review threads via GitHub GraphQL API (`resolveReviewThread` mutation)## Feature Implementation Workflowdiff --git a/project/aitoearn-backend/.claude/rules/hooks.md b/project/aitoearn-backend/.claude/rules/hooks.mdindex d1b891cc..93ed8c46 100644--- a/project/aitoearn-backend/.claude/rules/hooks.md+++ b/project/aitoearn-backend/.claude/rules/hooks.md@@ -1,5 +1,7 @@# Hooks System+> **Note:** This documents the local Claude Code hooks configuration (`~/.claude/settings.json`), not project coding standards. These hooks are configured per-developer.+## Hook Types- **PreToolUse**: Before tool execution (validation, parameter modification)diff --git a/project/aitoearn-backend/.claude/rules/patterns.md b/project/aitoearn-backend/.claude/rules/patterns.mdindex c6970b55..dc03cde8 100644--- a/project/aitoearn-backend/.claude/rules/patterns.md+++ b/project/aitoearn-backend/.claude/rules/patterns.md@@ -1,47 +1,43 @@# Common Patterns-## API Response Format+## Unified Response Format-```typescript-interface ApiResponse<T> {- success: boolean- data?: T- error?: string- meta?: {- total: number- page: number- limit: number- }-}-```--## Custom Hooks Pattern+All API responses are wrapped by `ResponseInterceptor` into:```typescript-export function useDebounce<T>(value: T, delay: number): T {- const [debouncedValue, setDebouncedValue] = useState<T>(value)-- useEffect(() => {- const handler = setTimeout(() => setDebouncedValue(value), delay)- return () => clearTimeout(handler)- }, [value, delay])-- return debouncedValue+{+ data: T // Business data+ code: number // 0 = success, 10000+ = business error+ message: string}```+Do not define custom response wrappers. Use `AppException + ResponseCode` to trigger error responses.+## Repository Pattern+Based on `BaseRepository` (`libs/mongodb/src/repositories/base.repository.ts`):+```typescript-interface Repository<T> {- findAll(filters?: Filters): Promise<T[]>- findById(id: string): Promise<T | null>- create(data: CreateDto): Promise<T>- update(id: string, data: UpdateDto): Promise<T>- delete(id: string): Promise<void>-}+// Public methods (exposed to Service)+getById(id: string): Promise<LeanDoc<T> | null>+create(data: Partial<T>): Promise<LeanDoc<T>>+createMany(data: Partial<T>[]): Promise<LeanDoc<T>[]>+updateById(id: string, update: UpdateQuery<T>): Promise<LeanDoc<T> | null>+deleteById(id: string): Promise<LeanDoc<T> | null>++// Protected methods (used within Repository subclasses)+findOne(filter: FilterQuery<T>): Promise<LeanDoc<T> | null>+find(filter: FilterQuery<T>): Promise<LeanDoc<T>[]>+findWithPagination(params: PaginationParams<T>): Promise<[LeanDoc<T>[], number]>+count(filter: FilterQuery<T>): Promise<number>+exists(filter: FilterQuery<T>): Promise<boolean>```+Subclass repositories expose domain-specific public methods following naming conventions:+- `getByXxx` / `listByXxx` / `countByXxx` / `listWithPagination`+- See `project-standards.md` for full naming rules.+## Skeleton ProjectsWhen implementing new functionality:diff --git a/project/aitoearn-backend/.claude/rules/project-standards.md b/project/aitoearn-backend/.claude/rules/project-standards.mdindex b28f2690..8d0282b1 100644--- a/project/aitoearn-backend/.claude/rules/project-standards.md+++ b/project/aitoearn-backend/.claude/rules/project-standards.md@@ -192,12 +192,4 @@ throw new AppException(ResponseCode.PaymentPriceNotFound, { priceId: 'price_xxx'- Must use `pnpm nx build <project>` to verify builds- Using `tsc` directly for compilation is prohibited- After renaming methods, must run `pnpm nx build` to ensure all references are updated--## Git Workflow--- Feature branches must be rebased onto target branch before merging: `git rebase <target-branch>`-- Use squash merge to combine all commits into one: `git merge --squash <feature-branch>`-- Merge commits are prohibited; keep commit history linear and clean-- Branch naming convention: `<type>/<description>`, e.g., `feat/user-auth`, `fix/login-bug`, `refactor/rename-files`-- Commit message format: `<type>: <description>`, types include: `feat`, `fix`, `refactor`, `chore`, `docs`, `test`, `perf`- Before merging, ensure all builds pass: `pnpm nx run-many --target=build --all`diff --git a/project/aitoearn-backend/.claude/rules/security.md b/project/aitoearn-backend/.claude/rules/security.mdindex a56a4b78..4e8d3bad 100644--- a/project/aitoearn-backend/.claude/rules/security.md+++ b/project/aitoearn-backend/.claude/rules/security.md@@ -4,28 +4,38 @@Before ANY commit:- [ ] No hardcoded secrets (API keys, passwords, tokens)-- [ ] All user inputs validated-- [ ] SQL injection prevention (parameterized queries)+- [ ] All user inputs validated (Zod DTOs at controller boundary)+- [ ] MongoDB injection prevention (validate query parameters, avoid `$where`, sanitize `$regex` inputs)- [ ] XSS prevention (sanitized HTML)-- [ ] CSRF protection enabled- [ ] Authentication/authorization verified-- [ ] Rate limiting on all endpoints+- [ ] Rate limiting on public endpoints- [ ] Error messages don't leak sensitive data## Secret Management```typescript-// NEVER: Hardcoded secrets-const apiKey = "sk-proj-xxxxx"+// NEVER: Hardcoded secrets or direct process.env+const apiKey = "sk-proj-xxxxx" // ❌+const apiKey = process.env.OPENAI_API_KEY // ❌ must go through config module-// ALWAYS: Environment variables-const apiKey = process.env.OPENAI_API_KEY--if (!apiKey) {- throw new Error('OPENAI_API_KEY not configured')-}+// ALWAYS: Use zod config schema + selectConfig+// Define in config.ts with zod schema, access via injected config object+const apiKey = this.config.openai.apiKey```+## MongoDB-Specific Security++- Validate ObjectId format on all ID parameters before querying+- Use `lean()` queries to avoid returning Mongoose document methods+- Never expose raw `_id` in API responses — transform via VO+- Sanitize string inputs used in `$regex` queries++## NestJS Security++- Use Guards for authentication, not middleware+- Use `@GetToken()` decorator from `@yikart/aitoearn-auth` for extracting auth info+- Filter permissions via query conditions in Service layer (not Controller)+## Security Response ProtocolIf security issue found:diff --git a/project/aitoearn-backend/.claude/rules/testing.md b/project/aitoearn-backend/.claude/rules/testing.mdindex 22440496..f26e4d73 100644--- a/project/aitoearn-backend/.claude/rules/testing.md+++ b/project/aitoearn-backend/.claude/rules/testing.md@@ -3,9 +3,44 @@## Minimum Test Coverage: 80%Test Types (ALL required):-1. **Unit Tests** - Individual functions, utilities, components+1. **Unit Tests** - Individual functions, utilities, services2. **Integration Tests** - API endpoints, database operations-3. **E2E Tests** - Critical user flows (Playwright)+3. **E2E Tests** - Critical user flows++## Running Tests++```bash+# Run tests for a specific project+pnpm nx run <project>:test++# Run E2E tests+pnpm nx run e2e:e2e++# Run affected tests+pnpm nx affected -t test+```++## Test File Conventions++- Test files: `*.spec.ts`, colocated with source files+- Test runner: Vitest (via `@nx/vite:test`)+- E2E infrastructure: Docker Compose (`e2e/docker-compose.e2e.yml`)++## NestJS Testing Patterns++**Unit testing services:**+```typescript+const module = await Test.createTestingModule({+ providers: [+ OrderService,+ { provide: OrderRepository, useValue: mockOrderRepository },+ ],+}).compile()+```++**Unit testing controllers:** Mock services, verify routing and VO transformation.++**Repository tests:** Test in integration/E2E only (repositories are thin wrappers over Mongoose).## Test-Driven Development@@ -23,8 +58,3 @@ MANDATORY workflow:2. Check test isolation3. Verify mocks are correct4. Fix implementation, not tests (unless tests are wrong)--## Agent Support--- **tdd-guide** - Use PROACTIVELY for new features, enforces write-tests-first-- **e2e-runner** - Playwright E2E testing specialistdiff --git a/project/aitoearn-backend/.github/pull_request_template.md b/project/aitoearn-backend/.github/pull_request_template.mdindex 233d1c6f..e99e8d97 100644--- a/project/aitoearn-backend/.github/pull_request_template.md+++ b/project/aitoearn-backend/.github/pull_request_template.md@@ -1,30 +1,39 @@# Pull Request-## 🧩 Issue Link+## Issue Link<!---必填:请至少关联一个 Issue。关闭型:Closes #123 / Fixes #123 / Resolves #123关联型:Related to #123 / Refs #123支持多条:Closes #12, Related to #34跨仓库:Closes owner/repo#123-->-Closes #-## 📝 描述-<!-- 请简要描述此 PR 的目的和主要更改内容 -->-## 📋 变更清单+## 描述+<!-- 简要描述此 PR 的目的和主要更改内容 -->++## 变更清单<!-- 列出此 PR 中的主要变更点 -->--+----## 🧪 测试-<!-- 描述已执行的测试 -->-- [ ] 本地通过 ESLint 检查-- [ ] 本地构建成功+## 检查清单+- [ ] 本地 lint 通过:`pnpm nx lint <affected-projects>`+- [ ] 本地构建通过:`pnpm nx build <affected-projects>`- [ ] 已添加/更新相关测试-- [ ] 所有测试通过+- [ ] 新接口已添加 `@ApiDoc` 装饰器,DTO/VO 字段已添加 `.describe()`+- [ ] 无破坏性 API 变更(或已在描述中说明)+- [ ] 已等待 Gemini code review 并修复其提出的问题++## 测试计划+<!-- 描述测试策略和覆盖范围 -->+- 测试类型:<!-- unit / integration / e2e -->+- 运行命令:<!-- pnpm nx run <project>:test -->++## 数据库迁移+<!-- 如无迁移请删除此部分 -->+- [ ] 迁移脚本已放置在 `migrations/` 目录+- [ ] 迁移脚本为纯 MongoDB shell 脚本-## 📝 备注+## 备注<!-- 其他需要说明的信息 -->diff --git a/project/aitoearn-backend/.github/workflows/build-and-deploy.yml b/project/aitoearn-backend/.github/workflows/build-and-deploy.ymlindex b419ceba..b6f16fea 100644--- a/project/aitoearn-backend/.github/workflows/build-and-deploy.yml+++ b/project/aitoearn-backend/.github/workflows/build-and-deploy.yml@@ -37,7 +37,6 @@ on:required: falsetype: booleandefault: false-permissions:id-token: writecontents: readdiff --git a/project/aitoearn-backend/.github/workflows/build.yml b/project/aitoearn-backend/.github/workflows/build.ymlindex d4309e98..dc37faaa 100644--- a/project/aitoearn-backend/.github/workflows/build.yml+++ b/project/aitoearn-backend/.github/workflows/build.yml@@ -42,7 +42,6 @@ on:required: falsetype: booleandefault: false-permissions:id-token: writecontents: read@@ -358,7 +357,7 @@ jobs:- name: Set up Docker Buildxuses: docker/setup-buildx-action@v3- - name: Build and push Docker image+ - name: Build Docker imageuses: docker/build-push-action@v6with:context: ./tmp/docker-context@@ -374,7 +373,6 @@ jobs:type=gha,scope=${{ matrix.app }}cache-to: |type=gha,mode=max,scope=${{ matrix.app }}- type=inline- name: Build summaryrun: |diff --git a/project/aitoearn-backend/.github/workflows/pr-check.yml b/project/aitoearn-backend/.github/workflows/pr-check.ymlindex c2ae9871..69300844 100644--- a/project/aitoearn-backend/.github/workflows/pr-check.yml+++ b/project/aitoearn-backend/.github/workflows/pr-check.yml@@ -67,13 +67,26 @@ jobs:node-version: 24cache: pnpm+ - name: Cache node_modules+ id: cache-node-modules+ uses: actions/cache@v4+ with:+ path: |+ node_modules+ apps/*/node_modules+ libs/*/node_modules+ key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}+- name: 安装依赖+ if: steps.cache-node-modules.outputs.cache-hit != 'true'run: pnpm install --frozen-lockfile- name: Cache Nx build outputsuses: actions/cache@v4with:- path: .nx/cache+ path: |+ .nx/cache+ .nx/workspace-datakey: nx-cache-pr-${{ github.event.pull_request.number }}-${{ github.sha }}restore-keys: |nx-cache-pr-${{ github.event.pull_request.number }}-diff --git a/project/aitoearn-backend/apps/aitoearn-ai/config/config.js b/project/aitoearn-backend/apps/aitoearn-ai/config/config.jsindex 97d2f633..26bf5850 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/config/config.js+++ b/project/aitoearn-backend/apps/aitoearn-ai/config/config.js@@ -16,11 +16,6 @@ const {INTERNAL_TOKEN,} = process.env-const {- FEISHU_WEBHOOK_URL,- FEISHU_WEBHOOK_SECRET,-} = process.env-const {VOLCENGINE_API_KEY,VOLCENGINE_ACCESS_KEY_ID,@@ -71,11 +66,6 @@ module.exports = {level: 'debug',pretty: false,},- feishu: {- enable: true,- url: FEISHU_WEBHOOK_URL,- secret: FEISHU_WEBHOOK_SECRET,- },},redis: {host: REDIS_HOST,@@ -131,8 +121,8 @@ module.exports = {gemini: {keyPairs: parseGeminiKeyPairs(),location: GEMINI_LOCATION || 'us-central1',- apiKey: OPENAI_API_KEY,- baseUrl: OPENAI_BASE_URL.replace(/\/v1$/, ''),+ apiKey: AICSO_API_KEY,+ baseUrl: AICSO_BASE_URL,...(AI_PROXY_URL && { proxyUrl: AI_PROXY_URL }),},aicso: {@@ -141,28 +131,28 @@ module.exports = {},aideo: {vCreative: {- basePrice: 0, // AI editing base price (cents/minute, 720P)+ basePrice: 0,},vision: {- basePrice: 0, // Video understanding base price (cents/minute)+ basePrice: 0,},highlight: {- basePrice: 0, // Highlight smart editing base price (cents/minute)+ basePrice: 0,},aiTranslation: {- facialTranslation: 0, // Facial translation price (cents/minute) - the only supported translation type+ facialTranslation: 0,},erase: {- basePrice: 0, // AI subtitle removal base price (cents/minute)+ basePrice: 0,},videoEdit: {- basePrice: 0, // Video editing base price (cents/minute, 720P)+ basePrice: 0,},dramaRecap: {- basePrice: 0, // Drama recap base price (cents/minute)+ basePrice: 0,},styleTransfer: {- basePrice: 0, // Video style transfer base price (cents/minute)+ basePrice: 0,},},models: {@@ -338,45 +328,6 @@ module.exports = {},video: {generation: [- {- name: 'grok-imagine-video',- description: 'Grok Video',- channel: 'grok',- modes: ['text2video', 'image2video', 'video2video'],- resolutions: ['720p'],- durations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],- maxInputImages: 1,- aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'],- defaults: {- duration: 8,- aspectRatio: '9:16',- },- pricing: [- { duration: 1, price: 0 },- { duration: 2, price: 0 },- { duration: 3, price: 0 },- { duration: 4, price: 0 },- { duration: 5, price: 0 },- { duration: 6, price: 0 },- { duration: 7, price: 0 },- { duration: 8, price: 0 },- { duration: 9, price: 0 },- { duration: 10, price: 0 },- { duration: 11, price: 0 },- { duration: 12, price: 0 },- { duration: 13, price: 0 },- { duration: 14, price: 0 },- { duration: 15, price: 0 },- { mode: 'video2video', duration: 1, price: 0 },- { mode: 'video2video', duration: 2, price: 0 },- { mode: 'video2video', duration: 3, price: 0 },- { mode: 'video2video', duration: 4, price: 0 },- { mode: 'video2video', duration: 5, price: 0 },- { mode: 'video2video', duration: 6, price: 0 },- { mode: 'video2video', duration: 7, price: 0 },- { mode: 'video2video', duration: 8, price: 0 },- ],- },{name: 'grok-video-3-15s',description: 'Grok Video 15s',@@ -386,7 +337,7 @@ module.exports = {durations: [15],maxInputImages: 1,aspectRatios: ['2:3', '3:2', '1:1'],- tags: ['限时'],+ tags: [{ 'en-US': 'Sale', 'zh-CN': '限时' }],defaults: {duration: 15,aspectRatio: '9:16',@@ -404,7 +355,7 @@ module.exports = {durations: [8],maxInputImages: 3,aspectRatios: ['9:16', '16:9', '1:1'],- tags: ['限时'],+ tags: [{ 'en-US': 'Sale', 'zh-CN': '限时' }],defaults: {duration: 8,aspectRatio: '9:16',@@ -422,7 +373,7 @@ module.exports = {durations: [8],maxInputImages: 3,aspectRatios: ['9:16', '16:9', '1:1'],- tags: ['限时'],+ tags: [{ 'en-US': 'Sale', 'zh-CN': '限时' }],defaults: {duration: 8,aspectRatio: '9:16',@@ -431,6 +382,45 @@ module.exports = {{ duration: 8, price: 0 },],},+ {+ name: 'grok-imagine-video',+ description: 'Grok Video',+ channel: 'grok',+ modes: ['text2video', 'image2video', 'video2video'],+ resolutions: ['720p'],+ durations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],+ maxInputImages: 1,+ aspectRatios: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'],+ defaults: {+ duration: 8,+ aspectRatio: '9:16',+ },+ pricing: [+ { duration: 1, price: 0 },+ { duration: 2, price: 0 },+ { duration: 3, price: 0 },+ { duration: 4, price: 0 },+ { duration: 5, price: 0 },+ { duration: 6, price: 0 },+ { duration: 7, price: 0 },+ { duration: 8, price: 0 },+ { duration: 9, price: 0 },+ { duration: 10, price: 0 },+ { duration: 11, price: 0 },+ { duration: 12, price: 0 },+ { duration: 13, price: 0 },+ { duration: 14, price: 0 },+ { duration: 15, price: 0 },+ { mode: 'video2video', duration: 1, price: 0 },+ { mode: 'video2video', duration: 2, price: 0 },+ { mode: 'video2video', duration: 3, price: 0 },+ { mode: 'video2video', duration: 4, price: 0 },+ { mode: 'video2video', duration: 5, price: 0 },+ { mode: 'video2video', duration: 6, price: 0 },+ { mode: 'video2video', duration: 7, price: 0 },+ { mode: 'video2video', duration: 8, price: 0 },+ ],+ },],},},diff --git a/project/aitoearn-backend/apps/aitoearn-ai/package.json b/project/aitoearn-backend/apps/aitoearn-ai/package.jsonindex d3684665..4574c3b9 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/package.json+++ b/project/aitoearn-backend/apps/aitoearn-ai/package.json@@ -35,12 +35,12 @@"@yikart/redlock": "workspace:*","axios": "^1.12.2","bignumber.js": "^9.3.1",- "bullmq": "^5.58.2",+ "bullmq": "^5.71.0","data-urls": "^5.0.0","dayjs": "^1.11.14","express": "5.1.0","image-size": "^1.1.1",- "ioredis": "^5.7.0",+ "ioredis": "5.9.3","js-yaml": "^4.1.0","jsonwebtoken": "^9.0.3","langchain": "^1.2.17",diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/config.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/config.tsindex 715a6c72..65067012 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/config.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/config.ts@@ -115,7 +115,7 @@ export const aiModelsConfigSchema = z.object({description: z.string(),summary: z.string().optional(),logo: z.string().optional(),- tags: z.string().array().default([]),+ tags: z.array(z.object({ 'en-US': z.string(), 'zh-CN': z.string() })).default([]),mainTag: z.string().optional(),channel: z.enum(AiLogChannel),modes: z.array(z.enum(['text2video', 'image2video', 'flf2video', 'lf2video', 'multi-image2video', 'video2video'])),diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/media.mcp.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/media.mcp.tsindex a1782250..146577e2 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/media.mcp.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/media.mcp.ts@@ -429,7 +429,7 @@ Returns task ID for status tracking.`,const result = await this.grokVideoService.getTask(userId, userType, taskId)if (result.videoUrl) {- return successResult(`Video is completed, task id: ${taskId} and video url is ${result.videoUrl}`)+ return successResult(`Video is completed, task id: ${taskId} and video url is ${FileUtil.buildUrl(result.videoUrl)}`)}if (result.error) {return errorResult(`Video failed, task id: ${taskId} and error message is ${result.error}`)diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/video-utils.mcp.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/video-utils.mcp.tsindex 2ce79b32..b12b611b 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/video-utils.mcp.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/agent/mcp/video-utils.mcp.ts@@ -4,7 +4,7 @@ import * as path from 'node:path'import { createSdkMcpServer, McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk'import { Injectable, Logger } from '@nestjs/common'import { AssetsService, VideoMetadataService } from '@yikart/assets'-import { UserType } from '@yikart/common'+import { FileUtil, UserType } from '@yikart/common'import { AssetType } from '@yikart/mongodb'import { execa } from 'execa'import * as subtitle from 'subtitle'@@ -20,20 +20,20 @@ const getVolcVideoInfoSchema = z.object({})const uploadAndGetVidSchema = z.object({- videoUrl: z.string().describe('Video URL'),+ videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),})const probeVideoMetadataSchema = z.object({- videoUrl: z.string().describe('Video URL'),+ videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),})const extractThumbnailSchema = z.object({- videoUrl: z.string().describe('Video URL'),+ videoUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video URL'),timeInSeconds: z.number().min(0).default(1).describe('Time point in seconds to extract frame, default 1 second'),})const generateSubtitleSchema = z.object({- mediaUrl: z.string().describe('Video or audio URL to transcribe'),+ mediaUrl: FileUtil.zodBuildUrl().nonoptional().describe('Video or audio URL to transcribe'),language: z.string().optional().describe('Target language code, e.g., "zh-CN", "en-US"'),})diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.consumer.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.consumer.tsindex 9e36207d..926047c1 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.consumer.ts@@ -71,7 +71,7 @@ export class ImageConsumer extends WorkerHost {if (errorMessage.includes('429') || errorMessage.includes('rate limit')) {return true // 429 Too Many Requests}- if (errorMessage.match(/5\d{2}/)) {+ if (/5\d{2}/.test(errorMessage)) {return true // 5xx 服务器错误}diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.dto.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.dto.tsindex 6e7220de..72f099b6 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.dto.ts@@ -86,7 +86,7 @@ export class UserGeminiImageGenerationDto extends createZodDto(userGeminiImageGe// 二维码艺术图生成请求const qrCodeArtSchema = z.object({content: z.string().min(1).max(2000).describe('二维码扫码后的内容'),- referenceImageUrl: z.string().url().optional().describe('参考样式图 URL'),+ referenceImageUrl: z.url().optional().describe('参考样式图 URL'),prompt: z.string().min(1).max(4000).describe('文字描述(提示词)'),model: z.string().default('gpt-image-1').describe('图片生成模型'),size: z.string().optional().describe('图片尺寸'),diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.service.tsindex 20256bfc..c42ffe4d 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/image/image.service.ts@@ -263,7 +263,7 @@ export class ImageService {type: AiLogType.Image,points,request: params,- response: result,+ response: { ...result, data: void 0 },status: AiLogStatus.Success,startedAt,duration,diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.config.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.config.tsindex b98d070a..b28af3de 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.config.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.config.ts@@ -18,7 +18,7 @@ export type GeminiKeyPair = z.infer<typeof geminiKeyPairSchema>export const geminiConfigSchema = z.object({// Key Pairs 配置(必填)- keyPairs: z.array(geminiKeyPairSchema).min(1).describe('Gemini Key Pairs'),+ keyPairs: z.array(geminiKeyPairSchema).describe('Gemini Key Pairs'),location: z.string().default('us-central1'),// 图片生成 API 配置(单 Key)diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.interface.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.interface.tsindex 8b5a076f..57b5bdbe 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.interface.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.interface.ts@@ -8,7 +8,7 @@ export enum VeoModel {/*** 图片生成尺寸选项*/-export type GeminiImageSize = '1K' | '2K' | '4K'+export type GeminiImageSize = '0.5K' | '1K' | '2K' | '4K'/*** 图片生成宽高比选项diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.service.tsindex 855f63de..efc6969d 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/gemini/gemini.service.ts@@ -5,7 +5,9 @@ import {GenerateVideosOperation,GenerateVideosParameters,GoogleGenAI,+ MediaModality,Modality,+ ModalityTokenCount,} from '@google/genai'import { Injectable, Logger } from '@nestjs/common'import { GeminiKeyPairSelection } from './gemini-key-manager.interface'@@ -15,6 +17,7 @@ import {GeminiGeneratedImage,GeminiImageGenerateRequest,GeminiImageGenerateResponse,+ GeminiImageSize,GeminiImageUsage,GeminiModalityTokenDetails,} from './gemini.interface'@@ -45,8 +48,8 @@ export class GeminiService {}async generateImage(request: GeminiImageGenerateRequest): Promise<GeminiImageGenerateResponse> {- const { prompt, imageUrls = [], imageSize, aspectRatio } = requestconst model = request.model || 'gemini-3.1-flash-image-preview'+ const { prompt, imageUrls = [], imageSize, aspectRatio } = requestthis.logger.debug({ prompt, imageUrlsCount: imageUrls.length, imageSize, aspectRatio }, 'Starting image generation')@@ -99,8 +102,8 @@ export class GeminiService {promptTokenCount: response.usageMetadata.promptTokenCount || 0,candidatesTokenCount: response.usageMetadata.candidatesTokenCount || 0,totalTokenCount: response.usageMetadata.totalTokenCount || 0,- inputTokenDetails: this.extractGeminiModalityTokenDetails((response.usageMetadata as unknown as Record<string, unknown>)['promptTokensDetails']),- outputTokenDetails: this.extractGeminiModalityTokenDetails((response.usageMetadata as unknown as Record<string, unknown>)['candidatesTokensDetails']),+ inputTokenDetails: this.extractGeminiModalityTokenDetails(response.usageMetadata['promptTokensDetails'] || []),+ outputTokenDetails: this.extractGeminiModalityTokenDetails(response.usageMetadata['candidatesTokensDetails'] || []),}: undefined@@ -110,14 +113,52 @@ export class GeminiService {usage,}, 'Image generation completed')+ if (usage && images.length > 0 && (!usage.outputTokenDetails || !usage.outputTokenDetails.image)) {+ const imageTokens = this.calculateImageTokens(model, imageSize)+ if (imageTokens > 0) {+ const totalImageTokens = imageTokens * images.length+ usage.outputTokenDetails = {+ ...usage.outputTokenDetails,+ image: (usage.outputTokenDetails?.image || 0) + totalImageTokens,+ }+ usage.candidatesTokenCount += totalImageTokens+ usage.totalTokenCount += totalImageTokens+ this.logger.debug({ model, imageSize, imageCount: images.length, totalImageTokens }, 'Manually calculated image tokens')+ }+ }+return { images, usage }}- private extractGeminiModalityTokenDetails(details: unknown): GeminiModalityTokenDetails | undefined {- if (!Array.isArray(details)) {- return undefined+ private calculateImageTokens(model: string, size?: GeminiImageSize): number {+ if (model.includes('gemini-3.1-flash')) {+ switch (size) {+ case '0.5K':+ return 747+ case '1K':+ return 1120+ case '2K':+ return 1680+ case '4K':+ return 2520+ default:+ return 1120 // Default to 1K+ }}+ else if (model.includes('gemini-3-pro')) {+ switch (size) {+ case '4K':+ return 2000+ case '1K':+ case '2K':+ default:+ return 1120 // 1K to 2K+ }+ }+ return 0+ }+ private extractGeminiModalityTokenDetails(details: ModalityTokenCount[]): GeminiModalityTokenDetails | undefined {const result: GeminiModalityTokenDetails = {}for (const detail of details) {@@ -125,9 +166,9 @@ export class GeminiService {continue}- const detailRecord = detail as Record<string, unknown>- const rawModality = detailRecord['modality']- const rawTokenCount = detailRecord['tokenCount']+ const detailRecord = detail+ const rawModality = detailRecord.modality+ const rawTokenCount = detailRecord.tokenCountif (typeof rawModality !== 'string') {continue@@ -140,16 +181,16 @@ export class GeminiService {continue}- if (modality.includes('text')) {+ if (modality === MediaModality.TEXT) {result.text = (result.text || 0) + tokenCount}- else if (modality.includes('image')) {+ else if (modality === MediaModality.IMAGE) {result.image = (result.image || 0) + tokenCount}- else if (modality.includes('audio')) {+ else if (modality === MediaModality.AUDIO) {result.audio = (result.audio || 0) + tokenCount}- else if (modality.includes('video')) {+ else if (modality === MediaModality.VIDEO) {result.video = (result.video || 0) + tokenCount}}diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/openai/openai.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/openai/openai.service.tsindex 8406b928..4382b9ab 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/openai/openai.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/libs/openai/openai.service.ts@@ -87,8 +87,6 @@ export class OpenaiService {}private normalizeVideoTimestamp(video: OpenAI.Videos.Video): OpenAI.Videos.Video {- // 判断阈值:10000000000 对应 2001-09-09- // 大于此值则认为是毫秒值,需转换为秒值if (video.created_at > 10000000000) {return {...video,diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/gemini/gemini.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/gemini/gemini.service.tsindex 3d8c220a..67995572 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/gemini/gemini.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/gemini/gemini.service.ts@@ -157,7 +157,6 @@ export class GeminiVideoService {}const result = await this.geminiLibService.createVideo(params)-if (!result.operation.name || result.operation.error) {this.logger.error(result, 'Gemini Veo createVideo failed')throw new AppException(ResponseCode.AiCallFailed, result.operation.error)diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/grok/grok.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/grok/grok.service.tsindex 4434ff43..fcd86e2c 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/grok/grok.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/grok/grok.service.ts@@ -85,20 +85,20 @@ export class GrokVideoService {const startedAt = new Date()- const result = videoUrl- ? await this.grokLibService.editVideo({+ const result = await (videoUrl+ ? this.grokLibService.editVideo({model,prompt,video: { url: videoUrl },})- : await this.grokLibService.createVideo({+ : this.grokLibService.createVideo({model,prompt,duration,aspect_ratio: aspectRatio as GrokAspectRatio,resolution: resolution as GrokResolution,image: imageUrl ? { url: imageUrl } : undefined,- })+ }))if (userType === UserType.User) {await this.creditsHelper.deductCredits({diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/openai/openai.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/openai/openai.service.tsindex 5195b713..0b4e8263 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/openai/openai.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/openai/openai.service.ts@@ -126,6 +126,7 @@ export class OpenAIVideoService {return {...result,id: aiLog.id,+ points: pricing,}}@@ -157,7 +158,7 @@ export class OpenAIVideoService {}const startedAt = new Date()- const result = await this.openaiLibService.remixVideo(aiLog.taskId, prompt)+ const result = await this.openaiLibService.remixVideo(aiLog.taskId!, prompt)if (userType === UserType.User) {await this.creditsHelper.deductCredits({diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.service.tsindex 2c29da0f..8fab6c3e 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.service.ts@@ -113,9 +113,10 @@ export class VideoService {const channel = modelConfig.channel- const createTaskResponse = (taskId: string) => ({+ const createTaskResponse = (taskId: string, points: number) => ({id: taskId,status: TaskStatus.Submitted,+ points,})switch (channel) {@@ -139,7 +140,7 @@ export class VideoService {*/private async handleVolcengineGeneration<T>(request: UserVideoGenerationRequestDto,- createTaskResponse: (taskId: string) => T,+ createTaskResponse: (taskId: string, points: number) => T,) {const { userId, userType, model, prompt, duration, size, image, image_tail } = request@@ -181,7 +182,7 @@ export class VideoService {model,content,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}/**@@ -189,7 +190,7 @@ export class VideoService {*/private async handleOpenAIGeneration<T>(request: UserVideoGenerationRequestDto,- createTaskResponse: (taskId: string) => T,+ createTaskResponse: (taskId: string, points: number) => T,) {const { userId, userType, model, prompt, image } = request@@ -206,7 +207,7 @@ export class VideoService {seconds: request.duration ? request.duration.toString() as '10' | '15' | '25' : undefined,size: request.size as '720x1280' | '1280x720' | '1024x1792' | '1792x1024' | undefined,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}/**@@ -214,7 +215,7 @@ export class VideoService {*/private async handleGrokGeneration<T>(request: UserVideoGenerationRequestDto,- createTaskResponse: (taskId: string) => T,+ createTaskResponse: (taskId: string, points: number) => T,) {const { userId, userType, model, prompt, video_url } = request@@ -228,7 +229,7 @@ export class VideoService {prompt,videoUrl,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}const imageUrl = Array.isArray(request.image) ? request.image[0] : request.image@@ -242,7 +243,7 @@ export class VideoService {resolution: request.metadata?.['resolution'] as string,imageUrl: imageUrl ? await this.toPresignedUrl(imageUrl) : undefined,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}/**@@ -250,7 +251,7 @@ export class VideoService {*/private async handleAicsoVeoGeneration<T>(request: UserVideoGenerationRequestDto,- createTaskResponse: (taskId: string) => T,+ createTaskResponse: (taskId: string, points: number) => T,) {const { userId, userType, model, prompt } = request@@ -282,12 +283,12 @@ export class VideoService {images: images.length > 0 ? images : undefined,aspectRatio: request.metadata?.['aspectRatio'] as string,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}private async handleAicsoGrokGeneration<T>(request: UserVideoGenerationRequestDto,- createTaskResponse: (taskId: string) => T,+ createTaskResponse: (taskId: string, points: number) => T,) {const { userId, userType, model, prompt } = request@@ -316,7 +317,7 @@ export class VideoService {aspectRatio: request.metadata?.['aspectRatio'] as string,size,})- return createTaskResponse(result.id)+ return createTaskResponse(result.id, result.points)}private extractInput(aiLog: AiLog): VideoTaskInput {diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.vo.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.vo.tsindex e190c407..c4d3ef2f 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.vo.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/video.vo.ts@@ -1,4 +1,4 @@-import { createPaginationVo, createZodDto } from '@yikart/common'+import { createPaginationVo, createZodDto, zodI18nString } from '@yikart/common'import { AiLogChannel } from '@yikart/mongodb'import { z } from 'zod'@@ -47,7 +47,7 @@ const videoGenerationModelSchema = z.object({description: z.string().describe('模型描述'),summary: z.string().optional(),logo: z.string().optional(),- tags: z.string().array().default([]),+ tags: z.array(zodI18nString()).default([]),mainTag: z.string().optional(),channel: z.enum(AiLogChannel).describe('渠道'),modes: z.array(z.enum(['text2video', 'image2video', 'flf2video', 'lf2video', 'multi-image2video', 'video2video'])).describe('支持的模式'),diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/volcengine/volcengine.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/volcengine/volcengine.service.tsindex 40e25a04..568f4d98 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/volcengine/volcengine.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/ai/video/volcengine/volcengine.service.ts@@ -130,7 +130,8 @@ export class VolcengineVideoService {return {...result,id: aiLog.id,- } as CreateVideoGenerationTaskResponse+ points: pricing,+ } as CreateVideoGenerationTaskResponse & { points: number }}/**diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.consumer.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.consumer.tsindex 10260f6e..1a3a6644 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.consumer.ts@@ -24,9 +24,9 @@ export class DraftGenerationConsumer extends WorkerHost {try {if (version === 'v2-image-text') {- const { prompt, imageUrls, imageModel, imageCount, aspectRatio } = job.data+ const { prompt, imageUrls, imageModel, imageCount, aspectRatio, imageTextDraftType, platforms } = job.datathis.logger.log(- { aiLogId, imageModel, imageCount, aspectRatio, imageUrlsCount: imageUrls?.length ?? 0, promptLength: prompt?.length ?? 0 },+ { aiLogId, imageModel, imageCount, aspectRatio, imageUrlsCount: imageUrls?.length ?? 0, promptLength: prompt?.length ?? 0, draftType: imageTextDraftType },'Processing v2-image-text generation',)const { consumedPoints } = await this.draftGenerationService.generateContentImageText(aiLogId, userId, userType, groupId, {@@ -35,11 +35,13 @@ export class DraftGenerationConsumer extends WorkerHost {imageModel: imageModel ?? 'gemini-3.1-flash-image-preview',imageCount: imageCount ?? 3,aspectRatio,+ draftType: imageTextDraftType,+ platforms,})this.logger.log({ aiLogId, consumedPoints }, 'v2-image-text generation completed')}else if (version === 'v2') {- const { prompt, imageUrls, model, duration, aspectRatio, videoUrls } = job.data+ const { prompt, imageUrls, model, duration, aspectRatio, videoUrls, draftType, platforms } = job.dataconst { consumedPoints } = await this.draftGenerationService.generateContentV2(aiLogId, userId, userType, groupId, {prompt,imageUrls,@@ -47,6 +49,8 @@ export class DraftGenerationConsumer extends WorkerHost {duration,aspectRatio,videoUrls,+ draftType,+ platforms,})this.logger.log({ aiLogId, consumedPoints }, 'v2 generation completed')}diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.controller.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.controller.tsindex e353c1d9..07fdc230 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.controller.ts@@ -3,8 +3,6 @@ import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, UserType } from '@yikart/common'import {- CreateDraftGenerationDto,- CreateDraftGenerationDtoSchema,CreateDraftGenerationV2Dto,CreateDraftGenerationV2DtoSchema,CreateImageTextDraftDto,@@ -99,33 +97,6 @@ export class DraftGenerationController {return DraftGenerationTaskVo.create(task)}- /**- * 创建草稿生成任务- *- * 完整流程:- * 1. [同步] Service.createDrafts 校验用户品牌库、解析目标素材组- * 2. [同步] 按 quantity 数量循环创建 AiLog(状态=Generating)并投递 BullMQ 任务- * 3. [同步] 立即返回 taskIds(AiLog ID 列表),前端可轮询查询进度- * 4. [异步] DraftGenerationConsumer 消费队列(并发=3,重试=3次,指数退避30s)- * 5. [异步] Service.generateContent 调用 Claude Agent + MCP 工具生成 TikTok 视频- * 6. [异步] 生成成功后创建 Material 素材记录、扣除积分、更新 AiLog 状态- */- @ApiDoc({- summary: '生成品牌内容草稿',- description: '根据用户品牌库信息生成 TikTok 视频内容草稿,保存到指定素材组。返回 taskIds 可用于查询 AiLog 获取进度。',- body: CreateDraftGenerationDtoSchema,- response: CreateDraftGenerationVo,- })- @Post('/')- async createDrafts(- @GetToken() token: TokenInfo,- @Body() body: CreateDraftGenerationDto,- ): Promise<CreateDraftGenerationVo> {- // 委托 Service 创建任务并投递队列,返回 AiLog ID 列表- const taskIds = await this.draftGenerationService.createDrafts(token.id, UserType.User, body)- return CreateDraftGenerationVo.create({ taskIds })- }-/*** V2: 直接调用 core/ai 服务的固定管线,省去 Agent 编排开销*diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.dto.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.dto.tsindex e36cd248..1c1f9f39 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.dto.ts@@ -1,12 +1,17 @@-import { createZodDto, PaginationDtoSchema } from '@yikart/common'+import { AccountType, createZodDto, PaginationDtoSchema } from '@yikart/common'import { z } from 'zod'export const IMAGE_TEXT_ASPECT_RATIOS = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9'] as const-export const GROK_ASPECT_RATIOS = ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'] as constexport const ALL_ASPECT_RATIOS = ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'] as const-export const GROK_MAX_DURATION = 15+/** 视频草稿生成类型:draft 完整草稿(含标题/描述/话题),video 仅生成视频 */+export const DRAFT_TYPES = ['draft', 'video'] as const+export type DraftType = (typeof DRAFT_TYPES)[number]++/** 图文草稿生成类型:draft 完整草稿(含标题/描述/话题),image 仅生成图片 */+export const IMAGE_TEXT_DRAFT_TYPES = ['draft', 'image'] as const+export type ImageTextDraftType = (typeof IMAGE_TEXT_DRAFT_TYPES)[number]export const CreateDraftGenerationDtoSchema = z.object({quantity: z.number().int().min(1).max(10).default(1).describe('生成数量'),@@ -26,8 +31,9 @@ export const CreateDraftGenerationV2DtoSchema = z.object({duration: z.number().int().min(1).max(15).optional().describe('视频时长(秒),1-15'),aspectRatio: z.enum(ALL_ASPECT_RATIOS).optional().describe('视频比例:1:1/16:9/9:16/4:3/3:4/3:2/2:3'),videoUrls: z.array(z.url()).max(3).optional().describe('运动参考视频 URL 数组,最多3个'),+ draftType: z.enum(DRAFT_TYPES).default('draft').describe('草稿类型:draft 完整草稿,video 仅生成视频'),+ platforms: z.array(z.enum(AccountType)).optional().describe('目标平台列表,如 ["tiktok", "youtube"]'),})-export class CreateDraftGenerationV2Dto extends createZodDto(CreateDraftGenerationV2DtoSchema, 'CreateDraftGenerationV2Dto') { }export const QueryDraftGenerationTasksDtoSchema = z.object({@@ -49,6 +55,8 @@ export const CreateImageTextDraftDtoSchema = z.object({imageCount: z.number().int().min(1).max(9).default(3).describe('生成图片数量'),imageSize: z.string().optional().describe('图片分辨率:1K、2K 或 4K'),aspectRatio: z.enum(IMAGE_TEXT_ASPECT_RATIOS).optional().describe('图片宽高比'),+ draftType: z.enum(IMAGE_TEXT_DRAFT_TYPES).default('draft').describe('草稿类型:draft 完整草稿,image 仅生成图片'),+ platforms: z.array(z.enum(AccountType)).optional().describe('目标平台列表,如 ["tiktok", "xhs"]'),})export class CreateImageTextDraftDto extends createZodDto(CreateImageTextDraftDtoSchema, 'CreateImageTextDraftDto') { }diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.service.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.service.tsindex 088a9bab..a0692155 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.service.ts@@ -4,8 +4,7 @@ import { ChatGoogleGenerativeAI } from '@langchain/google-genai'import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'import { QueueService } from '@yikart/aitoearn-queue'import { AssetsService, VideoMetadataService } from '@yikart/assets'-import { AppException, FileUtil, getErrorMessage, poll, ResponseCode, retry, UserType } from '@yikart/common'-import { CreditsHelperService } from '@yikart/helpers'+import { AccountType, AppException, FileUtil, getErrorMessage, poll, ResponseCode, retry, UserType } from '@yikart/common'import {AiLogChannel,AiLogRepository,@@ -17,7 +16,9 @@ import {MaterialSource,MaterialStatus,MaterialType,+ MediaRepository,MediaType,+ UserRepository,} from '@yikart/mongodb'import { z } from 'zod'import { TaskStatus } from '../../common'@@ -33,14 +34,14 @@ import { VideoService } from '../ai/video/video.service'import { getCompatibleAccountTypes } from '../material-adaptation/material-adaptation.constants'import { DRAFT_GENERATION_SYSTEM_PROMPT } from './draft-generation.constants'import {- CreateDraftGenerationDto,CreateDraftGenerationV2Dto,CreateImageTextDraftDto,-+ DraftType,+ ImageTextDraftType,ListDraftGenerationTasksDto,QueryDraftGenerationTasksDto,} from './draft-generation.dto'-import { DraftGenerationPricingVo, DraftGenerationResult, DraftGenerationResultSchema } from './draft-generation.vo'+import { DraftGenerationPricingVoInput, DraftGenerationResult, DraftGenerationResultSchema } from './draft-generation.vo'export class DraftGenerationError extends Error {constructor(@@ -96,11 +97,12 @@ export class DraftGenerationService implements OnModuleDestroy {private readonly videoUtilsMcp: VideoUtilsMcp,private readonly agentService: AgentService,private readonly queueService: QueueService,- private readonly creditsHelper: CreditsHelperService,+ private readonly userRepository: UserRepository,private readonly videoService: VideoService,private readonly assetsService: AssetsService,private readonly videoMetadataService: VideoMetadataService,private readonly imageService: ImageService,+ private readonly mediaRepository: MediaRepository,) { }/** 优雅关机:等待所有正在运行的生成任务完成后再销毁模块 */@@ -128,66 +130,6 @@ export class DraftGenerationService implements OnModuleDestroy {this.logger.debug('DraftGenerationService shutdown complete')}- /**- * 创建草稿生成任务(同步阶段)- *- * 流程:校验 → 创建 AiLog → 投递队列 → 返回任务ID- * 实际的 AI 生成由 DraftGenerationConsumer 异步消费完成- */- async createDrafts(userId: string, userType: UserType, dto: CreateDraftGenerationDto): Promise<string[]> {- // 解析目标素材组:优先使用指定的 groupId,否则使用用户默认草稿箱- let resolvedGroupId: string- if (dto.groupId) {- // 指定了素材组,校验存在性和归属权限- const group = await this.materialGroupRepository.getInfo(dto.groupId)- if (!group || group.userId !== userId) {- throw new AppException(ResponseCode.MaterialGroupNotFound)- }- resolvedGroupId = group.id- }- else {- // 未指定素材组,获取用户默认素材组- const defaultGroup = await this.materialGroupRepository.getDefaultGroup(userId)- if (!defaultGroup) {- throw new AppException(ResponseCode.MaterialGroupNotFound)- }- resolvedGroupId = defaultGroup.id- }-- // 按请求数量(默认1,最多10)逐个创建任务- const quantity = dto.quantity ?? 1- const aiLogIds: string[] = []-- for (let i = 0; i < quantity; i++) {- // 创建 AiLog 记录,初始状态为 Generating,作为任务进度追踪凭证- const aiLog = await this.aiLogRepository.create({- userId,- userType,- type: AiLogType.DraftGeneration,- model: 'claude-agent',- channel: AiLogChannel.ClaudeAgent,- status: AiLogStatus.Generating,- startedAt: new Date(),- points: 0,- request: { groupId: resolvedGroupId },- response: {},- })-- // 投递到 BullMQ 队列,配置:3次重试、指数退避(基准30s)、失败不移除- await this.queueService.addDraftGenerationJob({- aiLogId: aiLog.id,- userId,- userType,- groupId: resolvedGroupId,- })-- aiLogIds.push(aiLog.id)- }-- // 返回所有 AiLog ID,前端可通过 GET /ai/draft-generation/:id 或 POST /query 轮询状态- return aiLogIds- }-async getTask(taskId: string, userId: string, userType: UserType) {const aiLog = await this.aiLogRepository.getByIdAndUserId(taskId, userId, userType)if (!aiLog) {@@ -241,9 +183,8 @@ export class DraftGenerationService implements OnModuleDestroy {this.runningGenerations.set(aiLogId, taskInfo)try {- // 构建发送给 Agent 的消息内容const messageContent: MessageContent[] = [- { type: 'text', text: 'Generate an engaging TikTok video showcasing interesting content.' },+ { type: 'text', text: 'Create an engaging video for this content group.' },]// 调用 Claude Agent(claude-sonnet-4-5)+ MCP 工具执行视频生成@@ -399,7 +340,7 @@ export class DraftGenerationService implements OnModuleDestroy {/*** V2: 创建草稿生成任务(与 v1 相同的校验逻辑,投递队列时标记 version=v2)- * 支持选择 duration、aspectRatio+ * 支持选择 modelType(jimeng/grok)、duration、aspectRatio*/async createDraftsV2(userId: string, userType: UserType, dto: CreateDraftGenerationV2Dto): Promise<string[]> {const modelConfig = config.ai.models.video.generation.find(m => m.name === dto.model)@@ -442,6 +383,10 @@ export class DraftGenerationService implements OnModuleDestroy {model: dto.model,duration: dto.duration,aspectRatio: dto.aspectRatio,+ prompt: dto.prompt,+ imageUrls: dto.imageUrls,+ videoUrls: dto.videoUrls,+ draftType: dto.draftType ?? 'draft',},response: {},})@@ -458,6 +403,8 @@ export class DraftGenerationService implements OnModuleDestroy {duration: dto.duration,aspectRatio: dto.aspectRatio,videoUrls: dto.videoUrls,+ draftType: dto.draftType ?? 'draft',+ platforms: dto.platforms,})aiLogIds.push(aiLog.id)@@ -471,7 +418,7 @@ export class DraftGenerationService implements OnModuleDestroy {** 流程:* 1. Gemini Flash 分析品牌 → 选图 + 生成视频 prompt + 元数据(一次 LLM 调用)- * 2. 根据 model 选择对应渠道生成视频+ * 2. 根据 modelType 选择 Jimeng 或 Grok 生成视频,失败时兜底到对方* 3. 截帧生成封面* 4. 保存素材 + 更新 AiLog*@@ -489,20 +436,28 @@ export class DraftGenerationService implements OnModuleDestroy {duration?: numberaspectRatio?: stringvideoUrls?: string[]+ draftType?: DraftType+ platforms?: string[]},): Promise<{ consumedPoints: number }> {let consumedPoints = 0const startTime = Date.now()+ const draftType = options?.draftType ?? 'draft'try {const candidateImageUrls = options?.imageUrls ?? []- const { plan, points: planPoints } = await this.planWithGemini(userId, userType, candidateImageUrls, options?.prompt)- consumedPoints += planPoints-const model = options?.model ?? 'grok-imagine-video'const duration = options?.durationconst aspectRatio = options?.aspectRatio ?? '9:16'+ // 仅 draft 类型需要 Gemini 规划(生成标题/描述/话题)+ let plan: V2PlanResult | undefined+ if (draftType === 'draft') {+ const { plan: geminiPlan, points: planPoints } = await this.planWithGemini(userId, userType, candidateImageUrls, options?.prompt)+ plan = geminiPlan+ consumedPoints += planPoints+ }+const { videoUrl, points: videoPoints } = await this.generateVideo(aiLogId,userId,@@ -525,6 +480,31 @@ export class DraftGenerationService implements OnModuleDestroy {})const coverUrl = uploadResult.asset.path+ if (draftType === 'video') {+ // 仅生成视频:存入 Media 表,记录 materialGroupId+ const media = await this.mediaRepository.create({+ userId,+ userType,+ materialGroupId: groupId,+ type: MediaType.VIDEO,+ url: videoUrl,+ thumbUrl: coverUrl,+ })++ await this.aiLogRepository.updateById(aiLogId, {+ $set: {+ status: AiLogStatus.Success,+ model,+ points: consumedPoints,+ duration: Date.now() - startTime,+ response: { mediaId: media.id, videoUrl, coverUrl },+ },+ })++ return { consumedPoints }+ }++ // draft 类型:保存完整草稿素材const material = await this.materialRepository.create({userId,userType,@@ -532,29 +512,29 @@ export class DraftGenerationService implements OnModuleDestroy {type: MaterialType.VIDEO,source: MaterialSource.PlaceDraft,status: MaterialStatus.SUCCESS,- title: plan.title,- desc: plan.description,- topics: plan.topics,+ title: plan!.title,+ desc: plan!.description,+ topics: plan!.topics,coverUrl,mediaList: [{ url: videoUrl, type: MediaType.VIDEO, thumbUrl: coverUrl }],useCount: 0,autoDeleteMedia: false,openAffiliate: true,model,- accountTypes: getCompatibleAccountTypes({+ accountTypes: (options?.platforms as AccountType[]) ?? getCompatibleAccountTypes({type: 'video',- title: plan.title,- desc: plan.description,- topics: plan.topics,+ title: plan!.title,+ desc: plan!.description,+ topics: plan!.topics,duration,aspectRatio,}),})const result: DraftGenerationResult = {- title: plan.title,- description: plan.description,- topics: plan.topics,+ title: plan!.title,+ description: plan!.description,+ topics: plan!.topics,videoUrl,coverUrl,}@@ -714,12 +694,12 @@ Return the result as JSON.`{ taskName: `Video generation (${model})` },)- return { videoUrl: url, points: 0 }+ return { videoUrl: url, points: task.points }}// ==================== 图文草稿生成 ====================- getDraftGenerationPricing(): DraftGenerationPricingVo {+ getDraftGenerationPricing(): DraftGenerationPricingVoInput {const imageModels = config.ai.draftGeneration.imageModelsconst videoModels = config.ai.models.video.generation@@ -770,6 +750,9 @@ Return the result as JSON.`imageCount: dto.imageCount,imageSize: dto.imageSize,aspectRatio: dto.aspectRatio,+ prompt: dto.prompt,+ imageUrls: dto.imageUrls,+ draftType: dto.draftType ?? 'draft',},response: {},})@@ -786,6 +769,8 @@ Return the result as JSON.`imageCount: dto.imageCount ?? 3,imageSize: dto.imageSize,aspectRatio: dto.aspectRatio,+ imageTextDraftType: dto.draftType ?? 'draft',+ platforms: dto.platforms,})aiLogIds.push(aiLog.id)@@ -814,36 +799,51 @@ Return the result as JSON.`imageCount: numberimageSize?: stringaspectRatio?: string+ draftType?: ImageTextDraftType+ platforms?: string[]},): Promise<{ consumedPoints: number }> {let consumedPoints = 0const startTime = Date.now()+ const draftType = options.draftType ?? 'draft'try {const referenceImageUrls = options.imageUrls ?? []this.logger.log(- { aiLogId, imageModel: options.imageModel, imageCount: options.imageCount, aspectRatio: options.aspectRatio, refImageCount: referenceImageUrls.length },+ { aiLogId, imageModel: options.imageModel, imageCount: options.imageCount, aspectRatio: options.aspectRatio, refImageCount: referenceImageUrls.length, draftType },'ImageText: Starting generation',)- const { plan, points: planPoints } = await this.planImageTextWithGemini(- userId,- userType,- referenceImageUrls,- options.prompt,- options.imageCount,- )- consumedPoints += planPoints- this.logger.log(- { aiLogId, title: plan.title, imagePromptsCount: plan.imagePrompts.length, planPoints },- 'ImageText: Planning completed',- )+ // 仅 draft 类型需要 Gemini 规划(生成标题/描述/话题/图片 prompts)+ let plan: ImageTextPlanResult | undefined+ let imagePrompts: string[]++ if (draftType === 'draft') {+ const { plan: geminiPlan, points: planPoints } = await this.planImageTextWithGemini(+ userId,+ userType,+ referenceImageUrls,+ options.prompt,+ options.imageCount,+ )+ plan = geminiPlan+ imagePrompts = plan.imagePrompts+ consumedPoints += planPoints+ this.logger.log(+ { aiLogId, title: plan.title, imagePromptsCount: plan.imagePrompts.length, planPoints },+ 'ImageText: Planning completed',+ )+ }+ else {+ // image 类型:直接使用用户 prompt 作为每张图片的生成 prompt+ imagePrompts = Array.from({ length: options.imageCount }, () => options.prompt)+ }const { urls: generatedImageUrls, points: imagePoints } = await this.generateImages(userId,userType,options.imageModel,- plan.imagePrompts,+ imagePrompts,referenceImageUrls,options.aspectRatio,options.imageSize,@@ -854,11 +854,40 @@ Return the result as JSON.`'ImageText: Image generation completed',)- const coverUrl = generatedImageUrls[0]- if (!coverUrl) {+ if (generatedImageUrls.length === 0) {throw new Error('ImageText: No images were generated')}+ if (draftType === 'image') {+ // 仅生成图片:逐张存入 Media 表,记录 materialGroupId+ const mediaIds: string[] = []+ for (const imageUrl of generatedImageUrls) {+ const media = await this.mediaRepository.create({+ userId,+ userType,+ materialGroupId: groupId,+ type: MediaType.IMG,+ url: imageUrl,+ })+ mediaIds.push(media.id)+ }++ await this.aiLogRepository.updateById(aiLogId, {+ $set: {+ status: AiLogStatus.Success,+ model: options.imageModel,+ points: consumedPoints,+ duration: Date.now() - startTime,+ response: { mediaIds, imageUrls: generatedImageUrls },+ },+ })++ return { consumedPoints }+ }++ // draft 类型:保存完整图文草稿素材+ const coverUrl = generatedImageUrls[0]+const material = await this.materialRepository.create({userId,userType,@@ -866,29 +895,29 @@ Return the result as JSON.`type: MaterialType.ARTICLE,source: MaterialSource.PlaceDraft,status: MaterialStatus.SUCCESS,- title: plan.title,- desc: plan.description,- topics: plan.topics,+ title: plan!.title,+ desc: plan!.description,+ topics: plan!.topics,coverUrl,mediaList: generatedImageUrls.map(url => ({ url, type: MediaType.IMG })),useCount: 0,autoDeleteMedia: false,openAffiliate: true,model: options.imageModel,- accountTypes: getCompatibleAccountTypes({+ accountTypes: (options.platforms as AccountType[]) ?? getCompatibleAccountTypes({type: 'article',- title: plan.title,- desc: plan.description,- topics: plan.topics,+ title: plan!.title,+ desc: plan!.description,+ topics: plan!.topics,imageCount: generatedImageUrls.length,aspectRatio: options.aspectRatio,}),})const result: DraftGenerationResult = {- title: plan.title,- description: plan.description,- topics: plan.topics,+ title: plan!.title,+ description: plan!.description,+ topics: plan!.topics,coverUrl,imageUrls: generatedImageUrls,}diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.vo.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.vo.tsindex 97057a59..512ffb93 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.vo.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/draft-generation/draft-generation.vo.ts@@ -1,4 +1,4 @@-import { createPaginationVo, createZodDto } from '@yikart/common'+import { createPaginationVo, createZodDto, zodI18nString } from '@yikart/common'import { AiLogStatus } from '@yikart/mongodb'import { z } from 'zod'@@ -24,6 +24,7 @@ export const DraftGenerationTaskVoSchema = z.object({status: z.enum(AiLogStatus).describe('任务状态'),points: z.number().describe('消耗积分'),errorMessage: z.string().optional().describe('错误信息'),+ request: z.record(z.string(), z.unknown()).optional().describe('生成输入参数'),response: z.record(z.string(), z.unknown()).optional().describe('生成结果'),createdAt: z.date().describe('创建时间'),updatedAt: z.date().describe('更新时间'),@@ -69,7 +70,7 @@ export const VideoModelVoSchema = z.object({durations: z.array(z.number()).describe('支持的时长'),maxInputImages: z.number().describe('最大输入图片数'),aspectRatios: z.array(z.string()).describe('支持的宽高比列表'),- tags: z.array(z.string()).default([]).describe('标签'),+ tags: z.array(zodI18nString()).default([]).describe('标签'),defaults: z.object({resolution: z.string().optional().describe('默认分辨率'),aspectRatio: z.string().optional().describe('默认宽高比'),@@ -83,4 +84,6 @@ export const DraftGenerationPricingVoSchema = z.object({videoModels: z.array(VideoModelVoSchema).describe('视频生成模型价格列表'),})+export type DraftGenerationPricingVoInput = z.input<typeof DraftGenerationPricingVoSchema>+export class DraftGenerationPricingVo extends createZodDto(DraftGenerationPricingVoSchema, 'DraftGenerationPricingVo') {}diff --git a/project/aitoearn-backend/apps/aitoearn-ai/src/core/internal/ai.dto.ts b/project/aitoearn-backend/apps/aitoearn-ai/src/core/internal/ai.dto.tsindex 2650752e..7f4c1842 100644--- a/project/aitoearn-backend/apps/aitoearn-ai/src/core/internal/ai.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-ai/src/core/internal/ai.dto.ts@@ -67,7 +67,7 @@ const adminQrCodeArtSchema = z.object({userId: z.string().describe('用户Id'),userType: z.enum(UserType).describe('用户类型'),content: z.string().min(1).max(2000).describe('二维码扫码后的内容'),- referenceImageUrl: z.string().url().optional().describe('参考样式图 URL'),+ referenceImageUrl: z.url().optional().describe('参考样式图 URL'),prompt: z.string().min(1).max(4000).describe('文字描述(提示词)'),model: z.string().default('gpt-image-1').describe('图片生成模型'),size: z.string().optional().describe('图片尺寸'),diff --git a/project/aitoearn-backend/apps/aitoearn-server/config/config.js b/project/aitoearn-backend/apps/aitoearn-server/config/config.jsindex ed2f8fa8..d5030201 100644--- a/project/aitoearn-backend/apps/aitoearn-server/config/config.js+++ b/project/aitoearn-backend/apps/aitoearn-server/config/config.js@@ -29,21 +29,11 @@ const {APP_DOMAIN,} = process.env-const {- FEISHU_WEBHOOK_URL,- FEISHU_WEBHOOK_SECRET,-} = process.env-const {MAIL_USER,MAIL_PASS,} = process.env-const {- NEW_API_URL,- NEW_API_TOKEN,-} = process.env-const {BILIBILI_CLIENT_ID,BILIBILI_CLIENT_SECRET,@@ -83,6 +73,12 @@ const {ALI_SMS_TEMPLATE_CODE,} = process.env+const {+ RELAY_SERVER_URL,+ RELAY_API_KEY,+ RELAY_CALLBACK_URL,+} = process.env+module.exports = {// 应用基础appDomain: APP_DOMAIN,@@ -103,11 +99,6 @@ module.exports = {level: 'debug',pretty: false,},- feishu: {- enable: true,- url: FEISHU_WEBHOOK_URL,- secret: FEISHU_WEBHOOK_SECRET,- },},// 数据库@@ -293,9 +284,15 @@ module.exports = {// 业务credits: {+ registerBonus: 50,},- newApi: {- baseUrl: NEW_API_URL,- token: NEW_API_TOKEN,- },++ // 中转服务(可选)+ ...(RELAY_SERVER_URL && {+ relay: {+ serverUrl: RELAY_SERVER_URL,+ apiKey: RELAY_API_KEY,+ callbackUrl: RELAY_CALLBACK_URL,+ },+ }),}diff --git a/project/aitoearn-backend/apps/aitoearn-server/package.json b/project/aitoearn-backend/apps/aitoearn-server/package.jsonindex b757ad60..31987aa6 100644--- a/project/aitoearn-backend/apps/aitoearn-server/package.json+++ b/project/aitoearn-backend/apps/aitoearn-server/package.json@@ -30,7 +30,7 @@"@yikart/redlock": "workspace:*","axios": "^1.12.2","bignumber.js": "^9.3.1",- "bullmq": "^5.58.2",+ "bullmq": "^5.71.0","class-transformer": "^0.5.1","class-validator": "^0.14.2","data-urls": "^5.0.0",@@ -40,7 +40,7 @@"googleapis": "^150.0.1","header-generator": "^2.1.75","image-size": "^2.0.2",- "ioredis": "^5.7.0",+ "ioredis": "5.9.3","js-yaml": "^4.1.0","jsonwebtoken": "^9.0.2","lodash": "^4.17.23",diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/app.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/app.module.tsindex 6ef8cc83..1bdd3fd3 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/app.module.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/app.module.ts@@ -11,19 +11,19 @@ import { MailModule } from '@yikart/mail'import { MongodbModule } from '@yikart/mongodb'import { RedlockModule } from '@yikart/redlock'import { config } from './config'-import { AccountMcpModule } from './core/account/account-mcp.module'import { AccountModule } from './core/account/account.module'+import { ApiKeyModule } from './core/api-key/api-key.module'import { AssetsModule } from './core/assets/assets.module'import { ChannelModule } from './core/channel/channel.module'-import { PublishMcpModule } from './core/channel/publish.mcp.module'-import { ContentMcpModule } from './core/content/content-mcp.module'import { ContentModule } from './core/content/content.module'import { CreditsModule } from './core/credits/credits.module'import { InternalModule } from './core/internal/internal.module'import { NotificationModule } from './core/notification/notification.module'import { PublishModule } from './core/publish-record/publish-record.module'+import { RelayModule } from './core/relay/relay.module'import { ShortLinkModule } from './core/short-link/short-link.module'import { ToolsModule } from './core/tools/tools.module'+import { UnifiedMcpModule } from './core/unified-mcp/unified-mcp.module'import { UserModule } from './core/user/user.module'@Module({@@ -57,10 +57,9 @@ import { UserModule } from './core/user/user.module'InternalModule,ShortLinkModule,ToolsModule,- // MCP modules (after business modules to ensure @Global services are available)- AccountMcpModule,- PublishMcpModule,- ContentMcpModule,+ ApiKeyModule,+ RelayModule,+ UnifiedMcpModule,],controllers: [],providers: [],diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/common/utils/time.util.ts b/project/aitoearn-backend/apps/aitoearn-server/src/common/utils/time.util.tsindex fafb65b1..3d9c24c9 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/common/utils/time.util.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/common/utils/time.util.ts@@ -23,5 +23,5 @@ export function getTodayEnd(): Date {// 获取当前的秒级时间戳export function getCurrentTimestamp(): number {- return Math.floor(new Date().getTime() / 1000)+ return Math.floor(Date.now() / 1000)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/config.ts b/project/aitoearn-backend/apps/aitoearn-server/src/config.tsindex 5d66d523..1fdacf0f 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/config.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/config.ts@@ -134,6 +134,12 @@ const MetaOAuth2ConfigSchema = z.object({linkedin: OAuth2ConfigSchema,})+export const relayConfigSchema = z.object({+ serverUrl: z.string().url().describe('中转服务器地址'),+ apiKey: z.string().describe('用户 API Key'),+ callbackUrl: z.string().url().describe('OAuth 回调完整地址,如 http://localhost:3000/api/plat/relay-callback'),+})+export const channelConfigSchema = z.object({channelDb: channelDbConfigSchema,moreApi: moreApiConfigSchema,@@ -166,8 +172,9 @@ export const appConfigSchema = z.object({mail: mailConfigSchema,aiClient: aitoearnAiClientConfigSchema,credits: creditsConfigSchema,- newApi: newApiConfigSchema,+ newApi: newApiConfigSchema.optional(),channel: channelConfigSchema,+ relay: relayConfigSchema.optional(),})export class AppConfig extends createZodDto(appConfigSchema) { }diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account-group.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account-group.service.tsindex 15b8c3d8..10090b35 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account-group.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account-group.service.ts@@ -1,8 +1,6 @@import { Injectable } from '@nestjs/common'import { QueueService } from '@yikart/aitoearn-queue'-import { AccountType } from '@yikart/common'import { AccountGroup, AccountGroupRepository, AccountRepository } from '@yikart/mongodb'-import { AccountPortraitReportData } from '../channel/common'import { FingerprintService } from '../fingerprint/fingerprint.service'@Injectable()@@ -98,21 +96,7 @@ export class AccountGroupService {return accountGroupList}- private async reportGroupAccounts(userId: string, group: AccountGroup) {- const cursor = await this.accountRepository.getAccountCursor({ userId, groupId: group.id })- for (let account = await cursor.next(); account !== null; account = await cursor.next()) {- await this.queueService.addTaskAccountPortraitReportJob({- accountId: account.id,- userId: account.userId,- type: account.type as AccountType,- uid: account.uid,- countryCode: group.countryCode,- totalFollowers: account.fansCount,- totalWorks: account.workCount,- totalViews: account.readCount,- totalLikes: account.likeCount,- totalCollects: account.collectCount,- } satisfies AccountPortraitReportData)- }+ private async reportGroupAccounts(_userId: string, _group: AccountGroup) {+ // Task module removed — no-op}}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.controller.tsindex ebf5c011..7903e98b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.controller.ts@@ -2,11 +2,13 @@ import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, AppException, FileUtil, ResponseCode } from '@yikart/common'+import { PlatformService } from '../channel/platforms/platforms.service'import {AccountIdDto,AccountListByIdsDto,AccountListBySpaceIdsDto,AccountStatisticsDto,+ BatchAccountStatusDto,CreateAccountDto,DeleteAccountsDto,SortRankDto,@@ -15,11 +17,15 @@ import {UpdateAccountStatusDto,} from './account.dto'import { AccountService } from './account.service'+import { BatchAccountStatusVo } from './account.vo'@ApiTags('Home/Account')@Controller('account')export class AccountController {- constructor(private readonly accountService: AccountService) { }+ constructor(+ private readonly accountService: AccountService,+ private readonly platformService: PlatformService,+ ) { }@ApiDoc({summary: 'Create Account',@@ -231,4 +237,30 @@ export class AccountController {) {return this.accountService.sortRank(token.id, body.groupId, body.list)}++ @ApiDoc({+ summary: '批量查询账号 Token 状态',+ body: BatchAccountStatusDto.schema,+ response: BatchAccountStatusVo,+ })+ @Post('/batch-status')+ async batchAccountStatus(+ @GetToken() token: TokenInfo,+ @Body() body: BatchAccountStatusDto,+ ): Promise<BatchAccountStatusVo> {+ const statuses: Record<string, number> = {}+ for (const accountId of body.accountIds) {+ const account = await this.accountService.getAccountById(accountId)+ if (!account || account.userId !== token.id) {+ continue+ }+ try {+ statuses[accountId] = await this.platformService.getAccountTokenStatus(accountId, account.type)+ }+ catch {+ statuses[accountId] = 0+ }+ }+ return BatchAccountStatusVo.create({ statuses })+ }}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.dto.tsindex 5d83d3e0..936cccad 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.dto.ts@@ -134,3 +134,8 @@ export const AccountFilterSchema = z.object({types: z.array(z.enum(AccountType)).optional(),})export class AccountFilterDto extends createZodDto(AccountFilterSchema) {}++const BatchAccountStatusDtoSchema = z.object({+ accountIds: z.array(z.string().min(1)).min(1).describe('账号 ID 数组'),+})+export class BatchAccountStatusDto extends createZodDto(BatchAccountStatusDtoSchema, 'BatchAccountStatusDto') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.service.tsindex e47a2f21..0bb01d53 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.service.ts@@ -20,9 +20,9 @@ export class AccountService {* @param data*/private async accountPortraitReport(- data: AccountPortraitReportData,+ _data: AccountPortraitReportData,) {- return await this.queueService.addTaskAccountPortraitReportJob(data)+ // Task module removed — no-op}/**diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.vo.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.vo.tsnew file mode 100644index 00000000..2a11350a--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/account/account.vo.ts@@ -0,0 +1,7 @@+import { createZodDto } from '@yikart/common'+import { z } from 'zod'++const BatchAccountStatusVoSchema = z.object({+ statuses: z.record(z.string(), z.number()).describe('账号 ID → 状态映射'),+})+export class BatchAccountStatusVo extends createZodDto(BatchAccountStatusVoSchema, 'BatchAccountStatusVo') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.controller.tsnew file mode 100644index 00000000..b06f7496--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.controller.ts@@ -0,0 +1,56 @@+import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common'+import { ApiTags } from '@nestjs/swagger'+import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'+import { ApiDoc } from '@yikart/common'+import { CreateApiKeyDto } from './api-key.dto'+import { ApiKeyService } from './api-key.service'+import { ApiKeyCreatedVo, ApiKeyItemVo } from './api-key.vo'++@ApiTags('Auth/API-Key')+@Controller('/api-key')+export class ApiKeyController {+ constructor(private readonly apiKeyService: ApiKeyService) {}++ @ApiDoc({+ summary: '创建 API Key',+ description: '生成新的 API Key,明文仅返回一次',+ body: CreateApiKeyDto.schema,+ response: ApiKeyCreatedVo,+ })+ @Post('/create')+ async create(+ @GetToken() token: TokenInfo,+ @Body() dto: CreateApiKeyDto,+ ): Promise<ApiKeyCreatedVo> {+ const result = await this.apiKeyService.create(token.id, dto.name)+ return ApiKeyCreatedVo.create(result)+ }++ @ApiDoc({+ summary: '获取 API Key 列表',+ response: [ApiKeyItemVo],+ })+ @Get('/list')+ async list(+ @GetToken() token: TokenInfo,+ ): Promise<ApiKeyItemVo[]> {+ const keys = await this.apiKeyService.listByUserId(token.id)+ return keys.map(k => ApiKeyItemVo.create({+ id: k.id,+ name: k.name,+ lastUsedAt: k.lastUsedAt ?? null,+ createdAt: k.createdAt,+ }))+ }++ @ApiDoc({+ summary: '删除 API Key',+ })+ @Delete('/:id')+ async delete(+ @GetToken() token: TokenInfo,+ @Param('id') id: string,+ ): Promise<void> {+ await this.apiKeyService.deleteByIdAndUserId(id, token.id)+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.dto.tsnew file mode 100644index 00000000..ea93cf94--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.dto.ts@@ -0,0 +1,7 @@+import { createZodDto } from '@yikart/common'+import { z } from 'zod'++const CreateApiKeyDtoSchema = z.object({+ name: z.string().min(1).max(100).describe('API Key 名称'),+})+export class CreateApiKeyDto extends createZodDto(CreateApiKeyDtoSchema, 'CreateApiKeyDto') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.module.tsnew file mode 100644index 00000000..6afe0bcc--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.module.ts@@ -0,0 +1,10 @@+import { Module } from '@nestjs/common'+import { ApiKeyController } from './api-key.controller'+import { ApiKeyService } from './api-key.service'++@Module({+ controllers: [ApiKeyController],+ providers: [ApiKeyService],+ exports: [ApiKeyService],+})+export class ApiKeyModule {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.service.tsnew file mode 100644index 00000000..161baa6d--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.service.ts@@ -0,0 +1,57 @@+import { createHash } from 'node:crypto'+import { Injectable } from '@nestjs/common'+import { AppException, ResponseCode } from '@yikart/common'+import { ApiKeyRepository } from '@yikart/mongodb'+import { customAlphabet } from 'nanoid'++const generateId = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 48)++@Injectable()+export class ApiKeyService {+ constructor(+ private readonly apiKeyRepository: ApiKeyRepository,+ ) {}++ async create(userId: string, name: string) {+ const rawKey = `ak_${generateId()}`+ const keyHash = this.hashKey(rawKey)++ const apiKey = await this.apiKeyRepository.create({+ userId,+ name,+ keyHash,+ })++ return {+ id: apiKey.id,+ name: apiKey.name,+ key: rawKey,+ createdAt: apiKey.createdAt,+ }+ }++ async listByUserId(userId: string) {+ return await this.apiKeyRepository.listByUserId(userId)+ }++ async deleteByIdAndUserId(id: string, userId: string): Promise<void> {+ await this.apiKeyRepository.deleteByIdAndUserId(id, userId)+ }++ async validateKey(rawKey: string) {+ const keyHash = this.hashKey(rawKey)+ const apiKey = await this.apiKeyRepository.getByKeyHash(keyHash)++ if (!apiKey) {+ throw new AppException(ResponseCode.ApiKeyInvalid)+ }++ await this.apiKeyRepository.updateLastUsedAt(apiKey.id)++ return apiKey+ }++ private hashKey(rawKey: string): string {+ return createHash('sha1').update(rawKey).digest('hex')+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.vo.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.vo.tsnew file mode 100644index 00000000..d5697c0e--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/api-key/api-key.vo.ts@@ -0,0 +1,18 @@+import { createZodDto } from '@yikart/common'+import { z } from 'zod'++const ApiKeyCreatedVoSchema = z.object({+ id: z.string().describe('API Key ID'),+ name: z.string().describe('名称'),+ key: z.string().describe('API Key 明文(仅创建时返回一次)'),+ createdAt: z.date().describe('创建时间'),+})+export class ApiKeyCreatedVo extends createZodDto(ApiKeyCreatedVoSchema, 'ApiKeyCreatedVo') {}++const ApiKeyItemVoSchema = z.object({+ id: z.string().describe('API Key ID'),+ name: z.string().describe('名称'),+ lastUsedAt: z.date().nullable().describe('最后使用时间'),+ createdAt: z.date().describe('创建时间'),+})+export class ApiKeyItemVo extends createZodDto(ApiKeyItemVoSchema, 'ApiKeyItemVo') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.constants.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.constants.tsnew file mode 100644index 00000000..eedfc70c--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.constants.ts@@ -0,0 +1,17 @@+export class ChannelRedisKeys {+ static authTask(platform: string, id: string) {+ return `${platform}:auth_task:${id}`+ }++ static accessToken(platform: string, id: string) {+ return `${platform}:access_token:${id}`+ }++ static pageAccessToken(platform: string, pageId: string) {+ return `${platform}:page:access_token:${pageId}`+ }++ static userPageList(platform: string, accountId: string) {+ return `${platform}:user_page_list:${accountId}`+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.types.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.interfaces.tssimilarity index 100%rename from project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.types.tsrename to project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.interfaces.tsdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.module.tsindex 774483cf..548d3762 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.module.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.module.ts@@ -35,6 +35,6 @@ import { PublishModule as PublishingModule } from './publishing/publishing.modulEngagementController,ChannelController,],- exports: [ChannelService, PublishingModule],+ exports: [ChannelService, PublishingModule, PlatModule],})export class ChannelModule { }diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.service.tsindex 5add7640..573a693d 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/channel.service.ts@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'import { AppException, ResponseCode } from '@yikart/common'import { AccountStatus } from '@yikart/mongodb'import { AccountService } from '../account/account.service'+import { RelayAccountException } from '../relay/relay-account.exception'import { PlatformService } from './platforms/platforms.service'@Injectable()@@ -30,6 +31,9 @@ export class ChannelService {if (!account || account.userId !== userId) {throw new AppException(ResponseCode.AccountNotFound)}+ if (account.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, accountId)+ }try {const res = await this.platformsService.deletePost(accountId, account.type, postId)return resdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/common.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/common.tsindex 9babd946..b6136784 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/common.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/common.ts@@ -7,7 +7,7 @@ import {ThreadsPostOptions,WxGzhPublishOption,YoutubePublishOption,-} from './channel.types'+} from './channel.interfaces'export interface AccountPortraitReportData {accountId?: stringdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/data-cube/data-cube.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/data-cube/data-cube.controller.tsindex 0cdfe4fd..2ba929b0 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/data-cube/data-cube.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/data-cube/data-cube.controller.ts@@ -3,6 +3,7 @@ import { ApiTags } from '@nestjs/swagger'import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'import { AccountType } from '@yikart/aitoearn-server-client'import { ApiDoc, AppException, ResponseCode } from '@yikart/common'+import { RelayAccountException } from '../../relay/relay-account.exception'import { ChannelAccountService } from '../platforms/channel-account.service'import { BilibiliDataService } from './bilibili-data.service'import { DataCubeBase } from './data.base'@@ -29,6 +30,9 @@ export class DataCubeController {const account = await this.channelAccountService.getAccountInfo(accountId)if (!account)throw new AppException(ResponseCode.ChannelAccountNotFound)+ if (account.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, accountId)+ }const dataCube = this.dataCubeMap.get(account.type)if (!dataCube)throw new AppException(ResponseCode.DataCubeAccountTypeNotSupported)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.module.tsindex 85b56574..f2fdb856 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.module.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.module.ts@@ -1,4 +1,5 @@import { Module } from '@nestjs/common'+import { ChannelSharedModule } from '../platforms/channel-shared.module'import { MetaModule } from '../platforms/meta/meta.module'import { YoutubeModule } from '../platforms/youtube/youtube.module'import { EngagementController } from './engagement.controller'@@ -13,6 +14,7 @@ import { EngagementReplyToCommentConsumer } from './workers/reply-to-comment.con@Module({imports: [+ ChannelSharedModule,MetaModule,YoutubeModule,],diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.service.tsindex 75ad9468..3711311f 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/engagement.service.ts@@ -3,6 +3,8 @@ import { AiService, UserChatCompletionDto } from '@yikart/aitoearn-ai-client'import { QueueService } from '@yikart/aitoearn-queue'import { EngagementTargetScope, EngagementTaskStatus, EngagementTaskType } from '@yikart/channel-db'import { AppException, ResponseCode, UserType } from '@yikart/common'+import { RelayAccountException } from '../../relay/relay-account.exception'+import { ChannelAccountService } from '../platforms/channel-account.service'import { FacebookService } from '../platforms/meta/facebook.service'import { ReplyToCommentAnswer } from './ai.dto'import { AIGenCommentDto, FetchCommentRepliesRequest, FetchMetaPostsRequest, FetchPostCommentsRequest, FetchPostsRequest, LikePostRequest, PublishCommentReplyRequest, PublishCommentRequest, ReplyToCommentsDto } from './engagement.dto'@@ -25,6 +27,7 @@ export class EngagementService {private readonly engagementRecordService: EngagementRecordService,private readonly queueService: QueueService,private readonly facebookService: FacebookService,+ private readonly channelAccountService: ChannelAccountService,) {this.providerMap.set('facebook', facebookProvider)this.providerMap.set('instagram', instagramProvider)@@ -32,6 +35,13 @@ export class EngagementService {this.providerMap.set('youtube', youtubeProvider)}+ private async checkRelayAccount(accountId: string) {+ const account = await this.channelAccountService.getAccountInfo(accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, accountId)+ }+ }+private getProvider(providerKey: string): EngagementProvider {const provider = this.providerMap.get(providerKey)if (!provider) {@@ -41,6 +51,7 @@ export class EngagementService {}async fetchUserPosts(data: FetchPostsRequest) {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)let pagination = data.pagination || nullif (!pagination) {@@ -54,31 +65,37 @@ export class EngagementService {}async getMetaPostDetail(accountId: string, platform: string, postId: string) {+ await this.checkRelayAccount(accountId)const provider = this.getProvider(platform)return provider.getMetaPostDetail(accountId, postId)}async fetchPostComments(data: FetchPostCommentsRequest) {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)return provider.fetchPostComments(data.accountId, data.postId, data.pagination || null)}async fetchCommentReplies(data: FetchCommentRepliesRequest) {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)return provider.fetchCommentReplies(data.accountId, data.commentId, data.pagination || null)}async commentOnPost(data: PublishCommentRequest): Promise<PublishCommentResponse> {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)return provider.commentOnPost(data.accountId, data.postId, data.message)}async replyToComment(data: PublishCommentReplyRequest): Promise<PublishCommentResponse> {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)return provider.replyToComment(data.accountId, data.commentId, data.message)}async fetchMetaPosts(data: FetchMetaPostsRequest) {+ await this.checkRelayAccount(data.accountId)const provider = this.getProvider(data.platform)const pagination = data.pagination || {before: data.before || undefined,@@ -89,10 +106,12 @@ export class EngagementService {}async likePost(data: LikePostRequest): Promise<{ success: boolean }> {+ await this.checkRelayAccount(data.accountId)return this.facebookService.likePost(data.accountId, data.postId)}async unlikePost(data: LikePostRequest): Promise<{ success: boolean }> {+ await this.checkRelayAccount(data.accountId)return this.facebookService.unlikePost(data.accountId, data.postId)}@@ -132,6 +151,7 @@ export class EngagementService {}async ReplyToCommentsByAI(data: ReplyToCommentsDto): Promise<{ id: string }> {+ await this.checkRelayAccount(data.accountId)let targetScope = EngagementTargetScope.ALLif (data.comments?.length && data.comments.length > 0) {targetScope = EngagementTargetScope.PARTIALdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/workers/reply-to-comment.consumer.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/workers/reply-to-comment.consumer.tsindex bb1ed496..d41a24a9 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/workers/reply-to-comment.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/engagement/workers/reply-to-comment.consumer.ts@@ -3,6 +3,7 @@ import { Logger } from '@nestjs/common'import { QueueName, QueueProcessor } from '@yikart/aitoearn-queue'import { EngagementTaskStatus } from '@yikart/channel-db'import { Job } from 'bullmq'+import { ChannelAccountService } from '../../platforms/channel-account.service'import { EngagementProvider } from '../engagement.interface'import { EngagementRecordService } from '../engagement.record.service'import { FacebookEngagementProvider } from '../providers/facebook.provider'@@ -22,6 +23,7 @@ export class EngagementReplyToCommentConsumer extends WorkerHost {instagramProvider: InstagramEngagementProvider,threadsProvider: ThreadsEngagementProvider,private readonly engagementRecordService: EngagementRecordService,+ private readonly channelAccountService: ChannelAccountService,) {super()this.providerMap.set('facebook', facebookProvider)@@ -46,6 +48,15 @@ export class EngagementReplyToCommentConsumer extends WorkerHost {this.logger.error(`Sub task ${job.data.taskId} not found`)return}++ // 安全检查:relay 账号任务不应到达队列消费者+ const account = await this.channelAccountService.getAccountInfo(subTask.accountId)+ if (account?.relayAccountRef) {+ this.logger.warn(`Relay account ${subTask.accountId} task reached engagement consumer, skipping sub task ${job.data.taskId}`)+ await this.engagementRecordService.updateEngagementSubTaskStatus(job.data.taskId, EngagementTaskStatus.FAILED)+ return+ }+if (subTask.status === EngagementTaskStatus.CREATED) {const provider = this.getProvider(subTask.platform)const resp = await provider.replyToComment(subTask.accountId, subTask.commentId, subTask.replyContent)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interact.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interact.controller.tsindex bfa8384e..20cd0083 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interact.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interact.controller.ts@@ -4,6 +4,7 @@ import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'import { AccountType } from '@yikart/aitoearn-server-client'import { ApiDoc, AppException, ResponseCode, TableDto } from '@yikart/common'import { PublishRecordService } from '../../publish-record/publish-record.service'+import { RelayAccountException } from '../../relay/relay-account.exception'import { ChannelAccountService } from '../platforms/channel-account.service'import { InteracteBase } from './interact.base'import {@@ -30,6 +31,9 @@ export class InteracteController {const account = await this.channelAccountService.getAccountInfo(accountId)if (!account)throw new AppException(ResponseCode.ChannelAccountNotFound)+ if (account.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, accountId)+ }const interact = this.interactMap.get(account.type)if (!interact)throw new AppException(ResponseCode.InteractAccountTypeNotSupported)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interaction-record.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interaction-record.controller.tsindex c8e47d65..9479471e 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interaction-record.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/interaction-record.controller.ts@@ -36,7 +36,7 @@ export class InteractionRecordController {@Query() query: InteractionRecordListDto,@Param() param: TableDto,) {- return await this.interactionRecordService.getList(query.filters, param)+ return await this.interactionRecordService.getList({ ...query.filters, userId: token.id }, param)}@ApiDoc({diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/reply-comment-record.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/reply-comment-record.controller.tsindex bee6f5df..004569a6 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/reply-comment-record.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/interact/reply-comment-record.controller.ts@@ -36,7 +36,7 @@ export class ReplyCommentRecordController {@Query() query: ReplyCommentRecordListDto,@Param() param: TableDto,) {- return await this.replyCommentRecordService.getList(query.filters, param)+ return await this.replyCommentRecordService.getList({ ...query.filters, userId: token.id }, param)}@ApiDoc({diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/libs/pinterest/common.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/libs/pinterest/common.tsindex 7b9cec09..d63d81ef 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/libs/pinterest/common.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/libs/pinterest/common.ts@@ -76,6 +76,8 @@ export interface AuthInfo {expires_in?: numberrefresh_token_expires_in?: numberuserInfo?: object+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}export interface UserInfo {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/base.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/base.service.tsindex 57b14995..712da4c7 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/base.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/base.service.ts@@ -2,6 +2,7 @@ import { Inject, Injectable, Logger } from '@nestjs/common'import { OAuth2CredentialRepository } from '@yikart/channel-db'import { AccountType } from '@yikart/common'import { AccountRepository } from '@yikart/mongodb'+import { RelayAccountException } from '../../../core/relay/relay-account.exception'/*** 作品详情信息(用于创建发布记录)@@ -78,6 +79,14 @@ export abstract class PlatformBaseService {return true}+ protected async ensureLocalAccount(accountId: string) {+ const account = await this.accountRepository.getById(accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, accountId)+ }+ return account+ }+// 更新状态protected async updateAccountStatus(accountId: string, status: number) {await this.accountRepository.updateAccountStatus(accountId, status)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.controller.tsindex f48e0683..a5994e58 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.controller.ts@@ -1,7 +1,8 @@-import { Body, Controller, Get, Logger, Param, Post, Query, Render } from '@nestjs/common'+import { Body, Controller, Get, Logger, Param, Post, Query, Res } from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, AppException, ResponseCode, SkipResponseInterceptor, TableDto } from '@yikart/common'+import { Response } from 'express'import { BilibiliWebhookSchema } from '../../publishing/bilibili-webhook.dto'import { PublishingService } from '../../publishing/publishing.service'import { AccountIdDto, ArchiveListDto, GetArchiveListDto, GetArcStatDto } from './bilibili.dto'@@ -40,16 +41,24 @@ export class BilibiliController {summary: 'Handle Bilibili OAuth Callback',})@Get('auth/back/:taskId')- @Render('auth/back')async getAccessToken(@Param('taskId') taskId: string,@Query() query: { code: string, state: string },+ @Res() res: Response,) {- const res = await this.bilibiliService.createAccountAndSetAccessToken(+ const result = await this.bilibiliService.createAccountAndSetAccessToken(taskId,query,)- return res++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })+ }++ return res.render('auth/back', result)}@ApiDoc({@@ -60,11 +69,15 @@ export class BilibiliController {@GetToken() token: TokenInfo,@Param('type') type: 'h5' | 'pc',@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {return this.bilibiliService.createAuthTask({userId: token.id,type,spaceId: spaceId || '',+ callbackUrl,+ callbackMethod,})}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.dto.tsindex 87a85cf5..7d4d6378 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.dto.ts@@ -16,6 +16,8 @@ const GetAuthUrlSchema = UserIdSchema.extend({spaceId: z.string().describe('空间ID'),type: z.enum(['h5', 'pc']).describe('授权类型'),prefix: z.string().optional().describe('前缀'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.service.tsindex 89817836..8b692ce4 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/bilibili/bilibili.service.ts@@ -10,6 +10,8 @@ import { RedisService } from '@yikart/redis'import { v4 as uuidv4 } from 'uuid'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { BilibiliApiService } from '../../libs/bilibili/bilibili-api.service'import {AccessToken,@@ -19,7 +21,7 @@ import {} from '../../libs/bilibili/common'import { PlatformBaseService } from '../base.service'import { ChannelAccountService } from '../channel-account.service'-import { AuthTaskInfo } from '../common'+import { AuthCallbackResult, AuthTaskInfo } from '../common'import { PlatformAuthExpiredException } from '../platform.exception'import { BilibiliAuthInfo } from './common'@@ -39,10 +41,6 @@ export class BilibiliService extends PlatformBaseService {return config.channel.bilibili}- private getAuthDataCacheKey(taskId: string) {- return `channel:bilibili:authTask:${taskId}`- }-/*** 创建用户授权任务* @param data@@ -53,16 +51,21 @@ export class BilibiliService extends PlatformBaseService {userId: stringtype: 'h5' | 'pc'spaceId: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'},options?: {transpond?: stringaccountAddPath?: string},) {+ if (!config.channel.bilibili.id && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidv4()const urlInfo = await this.getAuthUrl(taskId, data.type)const rRes = await this.redisService.setJson(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('bilibili', taskId),{taskId,spaceId: data.spaceId,@@ -73,6 +76,8 @@ export class BilibiliService extends PlatformBaseService {userId: data.userId,},status: 0,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,},60 * 5,)@@ -107,11 +112,12 @@ export class BilibiliService extends PlatformBaseService {state: stringstatus: numberaccountId?: string- }>(this.getAuthDataCacheKey(taskId))+ }>(ChannelRedisKeys.authTask('bilibili', taskId))return data}async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const tokenInfo = await this.getOAuth2Credential(accountId)if (!tokenInfo) {this.updateAccountStatus(accountId, 0)@@ -130,7 +136,7 @@ export class BilibiliService extends PlatformBaseService {*/async getAccountAuthInfo(accountId: string) {const data = await this.redisService.getJson<AccessToken>(- `bilibili:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('bilibili', accountId),)return data}@@ -179,7 +185,7 @@ export class BilibiliService extends PlatformBaseService {data: accessTokenInfo,})const cached = await this.redisService.setJson(- `${this.platform}:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('bilibili', accountId),accessTokenInfo,)this.logger.debug({@@ -212,12 +218,8 @@ export class BilibiliService extends PlatformBaseService {async createAccountAndSetAccessToken(taskId: string,data: { code: string, state: string },- ): Promise<{- status: number- message?: string- accountId?: string- }> {- const cacheKey = this.getAuthDataCacheKey(taskId)+ ): Promise<AuthCallbackResult> {+ const cacheKey = ChannelRedisKeys.authTask('bilibili', taskId)const { code, state } = dataconst taskInfo@@ -302,22 +304,31 @@ export class BilibiliService extends PlatformBaseService {60 * 3,)- return res- ? {- status: 1,- accountId: accountInfo.id,- }- : {- status: 0,- message: '设置授权Token失败,请稍后再试',- }+ if (!res) {+ return {+ status: 0,+ message: '设置授权Token失败,请稍后再试',+ }+ }++ return {+ status: 1,+ accountId: accountInfo.id,+ nickname: accountInfo.nickname,+ avatar: accountInfo.avatar,+ platformUid: accountInfo.uid,+ accountType: AccountType.BILIBILI,+ callbackUrl: taskInfo.callbackUrl,+ callbackMethod: taskInfo.callbackMethod,+ taskId,+ }}private async getOAuth2Credential(accountId: string,): Promise<AccessToken | null> {let credential = await this.redisService.getJson<AccessToken>(- `${this.platform.toLowerCase()}:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('bilibili', accountId),)if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -343,6 +354,7 @@ export class BilibiliService extends PlatformBaseService {* @returns*/async getAccountAccessToken(accountId: string): Promise<string> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential || !credential.access_token) {throw new PlatformAuthExpiredException(this.platform, accountId)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/channel-account.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/channel-account.service.tsindex 68a0e308..90f44121 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/channel-account.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/channel-account.service.ts@@ -39,6 +39,10 @@ export class ChannelAccountService {return this.accountRepository.getAccountByUid(uid, type)}+ async listRelayAccountsByUserId(userId: string) {+ return this.accountRepository.listRelayAccountsByUserId(userId)+ }+async updateAccountStatus(id: string, status: AccountStatus) {return this.accountRepository.update(id, { status })}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/common.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/common.tsindex 6c136c52..8f29acaf 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/common.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/common.ts@@ -4,6 +4,21 @@ export interface AuthTaskInfo<T> {data?: Tstatus: -1 | 0 | 1 // -1: 未开始, 0: 进行中, 1: 完成error?: string // 错误信息+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'+}++export interface AuthCallbackResult {+ status: number+ message?: string+ accountId?: string+ nickname?: string+ avatar?: string+ platformUid?: string+ accountType?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'+ taskId?: string}export interface ChannelAccountDataCube {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.controller.tsindex 1aa1d804..d2f7b4f8 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.controller.ts@@ -6,12 +6,12 @@ import {Param,Post,Query,- Render,Res,} from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { AccountType, ApiDoc, AppException, ResponseCode, TableDto } from '@yikart/common'+import { Response } from 'express'import { DouyinWebhookSchema } from '../../publishing/douyin-webhook.dto'import { PublishingService } from '../../publishing/publishing.service'import { WebhookEvent } from './common'@@ -107,27 +107,40 @@ export class DouyinController {async getAuthUrl(@GetToken() token: TokenInfo,@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {return this.douyinService.createAuthTask({userId: token.id,spaceId: spaceId || '',+ callbackUrl,+ callbackMethod,})}@Public()@Get('auth/back')- @Render('auth/back')async getAccessToken(@Query()query: {code: stringstate: string},+ @Res() res: Response,) {- return this.douyinService.createAccountAndSetAccessToken(+ const result = await this.douyinService.createAccountAndSetAccessToken(query.state,{ code: query.code, state: query.state },)++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })+ }++ return res.render('auth/back', result)}@ApiDoc({diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.dto.tsindex efb0a30d..74f34002 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.dto.ts@@ -16,6 +16,8 @@ export class UserIdDto extends createZodDto(UserIdSchema) {}const GetAuthUrlSchema = UserIdSchema.extend({spaceId: z.string().describe('空间ID'),prefix: z.string().optional().describe('前缀'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.service.tsindex 5105e2af..6fde1fc0 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/douyin/douyin.service.ts@@ -10,11 +10,13 @@ import { RedisService } from '@yikart/redis'import { v4 as uuidv4 } from 'uuid'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { DouyinAccessTokenInfo, DouyinClientTokenInfo, DouyinOpenTicketInfo, DouyinShareSchemaOptions } from '../../libs/douyin/common'import { DouyinApiService } from '../../libs/douyin/douyin-api.service'import { PlatformBaseService } from '../base.service'import { ChannelAccountService } from '../channel-account.service'-import { AuthTaskInfo } from '../common'+import { AuthCallbackResult, AuthTaskInfo } from '../common'import { PlatformAuthExpiredException } from '../platform.exception'import { AccessToken, ArchiveStatus, DouyinAuthInfo } from './common'@@ -34,14 +36,6 @@ export class DouyinService extends PlatformBaseService {return config.channel.douyin}- private getAuthDataCacheKey(taskId: string) {- return `channel:douyin:authTask:${taskId}`- }-- private getAccessTokenCacheKey(taskId: string) {- return `channel:douyin:accessToken:${taskId}`- }-/*** 创建用户授权任务* @param data@@ -51,12 +45,17 @@ export class DouyinService extends PlatformBaseService {data: {userId?: stringspaceId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'},) {+ if (!config.channel.douyin.id && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidv4()const urlInfo = await this.getAuthUrl(taskId)const rRes = await this.redisService.setJson<AuthTaskInfo<DouyinAuthInfo>>(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('douyin', taskId),{taskId,spaceId: data.spaceId,@@ -66,6 +65,8 @@ export class DouyinService extends PlatformBaseService {accountId: '',},status: 0,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,},60 * 5,)@@ -99,11 +100,12 @@ export class DouyinService extends PlatformBaseService {state: stringstatus: numberaccountId?: string- }>(this.getAuthDataCacheKey(taskId))+ }>(ChannelRedisKeys.authTask('douyin', taskId))return data}async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const tokenInfo = await this.getOAuth2Credential(accountId)if (!tokenInfo) {this.updateAccountStatus(accountId, 0)@@ -122,7 +124,7 @@ export class DouyinService extends PlatformBaseService {*/async getAccountAuthInfo(accountId: string) {const data = await this.redisService.getJson<AccessToken>(- this.getAccessTokenCacheKey(accountId),+ ChannelRedisKeys.accessToken('douyin', accountId),)return data}@@ -152,7 +154,7 @@ export class DouyinService extends PlatformBaseService {accessTokenInfo: DouyinAccessTokenInfo,) {const cached = await this.redisService.setJson(- this.getAccessTokenCacheKey(accountId),+ ChannelRedisKeys.accessToken('douyin', accountId),accessTokenInfo,accessTokenInfo.expires_in,)@@ -177,12 +179,8 @@ export class DouyinService extends PlatformBaseService {async createAccountAndSetAccessToken(taskId: string,data: { code: string, state: string },- ): Promise<{- status: number- message?: string- accountId?: string- }> {- const cacheKey = this.getAuthDataCacheKey(taskId)+ ): Promise<AuthCallbackResult> {+ const cacheKey = ChannelRedisKeys.authTask('douyin', taskId)const { code, state } = dataconst taskInfo@@ -280,22 +278,31 @@ export class DouyinService extends PlatformBaseService {60 * 3,)- return res- ? {- status: 1,- accountId: accountInfo.id,- }- : {- status: 0,- message: '设置授权Token失败,请稍后再试',- }+ if (!res) {+ return {+ status: 0,+ message: '设置授权Token失败,请稍后再试',+ }+ }++ return {+ status: 1,+ accountId: accountInfo.id,+ nickname: accountInfo.nickname,+ avatar: accountInfo.avatar,+ platformUid: accountInfo.uid,+ accountType: AccountType.Douyin,+ callbackUrl: taskInfo.callbackUrl,+ callbackMethod: taskInfo.callbackMethod,+ taskId,+ }}private async getOAuth2Credential(accountId: string,): Promise<AccessToken | null> {let credential = await this.redisService.getJson<AccessToken>(- this.getAccessTokenCacheKey(accountId),+ ChannelRedisKeys.accessToken('douyin', accountId),)if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -321,6 +328,7 @@ export class DouyinService extends PlatformBaseService {* @returns*/async getAccountAccessToken(accountId: string): Promise<string> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential || !credential.access_token) {throw new PlatformAuthExpiredException(this.platform, accountId)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.controller.tsindex 3d331d7d..9399d391 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.controller.ts@@ -3,7 +3,7 @@ import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc } from '@yikart/common'import { Response } from 'express'-import { GoogleBusinessAuthCallbackDto } from './google-business.dto'+import { GetAuthUrlDto, GoogleBusinessAuthCallbackDto } from './google-business.dto'import { GoogleBusinessService } from './google-business.service'@ApiTags('Platform/Google Business')@@ -15,8 +15,15 @@ export class GoogleBusinessController {@ApiDoc({ summary: '获取授权 URL' })@Get('/auth/url')- async getAuthUrl(@GetToken() token: TokenInfo) {- return await this.googleBusinessService.getAuthUrl(token.id)+ async getAuthUrl(+ @GetToken() token: TokenInfo,+ @Query() query: GetAuthUrlDto,+ ) {+ return await this.googleBusinessService.getAuthUrl(+ token.id,+ query.callbackUrl,+ query.callbackMethod,+ )}@Public()@@ -28,12 +35,18 @@ export class GoogleBusinessController {) {const result = await this.googleBusinessService.handleCallback(query.code, query.state)- if (result.status === 1) {- res.redirect(`/auth/success?accountId=${result.accountId}`)+ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })}- else {- res.redirect(`/auth/error?message=${encodeURIComponent(result.message)}`)++ if (result.status === 1) {+ return res.redirect(`/auth/success?accountId=${result.accountId}`)}++ return res.redirect(`/auth/error?message=${encodeURIComponent(result.message || '')}`)}@ApiDoc({ summary: '获取授权状态' })diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.dto.tsindex 0c5aced2..ba4fa23e 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.dto.ts@@ -1,6 +1,12 @@import { createZodDto } from '@yikart/common'import { z } from 'zod'+export const GetAuthUrlSchema = z.object({+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),+})+export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema, 'GetAuthUrlDto') {}+export const GoogleBusinessAuthCallbackDtoSchema = z.object({code: z.string().describe('OAuth 授权码'),state: z.string().describe('状态码'),diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.service.tsindex 547493df..08848532 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/google-business/google-business.service.ts@@ -5,8 +5,11 @@ import { RedisService } from '@yikart/redis'import { Auth, google } from 'googleapis'import { v4 as uuidv4 } from 'uuid'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { PlatformBaseService } from '../base.service'import { ChannelAccountService } from '../channel-account.service'+import { AuthCallbackResult } from '../common'import { GoogleBusinessCredential } from './google-business.dto'interface AuthTaskInfo {@@ -14,6 +17,8 @@ interface AuthTaskInfo {userId: stringstatus: 0 | 1accountId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}interface GoogleAccountInfo {@@ -88,13 +93,20 @@ export class GoogleBusinessService extends PlatformBaseService {/*** 生成授权 URL*/- async getAuthUrl(userId: string): Promise<{ url: string, state: string }> {+ async getAuthUrl(+ userId: string,+ callbackUrl?: string,+ callbackMethod?: 'GET' | 'POST',+ ): Promise<{ url: string, state: string }> {+ if (!config.channel.googleBusiness?.clientId && config.relay) {+ throw new RelayAuthException()+ }const state = uuidv4()// 保存授权任务到 Redisawait this.redisService.setJson<AuthTaskInfo>(- `google-business:authTask:${state}`,- { state, userId, status: 0 },+ ChannelRedisKeys.authTask('google_business', state),+ { state, userId, status: 0, callbackUrl, callbackMethod },60 * 10, // 10 分钟过期)@@ -114,10 +126,10 @@ export class GoogleBusinessService extends PlatformBaseService {async handleCallback(code: string,state: string,- ): Promise<{ status: number, message: string, accountId?: string }> {+ ): Promise<AuthCallbackResult> {// 验证 stateconst authTask = await this.redisService.getJson<AuthTaskInfo>(- `google-business:authTask:${state}`,+ ChannelRedisKeys.authTask('google_business', state),)if (!authTask || authTask.state !== state) {@@ -179,15 +191,26 @@ export class GoogleBusinessService extends PlatformBaseService {// 更新 Redis 状态await this.redisService.setJson<AuthTaskInfo>(- `google-business:authTask:${state}`,+ ChannelRedisKeys.authTask('google_business', state),{ ...authTask, status: 1, accountId: account.id },60 * 5,)// 清理授权任务- await this.redisService.del(`google-business:authTask:${state}`)-- return { status: 1, message: '授权成功', accountId: account.id }+ await this.redisService.del(ChannelRedisKeys.authTask('google_business', state))++ return {+ status: 1,+ message: '授权成功',+ accountId: account.id,+ nickname: account.nickname,+ avatar: account.avatar,+ platformUid: account.uid,+ accountType: AccountType.GOOGLE_BUSINESS,+ callbackUrl: authTask.callbackUrl,+ callbackMethod: authTask.callbackMethod,+ taskId: state,+ }}catch (error) {this.logger.error('Google Business OAuth 回调处理失败', error)@@ -199,6 +222,7 @@ export class GoogleBusinessService extends PlatformBaseService {* 获取有效的 Access Token(自动刷新)*/async getValidAccessToken(accountId: string): Promise<string> {+ await this.ensureLocalAccount(accountId)const credential = await this.getCredential(accountId)if (!credential) {throw new AppException(ResponseCode.ChannelRefreshTokenFailed)@@ -297,13 +321,14 @@ export class GoogleBusinessService extends PlatformBaseService {* 获取授权状态*/async getAuthStatus(state: string): Promise<AuthTaskInfo | null> {- return this.redisService.getJson<AuthTaskInfo>(`google-business:authTask:${state}`)+ return this.redisService.getJson<AuthTaskInfo>(ChannelRedisKeys.authTask('google_business', state))}/*** 获取 Access Token 状态*/async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const credential = await this.getCredential(accountId)if (!credential || !credential.accessToken) {this.updateAccountStatus(accountId, 0)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.controller.tsindex d05916a5..a2534a86 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.controller.ts@@ -19,11 +19,15 @@ export class KwaiController {@GetToken() token: TokenInfo,@Param('type') type: 'h5' | 'pc',@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {return await this.kwaiService.createAuthTask({userId: token.id,type,spaceId: spaceId || '',+ callbackUrl,+ callbackMethod,})}@@ -52,6 +56,14 @@ export class KwaiController {taskId,query,)++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })+ }+return res.render('auth/back', result)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.dto.tsindex 33df55ac..4491ed4b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.dto.ts@@ -9,6 +9,8 @@ export class UserIdDto extends createZodDto(UserIdSchema) {}const GetAuthUrlSchema = UserIdSchema.extend({type: z.enum(['h5', 'pc']).describe('授权类型'),spaceId: z.string().describe('空间ID'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.service.tsindex 56071cdc..369b6ab0 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/kwai/kwai.service.ts@@ -4,6 +4,9 @@ import { AppException, ResponseCode } from '@yikart/common'import { RedisService } from '@yikart/redis'import { v4 as uuidv4 } from 'uuid'import { getCurrentTimestamp } from '../../../../common/utils/time.util'+import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { KwaiOAuthCredentialsResponse } from '../../libs/kwai/kwai.interfaces'import { KwaiApiService } from '../../libs/kwai/kwai.service'import { BilibiliAuthInfo } from '../../platforms/bilibili/common'@@ -27,7 +30,7 @@ export class KwaiService extends PlatformBaseService {private async getOAuth2Credential(accountId: string): Promise<KwaiOAuthCredentialsResponse | null> {let credential = await this.redisService.getJson<KwaiOAuthCredentialsResponse>(- `${this.platform.toLowerCase()}:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('kwai', accountId),)if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -69,6 +72,7 @@ export class KwaiService extends PlatformBaseService {* @param accountId*/async getAccessTokenAndRefresh(accountId: string) {+ await this.ensureLocalAccount(accountId)const accessTokenInfo = await this.getOAuth2Credential(accountId)if (!accessTokenInfo) {throw new PlatformAuthExpiredException(this.platform, accountId)@@ -101,10 +105,6 @@ export class KwaiService extends PlatformBaseService {return newAccountToken.access_token}- private getAuthDataCacheKey(taskId: string) {- return `channel:kwai:authTask:${taskId}`- }-/*** 创建用户授权任务* @returns@@ -116,16 +116,21 @@ export class KwaiService extends PlatformBaseService {userId: stringtype: 'h5' | 'pc'spaceId: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'},options?: {transpond?: stringaccountAddPath?: string},) {+ if (!config.channel.kwai.id && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidv4()const urlInfo = this.kwaiApiService.getAuthPage(taskId, data.type)const rRes = await this.redisService.setJson(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('kwai', taskId),{taskId,spaceId: data.spaceId,@@ -136,6 +141,8 @@ export class KwaiService extends PlatformBaseService {userId: data.userId,},status: 0,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,},60 * 5,)@@ -149,7 +156,7 @@ export class KwaiService extends PlatformBaseService {}async createAccountAndSetAccessToken(taskId: string, data: { code: string, state: string }) {- const cacheKey = this.getAuthDataCacheKey(taskId)+ const cacheKey = ChannelRedisKeys.authTask('kwai', taskId)const { code } = dataconst taskInfo = await this.redisService.getJson<AuthTaskInfo<BilibiliAuthInfo>>(cacheKey,@@ -174,7 +181,18 @@ export class KwaiService extends PlatformBaseService {taskInfo,60 * 3,)- return { status: 1, message: '添加账号成功', accountId: account.id }+ return {+ status: 1,+ message: '添加账号成功',+ accountId: account.id,+ nickname: account.nickname,+ avatar: account.avatar,+ platformUid: account.uid,+ accountType: AccountType.KWAI,+ callbackUrl: taskInfo.callbackUrl,+ callbackMethod: taskInfo.callbackMethod,+ taskId,+ }}else {return { status: 0, message: '添加账号失败' }@@ -191,7 +209,7 @@ export class KwaiService extends PlatformBaseService {state: stringstatus: numberaccountId?: string- }>(this.getAuthDataCacheKey(taskId))+ }>(ChannelRedisKeys.authTask('kwai', taskId))this.logger.log({path: 'debug----getAuthInfo',taskInfo,@@ -203,7 +221,7 @@ export class KwaiService extends PlatformBaseService {accessTokenInfo.expires_in = accessTokenInfo.expires_in + getCurrentTimestamp() - KWAI_TIME_CONSTANTS.TOKEN_REFRESH_MARGINaccessTokenInfo.refresh_token_expires_in = accessTokenInfo.refresh_token_expires_in + getCurrentTimestamp() - KWAI_TIME_CONSTANTS.TOKEN_REFRESH_MARGINconst cached = await this.redisService.setJson(- `${this.platform.toLowerCase()}:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('kwai', accountId),accessTokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -329,6 +347,7 @@ export class KwaiService extends PlatformBaseService {}async getAccessTokenStatus(accountId: string) {+ await this.ensureLocalAccount(accountId)const tokenInfo = await this.getOAuth2Credential(accountId)if (!tokenInfo) {this.updateAccountStatus(accountId, 0)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/base.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/base.service.tsindex 7cf2790c..f31f7f05 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/base.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/base.service.ts@@ -3,9 +3,10 @@ import { PublishType } from '@yikart/aitoearn-server-client'import { AccountType, AppException, ResponseCode } from '@yikart/common'import { RedisService } from '@yikart/redis'import { getCurrentTimestamp } from '../../../../common/utils/time.util'+import { ChannelRedisKeys } from '../../channel.constants'import { PlatformBaseService } from '../base.service'import { PlatformAuthExpiredException } from '../platform.exception'-import { META_TIME_CONSTANTS, MetaRedisKeys } from './constants'+import { META_TIME_CONSTANTS } from './constants'import { MetaUserOAuthCredential } from './meta.interfaces'@Injectable()@@ -21,9 +22,9 @@ export class MetaBaseService extends PlatformBaseService {}protected async getOAuth2Credential(accountId: string): Promise<MetaUserOAuthCredential | null> {- let key = MetaRedisKeys.getAccessTokenKey(this.platform, accountId)+ let key = ChannelRedisKeys.accessToken(this.platform, accountId)if (this.platform === AccountType.FACEBOOK) {- key = MetaRedisKeys.getUserPageAccessTokenKey(AccountType.FACEBOOK, accountId)+ key = ChannelRedisKeys.pageAccessToken(AccountType.FACEBOOK, accountId)}let credential = await this.redisService.getJson<MetaUserOAuthCredential>(key)if (!credential) {@@ -50,7 +51,7 @@ export class MetaBaseService extends PlatformBaseService {= now + tokenInfo.expires_in - META_TIME_CONSTANTS.TOKEN_REFRESH_MARGINtokenInfo.expires_in = expireTimeconst cached = await this.redisService.setJson(- MetaRedisKeys.getAccessTokenKey(platform, accountId),+ ChannelRedisKeys.accessToken(platform, accountId),tokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -73,6 +74,7 @@ export class MetaBaseService extends PlatformBaseService {override async getAccessTokenStatus(accountId: string,): Promise<number> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {this.updateAccountStatus(accountId, 0)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/constants.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/constants.tsindex 097af195..4d489256 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/constants.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/constants.ts@@ -3,27 +3,7 @@ import { InstagramOAuth2Config } from '../../libs/instagram/constants'import { LinkedinOAuth2Config } from '../../libs/linkedin/constants'import { ThreadsOAuth2Config } from '../../libs/threads/constants'-export class MetaRedisKeys {- private static readonly PREFIX = 'meta:'-- static getAuthTaskKey(state: string): string {- return `${this.PREFIX}auth_task:${state}`- }-- static getAccessTokenKey(platform: string, accountId: string): string {- return `${platform}:access_token:${accountId}`- }-- static getUserPageAccessTokenKey(platform: string, pageId: string): string {- return `${platform}:page:access_token:${pageId}`- }-- static getUserPageListKey(platform: string, accountId: string): string {- return `${platform}:user_page_list:${accountId}`- }-}--// thresholds for twitter oAuth+// thresholds for meta oAuthexport const META_TIME_CONSTANTS = {AUTH_TASK_EXPIRE: 5 * 60, // for oauth taskAUTH_TASK_EXTEND: 3 * 60, // extend oauth taskdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/facebook.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/facebook.service.tsindex 40574adc..8b7ec882 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/facebook.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/facebook.service.ts@@ -3,6 +3,7 @@ import { PublishType } from '@yikart/aitoearn-server-client'import { AccountType, AppException, ResponseCode } from '@yikart/common'import axios, { AxiosResponse } from 'axios'import { getCurrentTimestamp } from '../../../../common/utils/time.util'+import { ChannelRedisKeys } from '../../channel.constants'import {ChunkedVideoUploadRequest,ChunkedVideoUploadResponse,@@ -42,7 +43,7 @@ import {import { FacebookService as FacebookAPIService } from '../../libs/facebook/facebook.service'import { PlatformAuthExpiredException } from '../platform.exception'import { MetaBaseService } from './base.service'-import { META_TIME_CONSTANTS, metaOAuth2ConfigMap, MetaRedisKeys } from './constants'+import { META_TIME_CONSTANTS, metaOAuth2ConfigMap } from './constants'import { FacebookAccountResponse, FacebookPageCredentials, MetaFacebookPageResponse, MetaUserOAuthCredential } from './meta.interfaces'@Injectable()@@ -59,6 +60,7 @@ export class FacebookService extends MetaBaseService {private async authorize(accountId: string,): Promise<MetaUserOAuthCredential | null> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {throw new PlatformAuthExpiredException(this.platform, accountId)@@ -145,7 +147,7 @@ export class FacebookService extends MetaBaseService {newPageCredential = credential}await this.redisService.setJson(- MetaRedisKeys.getUserPageAccessTokenKey(+ ChannelRedisKeys.pageAccessToken('facebook',fbAccount.id,),diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/instagram.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/instagram.service.tsindex 359041d0..c4517065 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/instagram.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/instagram.service.ts@@ -38,6 +38,7 @@ export class InstagramService extends MetaBaseService {private async authorize(accountId: string,): Promise<MetaUserOAuthCredential> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {throw new PlatformAuthExpiredException(this.platform, accountId)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/linkedin.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/linkedin.service.tsindex bd6441bb..a25c7c47 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/linkedin.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/linkedin.service.ts@@ -23,6 +23,7 @@ export class LinkedinService extends MetaBaseService {private async authorize(accountId: string,): Promise<MetaUserOAuthCredential | null> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {throw new PlatformAuthExpiredException(this.platform, accountId)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.controller.tsindex 8db9e7dd..8eb3a57a 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.controller.ts@@ -1,4 +1,4 @@-import { Body, Controller, Get, Logger, Param, Post, Query, Render, Res } from '@nestjs/common'+import { Body, Controller, Get, Logger, Param, Post, Query, Res } from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc } from '@yikart/common'@@ -54,6 +54,8 @@ export class MetaController {data.platform,data.scopes,data.spaceId || '',+ data.callbackUrl,+ data.callbackMethod,)}@@ -96,14 +98,20 @@ export class MetaController {query: CreateAccountAndSetAccessTokenSchema,})@Get('/auth/back')- @Render('auth/meta')async createAccountAndSetAccessToken(@Query() query: CreateAccountAndSetAccessTokenDto,+ @Res() res: Response,) {- return await this.metaService.postOAuth2Callback(query.state, {+ const result = await this.metaService.postOAuth2Callback(query.state, {code: query.code,state: query.state,})++ if (result && 'callbackUrl' in result && result.callbackUrl) {+ return res.render('auth/back', { ...result, autoPostCallback: true })+ }++ return res.render('auth/meta', result ?? {})}@Public()diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.dto.tsindex f23ce538..7aa83d46 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.dto.ts@@ -32,6 +32,8 @@ export const GetAuthUrlBodySchema = z.object({scopes: z.array(z.string()).optional().describe('授权 scopes'),spaceId: z.string().optional().describe('空间ID'),platform: z.string().describe('平台标识'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlBodyDto extends createZodDto(GetAuthUrlBodySchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.interfaces.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.interfaces.tsindex d5f996b4..829a61a2 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.interfaces.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.interfaces.ts@@ -7,6 +7,8 @@ export interface MetaOAuth2TaskInfo {status: 0 | 1accountId?: stringspaceId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}export interface MetaOAuth2TaskStatus extends Partial<MetaOAuth2TaskInfo> {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.service.tsindex 815ffa8a..514e97b0 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/meta.service.ts@@ -11,6 +11,8 @@ import { RedisService } from '@yikart/redis'import axios, { AxiosRequestConfig, AxiosResponse, isAxiosError } from 'axios'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import {FacebookPageDetailRequest,FacebookPageDetailResponse,@@ -19,7 +21,6 @@ import { ChannelAccountService } from '../channel-account.service'import {META_TIME_CONSTANTS,metaOAuth2ConfigMap,- MetaRedisKeys,} from './constants'import {FacebookAccountResponse,@@ -55,11 +56,16 @@ export class MetaService {platform: string,oAuth2Scopes?: string[],spaceId = '',+ callbackUrl?: string,+ callbackMethod?: 'GET' | 'POST',) {this.logger.log(`Generating authorize URL for userId: ${userId}, platform: ${platform}}`,)const oauthConfig = config.channel.oauth[platform as keyof typeof config.channel.oauth]+ if (!oauthConfig.clientId && config.relay) {+ throw new RelayAuthException()+ }const scopes= oAuth2Scopes|| oauthConfig.scopes@@ -96,7 +102,7 @@ export class MetaService {this.logger.debug(`Generated meta auth URL: ${authorizeURL.toString()}`)const success = await this.redisService.setJson(- MetaRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('meta', state),{state,status: 0,@@ -104,6 +110,8 @@ export class MetaService {pkce: false,platform,spaceId,+ callbackUrl,+ callbackMethod,},META_TIME_CONSTANTS.AUTH_TASK_EXPIRE,)@@ -358,7 +366,7 @@ export class MetaService {async getOAuth2TaskInfo(state: string) {const result = await this.redisService.getJson<MetaOAuth2TaskStatus>(- MetaRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('meta', state),)if (!result) {this.logger.warn(`OAuth2 task not found for state: ${state}`)@@ -502,7 +510,7 @@ export class MetaService {}async getFacebookPageList(userId: string): Promise<FacebookPage[]> {- const key = MetaRedisKeys.getUserPageListKey('facebook', userId)+ const key = ChannelRedisKeys.userPageList('facebook', userId)const pages = await this.redisService.getJson<FacebookPage[]>(key)if (pages) {return pages@@ -519,7 +527,7 @@ export class MetaService {message: '',selectedPageIds: [],}- const key = MetaRedisKeys.getUserPageListKey('facebook', userId)+ const key = ChannelRedisKeys.userPageList('facebook', userId)const pages = await this.redisService.getJson<FacebookPage[]>(key)if (!pages || pages.length === 0) {this.logger.warn(`No Facebook pages found for userId: ${userId}`)@@ -540,7 +548,7 @@ export class MetaService {result.message = `Page ID ${pageId} not found in user's Facebook pages`return result}- const pageCredentialKey = MetaRedisKeys.getUserPageAccessTokenKey(+ const pageCredentialKey = ChannelRedisKeys.pageAccessToken('facebook',pageId,)@@ -570,7 +578,7 @@ export class MetaService {result.message = `Failed to create account for userId: ${userId}, pageId: ${pageId}`return result}- const newPageCredentialKey = MetaRedisKeys.getUserPageAccessTokenKey(+ const newPageCredentialKey = ChannelRedisKeys.pageAccessToken('facebook',accountInfo.id,)@@ -586,11 +594,11 @@ export class MetaService {raw: JSON.stringify(pageCredential),},)- const previousFacebookCredentialKey = MetaRedisKeys.getAccessTokenKey(+ const previousFacebookCredentialKey = ChannelRedisKeys.accessToken('facebook',userId,)- const newFacebookCredentialKey = MetaRedisKeys.getAccessTokenKey(+ const newFacebookCredentialKey = ChannelRedisKeys.accessToken('facebook',pageCredential.facebook_user_id,)@@ -656,7 +664,7 @@ export class MetaService {const { code } = authDataconst authTaskInfo = await this.redisService.getJson<MetaOAuth2TaskInfo>(- MetaRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('meta', state),)if (!authTaskInfo) {this.logger.error(`OAuth task not found for state: ${state}`)@@ -667,7 +675,7 @@ export class MetaService {}void this.redisService.expire(- MetaRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('meta', state),META_TIME_CONSTANTS.AUTH_TASK_EXTEND,)@@ -731,7 +739,7 @@ export class MetaService {+ credential.expires_in- META_TIME_CONSTANTS.TOKEN_REFRESH_MARGINawait this.redisService.setJson(- MetaRedisKeys.getUserPageAccessTokenKey(+ ChannelRedisKeys.pageAccessToken(authTaskInfo.platform,pageAccount.id,),@@ -749,7 +757,7 @@ export class MetaService {})}await this.redisService.setJson(- MetaRedisKeys.getUserPageListKey(+ ChannelRedisKeys.userPageList(authTaskInfo.platform,authTaskInfo.userId,),@@ -803,7 +811,17 @@ export class MetaService {)return null}- return accountInfo+ return {+ status: 1,+ accountId: accountInfo.id,+ nickname: accountInfo.nickname,+ avatar: accountInfo.avatar,+ platformUid: accountInfo.uid,+ accountType: accountInfo.type,+ callbackUrl: authTaskInfo?.callbackUrl,+ callbackMethod: authTaskInfo.callbackMethod,+ taskId: state,+ }}catch (error) {if (isAxiosError(error) && error.response) {@@ -871,7 +889,7 @@ export class MetaService {= now + tokenInfo.expires_in - META_TIME_CONSTANTS.TOKEN_REFRESH_MARGINtokenInfo.expires_in = expireTimeconst cached = await this.redisService.setJson(- MetaRedisKeys.getAccessTokenKey(platform, accountId),+ ChannelRedisKeys.accessToken(platform, accountId),tokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -900,16 +918,16 @@ export class MetaService {authTaskInfo.accountId = accountIdreturn await this.redisService.setJson(- MetaRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('meta', state),authTaskInfo,META_TIME_CONSTANTS.AUTH_TASK_EXTEND,)}private async getOAuth2Credential(platform: string, accountId: string): Promise<MetaUserOAuthCredential | null> {- let key = MetaRedisKeys.getAccessTokenKey(platform, accountId)+ let key = ChannelRedisKeys.accessToken(platform, accountId)if (platform === 'facebook') {- key = MetaRedisKeys.getUserPageAccessTokenKey('facebook', accountId)+ key = ChannelRedisKeys.pageAccessToken('facebook', accountId)}let credential = await this.redisService.getJson<MetaUserOAuthCredential>(key)if (!credential) {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/threads.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/threads.service.tsindex feacc59e..825cd689 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/threads.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/meta/threads.service.ts@@ -35,6 +35,7 @@ export class ThreadsService extends MetaBaseService {private async authorize(accountId: string,): Promise<MetaUserOAuthCredential> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {throw new PlatformAuthExpiredException(this.platform, accountId)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.controller.tsindex 16ac9e97..3545ce9d 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.controller.ts@@ -122,8 +122,10 @@ export class PinterestController {async getAuth(@GetToken() token: TokenInfo,@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {- return await this.pinterestService.getAuth(token.id, spaceId || '')+ return await this.pinterestService.getAuth(token.id, spaceId || '', callbackUrl, callbackMethod)}@ApiDoc({@@ -144,6 +146,9 @@ export class PinterestController {@Get('/authWebhook')async authWebhook(@Query() query: { code?: string, state?: string }, @Res() res: Response) {const result = await this.pinterestService.authWebhook(query)+ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', { ...result, autoPostCallback: true })+ }return res.render('auth/back', result)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.service.tsindex 2f618648..a4c07e96 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/pinterest/pinterest.service.ts@@ -9,6 +9,8 @@ import * as _ from 'lodash'import { v4 as uuidv4 } from 'uuid'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import {AuthInfo,CreateBoardBody,@@ -39,14 +41,6 @@ export class PinterestService extends PlatformBaseService {super()}- private getAuthDataCacheKey(taskId: string) {- return `channel:pinterest:authTask:${taskId}`- }-- private getAccessTokenKey(id: string) {- return `pinterest:accessToken:${id}`- }-private async saveOAuthCredential(accountId: string, tokenInfo: {access_token: stringrefresh_token?: string@@ -66,7 +60,7 @@ export class PinterestService extends PlatformBaseService {expires_in: accessTokenExpiresAt,refresh_token_expires_in: refreshTokenExpiresAt,}- const cached = await this.redisService.setJson(this.getAccessTokenKey(accountId), cacheData)+ const cached = await this.redisService.setJson(ChannelRedisKeys.accessToken('pinterest', accountId), cacheData)const persistResult = await this.oauth2CredentialRepository.upsertOne(accountId,@@ -84,7 +78,7 @@ export class PinterestService extends PlatformBaseService {}private async getOAuth2Credential(accountId: string): Promise<AuthInfo | null> {- let credential = await this.redisService.getJson<AuthInfo>(this.getAccessTokenKey(accountId))+ let credential = await this.redisService.getJson<AuthInfo>(ChannelRedisKeys.accessToken('pinterest', accountId))if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(accountId,@@ -314,14 +308,17 @@ export class PinterestService extends PlatformBaseService {* @param userId userId* @returns*/- async getAuth(userId: string, spaceId = '') {+ async getAuth(userId: string, spaceId = '', callbackUrl?: string, callbackMethod?: 'GET' | 'POST') {+ if (!config.channel.pinterest.id && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidv4().replace(/-/g, '')- const redisKeyByTaskId = this.getAuthDataCacheKey(taskId)+ const redisKeyByTaskId = ChannelRedisKeys.authTask('pinterest', taskId)const scope= 'scope=boards:read,boards:write,pins:write,pins:read,catalogs:read,catalogs:write,pins:write_secret,pins:read_secret,user_accounts:read'const path = `response_type=code&redirect_uri=${this.redirectURL}&client_id=${this.client_id}&${scope}&state=${taskId}`const uri = `https://www.pinterest.com/oauth/?${path}`- const tokenInfo = { taskId, userId, status: ILoginStatus.wait, spaceId }+ const tokenInfo = { taskId, userId, status: ILoginStatus.wait, spaceId, callbackUrl, callbackMethod }await this.redisService.setJson(redisKeyByTaskId, tokenInfo, 60 * 5)return { taskId, userId, status: ILoginStatus.wait, uri }}@@ -334,7 +331,7 @@ export class PinterestService extends PlatformBaseService {const userInfo= await this.pinterestApiService.getAccountInfo(access_token)// 获取到token后第一时间创建account信息- const redisKeyByTaskId = this.getAuthDataCacheKey(state || '')+ const redisKeyByTaskId = ChannelRedisKeys.authTask('pinterest', state || '')const redisCache= await this.redisService.getJson<AuthInfo & { spaceId?: string }>(redisKeyByTaskId)if (!redisCache) {@@ -399,6 +396,13 @@ export class PinterestService extends PlatformBaseService {status: 1,message: '授权成功',accountId: accountInfo.id,+ nickname: accountInfo.nickname,+ avatar: accountInfo.avatar,+ platformUid: accountInfo.uid,+ accountType: AccountType.PINTEREST,+ callbackUrl: redisCache.callbackUrl,+ callbackMethod: redisCache.callbackMethod,+ taskId: state,}}catch (error) {@@ -416,7 +420,7 @@ export class PinterestService extends PlatformBaseService {* @returns*/async checkAuth(taskId: string) {- const redisKeyByTaskId = this.getAuthDataCacheKey(taskId)+ const redisKeyByTaskId = ChannelRedisKeys.authTask('pinterest', taskId)const tokenInfo: AuthInfo | null= await this.redisService.getJson<AuthInfo>(redisKeyByTaskId)if (_.isEmpty(tokenInfo))@@ -426,6 +430,7 @@ export class PinterestService extends PlatformBaseService {}async getAccessToken(accountId: string) {+ await this.ensureLocalAccount(accountId)const credential = await this.authorize(accountId)if (!credential || !credential.access_token) {throw new AppException(ResponseCode.ChannelAuthorizationExpired)@@ -635,6 +640,7 @@ export class PinterestService extends PlatformBaseService {}async getAccessTokenStatus(accountId: string) {+ await this.ensureLocalAccount(accountId)const tokenInfo = await this.getOAuth2Credential(accountId)if (_.isEmpty(tokenInfo) || !tokenInfo?.expires_in) {this.updateAccountStatus(accountId, 0)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/platforms.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/platforms.service.tsindex 3d3d3057..6b22cf4b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/platforms.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/platforms.service.ts@@ -1,6 +1,9 @@import { Inject, Injectable, Logger } from '@nestjs/common'import { AccountStatus } from '@yikart/channel-db'import { AccountType, AppException, ResponseCode } from '@yikart/common'+import { BatchAccountStatusVo } from '../../account/account.vo'+import { RelayAccountException } from '../../relay/relay-account.exception'+import { RelayClientService } from '../../relay/relay-client.service'import { SocialMediaError } from '../libs/exception/base'import { PlatformBaseService, WorkDetailInfo } from './base.service'import { ChannelAccountService } from './channel-account.service'@@ -11,15 +14,22 @@ export class PlatformService {@Inject('CHANNEL_PROVIDERS')private readonly platformServices: Record<AccountType, PlatformBaseService>- @Inject(ChannelAccountService)+ @Inject()private readonly channelAccountService: ChannelAccountService+ @Inject()+ private readonly relayClientService: RelayClientService+async getUserAccounts(userId: string) {const accounts = await this.channelAccountService.getUserAccountList(userId)if (!accounts || accounts.length === 0) {return []}- for (const account of accounts) {++ const relayAccounts = accounts.filter(a => a.relayAccountRef)+ const localAccounts = accounts.filter(a => !a.relayAccountRef)++ for (const account of localAccounts) {const svc = this.platformServices[account.type]if (svc) {try {@@ -27,14 +37,41 @@ export class PlatformService {account.status = status}catch (error) {+ if (error instanceof RelayAccountException) {+ throw error+ }this.logger.error(`user:[${userId}] -- ${account.type} get access token status failed: ${error}`)account.status = AccountStatus.ABNORMAL}}}++ if (relayAccounts.length > 0 && this.relayClientService.enabled) {+ await this.fetchRelayAccountStatuses(relayAccounts)+ }+return accounts}+ private async fetchRelayAccountStatuses(relayAccounts: { _id: any, relayAccountRef: string | null, type: AccountType, status: number }[]) {+ try {+ const accountIds = relayAccounts.map(a => a.relayAccountRef).filter(Boolean) as string[]+ const result = await this.relayClientService.post<BatchAccountStatusVo>('/account/batch-status', { accountIds })+ const statusMap = result.statuses ?? {}+ for (const account of relayAccounts) {+ if (account.relayAccountRef && statusMap[account.relayAccountRef] !== undefined) {+ account.status = statusMap[account.relayAccountRef]+ }+ }+ }+ catch (error) {+ this.logger.error(`Fetch relay account statuses failed: ${error}`)+ for (const account of relayAccounts) {+ account.status = AccountStatus.ABNORMAL+ }+ }+ }+getWorkLinkInfo(accountType: AccountType, workLink: string, dataId?: string, accountId?: string) {const svc = this.platformServices[accountType]if (svc) {@@ -62,6 +99,14 @@ export class PlatformService {}}+ async getAccountTokenStatus(accountId: string, accountType: AccountType): Promise<number> {+ const svc = this.platformServices[accountType]+ if (!svc) {+ throw new AppException(ResponseCode.PlatformNotSupported)+ }+ return await svc.getAccessTokenStatus(accountId)+ }+async updateAccountStatus(accountId: string, status: number) {const res = await this.channelAccountService.updateAccountStatus(accountId, status)return resdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/constants.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/constants.tsindex 34e8cb63..9bc4ef1b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/constants.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/constants.ts@@ -6,27 +6,6 @@* @Description: TikTok模块常量定义*/-/**- * TikTok Redis键管理类- */-export class TiktokRedisKeys {- private static readonly PREFIX = 'tiktok:'-- /**- * 获取授权任务键- */- static getAuthTaskKey(taskId: string): string {- return `${this.PREFIX}auth_task:${taskId}`- }-- /**- * 获取访问令牌键- */- static getAccessTokenKey(accountId: string): string {- return `${this.PREFIX}access_token:${accountId}`- }-}-// 时间常量(秒)export const TIKTOK_TIME_CONSTANTS = {AUTH_TASK_EXPIRE: 5 * 60, // 认证任务过期时间:5分钟diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.controller.tsindex 8909a606..aecd76aa 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.controller.ts@@ -51,6 +51,8 @@ export class TiktokController {userId: token.id,scopes: data.scopes,spaceId: data.spaceId,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,})}@@ -117,6 +119,14 @@ export class TiktokController {data.state,{ code: data.code, state: data.state },)++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })+ }+return res.render('auth/back', result)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.dto.tsindex 4d7e3d7a..50f328eb 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.dto.ts@@ -72,7 +72,9 @@ const GetAuthUrlSchema = z.object({userId: z.string().optional(),spaceId: z.string().optional(),scopes: z.array(z.string()).optional(),- taskId: z.string().optional(), // 广告主推广任务ID+ taskId: z.string().optional().describe('广告主推广任务ID'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.service.tsindex 75a1f3b8..02b4ccad 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/tiktok/tiktok.service.ts@@ -5,6 +5,8 @@ import { AppException, ResponseCode } from '@yikart/common'import { RedisService } from '@yikart/redis'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { TiktokPostMode, TiktokPrivacyLevel, TiktokSourceType } from '../../libs/tiktok/tiktok.enum'import {TiktokCreatorInfo,@@ -20,7 +22,7 @@ import { TiktokService as TiktokApiService } from '../../libs/tiktok/tiktok.servimport { PlatformBaseService } from '../base.service'import { ChannelAccountService } from '../channel-account.service'import { PlatformAuthExpiredException } from '../platform.exception'-import { TIKTOK_DEFAULT_SCOPES, TIKTOK_TIME_CONSTANTS, TiktokRedisKeys } from './constants'+import { TIKTOK_DEFAULT_SCOPES, TIKTOK_TIME_CONSTANTS } from './constants'import {PhotoSourceInfoDto,PostInfoDto,@@ -37,6 +39,9 @@ export interface AuthTaskInfo {// QR Code 授权相关taskId?: string // 推广任务IDqrToken?: string // QR Code token+ // 通用 OAuth 回调+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}export interface NoUserAuthInfo {@@ -167,7 +172,13 @@ export class TiktokService extends PlatformBaseService {scopes?: string[]spaceId?: stringtaskId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}) {+ if (!config.channel.tiktok.clientId && config.relay) {+ throw new RelayAuthException()+ }+const state = randomBytes(32).toString('hex')const requestedScopes = data.scopes || this.defaultScopes@@ -179,10 +190,12 @@ export class TiktokService extends PlatformBaseService {userId: data.userId,spaceId: data.spaceId,taskId: data.taskId,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,}const success = await this.redisService.setJson(- TiktokRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('tiktok', state),authTaskInfo,TIKTOK_TIME_CONSTANTS.AUTH_TASK_EXPIRE,)@@ -206,7 +219,7 @@ export class TiktokService extends PlatformBaseService {: 0const cached = await this.redisService.setJson(- TiktokRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('tiktok', accountId),accessTokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -224,7 +237,7 @@ export class TiktokService extends PlatformBaseService {private async getOAuth2Credential(accountId: string): Promise<TiktokOAuthResponse | null> {let credential = await this.redisService.getJson<TiktokOAuthResponse>(- TiktokRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('tiktok', accountId),)if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -252,7 +265,7 @@ export class TiktokService extends PlatformBaseService {*/async getAuthInfo(taskId: string) {const result = await this.redisService.getJson<AuthTaskInfo>(- TiktokRedisKeys.getAuthTaskKey(taskId),+ ChannelRedisKeys.authTask('tiktok', taskId),)if (!result) {this.logger.warn(`OAuth2 task not found for taskId: ${taskId}`)@@ -274,7 +287,7 @@ export class TiktokService extends PlatformBaseService {const { code } = authDataconst authTaskInfo = await this.redisService.getJson<AuthTaskInfo>(- TiktokRedisKeys.getAuthTaskKey(taskId),+ ChannelRedisKeys.authTask('tiktok', taskId),)if (!authTaskInfo) {return {@@ -285,7 +298,7 @@ export class TiktokService extends PlatformBaseService {// 延长授权任务时间void this.redisService.expire(- TiktokRedisKeys.getAuthTaskKey(taskId),+ ChannelRedisKeys.authTask('tiktok', taskId),TIKTOK_TIME_CONSTANTS.AUTH_TASK_EXTEND,)@@ -349,22 +362,32 @@ export class TiktokService extends PlatformBaseService {accountInfo.id,)- return taskUpdated- ? {- status: 1,- message: '授权成功',- accountId: accountInfo.id,- }- : {- status: 0,- message: '更新任务状态失败',- }+ if (!taskUpdated) {+ return {+ status: 0,+ message: '更新任务状态失败',+ }+ }++ return {+ status: 1,+ message: '授权成功',+ accountId: accountInfo.id,+ callbackUrl: authTaskInfo.callbackUrl,+ callbackMethod: authTaskInfo.callbackMethod,+ taskId,+ nickname: userInfo.data.user.display_name || userInfo.data.user.username,+ avatar: userInfo.data.user.avatar_url,+ platformUid: accessTokenInfo.open_id,+ accountType: AccountType.TIKTOK,+ }}/*** 获取有效的访问令牌*/private async getValidAccessToken(accountId: string): Promise<string> {+ await this.ensureLocalAccount(accountId)let tokenInfo = await this.getOAuth2Credential(accountId)if (!tokenInfo) {throw new PlatformAuthExpiredException(this.platform, accountId)@@ -419,7 +442,7 @@ export class TiktokService extends PlatformBaseService {const accessToken = await this.getValidAccessToken(accountId)const result = await this.tiktokApiService.revokeAccessToken(accessToken)- await this.redisService.del(TiktokRedisKeys.getAccessTokenKey(accountId))+ await this.redisService.del(ChannelRedisKeys.accessToken('tiktok', accountId))return result}@@ -539,7 +562,7 @@ export class TiktokService extends PlatformBaseService {tokenInfo.expires_in = now + tokenInfo.expires_in - TIKTOK_TIME_CONSTANTS.TOKEN_EXPIRE_BUFFERtokenInfo.refresh_expires_in = now + tokenInfo.refresh_expires_in - TIKTOK_TIME_CONSTANTS.TOKEN_REFRESH_THRESHOLDreturn await this.redisService.setJson(- TiktokRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('tiktok', accountId),tokenInfo,)}@@ -556,7 +579,7 @@ export class TiktokService extends PlatformBaseService {authTaskInfo.accountId = accountIdreturn await this.redisService.setJson(- TiktokRedisKeys.getAuthTaskKey(taskId),+ ChannelRedisKeys.authTask('tiktok', taskId),authTaskInfo,TIKTOK_TIME_CONSTANTS.AUTH_TASK_EXTEND,)@@ -613,6 +636,7 @@ export class TiktokService extends PlatformBaseService {}async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const tokenInfo = await this.getOAuth2Credential(accountId)if (!tokenInfo) {this.updateAccountStatus(accountId, 0)@@ -718,7 +742,7 @@ export class TiktokService extends PlatformBaseService {}const success = await this.redisService.setJson(- TiktokRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('tiktok', state),authTaskInfo,TIKTOK_TIME_CONSTANTS.AUTH_TASK_EXPIRE,)@@ -737,7 +761,7 @@ export class TiktokService extends PlatformBaseService {*/async checkQRCodeAuthStatus(taskId: string) {const authTaskInfo = await this.redisService.getJson<AuthTaskInfo>(- TiktokRedisKeys.getAuthTaskKey(taskId),+ ChannelRedisKeys.authTask('tiktok', taskId),)if (!authTaskInfo || !authTaskInfo.qrToken) {return { status: 'expired' as const, message: '授权任务不存在或已过期' }diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/constants.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/constants.tsindex e2bb06c2..2e18972c 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/constants.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/constants.ts@@ -1,16 +1,3 @@-// copy from tiktok constants, keep the same thresholds-export class TwitterRedisKeys {- private static readonly PREFIX = 'twitter:'-- static getAuthTaskKey(state: string): string {- return `${this.PREFIX}auth_task:${state}`- }-- static getAccessTokenKey(accountId: string): string {- return `${this.PREFIX}access_token:${accountId}`- }-}-// thresholds for twitter oAuthexport const TWITTER_TIME_CONSTANTS = {AUTH_TASK_EXPIRE: 5 * 60, // for oauth taskdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.controller.tsindex 53d6f29f..0f18541b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.controller.ts@@ -21,11 +21,13 @@ export class TwitterController {})@Post('/auth/url')async getAuthUrl(@GetToken() token: TokenInfo, @Body() data: GetAuthUrlDto) {- return await this.twitterService.generateAuthorizeURL(- token.id,- data.scopes,- data.spaceId,- )+ return await this.twitterService.generateAuthorizeURL({+ userId: token.id,+ scopes: data.scopes,+ spaceId: data.spaceId,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,+ })}@ApiDoc({@@ -60,6 +62,14 @@ export class TwitterController {code: data.code,state: data.state,})++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', {+ ...result,+ autoPostCallback: true,+ })+ }+return res.render('auth/back', result)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.dto.tsindex 557a9d7c..998a2f70 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.dto.ts@@ -4,6 +4,8 @@ import z from 'zod'const GetAuthUrlSchema = z.object({scopes: z.array(z.string()).optional().describe('OAuth 权限范围'),spaceId: z.string().optional().describe('空间 ID'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.interfaces.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.interfaces.tsindex 0a3ef8f0..9bf0bd7d 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.interfaces.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.interfaces.ts@@ -6,4 +6,6 @@ export interface TwitterOAuthTaskInfo {accountId?: stringspaceId?: stringtaskId: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.service.tsindex 1f822de2..07bee0f0 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/twitter/twitter.service.ts@@ -7,13 +7,16 @@ import { isAxiosError } from 'axios'import { v4 as uuidV4 } from 'uuid'import { chunkedDownloadFile, fileUrlToBlob, getFileSizeFromUrl, getFileTypeFromUrl } from '../../../../common/utils/file.util'import { getCurrentTimestamp } from '../../../../common/utils/time.util'+import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { XMediaCategory, XMediaType } from '../../libs/twitter/twitter.enum'import { TwitterOAuthCredential, XChunkedMediaUploadRequest, XCreatePostRequest, XCreatePostResponse, XLikePostResponse, XMediaUploadInitRequest, XMediaUploadResponse, XPostDetailResponse, XRePostResponse, XUserTimelineRequest } from '../../libs/twitter/twitter.interfaces'import { TwitterService as TwitterApiService } from '../../libs/twitter/twitter.service'import { PlatformBaseService } from '../base.service'import { ChannelAccountService } from '../channel-account.service'import { PlatformAuthExpiredException } from '../platform.exception'-import { TWITTER_TIME_CONSTANTS, TwitterRedisKeys } from './constants'+import { TWITTER_TIME_CONSTANTS } from './constants'import { UserTimelineDto } from './twitter.dto'import { TwitterOAuthTaskInfo } from './twitter.interfaces'@@ -61,7 +64,7 @@ export class TwitterService extends PlatformBaseService {private async saveOAuthCredential(accountId: string, accessTokenInfo: TwitterOAuthCredential) {accessTokenInfo.expires_in = accessTokenInfo.expires_in + getCurrentTimestamp() - TWITTER_TIME_CONSTANTS.TOKEN_REFRESH_MARGINconst cached = await this.redisService.setJson(- TwitterRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('twitter', accountId),accessTokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -78,7 +81,7 @@ export class TwitterService extends PlatformBaseService {private async getOAuth2Credential(accountId: string): Promise<TwitterOAuthCredential | null> {let credential = await this.redisService.getJson<TwitterOAuthCredential>(- TwitterRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('twitter', accountId),)if (!credential) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -100,6 +103,7 @@ export class TwitterService extends PlatformBaseService {private async authorize(accountId: string,): Promise<TwitterOAuthCredential> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {throw new PlatformAuthExpiredException(this.platform, accountId)@@ -148,19 +152,38 @@ export class TwitterService extends PlatformBaseService {}}- async generateAuthorizeURL(userId: string, scopes?: string[], spaceId = '') {+ async generateAuthorizeURL(data: {+ userId: string+ scopes?: string[]+ spaceId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'+ }) {+ if (!config.channel.twitter.clientId && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidV4()const codeVerifier = randomBytes(64).toString('hex')const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url')const state = randomBytes(32).toString('hex')+ const authTaskInfo: TwitterOAuthTaskInfo = {+ state,+ status: 0,+ userId: data.userId,+ codeVerifier,+ taskId,+ spaceId: data.spaceId,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,+ }const success = await this.redisService.setJson(- TwitterRedisKeys.getAuthTaskKey(state),- { state, status: 0, userId, codeVerifier, taskId, spaceId },+ ChannelRedisKeys.authTask('twitter', state),+ authTaskInfo,TWITTER_TIME_CONSTANTS.AUTH_TASK_EXPIRE,)- scopes = scopes || this.defaultScopes+ const scopes = data.scopes || this.defaultScopesconst authorizeURL = this.twitterApiService.generateAuthorizeURL(scopes,state,@@ -171,7 +194,7 @@ export class TwitterService extends PlatformBaseService {async getOAuth2TaskInfo(state: string) {return await this.redisService.getJson<TwitterOAuthTaskInfo>(- TwitterRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('twitter', state),)}@@ -192,7 +215,7 @@ export class TwitterService extends PlatformBaseService {// 延长授权任务时间void this.redisService.expire(- TwitterRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('twitter', state),TWITTER_TIME_CONSTANTS.AUTH_TASK_EXTEND,)@@ -281,6 +304,13 @@ export class TwitterService extends PlatformBaseService {status: 1,message: '授权成功',accountId: accountInfo.id,+ callbackUrl: authTaskInfo.callbackUrl,+ callbackMethod: authTaskInfo.callbackMethod,+ taskId: state,+ nickname: userRes.data.name,+ avatar: userRes.data.profile_image_url,+ platformUid: userRes.data.id,+ accountType: AccountType.TWITTER,}}@@ -293,7 +323,7 @@ export class TwitterService extends PlatformBaseService {authTaskInfo.accountId = accountIdreturn await this.redisService.setJson(- TwitterRedisKeys.getAuthTaskKey(state),+ ChannelRedisKeys.authTask('twitter', state),authTaskInfo,TWITTER_TIME_CONSTANTS.AUTH_TASK_EXTEND,)@@ -310,7 +340,7 @@ export class TwitterService extends PlatformBaseService {)if (result.revoked) {await this.redisService.del(- TwitterRedisKeys.getAccessTokenKey(accountId),+ ChannelRedisKeys.accessToken('twitter', accountId),)return true}@@ -693,6 +723,7 @@ export class TwitterService extends PlatformBaseService {}async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential) {this.logger.warn(`No access token found for twitter accountId: ${accountId}`)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-gzh.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-gzh.controller.tsindex 3366f080..f4c7bb80 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-gzh.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-gzh.controller.ts@@ -22,9 +22,11 @@ export class WxGzhController {@GetToken() token: TokenInfo,@Param('type') type: 'h5' | 'pc',@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {const res = await this.wxPlatService.createAuthTask(- { userId: token.id, type, spaceId: spaceId || '' },+ { userId: token.id, type, spaceId: spaceId || '', callbackUrl, callbackMethod },)return {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.dto.tsindex b824ed44..6435dac2 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.dto.ts@@ -16,6 +16,8 @@ const GetAuthUrlSchema = UserIdSchema.extend({spaceId: z.string().describe('空间ID'),type: z.enum(['pc', 'h5']).describe('授权类型'),prefix: z.string().optional().describe('前缀'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.service.tsindex 7864e803..5958ce49 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/wx-plat/wx-plat.service.ts@@ -4,6 +4,8 @@ import { AppException, ResponseCode } from '@yikart/common'import { RedisService } from '@yikart/redis'import { v4 as uuidv4 } from 'uuid'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { WxPlatAuthorizerInfo } from '../../libs/my-wx-plat/comment'import { MyWxPlatApiService } from '../../libs/my-wx-plat/my-wx-plat.service'import { ChannelAccountService } from '../channel-account.service'@@ -24,10 +26,6 @@ export class WxPlatService {this.encodingAESKey = config.channel.wxPlat.encodingAESKey}- private getAuthDataCacheKey(taskId: string) {- return `channel:wxPlat:authTask:${taskId}`- }-// 公众号token缓存keyprivate getAuthAccessTokenCacheKey(accountId: string) {return `channel:wxPlat:authorizerAccessToken:${accountId}`@@ -50,12 +48,17 @@ export class WxPlatService {userId: stringtype: 'h5' | 'pc'spaceId: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'},options?: {transpond?: stringaccountAddPath?: string},) {+ if (!config.channel.wxPlat.id && config.relay) {+ throw new RelayAuthException()+ }const taskId = uuidv4()const authUrl = await this.getAuthPageUrl(data.type, taskId)@@ -63,7 +66,7 @@ export class WxPlatService {throw new AppException(ResponseCode.ChannelPlatformTokenNotFound)const rRes = await this.redisService.setJson(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('wx_gzh', taskId),{taskId,spaceId: data.spaceId,@@ -74,6 +77,8 @@ export class WxPlatService {userId: data.userId,},status: 0,+ callbackUrl: data.callbackUrl,+ callbackMethod: data.callbackMethod,},60 * 5,)@@ -90,7 +95,7 @@ export class WxPlatService {// 获取授权任务信息async getAuthTaskInfo(taskId: string) {const taskInfo = await this.redisService.getJson<AuthTaskInfo<WxPlatAuthInfo>>(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('wx_gzh', taskId),)return taskInfo@@ -139,7 +144,7 @@ export class WxPlatService {) {try {const taskInfo = await this.redisService.getJson<AuthTaskInfo<WxPlatAuthInfo>>(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('wx_gzh', taskId),)if (!taskInfo || !taskInfo.data)return { status: 0, message: '任务不存在或已完成' }@@ -148,17 +153,17 @@ export class WxPlatService {// 计算是否超时if (Date.now() - taskInfo.data.createTime > authData.expiresIn * 1000) {- void this.redisService.del(this.getAuthDataCacheKey(taskId))+ void this.redisService.del(ChannelRedisKeys.authTask('wx_gzh', taskId))return { status: 0, message: '任务已超时' }}// 延长授权时间- void this.redisService.expire(this.getAuthDataCacheKey(taskId), 60 * 3)+ void this.redisService.expire(ChannelRedisKeys.authTask('wx_gzh', taskId), 60 * 3)// 根据授权码获取授权信息const auth = await this.myWxPlatApiService.getQueryAuth(authData.authCode)if (!auth) {- void this.redisService.del(this.getAuthDataCacheKey(taskId))+ void this.redisService.del(ChannelRedisKeys.authTask('wx_gzh', taskId))return { status: 0, message: '获取授权信缓存失败' }}const { authorizer_appid, expires_in } = auth@@ -211,14 +216,21 @@ export class WxPlatService {taskInfo.data.accountId = accountInfo.idconst res = await this.redisService.setJson(- this.getAuthDataCacheKey(taskId),+ ChannelRedisKeys.authTask('wx_gzh', taskId),taskInfo,60 * 5,)if (!res)return { status: 0, message: '更新任务信息失败' }- return { status: 1, message: '添加账号成功', accountId: accountInfo.id }+ return {+ status: 1,+ message: '添加账号成功',+ accountId: accountInfo.id,+ callbackUrl: taskInfo.callbackUrl,+ callbackMethod: taskInfo.callbackMethod,+ taskId,+ }}catch (error) {this.logger.error('createAccountAndSetAccessToken error:', error)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.controller.tsindex a10c74fd..bcd0c44a 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.controller.ts@@ -57,6 +57,8 @@ export class YoutubeController {async getAuthUrl(@GetToken() token: TokenInfo,@Query('spaceId') spaceId?: string,+ @Query('callbackUrl') callbackUrl?: string,+ @Query('callbackMethod') callbackMethod?: 'GET' | 'POST',) {if (!token.mail) {throw new Error('缺少邮箱')@@ -66,6 +68,8 @@ export class YoutubeController {token.mail,undefined,spaceId || '',+ callbackUrl,+ callbackMethod,)}@@ -96,6 +100,11 @@ export class YoutubeController {taskId,query.code,)++ if (result.status === 1 && result.callbackUrl) {+ return res.render('auth/back', { ...result, autoPostCallback: true })+ }+return res.render('auth/back', result)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.dto.tsindex 65de6360..c9b7199a 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.dto.ts@@ -28,6 +28,8 @@ const GetAuthUrlSchema = UserIdSchema.extend({spaceId: z.string().describe('空间ID'),mail: z.email().describe('邮箱'),prefix: z.string().optional().describe('前缀'),+ callbackUrl: z.string().url().optional().describe('OAuth 完成后回调地址'),+ callbackMethod: z.enum(['GET', 'POST']).optional().describe('回调方式,默认 GET'),})export class GetAuthUrlDto extends createZodDto(GetAuthUrlSchema) {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.service.tsindex 777c1cfb..e5cac2f6 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/platforms/youtube/youtube.service.ts@@ -10,6 +10,8 @@ import { Auth, google, youtube_v3 } from 'googleapis'import { v4 as uuidv4 } from 'uuid'import { getCurrentTimestamp } from '../../../../common/utils/time.util'import { config } from '../../../../config'+import { RelayAuthException } from '../../../relay/relay-auth.exception'+import { ChannelRedisKeys } from '../../channel.constants'import { YoutubeApiService } from '../../libs/youtube/youtube-api.service'import { PlatformBaseService, WorkDetailInfo } from '../base.service'import { ChannelAccountService } from '../channel-account.service'@@ -28,6 +30,8 @@ interface AuthTaskInfo {type?: stringaccount?: stringspaceId?: string+ callbackUrl?: string+ callbackMethod?: 'GET' | 'POST'}@Injectable()@@ -72,7 +76,7 @@ export class YoutubeService extends PlatformBaseService {const { code } = dataconst authTask = await this.redisService.getJson<AuthTaskInfo>(- `youtube:authTask:${taskId}`,+ ChannelRedisKeys.authTask('youtube', taskId),)if (!authTask || authTask?.state !== taskId) {this.logger.error(`无效的任务ID: ${taskId}`)@@ -118,7 +122,7 @@ export class YoutubeService extends PlatformBaseService {// 缓存令牌let res = await this.redisService.setJson(- `youtube:accessToken:${accountInfo.id}`,+ ChannelRedisKeys.accessToken('youtube', accountInfo.id),{access_token,refresh_token,@@ -171,7 +175,7 @@ export class YoutubeService extends PlatformBaseService {authTask.accountId = accountInfo.idauthTask.mail = email || ''res = await this.redisService.setJson(- `youtube:authTask:${taskId}`,+ ChannelRedisKeys.authTask('youtube', taskId),authTask,60 * 3,)@@ -191,7 +195,7 @@ export class YoutubeService extends PlatformBaseService {private async saveOAuthCredential(accountId: string, accessTokenInfo: any) {accessTokenInfo.expires_in = getCurrentTimestamp() + accessTokenInfo.expires_inconst cached = await this.redisService.setJson(- `youtube:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('youtube', accountId),accessTokenInfo,)const persistResult = await this.oauth2CredentialRepository.upsertOne(@@ -209,7 +213,7 @@ export class YoutubeService extends PlatformBaseService {private async getOAuth2Credential(accountId: string): Promise<any | null> {let credential = await this.redisService.getJson<any>(- `youtube:accessToken:${accountId}`,+ ChannelRedisKeys.accessToken('youtube', accountId),)if (!credential || !credential.refresh_token) {const oauth2Credential = await this.oauth2CredentialRepository.getOne(@@ -237,7 +241,7 @@ export class YoutubeService extends PlatformBaseService {*/async setAccessToken(taskId: string, code: string) {const authTaskState = await this.redisService.getJson<AuthTaskInfo>(- `youtube:authTask:${taskId}`,+ ChannelRedisKeys.authTask('youtube', taskId),)if (!authTaskState || authTaskState.state !== taskId)return { status: 0, message: '无效的任务ID' }@@ -287,7 +291,7 @@ export class YoutubeService extends PlatformBaseService {authTaskState.type = 'youtube'authTaskState.account = accountInfo.idawait this.redisService.setJson(- `youtube:authTask:${taskId}`,+ ChannelRedisKeys.authTask('youtube', taskId),authTaskState,60 * 3,)@@ -296,6 +300,13 @@ export class YoutubeService extends PlatformBaseService {status: 1,message: '授权成功',accountId: accountInfo.id,+ nickname: accountInfo.nickname,+ avatar: accountInfo.avatar,+ platformUid: accountInfo.uid,+ accountType: AccountType.YOUTUBE,+ callbackUrl: authTaskState.callbackUrl,+ callbackMethod: authTaskState.callbackMethod,+ taskId,}}catch (error) {@@ -428,6 +439,7 @@ export class YoutubeService extends PlatformBaseService {* @returns 访问令牌*/async getUserAccessToken(accountId: string) {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (!credential || !credential.access_token) {this.logger.error(`youtube credential not found for accountId: ${accountId}`)@@ -490,7 +502,12 @@ export class YoutubeService extends PlatformBaseService {mail: string,prefix?: string,spaceId?: string,+ callbackUrl?: string,+ callbackMethod?: 'GET' | 'POST',) {+ if (!config.channel.youtube.id && config.relay) {+ throw new RelayAuthException()+ }const state = uuidv4()// 指定YouTube特定的scopeconst youtubeScopes = [@@ -527,8 +544,8 @@ export class YoutubeService extends PlatformBaseService {const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth')authUrl.search = params.toString()const rRes = await this.redisService.setJson(- `youtube:authTask:${state}`,- { state, status: 0, userId, mail, spaceId },+ ChannelRedisKeys.authTask('youtube', state),+ { state, status: 0, userId, mail, spaceId, callbackUrl, callbackMethod },60 * 5,)this.logger.log(`youtubeService getAuthUrl rRes: ${rRes}`)@@ -551,7 +568,7 @@ export class YoutubeService extends PlatformBaseService {state: stringstatus: numberaccountId?: string- }>(`youtube:authTask:${taskId}`)+ }>(ChannelRedisKeys.authTask('youtube', taskId))return data}@@ -2217,6 +2234,7 @@ export class YoutubeService extends PlatformBaseService {}async getAccessTokenStatus(accountId: string): Promise<number> {+ await this.ensureLocalAccount(accountId)const credential = await this.getOAuth2Credential(accountId)if (credential && credential.access_token) {this.updateAccountStatus(accountId, 1)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish-response.vo.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish-response.vo.tsindex 127a2173..10b783e8 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish-response.vo.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish-response.vo.ts@@ -1,7 +1,7 @@import { AccountType, createZodDto } from '@yikart/common'import { PublishStatus } from '@yikart/mongodb'import { z } from 'zod'-import { PublishingChannel } from './channel.types'+import { PublishingChannel } from './channel.interfaces'export const PublishRecordItemVoSchema = z.object({dataId: z.string().optional().describe('数据ID'),diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.controller.tsindex ac8ac06d..b13db43d 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.controller.ts@@ -5,13 +5,15 @@* @LastEditors: nevin* @Description: 发布*/-import { Body, Controller, Delete, Get, Param, Post, Query } from '@nestjs/common'+import { Body, Controller, Delete, Get, Logger, Param, Post, Query } from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, TableDto } from '@yikart/common'import { PublishStatus } from '@yikart/mongodb'import { plainToInstance } from 'class-transformer'import { PublishRecordService } from '../publish-record/publish-record.service'+import { RelayClientService } from '../relay/relay-client.service'+import { ChannelAccountService } from './platforms/channel-account.service'import { PostHistoryItemVo, PublishRecordItemVo } from './publish-response.vo'import {CreatePublishDto,@@ -27,10 +29,14 @@ import { PublishingService } from './publishing/publishing.service'@ApiTags('渠道/发布')@Controller('plat/publish')export class PublishController {+ private readonly logger = new Logger(PublishController.name)+constructor(private readonly publishService: PublishService,private readonly publishingService: PublishingService,private readonly publishRecordService: PublishRecordService,+ private readonly channelAccountService: ChannelAccountService,+ private readonly relayClientService: RelayClientService,) { }@ApiDoc({@@ -84,7 +90,9 @@ export class PublishController {@GetToken() token: TokenInfo,@Body() data: PubRecordListFilterDto,) {- return this.publishService.getList(data, token.id)+ const local = await this.publishService.getList(data, token.id)+ const relay = await this.fetchRelayData<PublishRecordItemVo[]>(token.id, '/plat/publish/getList', data)+ return [...local, ...relay]}@ApiDoc({@@ -97,7 +105,9 @@ export class PublishController {@GetToken() token: TokenInfo,@Body() data: PubRecordListFilterDto,) {- return this.publishService.getPostHistory(data, token.id)+ const local = await this.publishService.getPostHistory(data, token.id)+ const relay = await this.fetchRelayData<PostHistoryItemVo[]>(token.id, '/plat/publish/posts', data)+ return [...local, ...relay]}@ApiDoc({@@ -110,7 +120,9 @@ export class PublishController {@GetToken() token: TokenInfo,@Body() data: PubRecordListFilterDto,) {- return this.publishService.getQueuedPublishingTasks(data, token.id)+ const local = await this.publishService.getQueuedPublishingTasks(data, token.id)+ const relay = await this.fetchRelayData<PostHistoryItemVo[]>(token.id, '/plat/publish/statuses/queued/posts', data)+ return [...local, ...relay]}@ApiDoc({@@ -123,7 +135,9 @@ export class PublishController {@GetToken() token: TokenInfo,@Body() data: PubRecordListFilterDto,) {- return this.publishService.getPublishedPosts(data, token.id)+ const local = await this.publishService.getPublishedPosts(data, token.id)+ const relay = await this.fetchRelayData<PostHistoryItemVo[]>(token.id, '/plat/publish/statuses/published/posts', data)+ return [...local, ...relay]}@ApiDoc({@@ -199,4 +213,24 @@ export class PublishController {async updatePublishTask(@GetToken() token: TokenInfo, @Body() data: UpdatePublishTaskDto) {return this.publishService.updatePublishTask(data, token.id)}++ private async fetchRelayData<T extends unknown[]>(userId: string, path: string, data: PubRecordListFilterDto): Promise<T> {+ if (!this.relayClientService.enabled) {+ return [] as unknown as T+ }+ try {+ const relayAccounts = await this.channelAccountService.listRelayAccountsByUserId(userId)+ if (relayAccounts.length === 0) {+ return [] as unknown as T+ }+ return await this.relayClientService.post<T>(path, {+ ...data,+ accountIds: relayAccounts.map(a => a.relayAccountRef),+ })+ }+ catch (error) {+ this.logger.error(`Fetch relay publish records failed: ${error}`)+ return [] as unknown as T+ }+ }}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.dto.tsindex dba00822..26e2a4c2 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.dto.ts@@ -1,7 +1,7 @@import { AccountType, createZodDto } from '@yikart/common'import { PublishStatus, PublishType } from '@yikart/mongodb'import { z } from 'zod'-import { PublishingChannel } from './channel.types'+import { PublishingChannel } from './channel.interfaces'export const CreatePublishSchema = z.object({flowId: z.string({ message: '流水ID' }).optional(),diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.service.tsindex 7a03081e..66fa585b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publish.service.ts@@ -4,7 +4,7 @@ import { AppException, getErrorDetail, ResponseCode, TableDto } from '@yikart/coimport { PublishRecord } from '@yikart/mongodb'import { z } from 'zod'import { PublishRecordService } from '../publish-record/publish-record.service'-import { PublishingChannel } from './channel.types'+import { PublishingChannel } from './channel.interfaces'import { NewPublishData, PlatOptions } from './common'import { PostHistoryItemVoSchema } from './publish-response.vo'import { PublishDayInfoListFiltersDto, PubRecordListFilterDto, UpdatePublishTaskDto } from './publish.dto'diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/finalize-publish.consumer.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/finalize-publish.consumer.tsindex a9234d11..edaf4421 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/finalize-publish.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/finalize-publish.consumer.ts@@ -15,6 +15,7 @@ import { QueueName, QueueProcessor } from '@yikart/aitoearn-queue'import { AccountType, getErrorMessage, getErrorStack } from '@yikart/common'import { PublishStatus } from '@yikart/mongodb'import { Job } from 'bullmq'+import { ChannelAccountService } from '../../platforms/channel-account.service'import { PublishingErrorHandler } from '../error-handler.service'import { PublishService } from '../providers/base.service'import { PublishingUnrecoverableError } from '../publishing.exception'@@ -34,6 +35,7 @@ export class FinalizePublishPostConsumer extends WorkerHost {constructor(readonly publishingService: PublishingService,private readonly publishingErrorHandler: PublishingErrorHandler,+ private readonly channelAccountService: ChannelAccountService,) {super()}@@ -51,6 +53,20 @@ export class FinalizePublishPostConsumer extends WorkerHost {this.logger.error(`[task-${job.data.taskId}] Publish task not found: ${job.data.taskId}`)return}++ // 安全检查:relay 账号任务不应到达队列消费者+ if (publishTask.accountId) {+ const account = await this.channelAccountService.getAccountInfo(publishTask.accountId)+ if (account?.relayAccountRef) {+ this.logger.warn(`[task-${job.data.taskId}] Relay account ${publishTask.accountId} task reached queue consumer, skipping`)+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {+ status: PublishStatus.FAILED,+ errorMsg: 'Relay account task should not reach queue consumer',+ })+ return+ }+ }+// 获取对应平台的发布 Providerconst publishingProvider = this.publishingProviders[publishTask.accountType]if (!publishingProvider) {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/immediate-publish.consumer.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/immediate-publish.consumer.tsindex 05261c1c..24455fc9 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/immediate-publish.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/immediate-publish.consumer.ts@@ -19,6 +19,7 @@ import { QueueName, QueueProcessor } from '@yikart/aitoearn-queue'import { AccountType, getErrorMessage, getErrorStack } from '@yikart/common'import { PublishStatus } from '@yikart/mongodb'import { Job } from 'bullmq'+import { ChannelAccountService } from '../../platforms/channel-account.service'import { PublishingErrorHandler } from '../error-handler.service'import { PublishService } from '../providers/base.service'import { PublishingUnrecoverableError } from '../publishing.exception'@@ -38,6 +39,7 @@ export class ImmediatePublishPostConsumer extends WorkerHost {constructor(readonly publishingService: PublishingService,private readonly publishingErrorHandler: PublishingErrorHandler,+ private readonly channelAccountService: ChannelAccountService,) {super()}@@ -70,6 +72,19 @@ export class ImmediatePublishPostConsumer extends WorkerHost {return}+ // 安全检查:relay 账号任务不应到达队列消费者+ if (publishTaskInfo.accountId) {+ const account = await this.channelAccountService.getAccountInfo(publishTaskInfo.accountId)+ if (account?.relayAccountRef) {+ this.logger.warn(`[task-${taskId}] Relay account ${publishTaskInfo.accountId} task reached queue consumer, skipping`)+ await this.publishingService.updatePublishTaskStatus(taskId, {+ status: PublishStatus.FAILED,+ errorMsg: 'Relay account task should not reach queue consumer',+ })+ return { status: PublishStatus.FAILED }+ }+ }+// 标记为「发布中」await this.publishingService.updatePublishTaskStatus(taskId, {status: PublishStatus.PUBLISHING,diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/update-published-post.consumer.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/update-published-post.consumer.tsindex 01f63d46..31bcb153 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/update-published-post.consumer.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/consumers/update-published-post.consumer.ts@@ -16,6 +16,7 @@ import { QueueName, QueueProcessor } from '@yikart/aitoearn-queue'import { AccountType, getErrorMessage, getErrorStack } from '@yikart/common'import { PublishStatus } from '@yikart/mongodb'import { Job } from 'bullmq'+import { ChannelAccountService } from '../../platforms/channel-account.service'import { PublishingErrorHandler } from '../error-handler.service'import { PublishService } from '../providers/base.service'import { PublishingUnrecoverableError } from '../publishing.exception'@@ -35,6 +36,7 @@ export class UpdatePublishedPostConsumer extends WorkerHost {constructor(readonly publishingService: PublishingService,private readonly publishingErrorHandler: PublishingErrorHandler,+ private readonly channelAccountService: ChannelAccountService,) {super()}@@ -58,6 +60,18 @@ export class UpdatePublishedPostConsumer extends WorkerHost {return}+ if (publishTaskInfo.accountId) {+ const account = await this.channelAccountService.getAccountInfo(publishTaskInfo.accountId)+ if (account?.relayAccountRef) {+ this.logger.warn(`[task-${taskId}] Relay account task reached update consumer, skipping`)+ await this.publishingService.updatePublishTaskStatus(taskId, {+ status: PublishStatus.FAILED,+ errorMsg: 'Relay account task should not reach queue consumer',+ })+ return+ }+ }+if (publishTaskInfo.status !== PublishStatus.WAITING_FOR_UPDATE) {this.logger.warn(`[task-${taskId}] Update published post task not waiting for update: ${taskId}`)returndiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/credential-invalidation.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/credential-invalidation.service.tsindex 13eab723..d00dd13e 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/credential-invalidation.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/credential-invalidation.service.ts@@ -2,9 +2,7 @@ import { Inject, Injectable, Logger } from '@nestjs/common'import { AccountType } from '@yikart/aitoearn-server-client'import { OAuth2CredentialRepository } from '@yikart/channel-db'import { RedisService } from '@yikart/redis'-import { MetaRedisKeys } from '../platforms/meta/constants'-import { TiktokRedisKeys } from '../platforms/tiktok/constants'-import { TwitterRedisKeys } from '../platforms/twitter/constants'+import { ChannelRedisKeys } from '../channel.constants'@Injectable()export class CredentialInvalidationService {@@ -19,15 +17,15 @@ export class CredentialInvalidationService {private getRedisKeysToDelete(accountId: string, accountType: AccountType): string {switch (accountType) {case AccountType.FACEBOOK:- return MetaRedisKeys.getUserPageAccessTokenKey('facebook', accountId)+ return ChannelRedisKeys.pageAccessToken('facebook', accountId)case AccountType.INSTAGRAM:case AccountType.THREADS:case AccountType.LINKEDIN:- return MetaRedisKeys.getAccessTokenKey(accountType, accountId)+ return ChannelRedisKeys.accessToken(accountType, accountId)case AccountType.TWITTER:- return TwitterRedisKeys.getAccessTokenKey(accountId)+ return ChannelRedisKeys.accessToken('twitter', accountId)case AccountType.TIKTOK:- return TiktokRedisKeys.getAccessTokenKey(accountId)+ return ChannelRedisKeys.accessToken('tiktok', accountId)case AccountType.YOUTUBE:case AccountType.PINTEREST:case AccountType.BILIBILI:diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publish.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publish.dto.tsindex 57f027cc..23a71816 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publish.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publish.dto.ts@@ -130,11 +130,11 @@ export const GoogleBusinessPublishOptionSchema = z.object({topicType: z.enum(['STANDARD', 'EVENT', 'OFFER']).default('STANDARD').describe('帖子类型'),callToAction: z.object({actionType: z.enum(['BOOK', 'ORDER', 'LEARN_MORE', 'SIGN_UP', 'CALL', 'GET_OFFER']).describe('按钮类型'),- url: z.string().url().describe('跳转链接'),+ url: z.url().describe('跳转链接'),}).optional().describe('行动号召'),offer: z.object({couponCode: z.string().optional().describe('优惠码'),- redeemOnlineUrl: z.string().url().optional().describe('在线兑换链接'),+ redeemOnlineUrl: z.url().optional().describe('在线兑换链接'),termsConditions: z.string().max(500).optional().describe('使用条款'),}).optional().describe('优惠信息'),event: z.object({diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publishing.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publishing.service.tsindex 5d846c52..af9ff303 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publishing.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/channel/publishing/publishing.service.ts@@ -6,6 +6,7 @@ import { PublishRecord, PublishType } from '@yikart/mongodb'import { youtube_v3 } from 'googleapis'import { v4 as uuidv4 } from 'uuid'import { PublishRecordService } from '../../publish-record/publish-record.service'+import { RelayAccountException } from '../../relay/relay-account.exception'import { DouyinDownloadType, DouyinPrivateStatus } from '../libs/douyin/common'import { ChannelAccountService } from '../platforms/channel-account.service'import { FacebookService } from '../platforms/meta/facebook.service'@@ -112,6 +113,10 @@ export class PublishingService {if (!accountInfo)throw new AppException(ResponseCode.ChannelAccountInfoFailed)+ if (accountInfo.relayAccountRef) {+ throw new RelayAccountException(accountInfo.relayAccountRef, publishData.accountId)+ }+const { publishTime, accountType } = publishDataconst taskData = {...publishData,@@ -219,6 +224,13 @@ export class PublishingService {throw new AppException(ResponseCode.PublishTaskNotPublished)}+ if (task.accountId) {+ const account = await this.channelAccountService.getAccountInfo(task.accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, task.accountId)+ }+ }+if (!supportPlatforms.includes(task.accountType)) {throw new AppException(ResponseCode.PlatformNotSupported, '仅支持 Facebook 和 YouTube 平台更新')}@@ -414,6 +426,12 @@ export class PublishingService {if (!task || task.userId !== userId) {throw new AppException(ResponseCode.PublishTaskNotFound)}+ if (task.accountId) {+ const account = await this.channelAccountService.getAccountInfo(task.accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, task.accountId)+ }+ }if (task.queued && !!task.queueId) {await this.deleteQueueTask(task.queueId)}@@ -431,6 +449,12 @@ export class PublishingService {if (!task || task.userId !== userId) {throw new AppException(ResponseCode.PublishTaskNotFound)}+ if (task.accountId) {+ const account = await this.channelAccountService.getAccountInfo(task.accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, task.accountId)+ }+ }await this.publishRecordService.updateById(id,@@ -477,6 +501,13 @@ export class PublishingService {throw new AppException(ResponseCode.PublishTaskStatusInvalid)}+ if (taskInfo.accountId) {+ const account = await this.channelAccountService.getAccountInfo(taskInfo.accountId)+ if (account?.relayAccountRef) {+ throw new RelayAccountException(account.relayAccountRef, taskInfo.accountId)+ }+ }+await this.publishRecordService.updateById(id, { publishTime: new Date(), queued: true })await this.enqueuePublishingTask(taskInfo)}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/content.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/content.module.tsindex 33d26913..0806b959 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/content.module.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/content.module.ts@@ -9,7 +9,6 @@ import { MediaController } from './media.controller'import { MediaService } from './media.service'@Module({- imports: [],controllers: [MediaController, MediaGroupController, MaterialGroupController, MaterialController],providers: [MediaService, MediaGroupService, MaterialGroupService, MaterialService],exports: [MediaService, MediaGroupService, MaterialGroupService, MaterialService],diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.controller.tsindex 2a762cce..19e0b5ca 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.controller.ts@@ -1,15 +1,9 @@-/*- * @Author: nevin- * @Date: 2024-06-17 19:19:20- * @LastEditTime: 2024-12-23 12:45:22- * @LastEditors: nevin- * @Description: 草稿组- */import {Body,Controller,Delete,Get,+ Logger,Param,Post,Query,@@ -18,11 +12,15 @@ import { ApiTags } from '@nestjs/swagger'import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, AppException, ResponseCode, TableDto } from '@yikart/common'import { CreateMaterialGroupDto, MaterialGroupFilterDto, MaterialGroupFilterSchema, UpdateMaterialGroupDto } from './material-group.dto'+import { MaterialGroupService } from './material-group.service'+import { MaterialGroupVo } from './material-group.vo'@ApiTags('Me/MaterialGroup')@Controller('material/group')export class MaterialGroupController {+ private readonly logger = new Logger(MaterialGroupController.name)+constructor(private readonly materialGroupService: MaterialGroupService,) { }@@ -37,11 +35,10 @@ export class MaterialGroupController {@GetToken() token: TokenInfo,@Body() body: CreateMaterialGroupDto,) {- const res = await this.materialGroupService.createGroup({+ return this.materialGroupService.createGroup({...body,userId: token.id,})- return res}@ApiDoc({@@ -55,15 +52,12 @@ export class MaterialGroupController {) {const materialGroup = await this.materialGroupService.getGroupInfo(id)if (!materialGroup || materialGroup.userId !== token.id) {- throw new AppException(ResponseCode.MaterialGroupNotFound, 'Material Group not found')+ throw new AppException(ResponseCode.MaterialGroupNotFound)}- if (- materialGroup.isDefault- ) {- throw new AppException(ResponseCode.MaterialGroupDefaultNotAllowed, 'Default material group cannot be deleted')+ if (materialGroup.isDefault) {+ throw new AppException(ResponseCode.MaterialGroupDefaultNotAllowed)}- const res = await this.materialGroupService.delGroup(id)- return res+ return this.materialGroupService.delGroup(id)}@ApiDoc({@@ -79,10 +73,9 @@ export class MaterialGroupController {) {const materialGroup = await this.materialGroupService.getGroupInfo(id)if (!materialGroup || materialGroup.userId !== token.id) {- throw new AppException(ResponseCode.MaterialGroupNotFound, 'Material Group not found')+ throw new AppException(ResponseCode.MaterialGroupNotFound)}- const res = await this.materialGroupService.updateGroupInfo(id, body)- return res+ return this.materialGroupService.updateGroupInfo(id, body)}@ApiDoc({@@ -91,14 +84,14 @@ export class MaterialGroupController {})@Get('info/:id')async getGroupInfo(@Param('id') id: string) {- const res = await this.materialGroupService.getGroupInfo(id)- return res+ return this.materialGroupService.getGroupInfo(id)}@ApiDoc({summary: '获取草稿分组列表',description: '分页获取草稿分组列表。',query: MaterialGroupFilterSchema,+ response: [MaterialGroupVo],})@Get('list/:pageNo/:pageSize')async getGroupList(@@ -113,6 +106,9 @@ export class MaterialGroupController {...query,})- return { list, total }+ return {+ list: list.map(item => MaterialGroupVo.create(item)),+ total,+ }}}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.service.tsindex 16aa4288..ffbd18ff 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.service.ts@@ -10,37 +10,31 @@ export class MaterialGroupService {) { }async createGroup(newData: NewMaterialGroup) {- const res = await this.materialGroupRepository.create(newData)- return res+ return this.materialGroupRepository.create(newData)}async delGroup(id: string): Promise<boolean> {- const res = await this.materialGroupRepository.delete(id)- return res+ return this.materialGroupRepository.delete(id)}async updateGroupInfo(id: string, newData: UpdateMaterialGroup) {- const res = await this.materialGroupRepository.update(id, newData)- return res+ return this.materialGroupRepository.update(id, newData)}async getGroupInfo(id: string) {- const res = await this.materialGroupRepository.getById(id)- return res+ return this.materialGroupRepository.getById(id)}async getInfoByName(userId: string, name: string) {- const res = await this.materialGroupRepository.getInfoByName(userId, name)- return res+ return this.materialGroupRepository.getInfoByName(userId, name)}async getDefaultGroup(userId: string) {- const res = await this.materialGroupRepository.getDefaultGroup(userId)- return res+ return this.materialGroupRepository.getDefaultGroup(userId)}async ensureDefaultGroup(userId: string) {- return await this.materialGroupRepository.createDefault(userId)+ return this.materialGroupRepository.createDefault(userId)}async getGroupList(@@ -50,7 +44,6 @@ export class MaterialGroupService {title?: string},) {- const res = await this.materialGroupRepository.getList(filter, page)- return res+ return this.materialGroupRepository.getList(filter, page)}}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.vo.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.vo.tsnew file mode 100644index 00000000..eee761be--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material-group.vo.ts@@ -0,0 +1,15 @@+import { AccountType, createZodDto } from '@yikart/common'+import { z } from 'zod'++export const MaterialGroupVoSchema = z.object({+ id: z.string().describe('草稿箱 ID'),+ userId: z.string().describe('用户 ID'),+ name: z.string().describe('草稿箱名称'),+ desc: z.string().optional().describe('描述'),+ isDefault: z.boolean().describe('是否默认'),+ platforms: z.array(z.enum(AccountType)).default([]).describe('平台限制'),+ openAffiliate: z.boolean().optional().describe('是否开启推广'),+ createdAt: z.date().describe('创建时间'),+ updatedAt: z.date().describe('更新时间'),+})+export class MaterialGroupVo extends createZodDto(MaterialGroupVoSchema, 'MaterialGroupVo') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.controller.tsindex 687f69a1..86098a18 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.controller.ts@@ -180,7 +180,7 @@ export class MaterialController {@Get('optimal')async optimalInGroup(@Query() query: GetOptimalMaterialDto) {const type = getMaterialTypeByAccountType(query.accountType)- const res = await this.materialService.optimalInGroup(query.groupId, type)+ const res = await this.materialService.optimalInGroup(query.groupId, type, query.accountType)return res}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.dto.tsindex 3abf41a9..0df07e91 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.dto.ts@@ -1,4 +1,4 @@-import { AccountType, createZodDto, TableDto } from '@yikart/common'+import { AccountType, createZodDto, FileUtil, TableDto } from '@yikart/common'import { MaterialStatus, MaterialType, MediaType } from '@yikart/mongodb'import { z } from 'zod'@@ -9,16 +9,16 @@ export class MaterialIdDto extends createZodDto(MaterialIdSchema) { }export const MaterialMediaSchema = z.object({id: z.string().optional().describe('资源ID'),- url: z.string(),+ url: FileUtil.zodTrimHost(),type: z.enum(MediaType).describe('资源类型'),- thumbUrl: z.string().optional().describe('缩略图'),+ thumbUrl: FileUtil.zodTrimHost().optional().describe('缩略图'),content: z.string().optional().describe('文本内容'),mediaId: z.string().optional().describe('资源ID'),})export const CreateMaterialSchema = z.object({groupId: z.string().describe('分组ID'),- coverUrl: z.string().optional().describe('封面图'),+ coverUrl: FileUtil.zodTrimHost().optional().describe('封面图'),mediaList: z.array(MaterialMediaSchema).describe('资源列表'),title: z.string().describe('标题'),desc: z.string().optional().describe('描述'),@@ -32,7 +32,7 @@ export const CreateMaterialSchema = z.object({export class CreateMaterialDto extends createZodDto(CreateMaterialSchema) { }export const UpdateMaterialSchema = z.object({- coverUrl: z.string().optional().describe('封面图'),+ coverUrl: FileUtil.zodTrimHost().optional().describe('封面图'),mediaList: z.array(MaterialMediaSchema).describe('资源列表'),title: z.string().describe('标题'),desc: z.string().optional().describe('描述'),@@ -40,6 +40,7 @@ export const UpdateMaterialSchema = z.object({option: z.any().optional().describe('其他属性'),autoDeleteMedia: z.boolean().optional().describe('自动删除草稿'),maxUseCount: z.number().int().positive().optional().describe('最大使用次数'),+ accountTypes: z.array(z.enum(AccountType)).optional().describe('适用的频道类型'),})export class UpdateMaterialDto extends createZodDto(UpdateMaterialSchema) { }diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.service.tsindex 3b75ba22..57657b77 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/material.service.ts@@ -1,6 +1,6 @@import { Injectable, Logger } from '@nestjs/common'import { AssetsService, VideoMetadataService } from '@yikart/assets'-import { FileUtil, TableDto, UserType } from '@yikart/common'+import { AccountType, FileUtil, TableDto, UserType } from '@yikart/common'import { AssetType, Material, MaterialRepository, MaterialStatus, MaterialType, MediaType } from '@yikart/mongodb'import { NewMaterial, UpMaterial } from './common'import { MediaService } from './media.service'@@ -126,8 +126,8 @@ export class MaterialService {return res}- async optimalInGroup(groupId: string, type?: MaterialType): Promise<Material | null> {- const res = await this.materialRepository.getOptimalByGroup(groupId, type)+ async optimalInGroup(groupId: string, type?: MaterialType, accountType?: AccountType): Promise<Material | null> {+ const res = await this.materialRepository.getOptimalByGroup(groupId, type, accountType)return res}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.dto.tsindex 86989b0c..d8281b13 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.dto.ts@@ -27,6 +27,7 @@ export class CreateMediaDto extends createZodDto(CreateMediaSchema) {}export const MediaFilterSchema = z.object({groupId: z.string().optional().describe('组ID'),+ materialGroupId: z.string().optional().describe('草稿箱组ID'),type: z.enum(MediaType).optional().describe('类型'),useCount: z.coerce.number().optional().describe('use conut (min)'),})diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.service.tsindex 359fd6d6..3cd15ac8 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/content/media.service.ts@@ -124,6 +124,7 @@ export class MediaService {filter: {userId: stringgroupId?: string+ materialGroupId?: stringtype?: MediaTypeuserType?: UserTypeuseCount?: numberdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/publish-record/publish-record.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/publish-record/publish-record.service.tsindex f1b1b679..01cc527b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/publish-record/publish-record.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/publish-record/publish-record.service.ts@@ -5,15 +5,11 @@* @LastEditors: nevin* @Description: PublishRecord*/-import { Inject, Injectable, Logger, OnModuleInit } from '@nestjs/common'-import { EventEmitter2 } from '@nestjs/event-emitter'-import { QueueService } from '@yikart/aitoearn-queue'-import { AccountType, CreditsType, TableDto } from '@yikart/common'+import { Injectable, Logger } from '@nestjs/common'+import { AccountType, TableDto } from '@yikart/common'import { PublishRecord, PublishRecordRepository, PublishStatus, PublishType } from '@yikart/mongodb'-import dayjs from 'dayjs'import { UpdateQuery } from 'mongoose'import { MaterialService } from '../content/material.service'-import { CreditsService } from '../credits/credits.service'import {GetPublishRecordDetailDto,PublishDayInfoListFiltersDto,@@ -21,42 +17,13 @@ import {} from './publish-record.dto'@Injectable()-export class PublishRecordService implements OnModuleInit {+export class PublishRecordService {private readonly logger = new Logger(PublishRecordService.name)constructor(private readonly publishRecordRepository: PublishRecordRepository,private readonly materialService: MaterialService,- private eventEmitter: EventEmitter2,- private readonly creditsService: CreditsService,- @Inject(QueueService)- protected readonly queueService: QueueService,) { }- async onModuleInit() {- // const data = {- // "id": "69aa26a88d4edb16c4642293",- // "userId": "69908f81a8660002fc02522b",- // "userTaskId": "69aa26978d4edb16c464228a",- // "taskId": "69aa26778d4edb16c464227a",- // "type": PublishType.VIDEO,- // "title": "",- // "desc": "",- // "topics": [],- // "accountType": AccountType.TIKTOK,- // "imgUrlList": [],- // "publishTime": new Date("2026-03-06T00:58:16.583Z"),- // "status": 1,- // "inQueue": false,- // "queued": false,- // "dataId": "7610426383415774472",- // "uniqueId": "tiktok_7610426383415774472",- // "workLink": "https://www.tiktok.com/@arianalee0928/video/7610426383415774472",- // "createdAt": new Date("2026-03-06T00:58:16.587Z"),- // "updatedAt": new Date("2026-03-06T00:58:16.587Z")- // }- // await this.onPublishCompleted(data)- }-/*** 更新素材使用次数* @param materialId 素材ID@@ -83,7 +50,7 @@ export class PublishRecordService implements OnModuleInit {}/**- * 发布完成后的副作用:任务处理、每日统计、积分奖励、Redis 事件+ * 发布完成后的副作用:任务处理、每日统计、Redis 事件* @param data 已完成的发布记录*/private onPublishCompleted(data: PublishRecord) {@@ -93,8 +60,14 @@ export class PublishRecordService implements OnModuleInit {this.increaseMaterialUseCount(data.materialId)// 更新每日发布信息this.upDayPublishInfo(data)- // 发放发布奖励- this.grantPublishReward(data)+ }++ /**+ * 更新每日发布统计信息+ * @param data 发布记录数据+ */+ private async upDayPublishInfo(data: PublishRecord) {+ await this.publishRecordRepository.upDayPublishInfo(data)}/**@@ -154,46 +127,8 @@ export class PublishRecordService implements OnModuleInit {* 处理发布完成后的任务逻辑:触发任务追踪事件、自动删除或增加素材使用次数* @param data 发布记录数据*/- private async doTaskProcess(data: Partial<PublishRecord>) {- if (!data.userTaskId || !data.userId)- return-- if (data.accountType && data.uid && data.dataId) {- this.eventEmitter.emit(- 'statistics.task.userTaskPosts',- {- userId: data.userId,- accountId: data.accountId!,- taskId: data.taskId,- type: data.accountType,- uid: data.uid!,- postId: data.dataId,- },- )- }- }-- /**- * 为用户增加发布积分奖励- * @param userId 用户ID- */- private addPoints(userId: string) {- this.creditsService.addCredits({- userId,- amount: 10,- type: CreditsType.Publish,- description: '发布奖励',- metadata: {},- expiredAt: null,- })- }-- /**- * 更新每日发布统计信息- * @param data 发布记录数据- */- private async upDayPublishInfo(data: PublishRecord) {- await this.publishRecordRepository.upDayPublishInfo(data)+ private async doTaskProcess(_data: Partial<PublishRecord>) {+ // Task module removed — no-op}/**@@ -212,51 +147,6 @@ export class PublishRecordService implements OnModuleInit {)}- /**- * 发放发布奖励:根据连续发布天数发放积分- * @param data 发布记录数据- */- async grantPublishReward(data: PublishRecord) {- // 1. 查询发放状态- const recordInfo = await this.publishRecordRepository.getUserRecordInfo(data.userId)- if (!recordInfo) {- this.addPoints(data.userId)- this.publishRecordRepository.createPublishInfo({- userId: data.userId,- upInfoDate: new Date(),- days: 1,- })- return- }-- const { upInfoDate } = recordInfo- if (dayjs(upInfoDate).isSame(dayjs(), 'day')) {- return- }-- const isYesterday = dayjs(upInfoDate).isSame(- dayjs().subtract(1, 'day'),- 'day',- )-- if (!isYesterday) {- this.addPoints(data.userId)- await this.publishRecordRepository.updateUserPublishInfo(- data.userId,- { upInfoDate: new Date(), days: 1 },- )- return- }-- const { days } = recordInfo- this.addPoints(data.userId)- const newDays = days + 1- await this.publishRecordRepository.updateUserPublishInfo(- data.userId,- { upInfoDate: new Date(), days: newDays },- )- }-/*** 获取用户的发布信息概览数据* @param userId 用户IDdiff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-account.exception.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-account.exception.tsnew file mode 100644index 00000000..74d14565--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-account.exception.ts@@ -0,0 +1,8 @@+export class RelayAccountException extends Error {+ constructor(+ public readonly relayAccountRef: string,+ public readonly originalAccountId: string,+ ) {+ super('This account requires relay')+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-auth.exception.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-auth.exception.tsnew file mode 100644index 00000000..0fbe453e--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-auth.exception.ts@@ -0,0 +1,5 @@+export class RelayAuthException extends Error {+ constructor() {+ super('Auth request should be forwarded to relay server')+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-callback.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-callback.dto.tsnew file mode 100644index 00000000..82c68203--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-callback.dto.ts@@ -0,0 +1,12 @@+import { AccountType, createZodDto } from '@yikart/common'+import { z } from 'zod'++const RelayCallbackDtoSchema = z.object({+ relayAccountRef: z.string().min(1).describe('官方服务器上的账号 ID'),+ nickname: z.string().describe('账号昵称'),+ avatar: z.string().optional().describe('账号头像'),+ platformUid: z.string().min(1).describe('平台用户 ID'),+ accountType: z.enum(AccountType).describe('平台类型'),+ taskId: z.string().optional().describe('授权任务 ID'),+})+export class RelayCallbackDto extends createZodDto(RelayCallbackDtoSchema, 'RelayCallbackDto') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-client.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-client.service.tsnew file mode 100644index 00000000..1a83f345--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-client.service.ts@@ -0,0 +1,90 @@+import { basename } from 'node:path'+import { Injectable, Logger } from '@nestjs/common'+import { AppException, CommonResponse, ResponseCode } from '@yikart/common'+import { AssetType } from '@yikart/mongodb'+import axios, { AxiosRequestConfig } from 'axios'+import { config } from '../../config'++interface UploadSignResult {+ id: string+ path: string+ url: string+ uploadUrl: string+}++@Injectable()+export class RelayClientService {+ private readonly logger = new Logger(RelayClientService.name)++ get enabled() {+ return !!config.relay+ }++ async get<T>(path: string, params?: Record<string, any>): Promise<T> {+ return this.request<T>({ method: 'GET', url: path, params })+ }++ async post<T>(path: string, data?: unknown): Promise<T> {+ return this.request<T>({ method: 'POST', url: path, data })+ }++ async patch<T>(path: string, data?: unknown): Promise<T> {+ return this.request<T>({ method: 'PATCH', url: path, data })+ }++ async delete<T>(path: string, data?: unknown): Promise<T> {+ return this.request<T>({ method: 'DELETE', url: path, data })+ }++ async uploadFileFromLocalUrl(localUrl: string): Promise<string> {+ const filename = basename(new URL(localUrl).pathname)++ const fileResponse = await axios.get(localUrl, { responseType: 'arraybuffer' })+ const contentType = fileResponse.headers['content-type'] || 'application/octet-stream'+ const size = (fileResponse.data as ArrayBuffer).byteLength++ const signResult = await this.post<UploadSignResult>('/assets/uploadSign', {+ filename,+ type: AssetType.PublishMedia,+ size,+ })++ if (!signResult?.uploadUrl) {+ throw new Error(`uploadSign returned no uploadUrl: ${JSON.stringify(signResult)}`)+ }++ await axios.put(signResult.uploadUrl, fileResponse.data, {+ headers: { 'Content-Type': contentType },+ })++ await this.post(`/assets/${signResult.id}/confirm`, {})++ return signResult.url+ }++ private async request<T>(options: AxiosRequestConfig): Promise<T> {+ if (!config.relay) {+ throw new AppException(ResponseCode.RelayServerUnavailable)+ }++ try {+ const response = await axios<CommonResponse<T>>({+ ...options,+ url: `${config.relay.serverUrl}${options.url}`,+ headers: {+ ...options.headers,+ 'x-api-key': config.relay.apiKey,+ },+ })+ if (response.data.code !== 0) {+ this.logger.error({ message: 'Relay API returned error', url: options.url, code: response.data.code, relayMessage: response.data.message })+ throw new Error(`Relay API error [${response.data.code}]: ${response.data.message}`)+ }+ return response.data.data as T+ }+ catch (error) {+ this.logger.error(error, `Relay request failed: ${options.url}`)+ throw new AppException(ResponseCode.RelayServerUnavailable)+ }+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-exception.filter.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-exception.filter.tsnew file mode 100644index 00000000..6a38602b--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-exception.filter.ts@@ -0,0 +1,167 @@+import type { AssetsConfig } from '@yikart/assets'+import type { Method } from 'axios'+import type { Request, Response } from 'express'+import {+ ArgumentsHost,+ Catch,+ Logger,+} from '@nestjs/common'+import { AppException, GlobalExceptionFilter, ResponseCode } from '@yikart/common'+import axios from 'axios'+import { concatMap, from, of } from 'rxjs'+import { z } from 'zod'+import { relayConfigSchema } from '../../config'+import { RelayAccountException } from './relay-account.exception'+import { RelayAuthException } from './relay-auth.exception'+import { RelayClientService } from './relay-client.service'++type RelayConfig = z.infer<typeof relayConfigSchema>++@Catch(RelayAccountException, RelayAuthException)+export class RelayExceptionFilter extends GlobalExceptionFilter<unknown> {+ protected override readonly logger = new Logger(RelayExceptionFilter.name)+ private readonly localUrlPrefixes: string[]++ constructor(+ private readonly relayConfig: RelayConfig | undefined,+ private readonly assetsConfig: AssetsConfig | undefined,+ private readonly relayClientService: RelayClientService | undefined,+ ) {+ super()+ this.localUrlPrefixes = []+ if (assetsConfig?.endpoint) {+ this.localUrlPrefixes.push(assetsConfig.endpoint.replace(/\/+$/, ''))+ }+ if (assetsConfig?.cdnEndpoint) {+ this.localUrlPrefixes.push(assetsConfig.cdnEndpoint.replace(/\/+$/, ''))+ }+ }++ override catch(exception: RelayAccountException | RelayAuthException, host: ArgumentsHost) {+ if (!this.relayConfig) {+ return super.catch(exception, host)+ }++ return from(this.handleRelay(exception, host)).pipe(concatMap(v => v || of(v)))+ }++ private async handleRelay(exception: RelayAccountException | RelayAuthException, host: ArgumentsHost) {+ const relayConfig = this.relayConfig!+ try {+ const ctx = host.switchToHttp()+ const request = ctx.getRequest<Request & { user?: { id?: string } }>()+ const response = ctx.getResponse<Response>()++ const forwardHeaders = this.buildForwardHeaders(request)++ let targetUrl: string+ let targetBody: unknown++ if (exception instanceof RelayAccountException) {+ const { originalAccountId, relayAccountRef } = exception+ targetUrl = `${relayConfig.serverUrl}${request.originalUrl}`.replaceAll(+ originalAccountId,+ relayAccountRef,+ )+ targetBody = request.body+ ? JSON.parse(+ JSON.stringify(request.body).replaceAll(+ originalAccountId,+ relayAccountRef,+ ),+ )+ : undefined++ targetBody = await this.replaceLocalUrls(targetBody)+ }+ else {+ const userId = request.user?.id+ const callbackUrl = new URL(relayConfig.callbackUrl)+ if (userId) {+ callbackUrl.searchParams.set('userId', userId)+ }+ const callbackUrlStr = callbackUrl.toString()++ const isGet = request.method.toUpperCase() === 'GET'+ if (isGet) {+ const url = new URL(`${relayConfig.serverUrl}${request.originalUrl}`)+ url.searchParams.set('callbackUrl', callbackUrlStr)+ url.searchParams.set('callbackMethod', 'POST')+ targetUrl = url.toString()+ targetBody = undefined+ }+ else {+ targetUrl = `${relayConfig.serverUrl}${request.originalUrl}`+ targetBody = {+ ...request.body,+ callbackUrl: callbackUrlStr,+ callbackMethod: 'POST',+ }+ }+ }++ try {+ const proxyResponse = await axios({+ method: request.method as Method,+ url: targetUrl,+ data: targetBody,+ headers: forwardHeaders,+ validateStatus: () => true,+ })++ response.status(proxyResponse.status).json(proxyResponse.data)+ }+ catch (error) {+ this.logger.error(error, 'Relay proxy request failed')+ return super.catch(new AppException(ResponseCode.RelayServerUnavailable), host)+ }+ }+ catch (error) {+ this.logger.error(error, 'Relay exception filter failed')+ return super.catch(error as Error, host)+ }+ }++ private async replaceLocalUrls(body: unknown): Promise<unknown> {+ if (!body || this.localUrlPrefixes.length === 0 || !this.relayClientService) {+ return body+ }++ let bodyStr = JSON.stringify(body)+ const urlPattern = new RegExp(+ `(${this.localUrlPrefixes.map(p => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})/[^"\\s]+`,+ 'g',+ )++ const localUrls = [...new Set(bodyStr.match(urlPattern) || [])]++ for (const localUrl of localUrls) {+ let downloadUrl = localUrl+ const cdnPrefix = this.assetsConfig?.cdnEndpoint?.replace(/\/+$/, '')+ const endpointPrefix = this.assetsConfig?.endpoint?.replace(/\/+$/, '')+ if (cdnPrefix && endpointPrefix && localUrl.startsWith(cdnPrefix)) {+ const bucket = this.assetsConfig?.bucketName || ''+ const internalBase = `${endpointPrefix}${bucket ? `/${bucket}` : ''}`+ downloadUrl = localUrl.replace(cdnPrefix, internalBase)+ }+ const relayUrl = await this.relayClientService.uploadFileFromLocalUrl(downloadUrl)+ bodyStr = bodyStr.replaceAll(localUrl, relayUrl)+ }++ return JSON.parse(bodyStr)+ }++ private buildForwardHeaders(request: Request): Record<string, string> {+ const forwardHeaders: Record<string, string> = {}+ for (const [key, value] of Object.entries(request.headers)) {+ if (key === 'authorization' || key === 'host' || key === 'content-length') {+ continue+ }+ if (typeof value === 'string') {+ forwardHeaders[key] = value+ }+ }+ forwardHeaders['x-api-key'] = this.relayConfig!.apiKey+ return forwardHeaders+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-oauth.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-oauth.controller.tsnew file mode 100644index 00000000..aa1690ed--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay-oauth.controller.ts@@ -0,0 +1,67 @@+import { Body, Controller, Post, Query, Render } from '@nestjs/common'+import { ApiTags } from '@nestjs/swagger'+import { Public } from '@yikart/aitoearn-auth'+import { ApiDoc, AppException, ResponseCode } from '@yikart/common'+import { AccountStatus } from '@yikart/mongodb'+import { RedisService } from '@yikart/redis'+import { ChannelRedisKeys } from '../channel/channel.constants'+import { ChannelAccountService } from '../channel/platforms/channel-account.service'+import { RelayCallbackDto } from './relay-callback.dto'++@ApiTags('Relay/OAuth')+@Controller('plat')+export class RelayOAuthController {+ constructor(+ private readonly channelAccountService: ChannelAccountService,+ private readonly redisService: RedisService,+ ) {}++ @Public()+ @ApiDoc({+ summary: 'Relay OAuth 回调',+ description: '接收官方服务器 OAuth 完成后浏览器 form POST 过来的账号信息,在本地创建 relay 账号',+ body: RelayCallbackDto.schema,+ })+ @Post('/relay-callback')+ @Render('auth/back')+ async handleRelayCallback(+ @Body() body: RelayCallbackDto,+ @Query('userId') userId: string,+ ) {+ if (!userId) {+ throw new AppException(ResponseCode.UserNotFound)+ }++ const account = await this.channelAccountService.createAccount(+ { type: body.accountType, uid: body.platformUid },+ {+ userId,+ type: body.accountType,+ uid: body.platformUid,+ nickname: body.nickname,+ avatar: body.avatar,+ status: AccountStatus.NORMAL,+ relayAccountRef: body.relayAccountRef,+ },+ )++ if (body.taskId) {+ const authTaskPlatform = this.getAuthTaskPlatform(body.accountType)+ await this.redisService.setJson(+ ChannelRedisKeys.authTask(authTaskPlatform, body.taskId),+ { status: 1, accountId: account?.id },+ 600,+ )+ }++ return { status: 1, message: '授权成功', accountId: account?.id }+ }++ private getAuthTaskPlatform(accountType: string): string {+ const META_PLATFORMS = ['facebook', 'instagram', 'threads', 'linkedin']+ if (META_PLATFORMS.includes(accountType)) {+ return 'meta'+ }+ return accountType+ }+}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay.module.tsnew file mode 100644index 00000000..19e3bc51--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/relay/relay.module.ts@@ -0,0 +1,24 @@+import { Global, Module } from '@nestjs/common'+import { APP_FILTER } from '@nestjs/core'+import { config } from '../../config'+import { ChannelSharedModule } from '../channel/platforms/channel-shared.module'+import { RelayClientService } from './relay-client.service'+import { RelayExceptionFilter } from './relay-exception.filter'+import { RelayOAuthController } from './relay-oauth.controller'++@Global()+@Module({+ imports: [ChannelSharedModule],+ controllers: [RelayOAuthController],+ providers: [+ RelayClientService,+ {+ provide: APP_FILTER,+ useFactory: (relayClientService: RelayClientService) =>+ new RelayExceptionFilter(config.relay, config.assets, relayClientService),+ inject: [RelayClientService],+ },+ ],+ exports: [RelayClientService],+})+export class RelayModule {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/tools/tools.dto.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/tools/tools.dto.tsindex 876de174..43838e7b 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/tools/tools.dto.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/tools/tools.dto.ts@@ -3,7 +3,7 @@ import { z } from 'zod'export const GenerateQrCodeArtDtoSchema = z.object({content: z.string().min(1).max(2000).describe('二维码扫码后的内容'),- referenceImageUrl: z.string().url().optional().describe('参考样式图 URL'),+ referenceImageUrl: z.url().optional().describe('参考样式图 URL'),prompt: z.string().min(1).max(4000).describe('文字描述(提示词)'),model: z.string().default('gpt-image-1').describe('图片生成模型'),size: z.string().optional().describe('图片尺寸'),@@ -16,12 +16,12 @@ export const CreateQrCodeArtImageDtoSchema = z.object({relType: z.string().min(1).describe('关联的数据类型'),logId: z.string().min(1).describe('AI 任务日志 ID'),content: z.string().min(1).max(2000).describe('二维码扫码后的内容'),- referenceImageUrl: z.string().url().optional().describe('参考样式图 URL'),+ referenceImageUrl: z.url().optional().describe('参考样式图 URL'),prompt: z.string().min(1).max(4000).describe('文字描述(提示词)'),model: z.string().describe('图片生成模型'),size: z.string().optional().describe('图片尺寸'),status: z.string().describe('任务状态'),- imageUrl: z.string().url().optional().describe('生成的二维码艺术图 URL'),+ imageUrl: z.url().optional().describe('生成的二维码艺术图 URL'),})export class CreateQrCodeArtImageDto extends createZodDto(CreateQrCodeArtImageDtoSchema, 'CreateQrCodeArtImageDto') {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/unified-mcp/unified-mcp.module.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/unified-mcp/unified-mcp.module.tsnew file mode 100644index 00000000..8e452f15--- /dev/null+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/unified-mcp/unified-mcp.module.ts@@ -0,0 +1,29 @@+import { Module } from '@nestjs/common'+import { ApiTags } from '@nestjs/swagger'+import { McpModule } from '@yikart/nest-mcp'+import { AccountMcpController } from '../account/account.mcp.controller'+import { AccountModule } from '../account/account.module'+import { PublishMcpController } from '../channel/publish.mcp.controller'+import { PublishModule as PublishingModule } from '../channel/publishing/publishing.module'+import { ContentMcpController } from '../content/content.mcp.controller'+import { ContentModule } from '../content/content.module'++@Module({+ imports: [+ McpModule.forRoot({+ name: 'aitoearn',+ version: '1.0.0',+ apiPrefix: 'unified',+ decorators: [ApiTags('MCP/Unified')],+ }),+ AccountModule,+ PublishingModule,+ ContentModule,+ ],+ providers: [+ AccountMcpController,+ PublishMcpController,+ ContentMcpController,+ ],+})+export class UnifiedMcpModule {}diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.controller.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.controller.tsindex 95ecf5ed..4c216d02 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.controller.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.controller.ts@@ -1,6 +1,6 @@import { Body, Controller, Get, Param, Patch, Put } from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'-import { GetToken, Public, TokenInfo } from '@yikart/aitoearn-auth'+import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'import { ApiDoc, AppException, ResponseCode } from '@yikart/common'import {ReportLocationDto,@@ -28,7 +28,6 @@ export class UserController {description: 'Retrieve user information by specifying the email address.',response: UserInfoVO,})- @Public()@Get('info/mail/:mail')async infoByMail(@Param('mail') mail: string) {const res = await this.userService.getUserInfoByMail(mail)diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.service.ts b/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.service.tsindex e21cbfad..bd15f598 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.service.ts+++ b/project/aitoearn-backend/apps/aitoearn-server/src/core/user/user.service.ts@@ -258,12 +258,6 @@ export class UserService {this.userRepository.updateById(user.id, { locale })}- // Report user data- await this.queueService.addTaskUserPortraitReportJob({- userId: user.id,- lastLoginTime: (new Date()).toISOString(),- })-return true}@@ -301,19 +295,9 @@ export class UserService {this.materialGroupRepository.createDefault(user.id)this.mediaGroupRepository.createDefault(user.id)- // Report user data- await this.queueService.addTaskUserPortraitReportJob({- userId: user.id,- name: user.name,- avatar: user.avatar,- status: UserStatus.OPEN,- lastLoginTime: (new Date()).toISOString(),- })-// Generate invite codeawait this.generateUsePopularizeCode(user.id)this.redisPubSubService.emit(PsChannel.USER_CREATE, user)- await this.queueService.addTaskUserCreatePushJob({ userId: user.id })}async setAiConfig(userId: string, aiConfig: Partial<UserAiInfo>): Promise<boolean> {diff --git a/project/aitoearn-backend/apps/aitoearn-server/src/views/auth/back.ejs b/project/aitoearn-backend/apps/aitoearn-server/src/views/auth/back.ejsindex 1373d671..fe76ce9d 100644--- a/project/aitoearn-backend/apps/aitoearn-server/src/views/auth/back.ejs+++ b/project/aitoearn-backend/apps/aitoearn-server/src/views/auth/back.ejs@@ -263,34 +263,40 @@</div><% } %>- <div class="redirect-message">- Page will automatically close in <span id="countdown">5</span> seconds- </div>+ <% if (typeof autoPostCallback !== 'undefined' && autoPostCallback && typeof callbackUrl !== 'undefined') { %>+ <div class="redirect-message">+ Redirecting...+ </div>+ <form id="callbackForm" method="POST" action="<%= callbackUrl %>" style="display:none">+ <input type="hidden" name="relayAccountRef" value="<%= typeof accountId !== 'undefined' ? accountId : '' %>" />+ <input type="hidden" name="nickname" value="<%= typeof nickname !== 'undefined' ? nickname : '' %>" />+ <input type="hidden" name="avatar" value="<%= typeof avatar !== 'undefined' ? avatar : '' %>" />+ <input type="hidden" name="platformUid" value="<%= typeof platformUid !== 'undefined' ? platformUid : '' %>" />+ <input type="hidden" name="accountType" value="<%= typeof accountType !== 'undefined' ? accountType : '' %>" />+ <input type="hidden" name="taskId" value="<%= typeof taskId !== 'undefined' ? taskId : '' %>" />+ </form>+ <% } else { %>+ <div class="redirect-message">+ Page will automatically close in <span id="countdown">5</span> seconds+ </div>+ <% } %></div><script>- // Auto countdown to close page- let countdown = 5;- const countdownElement = document.getElementById('countdown');-- const countdownInterval = setInterval(() => {- countdown--;- countdownElement.textContent = countdown;-- if (countdown <= 0) {- clearInterval(countdownInterval);- // Try to close window, if unable to close then prompt user to close manually- window.close();- }- }, 1000);-- // If successful status, consider auto redirect to application homepage- // if (status === 'success') {- // setTimeout(() => {- // // Can add redirect logic here if needed- // // window.location.href = '/dashboard';- // }, 3000);- // }+ <% if (typeof autoPostCallback !== 'undefined' && autoPostCallback) { %>+ document.getElementById('callbackForm').submit();+ <% } else { %>+ var countdown = 5;+ var countdownElement = document.getElementById('countdown');+ var countdownInterval = setInterval(function() {+ countdown--;+ countdownElement.textContent = countdown;+ if (countdown <= 0) {+ clearInterval(countdownInterval);+ window.close();+ }+ }, 1000);+ <% } %></script></body>diff --git a/project/aitoearn-backend/eslint.config.mjs b/project/aitoearn-backend/eslint.config.mjsindex a3efe0fd..8920fb8b 100644--- a/project/aitoearn-backend/eslint.config.mjs+++ b/project/aitoearn-backend/eslint.config.mjs@@ -21,6 +21,9 @@ export default antfu(message: '禁止直接使用 Logger 的静态方法,请创建实例后使用(例如 this.logger.log())。',},],+ 'e18e/prefer-array-fill': ['off'],+ 'e18e/prefer-array-at': ['off'],+ 'e18e/prefer-static-regex': ['off'],'no-void': ['off'],'dot-notation': ['off'],'new-cap': ['off'],diff --git a/project/aitoearn-backend/libs/aitoearn-auth/package.json b/project/aitoearn-backend/libs/aitoearn-auth/package.jsonindex 4eedef9f..4fc1d511 100644--- a/project/aitoearn-backend/libs/aitoearn-auth/package.json+++ b/project/aitoearn-backend/libs/aitoearn-auth/package.json@@ -17,6 +17,7 @@"@nestjs/jwt": "^11.0.0","@nestjs/microservices": "^11.0.0","@yikart/common": "workspace:*",+ "@yikart/mongodb": "workspace:*","tslib": "^2.3.0","zod": "^4.3.5"},diff --git a/project/aitoearn-backend/libs/aitoearn-auth/src/aitoearn-auth.guard.ts b/project/aitoearn-backend/libs/aitoearn-auth/src/aitoearn-auth.guard.tsindex d4c244b1..7aff1584 100644--- a/project/aitoearn-backend/libs/aitoearn-auth/src/aitoearn-auth.guard.ts+++ b/project/aitoearn-backend/libs/aitoearn-auth/src/aitoearn-auth.guard.ts@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto'import {CanActivate,ExecutionContext,@@ -7,6 +8,7 @@ import {} from '@nestjs/common'import { Reflector } from '@nestjs/core'import { JwtService } from '@nestjs/jwt'+import { ApiKeyRepository, UserRepository, UserStatus } from '@yikart/mongodb'import { AitoearnAuthConfig } from './aitoearn-auth.config'import { IS_PUBLIC_KEY } from './aitoearn-auth.constants'@@ -18,6 +20,8 @@ export class AitoearnAuthGuard implements CanActivate {constructor(private readonly jwtService: JwtService,private readonly config: AitoearnAuthConfig,+ private readonly apiKeyRepository: ApiKeyRepository,+ private readonly userRepository: UserRepository,) {this.secret = config.secret}@@ -29,6 +33,29 @@ export class AitoearnAuthGuard implements CanActivate {])const request = context.switchToHttp().getRequest()++ // 1. API Key 认证+ const apiKey = request.headers['x-api-key'] as string | undefined+ if (apiKey) {+ const keyHash = createHash('sha1').update(apiKey).digest('hex')+ const record = await this.apiKeyRepository.getByKeyHash(keyHash)+ if (!record) {+ throw new UnauthorizedException()+ }+ await this.apiKeyRepository.updateLastUsedAt(record.id)+ const user = await this.userRepository.getById(record.userId)+ if (!user || user.isDelete || user.status !== UserStatus.OPEN) {+ throw new UnauthorizedException()+ }+ request['user'] = {+ id: record.userId,+ mail: user.mail,+ name: user.name,+ }+ return true+ }++ // 2. Bearer Token 认证const token = this.extractTokenFromHeader(request)if (!token) {if (isPublic) {diff --git a/project/aitoearn-backend/libs/aitoearn-queue/package.json b/project/aitoearn-backend/libs/aitoearn-queue/package.jsonindex 7c5af019..d810fb70 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/package.json+++ b/project/aitoearn-backend/libs/aitoearn-queue/package.json@@ -18,13 +18,13 @@"@yikart/common": "workspace:*","@yikart/mongodb": "workspace:*","@yikart/redis": "workspace:*",- "bullmq": "^5.0.0",- "nestjs-pino": "4.6.0",+ "bullmq": "^5.71.0",+ "nestjs-pino": "^4.6.1","prom-client": "^15.0.0","tslib": "^2.3.0","zod": "^4.3.5"},"dependencies": {- "ioredis": "^5.7.0"+ "ioredis": "5.9.3"}}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/enums/queue-name.enum.tsindex 3bb9bcbb..2dd455c9 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts@@ -3,18 +3,12 @@* 统一管理所有队列的名称*/export enum QueueName {- /** 素材生成队列 */- MaterialGenerate = 'bull_material_generate',-/** 发布任务队列 */PostPublish = 'post_publish',/** 发布媒体任务队列(Meta平台) */PostMediaTask = 'post_media_task',- /** 任务自动审核队列 */- TaskAudit = 'bull_aotu_task_audit',-/** AI图片异步生成队列 */AiImageAsync = 'ai_image_async',@@ -30,33 +24,15 @@ export enum QueueName {/** 更新发布任务队列 */UpdatePublishedPost = 'update_published_post',- /** 用户创建时推送任务队列 */- TaskUserCreatePush = 'task_user_create_push',-- /** 用户画像上报队列 */- TaskUserPortraitReport = 'task_user_portrait_report',-- /** 频道账号画像上报队列 */- TaskAccountPortraitReport = 'task_account_portrait_report',-- /** 支付 Webhook 处理队列 */- PaymentWebhookProcess = 'payment_webhook_process',-/** Credits 购买处理队列 */CreditsPurchase = 'credits_purchase',/** Credits 退款处理队列 */CreditsRefund = 'credits_refund',- /** 内容生成队列 */- ContentGenerationTask = 'content_generation_task',-/** 通知队列 */Notification = 'bull_notification',/** DraftGeneration 生成队列 */DraftGeneration = 'place_draft_generation',-- /** 用户任务异步验证队列(作品详情获取 + AI 检测) */- UserTaskAiVerify = 'user_task_ai_verify',}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/content-generation-task.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/content-generation-task.interface.tsdeleted file mode 100644index 473b1bf3..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/content-generation-task.interface.ts+++ /dev/null@@ -1,8 +0,0 @@-export interface ContentGenerationTaskData {- /** 任务ID */- taskId: string- /** 重试次数 */- attempts: number- /** 任务ID(可选) */- jobId?: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/draft-generation-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/draft-generation-data.interface.tsindex b1432bd8..b5ca809b 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/draft-generation-data.interface.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/draft-generation-data.interface.ts@@ -15,4 +15,7 @@ export interface DraftGenerationData {imageModel?: stringimageCount?: numberimageSize?: string+ draftType?: 'draft' | 'video'+ imageTextDraftType?: 'draft' | 'image'+ platforms?: string[]}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/index.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/index.tsindex 9ec704e2..66fd2fd4 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/index.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/index.ts@@ -2,12 +2,6 @@ export * from './ai-image-data.interface'export * from './credits-data.interface'export * from './draft-generation-data.interface'export * from './engagement-data.interface'-export * from './material-generate-data.interface'export * from './notification.interface'export * from './post-media-task-data.interface'export * from './post-publish-data.interface'-export * from './task-account-portrait-data.interface'-export * from './task-audit-data.interface'-export * from './task-user-create-data.interface'-export * from './task-user-portrait-data.interface'-export * from './user-task-ai-verify-data.interface'diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/material-generate-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/material-generate-data.interface.tsdeleted file mode 100644index 9305117b..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/material-generate-data.interface.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * 素材生成任务数据- */-export interface MaterialGenerateData {- /** 任务ID */- taskId: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/notification.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/notification.interface.tsindex 70be052b..0452ead2 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/notification.interface.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/notification.interface.ts@@ -26,14 +26,6 @@ type NotificationDataByTypetype: NotificationType.TaskReminderdata?: Record<string, unknown>})- | (BaseNotificationData & {- type: NotificationType.UserWithdraw- data?: Record<string, unknown>- })- | (BaseNotificationData & {- type: NotificationType.TaskPunish- data?: Record<string, unknown>- })| (BaseNotificationData & {type: NotificationType.AppReleasedata?: Record<string, unknown>diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-account-portrait-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-account-portrait-data.interface.tsdeleted file mode 100644index e94575d6..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-account-portrait-data.interface.ts+++ /dev/null@@ -1,22 +0,0 @@-import { AccountType } from '@yikart/common'-import { AccountStatus } from '@yikart/mongodb'--/**- * 频道账号画像上报数据接口- */-export interface TaskAccountPortraitData {- accountId?: string- userId?: string- type: AccountType // AccountType- uid: string // 频道平台唯一ID- avatar?: string- nickname?: string- status?: AccountStatus- contentTags?: Record<string, number>- totalFollowers?: number- totalWorks?: number- totalViews?: number- totalLikes?: number- totalCollects?: number- countryCode?: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-audit-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-audit-data.interface.tsdeleted file mode 100644index e7c6b251..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-audit-data.interface.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * 任务审核数据- */-export interface TaskAuditData {- /** 用户任务ID */- userTaskId: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-create-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-create-data.interface.tsdeleted file mode 100644index 87d31b12..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-create-data.interface.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * 用户创建时推送任务的数据接口- */-export interface TaskUserCreateData {- /** 用户ID */- userId: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-portrait-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-portrait-data.interface.tsdeleted file mode 100644index 96ccd48e..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/task-user-portrait-data.interface.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * 用户画像上报数据接口- */-export interface TaskUserPortraitData {- userId: string- name?: string- avatar?: string- status?: number- lastLoginTime?: string- contentTags?: Record<string, number>- totalFollowers?: number- totalWorks?: number- totalViews?: number- totalLikes?: number- totalCollects?: number-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/user-task-ai-verify-data.interface.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/user-task-ai-verify-data.interface.tsdeleted file mode 100644index 60d14580..00000000--- a/project/aitoearn-backend/libs/aitoearn-queue/src/interfaces/user-task-ai-verify-data.interface.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * 用户任务异步验证数据(作品详情获取 + AI 检测)- */-export interface UserTaskAiVerifyData {- /** 用户任务ID */- userTaskId: string- /** 平台类型,用于获取作品详情 */- accountType?: string- /** 账号 ID,用于 OAuth 授权获取详情 */- accountId?: string- /** 作品链接 */- workLink: string- /** 作品 dataId */- dataId: string-}diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/queue.module.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/queue.module.tsindex 77b134a3..414c39ea 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/queue.module.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/queue.module.ts@@ -40,6 +40,7 @@ export class AitoearnQueueModule {RedisModule.forRoot(config.redis),// 配置 Bull 连接BullModule.forRootAsync({+ imports: [],useFactory: (redis: Redis) => ({prefix: config.prefix,connection: redis,diff --git a/project/aitoearn-backend/libs/aitoearn-queue/src/queue.service.ts b/project/aitoearn-backend/libs/aitoearn-queue/src/queue.service.tsindex 4f212e5f..4d536611 100644--- a/project/aitoearn-backend/libs/aitoearn-queue/src/queue.service.ts+++ b/project/aitoearn-backend/libs/aitoearn-queue/src/queue.service.ts@@ -6,20 +6,13 @@ import type {DraftGenerationData,EngagementReplyToCommentData,EngagementTaskDistributionData,- MaterialGenerateData,NotificationData,PostMediaTaskData,PostPublishData,- TaskAccountPortraitData,- TaskAuditData,- TaskUserCreateData,- TaskUserPortraitData,- UserTaskAiVerifyData,} from './interfaces'import { InjectQueue } from '@nestjs/bullmq'import { Injectable } from '@nestjs/common'import { QueueName } from './enums'-import { ContentGenerationTaskData } from './interfaces/content-generation-task.interface'import { QueueConfig } from './queue.config'/**@@ -32,14 +25,10 @@ export class QueueService {constructor(private config: QueueConfig,- @InjectQueue(QueueName.MaterialGenerate)- private materialGenerateQueue: Queue,@InjectQueue(QueueName.PostPublish)private postPublishQueue: Queue,@InjectQueue(QueueName.PostMediaTask)private postMediaTaskQueue: Queue,- @InjectQueue(QueueName.TaskAudit)- private taskAuditQueue: Queue,@InjectQueue(QueueName.AiImageAsync)private aiImageAsyncQueue: Queue,@InjectQueue(QueueName.EngagementTaskDistribution)@@ -50,28 +39,15 @@ export class QueueService {private dumpSocialMediaAvatarQueue: Queue,@InjectQueue(QueueName.UpdatePublishedPost)private updatePublishedPostQueue: Queue,- @InjectQueue(QueueName.TaskUserCreatePush)- private taskUserCreatePushQueue: Queue,- @InjectQueue(QueueName.TaskUserPortraitReport)- private taskUserPortraitReportQueue: Queue,- @InjectQueue(QueueName.TaskAccountPortraitReport)- private taskAccountPortraitReportQueue: Queue,- @InjectQueue(QueueName.PaymentWebhookProcess)- private paymentWebhookProcessQueue: Queue,@InjectQueue(QueueName.CreditsPurchase)private creditsPurchaseQueue: Queue,@InjectQueue(QueueName.CreditsRefund)private creditsRefundQueue: Queue,- @InjectQueue(QueueName.ContentGenerationTask)- private contentGenerationTaskQueue: Queue,@InjectQueue(QueueName.Notification)private notificationQueue: Queue,@InjectQueue(QueueName.DraftGeneration)private draftGenerationQueue: Queue,- @InjectQueue(QueueName.UserTaskAiVerify)- private userTaskAiVerifyQueue: Queue,) {- // 从配置中读取默认的 job optionsthis.defaultOptions = config.jobOptions || {removeOnComplete: { age: 30, count: 1000 },removeOnFail: { age: 60, count: 1000 },@@ -79,19 +55,6 @@ export class QueueService {}}- /**- * 添加素材生成任务- */- async addMaterialGenerateJob(data: MaterialGenerateData, options?: JobsOptions) {- return await this.materialGenerateQueue.add('start', data, {- ...this.defaultOptions,- ...options,- })- }-- /**- * 添加发布任务- */async addPostPublishJob(data: PostPublishData, options?: JobsOptions) {return await this.postPublishQueue.add('publish', data, {...this.defaultOptions,@@ -100,16 +63,10 @@ export class QueueService {})}- /**- * 获取发布任务- */async getPostPublishJob(jobId: string): Promise<Job<PostPublishData> | undefined> {return await this.postPublishQueue.getJob(jobId)}- /**- * 添加发布媒体任务- */async addPostMediaTaskJob(data: PostMediaTaskData, options?: JobsOptions) {return await this.postMediaTaskQueue.add('media', data, {...this.defaultOptions,@@ -117,19 +74,6 @@ export class QueueService {})}- /**- * 添加任务审核任务- */- async addTaskAuditJob(data: TaskAuditData, options?: JobsOptions) {- return await this.taskAuditQueue.add('audit', data, {- ...this.defaultOptions,- ...options,- })- }-- /**- * 添加AI图片异步生成任务- */async addAiImageAsyncJob(data: AiImageData, options?: JobsOptions) {return await this.aiImageAsyncQueue.add('generate', data, {...this.defaultOptions,@@ -137,9 +81,6 @@ export class QueueService {})}- /**- * 添加互动任务分发任务- */async addEngagementTaskDistributionJob(data: EngagementTaskDistributionData,options?: JobsOptions,@@ -157,9 +98,6 @@ export class QueueService {})}- /**- * 添加评论回复任务- */async addEngagementReplyToCommentJob(data: EngagementReplyToCommentData, options?: JobsOptions) {return await this.engagementReplyToCommentQueue.add('reply', data, {...this.defaultOptions,@@ -174,52 +112,6 @@ export class QueueService {})}- /**- * 添加用户创建时推送任务- */- async addTaskUserCreatePushJob(data: TaskUserCreateData, options?: JobsOptions) {- return await this.taskUserCreatePushQueue.add('push', data, {- ...this.defaultOptions,- ...options,- })- }-- /**- * 添加用户画像上报任务- */- async addTaskUserPortraitReportJob(data: TaskUserPortraitData, options?: JobsOptions) {- return await this.taskUserPortraitReportQueue.add('report', data, {- ...this.defaultOptions,- ...options,- })- }-- /**- * 添加频道账号画像上报任务- */- async addTaskAccountPortraitReportJob(data: TaskAccountPortraitData, options?: JobsOptions) {- return await this.taskAccountPortraitReportQueue.add('report', data, {- ...this.defaultOptions,- ...options,- })- }-- /**- * 添加支付 Webhook 处理任务- */- async addPaymentWebhookProcessJob(data: { id: string }, options?: JobsOptions) {- return await this.paymentWebhookProcessQueue.add('process-webhook-event', data, {- ...this.defaultOptions,- jobId: data.id,- removeOnComplete: true,- removeOnFail: false,- ...options,- })- }-- /**- * 添加 Credits 购买处理任务- */async addCreditsPurchaseJob(data: CreditsPurchaseData, options?: JobsOptions) {return await this.creditsPurchaseQueue.add('purchase', data, {...this.defaultOptions,@@ -227,9 +119,6 @@ export class QueueService {})}- /**- * 添加 Credits 退款处理任务- */async addCreditsRefundJob(data: CreditsRefundData, options?: JobsOptions) {return await this.creditsRefundQueue.add('refund', data, {...this.defaultOptions,@@ -237,13 +126,6 @@ export class QueueService {})}- async addContentGenerationTaskJob(data: ContentGenerationTaskData, options?: JobsOptions) {- return await this.contentGenerationTaskQueue.add('generate', data, {- ...this.defaultOptions,- ...options,- })- }-async addNotificationJob(data: NotificationData, options?: JobsOptions) {return await this.notificationQueue.add('send-notification', data, {...this.defaultOptions,@@ -251,26 +133,9 @@ export class QueueService {})}- /**- * 添加 DraftGeneration 生成任务- */async addDraftGenerationJob(data: DraftGenerationData, options?: JobsOptions) {return await this.draftGenerationQueue.add('generate', data, {...this.defaultOptions,- attempts: 3,- backoff: { type: 'exponential', delay: 5000 },- ...options,- })- }-- /**- * 添加用户任务异步验证任务(作品详情获取 + AI 检测)- */- async addUserTaskAiVerifyJob(data: UserTaskAiVerifyData, options?: JobsOptions) {- return await this.userTaskAiVerifyQueue.add('verify', data, {- ...this.defaultOptions,- attempts: 3,- backoff: { type: 'exponential', delay: 5000 },...options,})}diff --git a/project/aitoearn-backend/libs/ali-oss/src/ali-oss.config.ts b/project/aitoearn-backend/libs/ali-oss/src/ali-oss.config.tsindex 09d8e171..c3a26240 100644--- a/project/aitoearn-backend/libs/ali-oss/src/ali-oss.config.ts+++ b/project/aitoearn-backend/libs/ali-oss/src/ali-oss.config.ts@@ -6,8 +6,8 @@ export const aliOssConfigSchema = z.object({accessKeySecret: z.string().describe('阿里云 AccessKey Secret'),bucket: z.string().describe('OSS Bucket 名称'),region: z.string().describe('OSS 区域,如 oss-cn-hangzhou'),- endpoint: z.string().optional().describe('自定义 endpoint'),- cdnEndpoint: z.string().optional().describe('CDN 加速域名'),+ endpoint: z.url().optional().describe('自定义 endpoint'),+ cdnEndpoint: z.url().optional().describe('CDN 加速域名'),internal: z.boolean().optional().describe('是否使用内网访问'),secure: z.boolean().optional().describe('是否使用 HTTPS'),timeout: z.union([z.string(), z.number()]).optional().describe('请求超时时间'),diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.config.tsindex f5fdf4fc..560f6612 100644--- a/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.config.ts@@ -8,8 +8,9 @@ export const s3ConfigSchema = z.object({bucketName: z.string(),endpoint: z.url(),cdnEndpoint: z.url().optional(),- signEndpoint: z.url().optional().describe('预签名 URL 使用的外部可达 endpoint,不设置则使用 endpoint'),signExpires: z.number().default(5 * 60).describe('sign expires in seconds'),+ forcePathStyle: z.boolean().default(false).describe('使用 path-style 访问,本地 S3 兼容服务需要开启'),+ publicEndpoint: z.url().optional().describe('客户端可访问的公网 endpoint,用于生成 presigned URL;不设置时使用 endpoint'),})export class S3Config extends createZodDto(s3ConfigSchema) {}diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.constants.tsindex f79c6b8c..de10ae5d 100644--- a/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.constants.ts@@ -1 +1 @@-export const SIGN_S3_CLIENT = Symbol('SIGN_S3_CLIENT')+export const S3_SIGNING_CLIENT = Symbol('S3_SIGNING_CLIENT')diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.module.tsindex 2f54517e..e019072b 100644--- a/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.module.ts@@ -2,7 +2,7 @@ import type { DynamicModule, Provider } from '@nestjs/common'import { S3Client } from '@aws-sdk/client-s3'import { Global, Module } from '@nestjs/common'import { S3Config } from './s3.config'-import { SIGN_S3_CLIENT } from './s3.constants'+import { S3_SIGNING_CLIENT } from './s3.constants'import { S3Service } from './s3.service'@Global()@@ -24,17 +24,17 @@ export class S3Module {useFactory: (s3Config: S3Config) => new S3Client({region: s3Config.region,endpoint: s3Config.endpoint,- forcePathStyle: true,+ forcePathStyle: s3Config.forcePathStyle,credentials: buildCredentials(s3Config),}),inject: [S3Config],},{- provide: SIGN_S3_CLIENT,+ provide: S3_SIGNING_CLIENT,useFactory: (s3Config: S3Config) => new S3Client({region: s3Config.region,- endpoint: s3Config.signEndpoint || s3Config.endpoint,- forcePathStyle: true,+ endpoint: s3Config.publicEndpoint || s3Config.endpoint,+ forcePathStyle: s3Config.forcePathStyle,credentials: buildCredentials(s3Config),}),inject: [S3Config],@@ -46,7 +46,7 @@ export class S3Module {global: true,module: S3Module,providers,- exports: [S3Service, SIGN_S3_CLIENT],+ exports: [S3Service],}}}diff --git a/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts b/project/aitoearn-backend/libs/aws-s3/src/s3.service.tsindex c5e8e04c..bb4cce6f 100644--- a/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts+++ b/project/aitoearn-backend/libs/aws-s3/src/s3.service.ts@@ -18,7 +18,7 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner'import { Inject, Injectable, Logger } from '@nestjs/common'import { AppException, ResponseCode } from '@yikart/common'import { S3Config } from './s3.config'-import { SIGN_S3_CLIENT } from './s3.constants'+import { S3_SIGNING_CLIENT } from './s3.constants'@Injectable()export class S3Service {@@ -27,7 +27,7 @@ export class S3Service {constructor(private readonly config: S3Config,private readonly client: S3Client,- @Inject(SIGN_S3_CLIENT) private readonly signClient: S3Client,+ @Inject(S3_SIGNING_CLIENT) private readonly signingClient: S3Client,) {}async putObject(@@ -79,7 +79,7 @@ export class S3Service {// 生成预签名上传 URLasync getUploadSignPost(objectPath: string, contentType?: string) {- const result = await createPresignedPost(this.signClient, {+ const result = await createPresignedPost(this.signingClient, {Bucket: this.config.bucketName,Key: objectPath,Expires: this.config.signExpires,@@ -90,7 +90,7 @@ export class S3Service {}async getUploadSignUrl(objectPath: string, contentType?: string, contentLength?: number) {- return getSignedUrl(this.signClient, new PutObjectCommand({+ return getSignedUrl(this.signingClient, new PutObjectCommand({Bucket: this.config.bucketName,Key: objectPath,ContentType: contentType,@@ -204,7 +204,7 @@ export class S3Service {* 生成预签名 GET URL(用于让外部服务读取 R2 对象,绕过 CDN 限制)*/async getReadSignUrl(objectPath: string, expiresIn = 3600) {- return getSignedUrl(this.signClient, new GetObjectCommand({+ return getSignedUrl(this.signingClient, new GetObjectCommand({Bucket: this.config.bucketName,Key: objectPath,}), { expiresIn })diff --git a/project/aitoearn-backend/libs/channel-db/src/repositories/engagement-task.repository.ts b/project/aitoearn-backend/libs/channel-db/src/repositories/engagement-task.repository.tsindex 3ca1f994..c93620a0 100644--- a/project/aitoearn-backend/libs/channel-db/src/repositories/engagement-task.repository.ts+++ b/project/aitoearn-backend/libs/channel-db/src/repositories/engagement-task.repository.ts@@ -34,14 +34,14 @@ export class EngagementTaskRepository extends BaseRepository<EngagementTask> {}async updateFailedSubTaskCount(taskId: string, count: number): Promise<EngagementTask | null> {- return this.engagementTaskModel.findByIdAndUpdate(taskId, { failedSubTaskCount: count }).lean({ virtuals: true })+ return this.engagementTaskModel.findByIdAndUpdate(taskId, { $inc: { failedSubTaskCount: count } }, { new: true }).lean({ virtuals: true })}async updateSubTaskCount(taskId: string, count: number): Promise<EngagementTask | null> {- return this.engagementTaskModel.findByIdAndUpdate(taskId, { subTaskCount: count }).lean({ virtuals: true })+ return this.engagementTaskModel.findByIdAndUpdate(taskId, { $inc: { subTaskCount: count } }, { new: true }).lean({ virtuals: true })}async updateCompletedSubTaskCount(taskId: string, count: number): Promise<EngagementTask | null> {- return this.engagementTaskModel.findByIdAndUpdate(taskId, { completedSubTaskCount: count }).lean({ virtuals: true })+ return this.engagementTaskModel.findByIdAndUpdate(taskId, { $inc: { completedSubTaskCount: count } }, { new: true }).lean({ virtuals: true })}}diff --git a/project/aitoearn-backend/libs/common/package.json b/project/aitoearn-backend/libs/common/package.jsonindex d04daef1..ad9f365a 100644--- a/project/aitoearn-backend/libs/common/package.json+++ b/project/aitoearn-backend/libs/common/package.json@@ -33,7 +33,7 @@"commander": "^14.0.0","nanoid": "^5.1.6","nest-typed-config": "^2.10.1",- "nestjs-pino": "^4.6.0",+ "nestjs-pino": "^4.6.1","pino": "^10.3.1","pino-pretty": "^13.1.1","prom-client": "^15.1.3",diff --git a/project/aitoearn-backend/libs/common/src/enums/notification.enum.ts b/project/aitoearn-backend/libs/common/src/enums/notification.enum.tsindex 0f718bbe..39035487 100644--- a/project/aitoearn-backend/libs/common/src/enums/notification.enum.ts+++ b/project/aitoearn-backend/libs/common/src/enums/notification.enum.ts@@ -7,8 +7,6 @@ export enum NotificationStatus {// 通知类型枚举export enum NotificationType {TaskReminder = 'task_reminder',- UserWithdraw = 'user_withdraw',- TaskPunish = 'task_punish',AgentResult = 'agent_result',AppRelease = 'app_release',AiReviewSkipped = 'ai_review_skipped',diff --git a/project/aitoearn-backend/libs/common/src/enums/response-code.enum.ts b/project/aitoearn-backend/libs/common/src/enums/response-code.enum.tsindex c3e1af2d..b02c1fdf 100755--- a/project/aitoearn-backend/libs/common/src/enums/response-code.enum.ts+++ b/project/aitoearn-backend/libs/common/src/enums/response-code.enum.ts@@ -13,8 +13,6 @@ export enum ResponseCode {// 10100-10199: s3/aws-s3/gcsS3DownloadFileFailed = 10100,- S3UploadFailed = 10101,- InvalidGcsUri = 10102,// ========================================// 12000-12999: aitoearn-server(主服务)@@ -23,51 +21,23 @@ export enum ResponseCode {// 12000-12099: user(用户模块)UserNotFound = 12000,UserCreditsInsufficient = 12001,- UserStorageExceeded = 12002,UserStatusError = 12003,- UserPasswordError = 12004,UserLoginCodeError = 12005,- UserInviteCodeError = 12006,- UserAlreadyExists = 12007,- UserBanned = 12008,- UserMembershipExpired = 12009,- GetUserTokenFailed = 12010,- UserAlreadyHasLibrary = 12011,- UserNoLibrary = 12012,-- // 12100-12199: balance-record/withdraw(余额记录/提现模块)- UserInsufficientBalance = 12102,- WithdrawRecordNotFound = 12105,- WithdrawRecordStatusError = 12106,- WithdrawRecordExists = 12107,-- // 12200-12299: wallet-account(钱包账户)- UserWalletAccountAlreadyExists = 12200,- UserWalletAccountLimitExceeded = 12201,// 12300-12399: ai(AI 模块)InvalidModel = 12300,AiCallFailed = 12301,InvalidAiTaskId = 12302,AiLogNotFound = 12303,- VideoUploadInvalidInput = 12304,- VideoUploadJobIdNotFound = 12305,- VideoUploadTaskInfoNotFound = 12306,VideoUploadVidNotFound = 12307,VideoUploadFailed = 12308,// 12400-12499: notification(通知)NotificationNotFound = 12400,- // 12500-12599: app-release(应用发布)- AppReleaseNotFound = 12500,- AppReleaseAlreadyExists = 12501,-// 12600-12699: account(社交账号)AccountNotFound = 12600,AccountGroupNotFound = 12601,- AccountStatisticsNotFound = 12602,- AccountGroupCountryCodeInvalid = 12603,AccountCreateFailed = 12604,// 12700-12799: media(媒体文件)@@ -82,232 +52,73 @@ export enum ResponseCode {// 12800-12899: material(素材)MaterialNotFound = 12800,MaterialGroupNotFound = 12801,- MaterialTaskNotFound = 12802,MaterialGroupDefaultNotAllowed = 12803,MaterialAdaptationNotFound = 12804,MaterialAdaptationFailed = 12805,- // 12900-12999: content(内容组合)- MaterialGroupEmpty = 12900,- MaterialGroupTypeError = 12901,- MediaGroupTypeNotSupported = 12902,- GroupInfoNotFound = 12903,-- // ========================================- // 13000-13999: aitoearn-admin-server(管理后台)- // ========================================-- // 13000-13099: manager(管理员)- ManagerAlreadyExists = 13000,- ManagerCreateFailed = 13001,- ManagerNotFound = 13002,- ManagerPasswordError = 13003,-- // 13100-13199: feedback(反馈)- FeedbackCreateFailed = 13100,-- // 13200-13299: admin-operation(管理后台操作)- AdminOperationPasswordError = 13200,-- // ========================================- // 14000-14999: aitoearn-payment(支付服务)- // ========================================-- // 14000-14099: payment(支付相关)- PaymentInvalidWebhookSignature = 14000,- PaymentCheckoutNotFound = 14001,- PaymentChargeNotFound = 14002,- PaymentSubscriptionNotFound = 14003,- PaymentMissingSubscriptionId = 14004,- PaymentInvalidPaymentIntent = 14005,- PaymentInvalidMode = 14006,- PaymentPriceNotFound = 14007,- PaymentProductCreateFailed = 14008,- PaymentProductUpdateFailed = 14009,- PaymentSubscriptionAlreadyExists = 14010,- PaymentSubscriptionNotPendingCancel = 14011,- ConnectedAccountNotFound = 14012,- ConnectedAccountNotActive = 14013,- ConnectedAccountOnboardingIncomplete = 14014,- ConnectedAccountOnboardingComplete = 14015,- TransferNotFound = 14016,- TransferFailed = 14017,- PaymentMembershipSuspended = 14018,-- // 14100-14199: balance/withdraw(余额/提现)- InsufficientBalance = 14100,- InsufficientFrozenBalance = 14101,- UserWalletAccountNotFound = 14102,- InvalidParameter = 14103,- NoPendingBalanceToWithdraw = 14104,- WithdrawRecordCannotCancel = 14105,- InvalidWalletAccountType = 14106,- UserWalletAccountNotVerified = 14107,-- // 14108-14119: Wise(Wise 转账)- WiseRecipientNotFound = 14108,- WiseRecipientCreateFailed = 14109,- WiseQuoteCreateFailed = 14110,- WiseTransferCreateFailed = 14111,- WiseTransferFundFailed = 14112,- WiseAccountRequirementsFailed = 14113,- WiseInvalidBankDetails = 14114,- WiseTransferNotFound = 14115,- WiseWebhookSignatureInvalid = 14116,-- // 14120-14199: balance-record(余额记录)- BalanceRecordNotFound = 14120,-- // 14200-14299: refund(退款)- PaymentNoRefundableCheckout = 14200,- PaymentRefundAmountExceeded = 14201,-// ========================================// 15000-15999: aitoearn-channel(渠道服务)// ========================================// 15000-15099: channel/publish(渠道发布相关)PublishRecordNotFound = 15000,- ChannelAccountNotAuthorized = 15001,ChannelAuthorizationExpired = 15002,ChannelAccountInfoFailed = 15003,PublishTaskNotFound = 15004,ChannelWebhookFailed = 15005,- ChannelCredentialNotFound = 15006,- ChannelRefreshTokenNotFound = 15007,- ChannelRefreshTokenExpired = 15008,ChannelRefreshTokenFailed = 15009,ChannelAccessTokenFailed = 15010,ChannelPlatformTokenNotFound = 15011,ChannelAuthTaskFailed = 15012,- ChannelNoAccountsFound = 15014,- PublishServiceNotFound = 15015,PublishTaskFailed = 15016,PublishTaskInProgress = 15017,PublishTaskStatusInvalid = 15018,- PublishTimeInvalid = 15019,EngagementTaskInProgress = 15020,ChannelAccountNotFound = 15021,InteractAccountTypeNotSupported = 15022,InteractRecordNotFound = 15023,DataCubeAccountTypeNotSupported = 15024,ChannelPublishTaskAlreadyExists = 15025,- PublishTaskAlreadyPublishing = 15026,- PublishTaskAlreadyCompleted = 15027,PublishTaskNotPublished = 15028,- PublishTaskAlreadyUpdating = 15029,- PublishTaskAlreadyWaitingForUpdate = 15030,PostCategoryNotSupported = 15031,PlatformNotSupported = 15032,PublishTaskUpdateFailed = 15033,DeletePostFailed = 15034,PublishTaskInvalid = 15035,- // 解析链接,获取视频IDInvalidWorkLink = 15036,- // 作品不属于该账号WorkNotBelongToAccount = 15037,// 15100-15199: short-link(短链接)ShortLinkNotFound = 15100,- ShortLinkExpired = 15101,// ========================================// 16000-16999: aitoearn-task(任务服务)// ========================================- // 16000-16099: task(任务核心)- TaskNotFound = 16000,- TaskOpportunityNotFound = 16001,- TaskOpportunityAlreadyExists = 16002,- UserTaskNotFound = 16003,- InvalidUserTaskId = 16004,- TaskOpportunityCannotDelete = 16005,- UserTaskStatusInvalid = 16006,- TaskExpired = 16007,- TaskRecruitsFullDec = 16008,- TaskAccountNotBelongToUser = 16009,- TaskAccountTypeInvalid = 16010,- TaskAlreadyTaken = 16011,- MaterialConsumed = 16012,- TaskMatcherNotFound = 16013,- FailedToSettleUserTasks = 16014,- UserTaskSettleNotFound = 16015,- UserTaskPostNotFound = 16016,- PostDataError = 16017,- WorkAlreadySubmitted = 16022, // 作品已被提交过- WorkDataIdNotFound = 16023, // 作品数据ID未找到- WorkDataNotMatch = 16024, // 作品数据不匹配- WorkLinkInfoNotFound = 16025, // 作品链接信息未找到- WorkDetailNotFound = 16026, // 作品详情未找到- WorkPublishTimeExpired = 16034, // 作品发布时间超过限制- TaskPricingNotFound = 16035, // 任务定价配置不存在- AdvertiserInsufficientBalance = 16036, // 广告主余额不足,请充值- AccountAuthRequired = 16037, // 该平台需要先授权账号- PlatformNotDetected = 16038, // 无法从链接识别平台- UserTaskKeepTimeExpired = 16039, // 用户任务保留时间已过期- TaskAlreadyCancelled = 16040, // 任务已停止- TaskNotOwnedByUser = 16041, // 任务不属于当前用户- LocationScreenshotRequired = 16042, // 同城任务需要提交位置截图- LocationVerifyFailed = 16043, // 位置截图与任务城市不匹配- UserTaskDisputeNotFound = 16044, // 争议记录未找到- UserTaskDisputeAlreadyExists = 16045, // 该任务已存在待处理争议- UserTaskDisputeStatusInvalid = 16046, // 争议状态无效-- // 16047: instance-capture(即时抓取)- InstanceCaptureTooFrequent = 16047, // 同一任务10分钟内只能提交一次-- // 16027-16049: promotion-code(推广码)- PromotionCodeNotFound = 16027,- PromotionCodeAlreadyExists = 16028,- PromotionCodeTaskNotFound = 16029,- PromotionCodeAlreadyLinked = 16030,- PromotionCodeDisabled = 16031,- PromotionCodeNotLinked = 16032,- PromotionCodeTaskNotActive = 16033,+ WorkDetailNotFound = 16026,+ AccountAuthRequired = 16037,// 16050-16099: task-material(任务素材)- TaskMaterialGroupNotFound = 16050,- TaskMaterialEmpty = 16051,MaterialGroupPlatformMismatch = 16052,+ // ========================================+ // 18000-18999: aitoearn-ai(AI 服务)+ // ========================================+// 18100-18199: agent(代理服务)AgentTaskNotFound = 18100,AgentTaskStatusInvalid = 18101,- GenerateImagesFailed = 18102,- GenerateVideosFailed = 18103,AgentTaskFailed = 18104,- DailyTaskQuotaExceeded = 18105,- GenerateContentFailed = 18106,AgentTaskTimeout = 18107,AgentTaskNotRunning = 18108,AgentSessionRecoveryFailed = 18109,- // 18300-18399: place-draft(地点草稿)- PlaceDraftNotFound = 18300,-// 18400-18499: tools(工具模块)QrCodeArtImageNotFound = 18400,- // 18500-18599: campaign(探店活动)- CampaignNotFound = 18500,- CampaignAlreadyClosed = 18501,- CampaignBudgetExceeded = 18502,- CampaignQuestionnaireGenerateFailed = 18503,- CampaignStatusInvalid = 18504,-- // 18600-18699: campaign-application(探店报名)- CampaignApplicationNotFound = 18600,- CampaignApplicationDuplicate = 18601,- CampaignApplicationSlotsFull = 18602,- CampaignApplicationFollowersInsufficient = 18603,- CampaignApplicationLotteryNotDrawn = 18604,- CampaignApplicationVerifyCodeInvalid = 18605,- CampaignApplicationAlreadyVerified = 18606,- CampaignApplicationStatusInvalid = 18607,-- // 18608-18610: campaign-application(探店内容提交)- CampaignApplicationContentNotReady = 18608,- CampaignApplicationContentDeadlineExpired = 18609,- CampaignApplicationContentRetryExceeded = 18610,- CampaignApplicationVerifyCodeExpired = 18611,+ // ========================================+ // 19000-19099: api-key / relay+ // ========================================+ ApiKeyInvalid = 19000,+ RelayServerUnavailable = 19001,}diff --git a/project/aitoearn-backend/libs/common/src/filters/global-exception.filter.ts b/project/aitoearn-backend/libs/common/src/filters/global-exception.filter.tsindex 73faa7a5..35234a6f 100755--- a/project/aitoearn-backend/libs/common/src/filters/global-exception.filter.ts+++ b/project/aitoearn-backend/libs/common/src/filters/global-exception.filter.ts@@ -1,18 +1,18 @@-import type {- ArgumentsHost,- ExceptionFilter,-} from '@nestjs/common'import type { Response } from 'express'-import type { Observable } from 'rxjs'+import type { CommonResponse } from '../interfaces'import {+ ArgumentsHost,Catch,+ ExceptionFilter,+ HttpException,InternalServerErrorException,Logger,UnauthorizedException,} from '@nestjs/common'import { of } from 'rxjs'+import { AppException } from '../exceptions'import { getExceptionPayload } from '../utils'export interface GlobalExceptionFilterOptions {@@ -24,18 +24,21 @@ export class GlobalExceptionFilter<T> implements ExceptionFilter<T> {protected readonly logger = new Logger(GlobalExceptionFilter.name)constructor(private options: GlobalExceptionFilterOptions = {}) { }- catch(exception: T, host: ArgumentsHost): void | Observable<CommonResponse<unknown>> {- if (exception instanceof UnauthorizedException) {- this.logger.warn(exception)- }- else if (+ catch(exception: T, host: ArgumentsHost): void | Observable<CommonResponse<unknown> | void> {+ if (exception instanceof InternalServerErrorException) {this.logger.fatal(exception)}- else {+ else if (exception instanceof UnauthorizedException || exception instanceof AppException) {+ this.logger.warn(exception)+ }+ else if (exception instanceof HttpException) {this.logger.error(exception)}+ else {+ this.logger.fatal(exception)+ }const payload = getExceptionPayload(exception, this.options.returnBadRequestDetails)diff --git a/project/aitoearn-backend/libs/common/src/i18n/messages.ts b/project/aitoearn-backend/libs/common/src/i18n/messages.tsindex 4f4a6670..35c1f5d3 100644--- a/project/aitoearn-backend/libs/common/src/i18n/messages.ts+++ b/project/aitoearn-backend/libs/common/src/i18n/messages.ts@@ -35,14 +35,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Failed to download file from S3','zh-CN': 'S3 文件下载失败',},- [ResponseCode.S3UploadFailed]: {- 'en-US': 'Failed to upload file to S3',- 'zh-CN': 'S3文件上传失败',- },- [ResponseCode.InvalidGcsUri]: {- 'en-US': 'Invalid GCS URI format',- 'zh-CN': '无效的 GCS URI 格式',- },// 12000 (user)[ResponseCode.UserNotFound]: {@@ -53,80 +45,14 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Insufficient user credits','zh-CN': '用户Credits不足',},- [ResponseCode.UserStorageExceeded]: {- 'en-US': 'User storage exceeded',- 'zh-CN': '用户存储空间超限',- },[ResponseCode.UserStatusError]: {'en-US': 'User status error','zh-CN': '用户状态错误',},- [ResponseCode.UserPasswordError]: {- 'en-US': 'Incorrect password',- 'zh-CN': '密码错误',- },[ResponseCode.UserLoginCodeError]: {'en-US': 'Incorrect login code','zh-CN': '登录验证码错误',},- [ResponseCode.UserInviteCodeError]: {- 'en-US': 'Invalid invite code',- 'zh-CN': '邀请码无效',- },- [ResponseCode.UserAlreadyExists]: {- 'en-US': 'User already exists',- 'zh-CN': '用户已存在',- },-- [ResponseCode.UserBanned]: {- 'en-US': 'User has been banned',- 'zh-CN': '用户已被封禁',- },- [ResponseCode.UserMembershipExpired]: {- 'en-US': 'User membership expired',- 'zh-CN': '用户会员已过期',- },- [ResponseCode.GetUserTokenFailed]: {- 'en-US': 'Failed to get user token',- 'zh-CN': '获取用户Token失败',- },- [ResponseCode.UserAlreadyHasLibrary]: {- 'en-US': 'User already has a linked restaurant',- 'zh-CN': '用户已关联餐厅',- },- [ResponseCode.UserNoLibrary]: {- 'en-US': 'User has no linked restaurant',- 'zh-CN': '用户未关联餐厅',- },-- // 12100 (balance-record/withdraw)- [ResponseCode.UserInsufficientBalance]: {- 'en-US': 'Insufficient balance',- 'zh-CN': '余额不足',- },-- [ResponseCode.WithdrawRecordNotFound]: {- 'en-US': 'Withdraw record not found',- 'zh-CN': '提现记录未找到',- },- [ResponseCode.WithdrawRecordStatusError]: {- 'en-US': 'Withdraw record status error',- 'zh-CN': '提现记录状态错误',- },- [ResponseCode.WithdrawRecordExists]: {- 'en-US': 'Withdraw record already exists',- 'zh-CN': '提现记录已存在',- },-- // 12200 (wallet-account)- [ResponseCode.UserWalletAccountAlreadyExists]: {- 'en-US': 'Wallet account already exists',- 'zh-CN': '钱包账户已存在',- },- [ResponseCode.UserWalletAccountLimitExceeded]: {- 'en-US': 'Wallet account limit exceeded',- 'zh-CN': '钱包账户数量超限',- },// 12300 (ai)[ResponseCode.InvalidModel]: {@@ -145,18 +71,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'AI log not found','zh-CN': 'AI 日志未找到',},- [ResponseCode.VideoUploadInvalidInput]: {- 'en-US': 'Invalid video input type',- 'zh-CN': '无效的视频输入类型',- },- [ResponseCode.VideoUploadJobIdNotFound]: {- 'en-US': 'Failed to get upload job ID',- 'zh-CN': '获取上传任务 ID 失败',- },- [ResponseCode.VideoUploadTaskInfoNotFound]: {- 'en-US': 'Failed to get upload task information',- 'zh-CN': '获取上传任务信息失败',- },[ResponseCode.VideoUploadVidNotFound]: {'en-US': 'Failed to get video ID from upload result','zh-CN': '从上传结果中获取视频 ID 失败',@@ -172,16 +86,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'zh-CN': '通知未找到',},- // 12500 (app-release)- [ResponseCode.AppReleaseNotFound]: {- 'en-US': 'App release not found',- 'zh-CN': '应用发布版本未找到',- },- [ResponseCode.AppReleaseAlreadyExists]: {- 'en-US': 'App release already exists',- 'zh-CN': '应用发布版本已存在',- },-// 12600 (account)[ResponseCode.AccountNotFound]: {'en-US': 'Account not found',@@ -191,14 +95,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Account group not found','zh-CN': '账号分组未找到',},- [ResponseCode.AccountStatisticsNotFound]: {- 'en-US': 'Account statistics not found',- 'zh-CN': '账号不存在',- },- [ResponseCode.AccountGroupCountryCodeInvalid]: {- 'en-US': 'Account group country code invalid',- 'zh-CN': '账号分组国家代码无效',- },[ResponseCode.AccountCreateFailed]: {'en-US': 'Account create failed','zh-CN': '账号创建失败',@@ -237,10 +133,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Material group not found','zh-CN': '素材分组未找到',},- [ResponseCode.MaterialTaskNotFound]: {- 'en-US': 'Material task not found',- 'zh-CN': '素材任务不存在',- },[ResponseCode.MaterialGroupDefaultNotAllowed]: {'en-US': 'Default material group cannot be deleted','zh-CN': '默认素材组不能删除',@@ -253,237 +145,12 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Failed to adapt material','zh-CN': '素材适配失败',},- // 12900 (content/material)- [ResponseCode.MaterialGroupEmpty]: {- 'en-US': 'Material group cannot be empty',- 'zh-CN': '素材组不能为空',- },- [ResponseCode.MaterialGroupTypeError]: {- 'en-US': 'Material group type error',- 'zh-CN': '素材组类型错误',- },- [ResponseCode.MediaGroupTypeNotSupported]: {- 'en-US': 'Media group type not supported',- 'zh-CN': '暂不支持该素材类型',- },- [ResponseCode.GroupInfoNotFound]: {- 'en-US': 'Group information not found',- 'zh-CN': '组信息不存在',- },-- // 13000 (manager)- [ResponseCode.ManagerAlreadyExists]: {- 'en-US': 'Manager already exists',- 'zh-CN': '管理员已存在',- },- [ResponseCode.ManagerCreateFailed]: {- 'en-US': 'Failed to create manager',- 'zh-CN': '创建管理员失败',- },- [ResponseCode.ManagerNotFound]: {- 'en-US': 'Manager not found',- 'zh-CN': '账号不存在',- },- [ResponseCode.ManagerPasswordError]: {- 'en-US': 'Incorrect password',- 'zh-CN': '密码错误',- },-- // 13100 (feedback)- [ResponseCode.FeedbackCreateFailed]: {- 'en-US': 'Failed to create feedback',- 'zh-CN': '创建失败',- },-- // 13200 (admin-operation)- [ResponseCode.AdminOperationPasswordError]: {- 'en-US': 'Incorrect operation password',- 'zh-CN': '操作密码错误',- },-- // 14000 (payment)- [ResponseCode.PaymentInvalidWebhookSignature]: {- 'en-US': 'Invalid webhook signature',- 'zh-CN': 'Webhook 签名无效',- },- [ResponseCode.PaymentCheckoutNotFound]: {- 'en-US': 'Checkout not found',- 'zh-CN': '结账会话未找到',- },- [ResponseCode.PaymentChargeNotFound]: {- 'en-US': 'Charge not found',- 'zh-CN': '支付记录未找到',- },- [ResponseCode.PaymentSubscriptionNotFound]: {- 'en-US': 'Subscription not found',- 'zh-CN': '订阅未找到',- },- [ResponseCode.PaymentMissingSubscriptionId]: {- 'en-US': 'Missing subscription ID',- 'zh-CN': '缺少订阅 ID',- },- [ResponseCode.PaymentInvalidPaymentIntent]: {- 'en-US': 'Invalid payment intent',- 'zh-CN': '无效的支付意图',- },- [ResponseCode.PaymentInvalidMode]: {- 'en-US': 'Invalid payment mode',- 'zh-CN': '无效的支付模式',- },- [ResponseCode.PaymentPriceNotFound]: {- 'en-US': 'Price not found',- 'zh-CN': '价格未找到',- },- [ResponseCode.PaymentProductCreateFailed]: {- 'en-US': 'Failed to create product',- 'zh-CN': '产品创建失败',- },- [ResponseCode.PaymentProductUpdateFailed]: {- 'en-US': 'Failed to update product',- 'zh-CN': '产品更新失败',- },- [ResponseCode.PaymentSubscriptionAlreadyExists]: {- 'en-US': 'Subscription already exists',- 'zh-CN': '订阅已存在',- },- [ResponseCode.PaymentSubscriptionNotPendingCancel]: {- 'en-US': 'Subscription is not pending cancellation',- 'zh-CN': '订阅未处于待取消状态',- },- [ResponseCode.ConnectedAccountNotFound]: {- 'en-US': 'Connected account not found',- 'zh-CN': '商家账户未找到',- },- [ResponseCode.ConnectedAccountNotActive]: {- 'en-US': 'Connected account is not active',- 'zh-CN': '商家账户未激活',- },- [ResponseCode.ConnectedAccountOnboardingIncomplete]: {- 'en-US': 'Connected account onboarding is incomplete',- 'zh-CN': '商家账户入驻流程未完成',- },- [ResponseCode.ConnectedAccountOnboardingComplete]: {- 'en-US': 'Connected account onboarding is complete',- 'zh-CN': '商家账户入驻流程已完成',- },- [ResponseCode.TransferNotFound]: {- 'en-US': 'Transfer not found',- 'zh-CN': '转账记录未找到',- },- [ResponseCode.TransferFailed]: {- 'en-US': 'Transfer failed',- 'zh-CN': '转账失败',- },- [ResponseCode.PaymentMembershipSuspended]: {- 'en-US': 'Membership purchase is temporarily suspended',- 'zh-CN': '会员暂停使用',- },-- // 14100 (balance/withdraw)- [ResponseCode.InsufficientBalance]: {- 'en-US': 'Insufficient balance',- 'zh-CN': '余额不足',- },- [ResponseCode.InsufficientFrozenBalance]: {- 'en-US': 'Insufficient frozen balance',- 'zh-CN': '冻结余额不足',- },- [ResponseCode.UserWalletAccountNotFound]: {- 'en-US': 'Wallet account not found',- 'zh-CN': '钱包账户未找到',- },- [ResponseCode.InvalidParameter]: {- 'en-US': 'Invalid parameter',- 'zh-CN': '参数无效',- },- [ResponseCode.NoPendingBalanceToWithdraw]: {- 'en-US': 'No available balance to withdraw',- 'zh-CN': '没有可提现的余额',- },- [ResponseCode.WithdrawRecordCannotCancel]: {- 'en-US': 'Withdraw record cannot be cancelled',- 'zh-CN': '提现记录无法取消',- },- [ResponseCode.InvalidWalletAccountType]: {- 'en-US': 'Invalid wallet account type for this operation',- 'zh-CN': '钱包账户类型不支持此操作',- },- [ResponseCode.UserWalletAccountNotVerified]: {- 'en-US': 'Wallet account is not verified',- 'zh-CN': '钱包账户未验证',- },-- // 14108-14116 (Wise)- [ResponseCode.WiseRecipientNotFound]: {- 'en-US': 'Wise recipient not found',- 'zh-CN': 'Wise 收款人未找到',- },- [ResponseCode.WiseRecipientCreateFailed]: {- 'en-US': 'Failed to create Wise recipient',- 'zh-CN': 'Wise 收款人创建失败',- },- [ResponseCode.WiseQuoteCreateFailed]: {- 'en-US': 'Failed to create Wise quote',- 'zh-CN': 'Wise 报价创建失败',- },- [ResponseCode.WiseTransferCreateFailed]: {- 'en-US': 'Failed to create Wise transfer',- 'zh-CN': 'Wise 转账创建失败',- },- [ResponseCode.WiseTransferFundFailed]: {- 'en-US': 'Failed to fund Wise transfer',- 'zh-CN': 'Wise 转账资金发送失败',- },- [ResponseCode.WiseAccountRequirementsFailed]: {- 'en-US': 'Failed to get Wise account requirements',- 'zh-CN': '获取 Wise 账户要求失败',- },- [ResponseCode.WiseInvalidBankDetails]: {- 'en-US': 'Invalid bank details for Wise transfer',- 'zh-CN': 'Wise 转账银行信息无效',- },- [ResponseCode.WiseTransferNotFound]: {- 'en-US': 'Wise transfer not found',- 'zh-CN': 'Wise 转账记录未找到',- },- [ResponseCode.WiseWebhookSignatureInvalid]: {- 'en-US': 'Invalid Wise webhook signature',- 'zh-CN': 'Wise Webhook 签名无效',- },-- // 14120 (balance-record)- [ResponseCode.BalanceRecordNotFound]: {- 'en-US': 'Balance record not found',- 'zh-CN': '余额记录未找到',- },-- // 14200 (refund)- [ResponseCode.PaymentNoRefundableCheckout]: {- 'en-US': 'No refundable checkout found',- 'zh-CN': '没有可退款的订单',- },- [ResponseCode.PaymentRefundAmountExceeded]: {- 'en-US': 'Refund amount exceeds maximum refundable amount',- 'zh-CN': '退款金额超过最大可退款金额',- },// 15000 (channel/publish)[ResponseCode.PublishRecordNotFound]: {'en-US': 'publish record with flowId {{flowId}} not found.','zh-CN': '发布记录未找到',},- [ResponseCode.PublishTaskAlreadyPublishing]: {- 'en-US': 'Publish task is already publishing',- 'zh-CN': '发布任务正在执行中',- },- [ResponseCode.PublishTaskAlreadyCompleted]: {- 'en-US': 'Publish task is already completed',- 'zh-CN': '发布任务已完成',- },- [ResponseCode.ChannelAccountNotAuthorized]: {- 'en-US': 'Account not authorized',- 'zh-CN': '账号未授权',- },[ResponseCode.ChannelAuthorizationExpired]: {'en-US': 'Authorization expired','zh-CN': '授权已过期',@@ -500,18 +167,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Webhook processing failed','zh-CN': 'Webhook 处理失败',},- [ResponseCode.ChannelCredentialNotFound]: {- 'en-US': template.compile('{{channel}} credential not found for accountId: {{accountId}}'),- 'zh-CN': template.compile('{{channel}} 凭证未找到,账号ID: {{accountId}}'),- },- [ResponseCode.ChannelRefreshTokenNotFound]: {- 'en-US': template.compile('{{channel}} refresh token not found for accountId: {{accountId}}'),- 'zh-CN': template.compile('{{channel}} 刷新令牌未找到,账号ID: {{accountId}}'),- },- [ResponseCode.ChannelRefreshTokenExpired]: {- 'en-US': template.compile('{{channel}} refresh Token expired for accountId: {{accountId}}, expired at: {{credential.refresh_expires_in}}, please re-authorize'),- 'zh-CN': '刷新令牌已过期',- },[ResponseCode.ChannelRefreshTokenFailed]: {'en-US': 'refresh Token failed for accountId: {{accountId}}','zh-CN': '刷新令牌失败',@@ -528,14 +183,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Failed to create authorization task','zh-CN': '创建授权任务失败',},- [ResponseCode.ChannelNoAccountsFound]: {- 'en-US': 'No accounts found',- 'zh-CN': '未找到账号',- },- [ResponseCode.PublishServiceNotFound]: {- 'en-US': 'publish service for {{publishTask.accountType}} not found',- 'zh-CN': '未找到发布服务',- },[ResponseCode.PublishTaskFailed]: {'en-US': 'task publish failed, accountType: {{accountType}}','zh-CN': '任务发布失败',@@ -548,10 +195,6 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Task has been published or is in progress','zh-CN': '任务已发布或正在进行中',},- [ResponseCode.PublishTimeInvalid]: {- 'en-US': 'Publish time cannot be in the past',- 'zh-CN': '发布时间不能小于当前时间',- },[ResponseCode.EngagementTaskInProgress]: {'en-US': 'Reply task for this post is already in progress','zh-CN': '该帖子的回复任务已在进行中',@@ -580,21 +223,13 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Publish task not published','zh-CN': '发布任务未发布',},- [ResponseCode.PublishTaskAlreadyUpdating]: {- 'en-US': 'Publish task is already updating',- 'zh-CN': '发布任务正在更新中',- },- [ResponseCode.PlatformNotSupported]: {- 'en-US': 'Platform not supported for update published post',- 'zh-CN': '暂不支持该平台',- },[ResponseCode.PostCategoryNotSupported]: {'en-US': 'Post category not supported for update published post','zh-CN': '暂不支持该帖子类型',},- [ResponseCode.PublishTaskAlreadyWaitingForUpdate]: {- 'en-US': 'Publish task is already waiting for update',- 'zh-CN': '发布任务已等待更新',+ [ResponseCode.PlatformNotSupported]: {+ 'en-US': 'Platform not supported for update published post',+ 'zh-CN': '暂不支持该平台',},[ResponseCode.PublishTaskUpdateFailed]: {'en-US': 'Failed to update publish task',@@ -622,205 +257,24 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Short link not found','zh-CN': '短链接不存在',},- [ResponseCode.ShortLinkExpired]: {- 'en-US': 'Short link has expired',- 'zh-CN': '短链接已过期',- },// 16000 (task)- [ResponseCode.TaskNotFound]: {- 'en-US': 'Task not found',- 'zh-CN': '任务未找到',- },- [ResponseCode.TaskOpportunityNotFound]: {- 'en-US': 'Task opportunity not found',- 'zh-CN': '任务机会未找到',- },- [ResponseCode.TaskOpportunityAlreadyExists]: {- 'en-US': 'Task opportunity already exists',- 'zh-CN': '任务机会已存在',- },- [ResponseCode.UserTaskNotFound]: {- 'en-US': 'User task not found',- 'zh-CN': '用户任务未找到',- },- [ResponseCode.InvalidUserTaskId]: {- 'en-US': 'Invalid user task ID',- 'zh-CN': '无效的用户任务 ID',- },- [ResponseCode.TaskOpportunityCannotDelete]: {- 'en-US': 'Task has been accepted or does not exist and cannot be deleted',- 'zh-CN': '任务已被接受或不存在,无法删除',- },- [ResponseCode.UserTaskStatusInvalid]: {- 'en-US': 'Task status is invalid',- 'zh-CN': '任务状态无效',- },- [ResponseCode.TaskExpired]: {- 'en-US': 'Task expired',- 'zh-CN': '任务已过期',- },- [ResponseCode.TaskRecruitsFullDec]: {- 'en-US': 'Task recruits full',- 'zh-CN': '任务招募已满',- },- [ResponseCode.TaskAccountNotBelongToUser]: {- 'en-US': 'Account does not belong to user',- 'zh-CN': '账号不属于该用户',- },- [ResponseCode.TaskAccountTypeInvalid]: {- 'en-US': 'Task account type is invalid',- 'zh-CN': '任务账号类型无效',- },- [ResponseCode.TaskAlreadyTaken]: {- 'en-US': 'This task has already been taken by this account',- 'zh-CN': '该账号已接取此任务',- },- [ResponseCode.MaterialConsumed]: {- 'en-US': 'The materials for this task have been consumed',- 'zh-CN': '该任务的素材已被消耗',- },- [ResponseCode.TaskMatcherNotFound]: {- 'en-US': 'Task matcher not found',- 'zh-CN': '任务匹配规则未找到',- },- [ResponseCode.FailedToSettleUserTasks]: {- 'en-US': 'Failed to settle user tasks',- 'zh-CN': '结算用户任务失败',- },- [ResponseCode.UserTaskSettleNotFound]: {- 'en-US': 'User task settle not found',- 'zh-CN': '用户任务结算未找到',- },- [ResponseCode.UserTaskPostNotFound]: {- 'en-US': 'User task post not found',- 'zh-CN': '用户任务作品未找到',- },- [ResponseCode.PostDataError]: {- 'en-US': 'Post data error',- 'zh-CN': '作品数据错误',- },- [ResponseCode.WorkAlreadySubmitted]: {- 'en-US': 'This work has already been submitted',- 'zh-CN': '该作品已被提交过',- },- [ResponseCode.WorkDataIdNotFound]: {- 'en-US': 'Work data ID not found',- 'zh-CN': '作品数据ID未找到',- },- [ResponseCode.WorkDataNotMatch]: {- 'en-US': 'Work data does not match task requirements',- 'zh-CN': '作品数据不匹配任务要求',- },- [ResponseCode.WorkLinkInfoNotFound]: {- 'en-US': 'Work link info not found',- 'zh-CN': '无法解析作品链接信息',- },[ResponseCode.WorkDetailNotFound]: {'en-US': 'Work detail not found','zh-CN': '无法获取作品详情',},- [ResponseCode.WorkPublishTimeExpired]: {- 'en-US': 'Work publish time exceeded the limit (must be within 31 days)',- 'zh-CN': '作品发布时间超过限制(必须在31天内)',- },- [ResponseCode.TaskPricingNotFound]: {- 'en-US': 'Task pricing configuration not found',- 'zh-CN': '任务定价配置不存在',- },- [ResponseCode.AdvertiserInsufficientBalance]: {- 'en-US': 'Advertiser balance is insufficient, please recharge',- 'zh-CN': '广告主余额不足,请充值',- },[ResponseCode.AccountAuthRequired]: {'en-US': 'This platform requires account authorization before submission','zh-CN': '该平台需要先授权账号才能提交',},- [ResponseCode.PlatformNotDetected]: {- 'en-US': 'Unable to detect platform from the provided link',- 'zh-CN': '无法从链接中识别平台类型',- },- [ResponseCode.UserTaskKeepTimeExpired]: {- 'en-US': 'Task submission window has expired',- 'zh-CN': '任务提交时间窗口已过期',- },- [ResponseCode.TaskAlreadyCancelled]: {- 'en-US': 'Task has already been cancelled',- 'zh-CN': '任务已停止',- },- [ResponseCode.TaskNotOwnedByUser]: {- 'en-US': 'Task not found',- 'zh-CN': '任务未找到',- },- [ResponseCode.LocationScreenshotRequired]: {- 'en-US': 'Location screenshot is required for local tasks',- 'zh-CN': '同城任务需要提交位置截图',- },- [ResponseCode.LocationVerifyFailed]: {- 'en-US': 'Location screenshot does not match the task city',- 'zh-CN': '位置截图与任务城市不匹配',- },- [ResponseCode.UserTaskDisputeNotFound]: {- 'en-US': 'Dispute record not found',- 'zh-CN': '争议记录未找到',- },- [ResponseCode.UserTaskDisputeAlreadyExists]: {- 'en-US': 'A pending dispute already exists for this task',- 'zh-CN': '该任务已存在待处理的争议',- },- [ResponseCode.UserTaskDisputeStatusInvalid]: {- 'en-US': 'Dispute status is invalid for this operation',- 'zh-CN': '争议状态不允许此操作',- },- [ResponseCode.InstanceCaptureTooFrequent]: {- 'en-US': 'Instance capture too frequent, please try again after 10 minutes',- 'zh-CN': '抓取请求过于频繁,同一任务10分钟内只能提交一次',- },- // 16027-16049 (promotion-code)- [ResponseCode.PromotionCodeNotFound]: {- 'en-US': 'Promotion code not found',- 'zh-CN': '推广码未找到',- },- [ResponseCode.PromotionCodeAlreadyExists]: {- 'en-US': 'Promotion code already exists',- 'zh-CN': '推广码已存在',- },- [ResponseCode.PromotionCodeTaskNotFound]: {- 'en-US': 'Task associated with promotion code not found',- 'zh-CN': '推广码关联的任务未找到',- },- [ResponseCode.PromotionCodeAlreadyLinked]: {- 'en-US': 'Promotion code is already linked to a task and cannot be deleted',- 'zh-CN': '推广码已绑定任务,无法删除',- },- [ResponseCode.PromotionCodeDisabled]: {- 'en-US': 'Promotion code is disabled',- 'zh-CN': '推广码已禁用',- },- [ResponseCode.PromotionCodeNotLinked]: {- 'en-US': 'Promotion code is not linked to any task',- 'zh-CN': '推广码未绑定任务',- },- [ResponseCode.PromotionCodeTaskNotActive]: {- 'en-US': 'The task linked to promotion code is not active',- 'zh-CN': '推广码关联的任务已失效',- },// 16050 (task-material)- [ResponseCode.TaskMaterialGroupNotFound]: {- 'en-US': 'Task material group not found',- 'zh-CN': '任务未配置草稿箱',- },- [ResponseCode.TaskMaterialEmpty]: {- 'en-US': 'No available material in task draft box',- 'zh-CN': '任务草稿箱中没有可用素材',- },[ResponseCode.MaterialGroupPlatformMismatch]: {'en-US': 'Material group platform does not match task platforms','zh-CN': '草稿箱平台限制与任务平台不匹配',},- // 18000 (agent)+ // 18100 (agent)[ResponseCode.AgentTaskNotFound]: {'en-US': 'Agent task not found','zh-CN': '代理任务未找到',@@ -829,26 +283,10 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'en-US': 'Agent task status is invalid','zh-CN': '代理任务状态无效',},- [ResponseCode.GenerateImagesFailed]: {- 'en-US': 'Failed to generate images',- 'zh-CN': '生成图片失败',- },- [ResponseCode.GenerateVideosFailed]: {- 'en-US': 'Failed to generate videos',- 'zh-CN': '生成视频失败',- },[ResponseCode.AgentTaskFailed]: {'en-US': 'Agent task failed','zh-CN': '代理任务失败',},- [ResponseCode.DailyTaskQuotaExceeded]: {- 'en-US': 'Daily task quota exceeded',- 'zh-CN': '每日代理任务配额已超出',- },- [ResponseCode.GenerateContentFailed]: {- 'en-US': 'Failed to generate content',- 'zh-CN': '生成内容失败',- },[ResponseCode.AgentTaskTimeout]: {'en-US': 'Agent task timeout: task has been running for too long without updates','zh-CN': '代理任务超时:任务运行时间过长且未更新',@@ -862,87 +300,19 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {'zh-CN': '恢复代理任务会话失败, 请尝试新建会话',},- // 18300 (place-draft)- [ResponseCode.PlaceDraftNotFound]: {- 'en-US': 'Place draft not found',- 'zh-CN': '地点草稿未找到',- },-// 18400 (tools)[ResponseCode.QrCodeArtImageNotFound]: {'en-US': 'QR code art image not found','zh-CN': '二维码艺术图未找到',},- // 18500 (campaign)- [ResponseCode.CampaignNotFound]: {- 'en-US': 'Campaign not found',- 'zh-CN': '活动未找到',+ // 19000 (api-key / relay)+ [ResponseCode.ApiKeyInvalid]: {+ 'en-US': 'Invalid API key',+ 'zh-CN': 'API Key 无效',},- [ResponseCode.CampaignAlreadyClosed]: {- 'en-US': 'Campaign is already closed',- 'zh-CN': '活动已关闭',- },- [ResponseCode.CampaignBudgetExceeded]: {- 'en-US': 'Campaign budget exceeded',- 'zh-CN': '活动预算已超出',- },- [ResponseCode.CampaignQuestionnaireGenerateFailed]: {- 'en-US': 'Failed to generate questionnaire',- 'zh-CN': '问卷生成失败',- },- [ResponseCode.CampaignStatusInvalid]: {- 'en-US': 'Campaign status is invalid for this operation',- 'zh-CN': '活动状态不允许此操作',- },-- // 18600 (campaign-application)- [ResponseCode.CampaignApplicationNotFound]: {- 'en-US': 'Application not found',- 'zh-CN': '报名记录未找到',- },- [ResponseCode.CampaignApplicationDuplicate]: {- 'en-US': 'You have already applied for this campaign',- 'zh-CN': '您已报名此活动',- },- [ResponseCode.CampaignApplicationSlotsFull]: {- 'en-US': 'No available slots',- 'zh-CN': '名额已满',- },- [ResponseCode.CampaignApplicationFollowersInsufficient]: {- 'en-US': 'Follower count does not meet the requirement',- 'zh-CN': '粉丝数不满足要求',- },- [ResponseCode.CampaignApplicationLotteryNotDrawn]: {- 'en-US': 'Lottery has not been drawn yet',- 'zh-CN': '尚未开奖',- },- [ResponseCode.CampaignApplicationVerifyCodeInvalid]: {- 'en-US': 'Invalid verify code',- 'zh-CN': '验证码无效',- },- [ResponseCode.CampaignApplicationAlreadyVerified]: {- 'en-US': 'Already verified',- 'zh-CN': '已核销',- },- [ResponseCode.CampaignApplicationStatusInvalid]: {- 'en-US': 'Application status is invalid for this operation',- 'zh-CN': '报名状态不允许此操作',- },- [ResponseCode.CampaignApplicationContentNotReady]: {- 'en-US': 'Content status does not allow this operation',- 'zh-CN': '内容状态不允许此操作',- },- [ResponseCode.CampaignApplicationContentDeadlineExpired]: {- 'en-US': 'Content submission deadline has expired',- 'zh-CN': '提交截止时间已过',- },- [ResponseCode.CampaignApplicationContentRetryExceeded]: {- 'en-US': 'Content retry limit exceeded',- 'zh-CN': '重试次数已达上限',- },- [ResponseCode.CampaignApplicationVerifyCodeExpired]: {- 'en-US': 'Verify code has expired',- 'zh-CN': '核销码已过期',+ [ResponseCode.RelayServerUnavailable]: {+ 'en-US': 'Relay server unavailable',+ 'zh-CN': '中转服务器不可用',},}diff --git a/project/aitoearn-backend/libs/common/src/i18n/notification-messages.ts b/project/aitoearn-backend/libs/common/src/i18n/notification-messages.tsindex 18bd6369..cf83ecde 100644--- a/project/aitoearn-backend/libs/common/src/i18n/notification-messages.ts+++ b/project/aitoearn-backend/libs/common/src/i18n/notification-messages.ts@@ -11,6 +11,7 @@ export enum NotificationMessageKey {TaskReminderAccountBinding = 'task_reminder_account_binding',TaskReminderLogin = 'task_reminder_login',TaskReminderAccountLogin = 'task_reminder_account_login',+ InteractionAiReviewFailed = 'interaction_ai_review_failed',TaskPunish = 'task_punish',AgentResult = 'agent_result',AgentResultRequiresAction = 'agent_result_requires_action',@@ -125,6 +126,17 @@ const notificationMessages: Record<NotificationMessageKey, NotificationMessageDe},},+ [NotificationMessageKey.InteractionAiReviewFailed]: {+ title: {+ 'en-US': 'Interaction task needs manual review',+ 'zh-CN': '互动任务需要人工审核',+ },+ content: {+ 'en-US': template.compile('AI review failed for interaction task "{{taskTitle}}". Reason: {{reason}}. Please review manually.'),+ 'zh-CN': template.compile('互动任务"{{taskTitle}}"的 AI 审核未通过,原因:{{reason}},请手动复审。'),+ },+ },+[NotificationMessageKey.TaskPunish]: {title: {'en-US': 'Punishment',diff --git a/project/aitoearn-backend/libs/common/src/utils/i18n.util.ts b/project/aitoearn-backend/libs/common/src/utils/i18n.util.tsnew file mode 100644index 00000000..0af8334a--- /dev/null+++ b/project/aitoearn-backend/libs/common/src/utils/i18n.util.ts@@ -0,0 +1,16 @@+import { z } from 'zod'+import { getLocale } from '../interceptors/request-context.interceptor'++const i18nObjectSchema = z.object({+ 'en-US': z.string(),+ 'zh-CN': z.string(),+})++export type I18nObject = z.infer<typeof i18nObjectSchema>++export function zodI18nString() {+ return i18nObjectSchema.transform((obj) => {+ const locale = getLocale()+ return obj[locale] || obj['en-US']+ })+}diff --git a/project/aitoearn-backend/libs/common/src/utils/index.ts b/project/aitoearn-backend/libs/common/src/utils/index.tsindex d9688071..0088191c 100644--- a/project/aitoearn-backend/libs/common/src/utils/index.ts+++ b/project/aitoearn-backend/libs/common/src/utils/index.ts@@ -4,6 +4,7 @@ export * from './exception.util'export * from './file.util'export * from './get-code-message.util'export * from './get-ext-by-mime-type.util'+export * from './i18n.util'export * from './password-generator.util'export * from './platform-url.util'export * from './poll.util'diff --git a/project/aitoearn-backend/libs/mail/package.json b/project/aitoearn-backend/libs/mail/package.jsonindex 3ffd27f1..4e707ff6 100644--- a/project/aitoearn-backend/libs/mail/package.json+++ b/project/aitoearn-backend/libs/mail/package.json@@ -12,13 +12,13 @@"registry": "https://npm.pkg.github.com"},"peerDependencies": {- "@nestjs-modules/mailer": "^2.0.2",+ "@nestjs-modules/mailer": "^2.3.0","@nestjs/common": "^11.0.0","@yikart/common": "workspace:*","tslib": "^2.3.0","zod": "^4.3.5"},"dependencies": {- "ioredis": "^5.7.0"+ "ioredis": "5.9.3"}}diff --git a/project/aitoearn-backend/libs/mail/src/mail.module.ts b/project/aitoearn-backend/libs/mail/src/mail.module.tsindex e405f5e7..c940335a 100644--- a/project/aitoearn-backend/libs/mail/src/mail.module.ts+++ b/project/aitoearn-backend/libs/mail/src/mail.module.ts@@ -1,5 +1,5 @@import { MailerModule } from '@nestjs-modules/mailer'-import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter'+import { HandlebarsAdapter } from '@nestjs-modules/mailer/adapters/handlebars.adapter'import { DynamicModule, Global, Module } from '@nestjs/common'import { MailConfig } from './mail.config'import { MailService } from './mail.service'diff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/account.repository.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/account.repository.tsindex da4acf9e..102f0ee2 100644--- a/project/aitoearn-backend/libs/mongodb/src/repositories/account.repository.ts+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/account.repository.ts@@ -52,6 +52,10 @@ export class AccountRepository extends BaseRepository<Account> {return await this.accountModel.find({ userId }).lean({ virtuals: true }).exec()}+ async listRelayAccountsByUserId(userId: string) {+ return await this.accountModel.find({ userId, relayAccountRef: { $ne: null } }).lean({ virtuals: true }).exec()+ }+async getList(page: {pageNo: numberdiff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/api-key.repository.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/api-key.repository.tsnew file mode 100644index 00000000..491913be--- /dev/null+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/api-key.repository.ts@@ -0,0 +1,28 @@+import { InjectModel } from '@nestjs/mongoose'+import { Model } from 'mongoose'+import { ApiKey } from '../schemas'+import { BaseRepository } from './base.repository'++export class ApiKeyRepository extends BaseRepository<ApiKey> {+ constructor(+ @InjectModel(ApiKey.name) apiKeyModel: Model<ApiKey>,+ ) {+ super(apiKeyModel)+ }++ async getByKeyHash(keyHash: string) {+ return await this.findOne({ keyHash })+ }++ async listByUserId(userId: string) {+ return await this.find({ userId })+ }++ async updateLastUsedAt(id: string) {+ await this.updateById(id, { lastUsedAt: new Date() })+ }++ async deleteByIdAndUserId(id: string, userId: string) {+ await this.deleteOne({ _id: id, userId })+ }+}diff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/index.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/index.tsindex d7fc509f..e55c2a4b 100644--- a/project/aitoearn-backend/libs/mongodb/src/repositories/index.ts+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/index.ts@@ -1,6 +1,7 @@import { AccountGroupRepository } from './account-group.repository'import { AccountRepository } from './account.repository'import { AiLogRepository } from './ai-log.repository'+import { ApiKeyRepository } from './api-key.repository'import { AssetRepository } from './asset.repository'import { BlogRepository } from './blog.repository'import { ContentGenerationTaskRepository } from './content-generation-task.repository'@@ -13,7 +14,6 @@ import { MaterialRepository } from './material.repository'import { MediaGroupRepository } from './media-group.repository'import { MediaRepository } from './media.repository'import { NotificationRepository } from './notification.repository'-import { OAuth2CredentialRepository } from './oauth2-credential.repository'import { PointsRecordRepository } from './points-record.repository'import { PublishRecordRepository } from './publish-record.repository'import { QrCodeArtImageRepository } from './qr-code-art-image.repository'@@ -23,6 +23,7 @@ import { UserRepository } from './user.repository'export * from './account-group.repository'export * from './account.repository'export * from './ai-log.repository'+export * from './api-key.repository'export * from './asset.repository'export * from './base.repository'export * from './blog.repository'@@ -54,6 +55,7 @@ export const repositories = [UserRepository,AccountRepository,AccountGroupRepository,+ ApiKeyRepository,MediaRepository,MediaGroupRepository,MaterialAdaptationRepository,@@ -61,7 +63,6 @@ export const repositories = [MaterialRepository,MaterialTaskRepository,PublishRecordRepository,- OAuth2CredentialRepository,ContentGenerationTaskRepository,UserNotificationControlRepository,QrCodeArtImageRepository,diff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/material-group.repository.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/material-group.repository.tsindex eac1f677..7cb59610 100644--- a/project/aitoearn-backend/libs/mongodb/src/repositories/material-group.repository.ts+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/material-group.repository.ts@@ -92,6 +92,10 @@ export class MaterialGroupRepository extends BaseRepository<MaterialGroup> {return await this.materialGroupModel.findOne({ userId, isDefault: true }).sort({ createdAt: -1 }).lean({ virtuals: true })}+ async listByIds(ids: string[]): Promise<MaterialGroup[]> {+ return this.materialGroupModel.find({ _id: { $in: ids } }).lean({ virtuals: true })+ }+// 获取列表async getList(inFilter: {userId?: string@@ -144,6 +148,29 @@ export class MaterialGroupRepository extends BaseRepository<MaterialGroup> {return res.modifiedCount}+ async listByLibraryId(libraryId: string): Promise<MaterialGroup[]> {+ return this.materialGroupModel.find({ libraryId }).lean({ virtuals: true })+ }++ async countByLibraryIdAndUserId(libraryId: string, userId: string): Promise<number> {+ return this.materialGroupModel.countDocuments({ libraryId, userId })+ }++ async updateLibraryIdById(id: string, libraryId: string | null): Promise<boolean> {+ const res = await this.materialGroupModel.updateOne(+ { _id: id },+ { $set: { libraryId } },+ )+ return res.modifiedCount > 0+ }++ async updateLibraryIdToNullByLibraryId(libraryId: string): Promise<void> {+ await this.materialGroupModel.updateMany(+ { libraryId },+ { $set: { libraryId: null } },+ ).exec()+ }+// 获取开启 openAffiliate 的素材组(最新的一个)async getOpenAffiliate(userId: string) {return await this.materialGroupModeldiff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/material.repository.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/material.repository.tsindex cf172e43..64077cee 100644--- a/project/aitoearn-backend/libs/mongodb/src/repositories/material.repository.ts+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/material.repository.ts@@ -74,11 +74,12 @@ export class MaterialRepository extends BaseRepository<Material> {return await this.materialModel.findOne({ _id: id }).lean({ virtuals: true })}- async getOptimalByGroup(groupId: string, type?: string) {+ async getOptimalByGroup(groupId: string, type?: string, accountType?: string) {const filter = {groupId,status: MaterialStatus.SUCCESS,...(type && { type }),+ ...(accountType && { accountTypes: accountType }),}const [data = null] = await this.materialModel.aggregate([diff --git a/project/aitoearn-backend/libs/mongodb/src/repositories/media.repository.ts b/project/aitoearn-backend/libs/mongodb/src/repositories/media.repository.tsindex 592e7ff8..b8398e2b 100644--- a/project/aitoearn-backend/libs/mongodb/src/repositories/media.repository.ts+++ b/project/aitoearn-backend/libs/mongodb/src/repositories/media.repository.ts@@ -64,6 +64,7 @@ export class MediaRepository extends BaseRepository<Media> {async getList(inFilter: {userId?: stringgroupId?: string+ materialGroupId?: stringtype?: MediaTypeuserType?: UserTypeuseCount?: number@@ -76,6 +77,7 @@ export class MediaRepository extends BaseRepository<Media> {const filter: RootFilterQuery<Media> = {...(inFilter.userId && { userId: inFilter.userId }),...(inFilter.groupId && { groupId: inFilter.groupId }),+ ...(inFilter.materialGroupId && { materialGroupId: inFilter.materialGroupId }),...(inFilter.userType && { userType: inFilter.userType }),...(inFilter.type && { type: inFilter.type }),...(inFilter.useCount !== undefined && { useCount: { $gte: inFilter.useCount } }),diff --git a/project/aitoearn-backend/libs/mongodb/src/schemas/account.schema.ts b/project/aitoearn-backend/libs/mongodb/src/schemas/account.schema.tsindex bacac664..6b1c1553 100644--- a/project/aitoearn-backend/libs/mongodb/src/schemas/account.schema.ts+++ b/project/aitoearn-backend/libs/mongodb/src/schemas/account.schema.ts@@ -170,6 +170,9 @@ export class Account extends WithTimestampSchema {default: 1,})rank: number++ @Prop({ type: String, default: null })+ relayAccountRef: string | null}export const AccountSchema = SchemaFactory.createForClass(Account)diff --git a/project/aitoearn-backend/libs/mongodb/src/schemas/api-key.schema.ts b/project/aitoearn-backend/libs/mongodb/src/schemas/api-key.schema.tsnew file mode 100644index 00000000..08a6faf5--- /dev/null+++ b/project/aitoearn-backend/libs/mongodb/src/schemas/api-key.schema.ts@@ -0,0 +1,22 @@+import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'+import { DEFAULT_SCHEMA_OPTIONS } from '../mongodb.constants'+import { WithTimestampSchema } from './timestamp.schema'++@Schema({ ...DEFAULT_SCHEMA_OPTIONS, collection: 'apiKey' })+export class ApiKey extends WithTimestampSchema {+ id: string++ @Prop({ required: true, index: true })+ userId: string++ @Prop({ required: true })+ name: string++ @Prop({ required: true, unique: true, index: true })+ keyHash: string++ @Prop()+ lastUsedAt: Date+}++export const ApiKeySchema = SchemaFactory.createForClass(ApiKey)diff --git a/project/aitoearn-backend/libs/mongodb/src/schemas/index.ts b/project/aitoearn-backend/libs/mongodb/src/schemas/index.tsindex 74d3d51a..955a466b 100644--- a/project/aitoearn-backend/libs/mongodb/src/schemas/index.ts+++ b/project/aitoearn-backend/libs/mongodb/src/schemas/index.ts@@ -1,6 +1,7 @@import { AccountGroup, AccountGroupSchema } from './account-group.schema'import { Account, AccountSchema } from './account.schema'import { AiLog, AiLogSchema } from './ai-log.schema'+import { ApiKey, ApiKeySchema } from './api-key.schema'import { Asset, AssetSchema } from './asset.schema'import { Blog, BlogSchema } from './blog.schema'import { ContentGenerationTask, ContentGenerationTaskSchema } from './content-generation-task.schema'@@ -12,6 +13,8 @@ import {CreditsRecord,CreditsRecordSchema,} from './credits-record.schema'+import { EngagementSubTask, EngagementSubTaskSchema, EngagementTask, EngagementTaskSchema } from './engagement.task.schema'+import { InteractionRecord, InteractionRecordSchema } from './interaction-record.schema'import { MaterialAdaptation, MaterialAdaptationSchema } from './material-adaptation.schema'import { MaterialGroup, MaterialGroupSchema } from './material-group.schema'import { MaterialTask, MaterialTaskSchema } from './material-task.schema'@@ -19,7 +22,6 @@ import { Material, MaterialSchema } from './material.schema'import { MediaGroup, MediaGroupSchema } from './media-group.schema'import { Media, MediaSchema } from './media.schema'import { Notification, NotificationSchema } from './notification.schema'-import { OAuth2Credential, OAuth2CredentialSchema } from './oauth2-credential.schema'import {PointsRecord,PointsRecordSchema,@@ -28,6 +30,7 @@ import { PublishDayInfo, PublishDayInfoSchema } from './publish-day-info.schema'import { PublishInfo, PublishInfoSchema } from './publish-info.schema'import { PublishRecord, PublishRecordSchema } from './publish-record.schema'import { QrCodeArtImage, QrCodeArtImageSchema } from './qr-code-art-image.schema'+import { ReplyCommentRecord, ReplyCommentRecordSchema } from './reply-comment-record.schema'import {UserNotificationControl,UserNotificationControlSchema,@@ -40,11 +43,14 @@ import {export * from './account-group.schema'export * from './account.schema'export * from './ai-log.schema'+export * from './api-key.schema'export * from './asset.schema'export * from './blog.schema'export * from './content-generation-task.schema'export * from './credits-balance.schema'export * from './credits-record.schema'+export * from './engagement.task.schema'+export * from './interaction-record.schema'export * from './material-adaptation.schema'export * from './material-group.schema'export * from './material-task.schema'@@ -57,7 +63,10 @@ export * from './points-record.schema'export * from './publish-day-info.schema'export * from './publish-info.schema'export * from './publish-record.schema'+export * from './publishing-task-meta.schema'export * from './qr-code-art-image.schema'+export * from './reply-comment-record.schema'+export * from './timestamp.schema'export * from './user-notification-control.schema'export * from './user.schema'@@ -70,6 +79,7 @@ export const schemas = [{ name: Blog.name, schema: BlogSchema },{ name: Notification.name, schema: NotificationSchema },{ name: Account.name, schema: AccountSchema },+ { name: ApiKey.name, schema: ApiKeySchema },{ name: AccountGroup.name, schema: AccountGroupSchema },{ name: MediaGroup.name, schema: MediaGroupSchema },{ name: Media.name, schema: MediaSchema },@@ -80,10 +90,12 @@ export const schemas = [{ name: PublishDayInfo.name, schema: PublishDayInfoSchema },{ name: PublishInfo.name, schema: PublishInfoSchema },{ name: PublishRecord.name, schema: PublishRecordSchema },- { name: OAuth2Credential.name, schema: OAuth2CredentialSchema },{ name: ContentGenerationTask.name, schema: ContentGenerationTaskSchema },{ name: UserNotificationControl.name, schema: UserNotificationControlSchema },{ name: Asset.name, schema: AssetSchema },- // QR Code Art{ name: QrCodeArtImage.name, schema: QrCodeArtImageSchema },+ { name: EngagementTask.name, schema: EngagementTaskSchema },+ { name: EngagementSubTask.name, schema: EngagementSubTaskSchema },+ { name: InteractionRecord.name, schema: InteractionRecordSchema },+ { name: ReplyCommentRecord.name, schema: ReplyCommentRecordSchema },] as constdiff --git a/project/aitoearn-backend/libs/mongodb/src/schemas/material-group.schema.ts b/project/aitoearn-backend/libs/mongodb/src/schemas/material-group.schema.tsindex fe26dbc4..c85facc0 100644--- a/project/aitoearn-backend/libs/mongodb/src/schemas/material-group.schema.ts+++ b/project/aitoearn-backend/libs/mongodb/src/schemas/material-group.schema.ts@@ -56,6 +56,9 @@ export class MaterialGroup extends WithTimestampSchema {})platforms: AccountType[]+ @Prop({ required: false, index: true })+ libraryId?: string+// 是否开启推广@Prop({required: true,diff --git a/project/aitoearn-backend/libs/mongodb/src/schemas/media.schema.ts b/project/aitoearn-backend/libs/mongodb/src/schemas/media.schema.tsindex 0c6cc86b..c8fe8d0b 100644--- a/project/aitoearn-backend/libs/mongodb/src/schemas/media.schema.ts+++ b/project/aitoearn-backend/libs/mongodb/src/schemas/media.schema.ts@@ -43,6 +43,12 @@ export class Media extends WithTimestampSchema {})groupId?: string // 所属组ID+ @Prop({+ required: false,+ index: true,+ })+ materialGroupId?: string // 所属组ID+@Prop({required: true,enum: MediaType,diff --git a/project/aitoearn-backend/libs/redis/package.json b/project/aitoearn-backend/libs/redis/package.jsonindex 766d3c57..c93849d5 100644--- a/project/aitoearn-backend/libs/redis/package.json+++ b/project/aitoearn-backend/libs/redis/package.json@@ -18,6 +18,6 @@"zod": "^4.3.5"},"dependencies": {- "ioredis": "^5.7.0"+ "ioredis": "5.9.3"}}diff --git a/project/aitoearn-backend/package.json b/project/aitoearn-backend/package.jsonindex 51de3d6e..aec13adf 100644--- a/project/aitoearn-backend/package.json+++ b/project/aitoearn-backend/package.json@@ -7,11 +7,7 @@"prepare": "command -v git >/dev/null 2>&1 && npx simple-git-hooks || echo 'Git not available, skipping git hooks setup'","lint": "nx run-many --target=lint --nxBail --outputStyle=static --parallel=\"75%\"","ai:serve": "nx serve aitoearn-ai",- "ai:dev": "npx nx serve aitoearn-ai --c=local",- "task:dev": "npx nx serve aitoearn-task --c=local",- "payment:serve": "nx serve aitoearn-payment",- "server:serve": "nx serve aitoearn-server",- "admin:serve": "nx serve aitoearn-admin-server"+ "server:serve": "nx serve aitoearn-server"},"dependencies": {"apify-client": "^2.22.2",diff --git a/project/aitoearn-backend/pnpm-lock.yaml b/project/aitoearn-backend/pnpm-lock.yamlindex 295905ee..19dbbbe2 100644--- a/project/aitoearn-backend/pnpm-lock.yaml+++ b/project/aitoearn-backend/pnpm-lock.yaml@@ -146,7 +146,7 @@ importers:version: 4.0.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])'@nestjs/bullmq':specifier: ^11.0.3- version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])+ version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])'@nestjs/common':specifier: ^11.0.0@@ -158,7 +158,7 @@ importers:version: 11.0.2(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))'@nestjs/microservices':specifier: ^11.1.6- version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express':specifier: ^11.1.6version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])@@ -208,8 +208,8 @@ importers:specifier: ^9.3.1version: 9.3.1bullmq:- specifier: ^5.58.2- version: 5.67.2+ specifier: ^5.71.0+ version: 5.71.0data-urls:specifier: ^5.0.0version: 5.0.0@@ -223,8 +223,8 @@ importers:specifier: ^1.1.1version: 1.2.1ioredis:- specifier: ^5.7.0- version: 5.9.2+ specifier: 5.9.3+ version: 5.9.3js-yaml:specifier: ^4.1.0version: 4.1.1@@ -297,7 +297,7 @@ importers:version: 4.0.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])'@nestjs/bullmq':specifier: ^11.0.3- version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])+ version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])'@nestjs/common':specifier: ^11.0.0@@ -312,7 +312,7 @@ importers:version: 11.0.2(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))'@nestjs/microservices':specifier: ^11.1.6- version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express':specifier: ^11.1.6version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])@@ -371,8 +371,8 @@ importers:specifier: ^9.3.1version: 9.3.1bullmq:- specifier: ^5.58.2- version: 5.67.2+ specifier: ^5.71.0+ version: 5.71.0class-transformer:specifier: ^0.5.1version: 0.5.1@@ -401,8 +401,8 @@ importers:specifier: ^2.0.2version: 2.0.2ioredis:- specifier: ^5.7.0- version: 5.9.2+ specifier: 5.9.3+ version: 5.9.3js-yaml:specifier: ^4.1.0version: 4.1.1@@ -490,10 +490,13 @@ importers:version: 11.0.2(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))'@nestjs/microservices':specifier: ^11.0.0- version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@yikart/common':specifier: workspace:*version: link:../common+ '@yikart/mongodb':+ specifier: workspace:*+ version: link:../mongodbrxjs:specifier: ^7.8.0version: 7.8.2@@ -508,7 +511,7 @@ importers:dependencies:'@nestjs/bullmq':specifier: ^11.0.0- version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])+ version: 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])'@nestjs/common':specifier: ^11.0.0@@ -525,14 +528,14 @@ importers:specifier: workspace:*version: link:../redisbullmq:- specifier: ^5.0.0- version: 5.67.2+ specifier: ^5.71.0+ version: 5.71.0ioredis:- specifier: ^5.7.0- version: 5.9.2+ specifier: 5.9.3+ version: 5.9.3nestjs-pino:- specifier: 4.6.0- version: 4.6.0(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])+ specifier: ^4.6.1+ version: 4.6.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])prom-client:specifier: ^15.0.0version: 15.1.3@@ -742,7 +745,7 @@ importers:version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])'@nestjs/microservices':specifier: ^11.1.6- version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express':specifier: ^11.0.0version: 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])@@ -771,8 +774,8 @@ importers:specifier: ^2.10.1version: 2.10.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])nestjs-pino:- specifier: ^4.6.0- version: 4.6.0(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])+ specifier: ^4.6.1+ version: 4.6.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])pino:specifier: ^10.3.1version: 10.3.1@@ -838,8 +841,8 @@ importers:libs/mail:dependencies:'@nestjs-modules/mailer':- specifier: ^2.0.2- version: 2.0.2(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])+ specifier: ^2.3.0+ version: 2.3.0(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/common':specifier: ^11.0.0@@ -847,8 +850,8 @@ importers:specifier: workspace:*version: link:../commonioredis:- specifier: ^5.7.0- version: 5.9.2+ specifier: 5.9.3+ version: 5.9.3tslib:specifier: ^2.3.0version: 2.8.1@@ -944,8 +947,8 @@ importers:specifier: workspace:*version: link:../commonioredis:- specifier: ^5.7.0- version: 5.9.2+ specifier: 5.9.3+ version: 5.9.3tslib:specifier: ^2.3.0version: 2.8.1@@ -1955,68 +1958,74 @@ packages:resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}engines: {node: '>=12'}- '@css-inline/[email protected]':- resolution: {integrity: sha512-LNUR8TY4ldfYi0mi/d4UNuHJ+3o8yLQH9r2Nt6i4qeg1i7xswfL3n/LDLRXvGjBYqeEYNlhlBQzbPwMX1qrU6A==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-w1+cicyd2xGzuOcFYxL9Yp3E/KT6opGpdhaKo1vFAepyn8zHrpAR3c1DHH1RWSWK3ZVcD3ne1naqJXQa4k/9uw==}engines: {node: '>= 10'}cpu: [arm]os: [android]- '@css-inline/[email protected]':- resolution: {integrity: sha512-tH5us0NYGoTNBHOUHVV7j9KfJ4DtFOeTLA3cM0XNoMtArNu2pmaaBMFJPqECzavfXkLc7x5Z22UPZYjoyHfvCA==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-V6ELV+DEjhYPqRcyCezUcMDSrXINMSCL4RBseEqWG18WhOZ9GoGd5XFpZzciQhHq/2MQS+06Jcc6RX59k7QS5g==}engines: {node: '>= 10'}cpu: [arm64]os: [android]- '@css-inline/[email protected]':- resolution: {integrity: sha512-QE5W1YRIfRayFrtrcK/wqEaxNaqLULPI0gZB4ArbFRd3d56IycvgBasDTHPre5qL2cXCO3VyPx+80XyHOaVkag==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-hT8Mtwp4PJ9mMYFDG/xg7KCa7nPqseJdXaajxXVjXB8+6oemxgx+7TUO7HSfmeY4Ox7X2vaNfaIfti4ySgNvyg==}engines: {node: '>= 10'}cpu: [arm64]os: [darwin]- '@css-inline/[email protected]':- resolution: {integrity: sha512-mAvv2sN8awNFsbvBzlFkZPbCNZ6GCWY5/YcIz7V5dPYw+bHHRbjnlkNTEZq5BsDxErVrMIGvz05PGgzuNvZvdQ==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-caFvVySabHZG4N1QUysbhWp2+VstMlYLysZYfAX0I6c9QfWcr+OZThoGOO2gC9lYy6QMCTBSD+9t+iceH9oBQw==}engines: {node: '>= 10'}cpu: [x64]os: [darwin]- '@css-inline/[email protected]':- resolution: {integrity: sha512-AWC44xL0X7BgKvrWEqfSqkT2tJA5kwSGrAGT+m0gt11wnTYySvQ6YpX0fTY9i3ppYGu4bEdXFjyK2uY1DTQMHA==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-9/TdB6cHgJ285uL7Y+1XjdJGjIQOeF9/YNq47N+azf2SiYdA3ahGYBmZhCGtYG7aBTJly9iJCxjP9ZZN8+Lajw==}engines: {node: '>= 10'}cpu: [arm]os: [linux]- '@css-inline/[email protected]':- resolution: {integrity: sha512-drj0ciiJgdP3xKXvNAt4W+FH4KKMs8vB5iKLJ3HcH07sNZj58Sx++2GxFRS1el3p+GFp9OoYA6dgouJsGEqt0Q==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-umcG26teSSUxWGQm7sECI8KweUgBgq9Cqd6yNMTNzqC1K56ZhW3Iwi7QewVNGOpVPXoGsywIIwIuY9lyed1Jdw==}engines: {node: '>= 10'}cpu: [arm64]os: [linux]- '@css-inline/[email protected]':- resolution: {integrity: sha512-FzknI+st8eA8YQSdEJU9ykcM0LZjjigBuynVF5/p7hiMm9OMP8aNhWbhZ8LKJpKbZrQsxSGS4g9Vnr6n6FiSdQ==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-wHQykZw3pX2R5Yp5VChOWzVXXO3XPdgWkQH1B9QBmft926EOkZpwxvubeAYy9I89qJzzdGNqiRl26+AUP88J3A==}engines: {node: '>= 10'}cpu: [arm64]os: [linux]- '@css-inline/[email protected]':- resolution: {integrity: sha512-yubbEye+daDY/4vXnyASAxH88s256pPati1DfVoZpU1V0+KP0BZ1dByZOU1ktExurbPH3gZOWisAnBE9xon0Uw==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-lHQZ+31CN3XJTn5MMFv1NYjyvuhAWEvul0fAYyppw4haA1TM+9UuA9jXdjqWXp26ItmainUnDMBlNLYQwMYt7g==}engines: {node: '>= 10'}cpu: [x64]os: [linux]- '@css-inline/[email protected]':- resolution: {integrity: sha512-6CRAZzoy1dMLPC/tns2rTt1ZwPo0nL/jYBEIAsYTCWhfAnNnpoLKVh5Nm+fSU3OOwTTqU87UkGrFJhObD/wobQ==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-DO/cba/zndTY3s86nNNfeHx7DvrvLb+IxhkQWTr29IQeiUgbawCH9X3B/4Li2eo/sEx/imOOnYDdXYu8PeX2Fg==}engines: {node: '>= 10'}cpu: [x64]os: [linux]- '@css-inline/[email protected]':- resolution: {integrity: sha512-nzotGiaiuiQW78EzsiwsHZXbxEt6DiMUFcDJ6dhiliomXxnlaPyBfZb6/FMBgRJOf6sknDt/5695OttNmbMYzg==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-1o8xla5ljVHS7SguH6nTV6uoAIMRZv+2MrcxfLRObpkUtCO7oKXDeWnia7XlmnLhDX8Ncx5bDOenZb1N35kCiA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@css-inline/[email protected]':+ resolution: {integrity: sha512-pdO/QXLRwuq/RxO5PSFMhmWGJSQOvkiDyV4RrewEkE7SOCY8HAYNhx1T0y0pj2WzxuVdbNQbpwiCHAdQNplUJw==}engines: {node: '>= 10'}cpu: [x64]os: [win32]- '@css-inline/[email protected]':- resolution: {integrity: sha512-u4eku+hnPqqHIGq/ZUQcaP0TrCbYeLIYBaK7qClNRGZbnh8RC4gVxLEIo8Pceo1nOK9E5G4Lxzlw5KnXcvflfA==}+ '@css-inline/[email protected]':+ resolution: {integrity: sha512-WABsvMSBs/DDadwhAUDw6uXwUE6w4DC/bnC4E2Y2rqbCTw5E1PPfj6VksnSCALkv9ynZfYGYYO4+Rvhmn5kgpw==}engines: {node: '>= 10'}'@dabh/[email protected]':@@ -2797,12 +2806,22 @@ packages:'@napi-rs/[email protected]':resolution: {integrity: sha512-9zESzOO5aDByvhIAsOy9TbpZ0Ur2AJbUI7UT73kcUTS2mxAMHOBaa1st/jAymNoCtvrit99kkzT1FZuXVcgfIQ==}- '@nestjs-modules/[email protected]':- resolution: {integrity: sha512-+z4mADQasg0H1ZaGu4zZTuKv2pu+XdErqx99PLFPzCDNTN/q9U59WPgkxVaHnsvKHNopLj5Xap7G4ZpptduoYw==}+ '@nestjs-modules/[email protected]':+ resolution: {integrity: sha512-C9FQOz+GKSIgJKWfUVJHuOCfbhhcQxitHcH1+Gl/nSVR/w+PhvrC/dk4h+pwB//5KYe4aPeE7Ia1slgIVjeAJQ==}peerDependencies:'@nestjs/common': '>=7.0.9''@nestjs/core': '>=7.0.9'+ '@nestjs/event-emitter': '>=2.0.0'+ '@nestjs/terminus': '>=10.0.0'+ bullmq: '>=4.0.0'nodemailer: '>=6.4.6'+ peerDependenciesMeta:+ '@nestjs/event-emitter':+ optional: true+ '@nestjs/terminus':+ optional: true+ bullmq:+ optional: true'@nestjs/[email protected]':resolution: {integrity: sha512-68pFJgu+/AZbWkGu65Z3r55bTsCPlgyKaV4BSG8yUAD72q1PPuyVRgUwFv6BxdnibTUHlyxm06FmYWNC+bjN7A==}@@ -3106,9 +3125,6 @@ packages:'@nx/[email protected]':resolution: {integrity: sha512-XnmBV7AFadNVdPLqZyYtGTVCIeGpScJTYUIii6wILB+pH8Qx2kTsDWVaWeHcUDeiymTVsbJfcwiXqn8nAISkfQ==}- '@one-ini/[email protected]':- resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==}-'@opentelemetry/[email protected]':resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}engines: {node: '>=8.0.0'}@@ -3721,6 +3737,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-bTQCKsVbIdzLqZhLkF5fcJQreE4y1ro4DIyVrlDNSCJRRwHhB8Z+4zXXa8jN6eDvc2HbRsEYgbvrnGvi54EpSw==}+'@types/[email protected]':resolution: {integrity: sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg==}@@ -4010,9 +4029,8 @@ packages:'@zone-eu/[email protected]':resolution: {integrity: sha512-eEyACj4JZ7sjzRvy26QhLgKEMWwQbsw1+QZnlLX+/gihcNH07lVPOcnwf5U6UAL7gkc//J3jVd76o/WS+taUiA==}- resolution: {integrity: sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ==}- engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+ resolution: {integrity: sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==}resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}@@ -4306,6 +4324,10 @@ packages:resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}+ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}+ engines: {node: 18 || 20 || >=22}+resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -4349,6 +4371,10 @@ packages:resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}+ resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==}+ engines: {node: 18 || 20 || >=22}+resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}engines: {node: '>=8'}@@ -4384,8 +4410,8 @@ packages:resolution: {integrity: sha512-HpGFw18DgFWlncDfjTa2rcQ4W88O1mC8e8yZ2AvQY5KDaktSTwo+KRf6nHK6FRI5FyRyb/5T6+TSxfP7QyGsmQ==}- resolution: {integrity: sha512-3KYqNqQptKcgksACO1li4YW9/jxEh6XWa1lUg4OFrHa80Pf0C7H9zeb6ssbQQDfQab/K3QCXopbZ40vrvcyrLw==}+ resolution: {integrity: sha512-aeNWh4drsafSKnAJeiNH/nZP/5O8ZdtdMbnOPZmpjXj7NZUP5YC901U3bIH41iZValm7d1i3c34ojv7q31m30w==}resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==}@@ -4426,6 +4452,9 @@ packages:resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-bsTwuIg/BZZK/vreVTYYbSWoe2F+71P7K5QGEX+pT250DZbfU1MQ5prOKpPR+LL6uWKK3KMwMCAS74QB3Um1uw==}+resolution: {integrity: sha512-34+zUAMhSH+r+9eKmYG+k2Rpt8XttfE4yXAjoZvkAPs15xcYQhyBYdalJ65BzivAvGRMViEjy6oKr/S91loekQ==}@@ -4464,9 +4493,9 @@ packages:resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}- resolution: {integrity: sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==}- engines: {node: '>= 6'}+ resolution: {integrity: sha512-quS9HgjQpdaXOvsZz82Oz7uxtXiy6UIsIQcpBj7HRw2M63Skasm9qlDocAM7jNuaxdhpPU7c4kJN+gA5MCu4ww==}+ engines: {node: '>=18.17'}resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}@@ -4572,6 +4601,9 @@ packages:resolution: {integrity: sha512-ezmVcLR3xAVp8kYOm4GS45ZLLgIE6SPAFoduLr6hTDajwb3KZ2F46gulK3XpcwRFb5KKGCSezCBAY4Dw4HsyXA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==}+resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}@@ -4587,6 +4619,14 @@ packages:resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==}engines: {node: '>=14'}+ resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==}+ engines: {node: '>=16'}++ resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}engines: {node: '>=20'}@@ -4600,8 +4640,8 @@ packages:resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}- resolution: {integrity: sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA==}+ resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==}engines: {node: '>= 6'}@@ -4633,9 +4673,6 @@ packages:resolution: {integrity: sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==}- resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==}-resolution: {integrity: sha512-JsPKdmh8ZkmnHxDk55FZ1TqVLvEQTvoByJZRN9jzI0UjxK/QgAmsphz7PGtqgPieQZ/CQcHWXCR7ATDNhGe+YA==}@@ -4729,9 +4766,23 @@ packages:resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}+ resolution: {integrity: sha512-gz6x+KkgNCjxq3Var03pRYLhyNfwhkKF1g/yoLgDNtFvVu0/fOLV9C8fFEZRjACp/XQLumjAYo7JVjzH3wLbxA==}+ engines: {node: ^14 || ^16 || >=18}+ peerDependencies:+ postcss: ^8.0.9+resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}+ resolution: {integrity: sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==}+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'}++ resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}+resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==}engines: {node: '>= 6'}@@ -4741,6 +4792,34 @@ packages:engines: {node: '>=4'}hasBin: true+ resolution: {integrity: sha512-waWlAMuCakP7//UCY+JPrQS1z0OSLeOXk2sKWJximKWGupVxre50bzPlvpbUwZIDylhf/ptf0Pk+Yf7C+hoa3g==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-iV7xT9JEk0OJwRWuSV2Y48IkntNjvoiscoioFDcgmuoIvpZV8gIg1++GBHTj72HgmDCALH8y9ELgt+aFM2Nh9g==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-ZIP71eQgG9JwjVZsTPSqhc6GHgEr53uJ7tK5///VfyWj6Xp2DBmixWHqJgPno+PqATzn48pL42ww9x5SSGmhZg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-mLFHQAzyapMVFLiJIn7Ef4C2UCEvtlTlbyILR6B5ZsUAV3D/Pa761R5uC1YPhyBkRd3eqaDm2ncaNrD7R4mTRg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==}+ engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'}+resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}engines: {node: '>= 12'}@@ -4943,10 +5022,6 @@ packages:resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}- resolution: {integrity: sha512-J1C5rIANUbuYK+FuFL98650rihynUOEzRLxW+90bKZRWB6A1X1Tf82GxR1qAWLyfNPRvjqfip3Q5tdYlmAa9lA==}- engines: {node: '>= 4'}-resolution: {integrity: sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==}engines: {node: '>= 4'}@@ -5001,11 +5076,6 @@ packages:resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}- resolution: {integrity: sha512-L9Qe08KWTlqYMVvMcTIvMAdl1cDUubzRNYL+WfA4bLDMHe4nemKkpmYzkznE1FwLKu0EEmy6obgQKzMJrg4x9Q==}- engines: {node: '>=14'}- hasBin: true-resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}@@ -5014,6 +5084,11 @@ packages:engines: {node: '>=0.10.0'}hasBin: true+ resolution: {integrity: sha512-COqBPFMxuPTPspXl2DkVYaDS3HtrD1GpzOGkNTJ1IYkifq/r9h8SVEFrjA3D9/VJGOEoMQcrlhpntcSUrM8k6A==}+ engines: {node: '>=0.12.18'}+ hasBin: true+resolution: {integrity: sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==}@@ -5045,6 +5120,9 @@ packages:resolution: {integrity: sha512-EuJWwlHPZ1LbADuKTClvHtwbaFn4rOD+dRAbWysqEOXRc2Uui0hJInNJrsdH0c+OhJA4nrCBdSkW4DD5YxAo6A==}engines: {node: '>=8.10.0'}+ resolution: {integrity: sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==}+resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}@@ -5063,6 +5141,10 @@ packages:resolution: {integrity: sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==}+ resolution: {integrity: sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}engines: {node: '>=0.12'}@@ -5789,17 +5871,15 @@ packages:resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}engines: {node: '>=10.13.0'}- resolution: {integrity: sha512-TCNv8vJ+xz4QiqTpfOJA7HvYv+tNIRHKfUWw/q+v2jdgN4ebz+KY9tGx5J4rHP0o84mNP+ApH66HRX8us3Khqg==}- engines: {node: '>=16 || 14 >=14.17'}- deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]- hasBin: true-resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]hasBin: true+ resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}+ engines: {node: 18 || 20 || >=22}+resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]@@ -5934,17 +6014,42 @@ packages:engines: {node: '>=4'}hasBin: true- resolution: {integrity: sha512-aoGxanpFPLg7MkIl/DDFYtb0iWz7jMFGqFhvEDZga6/4QTjneiD8I/NXL1x5aaoCp7FSIT6h/OhykDdPsbtMig==}- engines: {node: '>=6'}- hasBin: true-resolution: {integrity: sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==}engines: {node: '>=14'}- resolution: {integrity: sha512-vKZZra6CSe9qsJzh0BjBGXo8dvzNsq/oGvsjfRdOrrryfeD9UOBEEQdeoqCRmKZchF5h2zOBMQ6YuQ0uRUmdbQ==}+ resolution: {integrity: sha512-ZUCyB3w9EdpkaePGuYTBF7hT1MWdcz7y0/h2Cnl1MKLwbyj7aIM+Eq7SRg+ILF1mvR7zJKu06lw9zpgCxOFymw==}+ hasBin: true+ peerDependencies:+ cssnano: ^7.0.0+ postcss: ^8.3.11+ purgecss: ^8.0.0+ relateurl: ^0.2.7+ srcset: ^5.0.1+ svgo: ^4.0.0+ terser: ^5.21.0+ uncss: ^0.17.3+ peerDependenciesMeta:+ cssnano:+ optional: true+ postcss:+ optional: true+ purgecss:+ optional: true+ relateurl:+ optional: true+ srcset:+ optional: true+ svgo:+ optional: true+ terser:+ optional: true+ uncss:+ optional: true++ resolution: {integrity: sha512-H7MImA4MS6cw7nbyURtLPO1Tms7C5H602LRETv95z1MxO/7CP7rDVROehUYeYBUYEON94NXXDEPmZuq+hX4sog==}resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}@@ -6045,8 +6150,8 @@ packages:resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-tAAg/72/VxOUW7RQSX1pIxJVucYKcjFjfvj60L57jrZpYCHC3XN0WCQ3sNYL4Gmvv+7GPvTAjc+KSdeNuE8oWQ==}+ resolution: {integrity: sha512-VI5tMCdeoxZWU5vjHWsiE/Su76JGhBvWF1MJnV9ZtGltHk9BmD48oDq8Tj8haZ85aceXZMxLNDQZRVo5QKNgXA==}engines: {node: '>=12.22.0'}@@ -6151,6 +6256,9 @@ packages:resolution: {integrity: sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==}engines: {node: '>=8'}+ resolution: {integrity: sha512-6BEnpVn1rcf3ngfmViLM6vjUjGErbdrL4rwlv+u1NO1XO8kqT4YGL8+19Q+Z/bas8tY90BTWMk2+fW1g6hQjbA==}+resolution: {integrity: sha512-EW8wNCNvomPa/jsH1g0DmLfPakkRCRTcTML1v1fZMLiVCvQ/1YB+tKsRzShBiWQhqrYCi5a+WsepA4Z8TA9iaA==}engines: {node: '>=0.10.0'}@@ -6307,10 +6415,6 @@ packages:resolution: {integrity: sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==}engines: {node: '>=6'}- resolution: {integrity: sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ==}- engines: {node: '>=14'}-resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}@@ -6429,15 +6533,6 @@ packages:resolution: {integrity: sha512-pZe//GGmwJndub7ZghVHz7vjb2LgC1m8B07Au3eYqeqv9emhESByMXxaEgkUkEqJe87oBbSniGYoQNIBklc7IQ==}- resolution: {integrity: sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==}- engines: {node: '>=14'}- hasBin: true-- resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==}- engines: {node: '>=14'}-resolution: {integrity: sha512-rtS5ATOo2Q5k1G+DADISilDA6lv79zIiwFd6CcjuIxGKLFm5C+RLImRscVap9k55i+MOZwgliw+NejvkLuGD5g==}@@ -6532,9 +6627,9 @@ packages:resolution: {integrity: sha512-C9YK3Rf8q6VAPDCCU9fnqo3mAfOH6vUGnMcP4AQAYIEpWtfGLpwOTmZ+igtdK5y+VvI2n3CyYSzy4Qh34eq24A==}- resolution: {integrity: sha512-ZhJT1soxJCkOiO55/mz8yeBKTAJhRzX9WBO+16ZTqNTONnnVlUPyVBIzQ7lDRjaBdTbid+bAnyIon/GM3yp4cA==}- engines: {node: '>=10.0.0'}+ resolution: {integrity: sha512-4SBfZqKcc6DrIS+5b/WiGoWaZsdUPBH+e6SbRlNjJpaIRtfoBhYReAtobIEW6mcLeFFDXLBJMuZwkJLkBJjs2w==}+ engines: {node: '>=18.17'}hasBin: true@@ -6614,6 +6709,10 @@ packages:resolution: {integrity: sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==}+ resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}+ engines: {node: '>=14'}+resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}@@ -6629,8 +6728,8 @@ packages:engines: {node: '>=20.17'}hasBin: true- resolution: {integrity: sha512-TAUNAdgwaAXjjcUFuYVJm9kOVH7zc0mTKxsG9t9Lu4qdWjB2BEblyVIYpjWcmJLMGgiYqnGNJjpNMHx0gp/46A==}+ resolution: {integrity: sha512-D+jsJvkGigFn8qNUgh8U6XNHhGFBp+p8Dk26ea/Hl+XrjFVSg9OXlN31hGAfS3MYQ3Kr8Xi9sEVBVQa/VTVSmg==}engines: {node: '>=16'}hasBin: true@@ -6692,12 +6791,18 @@ packages:resolution: {integrity: sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==}+ resolution: {integrity: sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==}+resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}+ resolution: {integrity: sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==}+resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}@@ -6728,6 +6833,10 @@ packages:resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}+ resolution: {integrity: sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==}+ engines: {node: 20 || >=22}+resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}@@ -6804,6 +6913,12 @@ packages:resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}+ resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==}++ resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}+resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==}engines: {node: '>= 0.6'}@@ -6960,6 +7075,10 @@ packages:resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==}engines: {node: 20 || >=22}+ resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}+ engines: {node: 18 || 20 || >=22}+resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}@@ -6967,10 +7086,6 @@ packages:resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==}engines: {node: '>=10'}- resolution: {integrity: sha512-0jWhJpD/MdhPXwPuiRkCbfYfSKp2qnn2eOc279qI7f+osl/l+prKSrvhg157zSYvx/1nmgn2NqdT6k2Z7zSH9w==}- engines: {node: '>=16 || 14 >=14.17'}-resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}engines: {node: '>=16 || 14 >=14.17'}@@ -6982,103 +7097,103 @@ packages:resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}engines: {node: '>=16 || 14 >=14.17'}- resolution: {integrity: sha512-9PUmy2JxIOGgAaVHvgVYX21nVAo3o/+wJckTTF/YTLGAqB+nm+44buxRzaXxVk7qXRwbCNfE8c8mlGVNh7vB1g==}+ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}+ engines: {node: '>=16 || 14 >=14.17'}- resolution: {integrity: sha512-34AwX70/7NkRIajPsa5j6NySRiNrlLatTKhiLwTVFiVtrEFlfCcbeMNmdVixI3Ldvs8209ZC6euaAnXDRyR1zw==}+ resolution: {integrity: sha512-uThyWaQOkZu6143NIt17WINo574kY71NACI53N6wtHaNQJ8h8JxmxM3H/hkFhy2jO2ziYUBZhg9+pcOp8SWGQg==}- resolution: {integrity: sha512-ZsWMI0j7EcFCMqbqdVwMWhmsVc03FhmypWXokKopGhwySn4IAB4AOURonRmFrO7k6sDeQ+iJ9QtTu7jA+S8wmg==}+ resolution: {integrity: sha512-jBt1hu1Pnqm74PuwaDN2Fhs2Ub7LSM6YaoUUAVYpd/paex7h09dxGRH3XdQoTnVGbhztshk7LSsRzcfcTen8uQ==}- resolution: {integrity: sha512-wY4g1CHCOoVSZuar7CLFon/qkPbICu71IT+6pa4BDwkAiaAMAemZPyy+a+iIUgdc8kHgSuHGsGf6PQzBSMWRZA==}+ resolution: {integrity: sha512-T9L4n6pl8s1Lg7xbsvbfVd736E+MJbRglUbMLexE7CemkAzKYN2uttKO1qaFPtxvPUzE+ZCNT1G1WdAZ+9noBw==}- resolution: {integrity: sha512-N6CnA4o/q/VRnGPxTzvVnjAEcF7WUVVQGYfS9SPAp0qwyf7RysMmewdS9yN8GwXwZV6L2sKdn+3ANNi2FNsJ7w==}- hasBin: true+ resolution: {integrity: sha512-kSpRIf/1C2Hi3MmN/sibxgpwDjuyxRA5w4CNv5r9t+j6P6ZOJA5HB5s1NEFxzzaAg/ymzaf5viSIQCaLpymOfw==}- resolution: {integrity: sha512-0QZ1whxbHUmJaRT8tW+wmr3fWZ/kpsHKAd24c7Z/N1Otm/U2G0T/FFEFJ6cB25X6ZN0K40QZ8L9gdLfiSVuRbA==}+ resolution: {integrity: sha512-G72mqob9JWgOiqUInFjD+G53FzAIzNvJbYobkzFh8MC6u5vn7GB2gUd/knZuvwQzIIbGkfuMDWVjcS/vFNPAlA==}+ hasBin: true- resolution: {integrity: sha512-yey72LszXvIo5p0R6DB+YU8er/nP2wPsqpLKQCB0H8vG0WRT1sbSUvnCUOkKGn7subuyWDTdzHKbQO3XYIOmvg==}+ resolution: {integrity: sha512-ZlcJJoFL/rxJlhfa6Sm21aWWo4nNUF9R/z7+dBZxDyYsp3tgiKFeiGtGxme9WBdvizkXqmJ+nnXKYHmRwqIP3A==}- resolution: {integrity: sha512-FmGUVJqi4RYroh7y85vDx0aUKZgECkxHtMQ4pkLGQbZ2g93/Qt0Ek88DVCNJ5XwUAQQkE/TvrGMLHp3CIqpQ9Q==}+ resolution: {integrity: sha512-93d2GWeWdLEbHGXBa6haVleV/ZAj5EI0lEzY8KOGGFvJQoSrvTUna5fhiNop0CkCpohAWEJsR7PjTAS3URqxGA==}- resolution: {integrity: sha512-28ABkXsKljBqj7XCC8GkQ94xz8HEU2XTyD+9LTlkDafzGp/MGJb8DcLh/7IkxCwqkQWyeMiDNLf1djsQ909Vxw==}+ resolution: {integrity: sha512-zGgN7uAqYmzQK6fqjtGLEctQ6OqV6JlvbsqL892FsO7v6r6DZapDBnNdUYz1b6j0tkZqfNMzIptGCfD/Om58Mg==}- resolution: {integrity: sha512-nLzix1wrMnojE0RPGhk4iKqSRwHKjie2EPzgKT7CDzfqN+Ref03E5Q19x3cQTLgxvq3C3CnvCQBfnhoS3Eakug==}+ resolution: {integrity: sha512-TZ/S8SkPBGA+7Rq5FSjNZHnPTu3pIJElUiu+acW5Y7tmSeYkPocCyG+3Nxr+2GNBeVHvhlcq+nXTFJpujlfkoQ==}- resolution: {integrity: sha512-k6rwff+7i+vTQYJ/CjBfE20qNqPaW60IRH2x2oEPuCzmwDmoVWOcplJIuotSqIAdfwF9hLkICknisp1BpczVlQ==}+ resolution: {integrity: sha512-BO07AJuxcFJu6YJcyNIDOEuWv1KIFVSv4taEujy0T9iVMuudTHdpsUdkgPIfZx3G7Amn+zvcJCY6xLtFpis5LQ==}- resolution: {integrity: sha512-ao8HB5nf+Dmxw4GO6lMMOlnj1lNZONai0GC9RobrZgPlghZw6hpURWGpkON7pQcy6XnOHwYwkV7Go/npzA2i7w==}+ resolution: {integrity: sha512-bBcnqVz9RlkhUMWpdsJmmQGc61mxhZrwD6RublSZJMOX9W3x/XrfGzcJDs0RN9oLQjySBrSOYySnDozaPCxbyQ==}- resolution: {integrity: sha512-xaQE1rthe0RrNotwEr71X1tE+QQ489Yc0ynMm3oNMrohDI/TaCeazx8GAHPMM7VLduDA8D4A5wkZ6PuEvlJu4w==}+ resolution: {integrity: sha512-J18AEbHMD7XMhYSEhZlJwmjpOoLFoQSb4ywLX5k5Gp75KH3H4NsqV/UVFZiCPdi6rksWaa0T2Vhn2cdHnHuyrg==}- resolution: {integrity: sha512-2JvYqhbLyU/+Te6/1AXxzTNoHYCDYhXOVZP7wMvU4t7K34pXqyRUNO405atyHUY1MRafrl6RJ8cIx0x5vUX7PA==}+ resolution: {integrity: sha512-CVYgy3J/d5GQt7b7K1GZMl0hoeKalvByvZLkH2IJdjxThBUC+14JEoyjaW7auiFEScUnx3CpymPs9ozExH/PnA==}- resolution: {integrity: sha512-nEwDHkAqY3Fm7QWeAZc/a7MakZpXh6THfrE8/AWrfpgzTHrD/wihNUc09ztNpr6z/K1+JWgQfSF2BRc+X3P46g==}+ resolution: {integrity: sha512-33I+Pujw+HSCPBNYtTCSzbBN2WxoIP1AMfXYN7infBFqUAdXf2btAHddB77JfopQS5U3/7Ufxjd3GzYtKBa86g==}- resolution: {integrity: sha512-0Hm8o50rPMUQLSCOOa4D4pz9NajmCDccLvBYE4fwKdeUXjSJ6bwAYeMpveel8oNZMDUVJ4Hx+PskisEGHMHM2w==}+ resolution: {integrity: sha512-rySJtKbUpt6MXnZ2dQFRFnEPSfWu9MtlAKpdgqOS91LgE/j1L6rUh7iYW3DI3eS9lyV45etDOIvNhdIM+KaYfw==}- resolution: {integrity: sha512-DS0adpIAsVMDIk2DOsHzjg+RNjQU0fF8jiVP9BmdRHVGrLPmpL9wIHZk2KvsKvZe7VaXXBijFt3DZ5/CQ/+D7Q==}+ resolution: {integrity: sha512-o0TU17mRHCRChSu6uiKfPUPrgNpzA3pUv3vGEDn4zINSx+W6UJbuKRotgkptuWrfDrHwqx2yNsFs3t7WZ86GkA==}- resolution: {integrity: sha512-rujm0ROM4QGWw77vnl3NaVaCKXrT4xTSHeAnkHKiY5AuRf6HPTgEtutq5pdel/y6Q9GrmxvN3HRESum7tpJCJw==}+ resolution: {integrity: sha512-xLy2+uFTdGgMlmSZFB05ng/H1xeUp1MiPgDlEYiowcp4r27zVuGDT2VUZIQkH5cv7UasEMXfMTJZ23qAvERjjg==}- resolution: {integrity: sha512-e09NkoYwvzMcTv7V6H5doWD6Te2E1y2EvOLQJoXKVdQpDwyBWGdfnZke0scJGdA58HLAB+0mLYogpLwmfLaP5Q==}+ resolution: {integrity: sha512-kH2z02VtOacH/c8IT+EsHJMf4Ce9ZXp0ErR0FgwpaeSpG+XHw2Ov8s61abXOh7QFdPUkhgVUydqz2+nQBp0nwg==}- resolution: {integrity: sha512-qfNCgW9zhJIsbPyXFA5RT/WY4mlje3N0WhHHOsHc0nY89Q01DenyslUy9nLLGXwi4K5FHS58oCjwWbMhwDcj1w==}- hasBin: true+ resolution: {integrity: sha512-eLF6vv5lvdxU1y3ahAx3QJIhW1G57Ou7Ur9UGZ5W5bnjIbS77GjHqMMO95hVPAdw54j8YGuwGUAj7cI+ZrRozg==}- resolution: {integrity: sha512-uho/MS2tfNAe+V9u2X7NoCco34MDbdp30ETA8009Qo1VCP/D8lZ+s69WGRPu6hvN/Y2pzBgZly++CMg3qFZqBQ==}+ resolution: {integrity: sha512-+3UaYTYGpQMKCVyqt/mp+WDs7lE2n0mmbIYrADxmfnRPrixu4zz72TSMvdHKL0hSRP/IIC2tUOh6+pxihV0mJQ==}- resolution: {integrity: sha512-sHSsZg4afY1heThuJzxa1Kvfh/QzB7/9P5fFUHeVnnxb07ZTXnhXWA6YbobdND5/l9+5yjN5/UgqDZm3tIT4Uw==}+ resolution: {integrity: sha512-CVWdHy75ftf0GGvDT4juX5AQMvzH/bx3zlNos37hB0v7onJ1bjHfFzDYedzzll00aGhOM1HiMGmX0mrObhYKqQ==}- resolution: {integrity: sha512-x3l8vMVtsaqM/jauMeZIN7HFD2t5A28J4U0o4849yIlRxiWguLFV5l3BL8Byol+YLkoLuT9PjaZs9RYv+FGfeg==}+ resolution: {integrity: sha512-yZyH8t7BcTKgLXyelU71Ye2IvuQGlhqv8hOEUIiw66ZMcnWWnWJlcaVEkaFPSnIX/IwLNyXIM4LQ1ZHSX3rgxg==}- resolution: {integrity: sha512-F/kViAwXm3ccPP52kw++/mHQbcYbYYxC8JH15TZxH8GLVZkX5CGKgcBrHhDK7WoIlfEIsVRZ6IZdlHjH8vgyxw==}+ resolution: {integrity: sha512-H4gN+wJRKS7BKlX8vdXCzyrLiCi6qeTDDDB3nm6CwSg5bxlE+19bVHHUXHxBjkeV5acipXDhbaCIHLUfeRFN0g==}- resolution: {integrity: sha512-bB8My9zvIEkTOxej+TrjEeaeRT0lsypGeRADtdrRZXeqUClkkuCnCXlsNKSLGT8ZRqjUqWRc5z8ubDOvGk2+Gg==}+ resolution: {integrity: sha512-Z7x56JTcn2yKvqlcL7gRQrcyLimQC4BZJKk3JQN8xIByZucRfVfmE5L+2KA78+uc7NMnNKIPl7eXYECun6fM8A==}- resolution: {integrity: sha512-iAQc9g59L6L3VHDd55BxeIvk/zHkxflxmvuyYyOOvpmmKAvUBC//ULfpxiiM4yupofsThqFfrO+wc8d4kTRkbQ==}+ resolution: {integrity: sha512-006HWAszTUP7vNJvQnPrX1CvOvWAy9AEfhAVlkNKyEkr/F+z1Qpq+dVE7W1jXsq7GUeWT6AIr6EQrmKRXe+19A==}- resolution: {integrity: sha512-FK/0f5IBiONgaRpwNBs7G8EbLdAbmYqcIfHR8O8tP4LipAChLQKHO9vX3vrRMGLBZZNTESLObcFSVWmA40Mfpw==}+ resolution: {integrity: sha512-mKpxKWPHYlgd65hFLNddzgjqykqB/4crfrkAdWP06nCsLZpxRe94jLVyKHHwfCv8XUGsg+Srh+79kfQYSF7kig==}- resolution: {integrity: sha512-vJysCPUL3CHcsQDAFpW+skzBtY0RYsmMBYswI4WX0B05GLKlOjXqpYOwcmAupWeGoBVL5r/t28ynu2PqnOlN3w==}+ resolution: {integrity: sha512-o+EiFn4q+Pjbbi3jQLpLs65Ss3TGW/0Z/7GGBL35L4sLDJ/+4ek0pgkTjmWlS6SgXSy2Oua9MCZj2qX3MjfzWQ==}- resolution: {integrity: sha512-hBLmF3JgveUKktKQFWHqHAr7qr92j1CxAvq7mtpDUgiWgyPFzqRX8mUsFYgZ7DmRxG4UE+Kzpt8/YFd9+E98lw==}+ resolution: {integrity: sha512-gLoZTMucbK/ffuUFJiKBpm7Pi+m9zyjqL/RKePUExzH8Ad5qDCqjND2QFKuuSLy8jp02qjnKVudbtWnF2H3ALQ==}- resolution: {integrity: sha512-JmpWAsNTUlAxJOz2zHYfF8Vod8OzM3Qp5JXtrVw5tivZQzq88ZfqVGuqsas51z0pp1/ilfD4lC17YGfGwKGyhA==}+ resolution: {integrity: sha512-zVztkHNlkxkOre+7p5BRL71Y+1EKUs1awpyw2T+Cs7UAimWiaFiB9FhGEdnTffTc/HWfrmSKp3wq4W1zbuSRsg==}- resolution: {integrity: sha512-TZeOvLjIhXEK60rjWNiYhEYNlv5GKYahE+96ifcT5OGkWkRA0DsQDfp+6VI32OS5VxsfKq2h/UdERPlQijjpAQ==}+ resolution: {integrity: sha512-dXgxXZpyRkrSdL6z8xqzMiF3WacJ+DYlqEgtAVmRd4lUAB/UlgNLrpzQDpmFKxc0is8JB2lB6hF7APO1nT7BBQ==}- resolution: {integrity: sha512-rQM4aqFRrNvV1k733e8hJSopBjZvoSdBpRYzNTMAN+As0jqJsO5eN0wTT2IFtfe4PREzzu5b06RkPiUQdd0IIg==}+ resolution: {integrity: sha512-f8ImzVBa/Kp3IHUw82fDn2kvxHz351F53suF1KGP0imOjU0iKgMoYJGs0BwzHhOhW+XO4zw4btRMsSJc2LOBbQ==}hasBin: true@@ -7222,8 +7337,8 @@ packages:reflect-metadata: '>= 0.1.12 < 0.3'rxjs: '>= 6.0.0 < 8'- resolution: {integrity: sha512-MzSgnOu9MhRT/f7MsvoDnxat11D9JRJYwL1t+tI6J44UrNz9rUVDpceEh9VFsyfiiIJKUri5S+/snMOoaWh7YA==}+ resolution: {integrity: sha512-nuARXa0xpdJ1lY2+fgycIQr6H3g0VgqAWNK3xMYjOFcj2DoPETNXj0lV3Y86nRuI7BUfQp5PGiVoZvT4dTWbpQ==}engines: {node: '>= 14'}peerDependencies:'@nestjs/common': ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0@@ -7287,11 +7402,6 @@ packages:resolution: {integrity: sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==}engines: {node: '>=6.0.0'}- resolution: {integrity: sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w==}- engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}- hasBin: true-resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}engines: {node: '>=0.10.0'}@@ -7311,6 +7421,16 @@ packages:resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}+ resolution: {integrity: sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==}+ engines: {node: '>= 6.9.0'}+ hasBin: true+ peerDependencies:+ chokidar: ^3.3.0+ peerDependenciesMeta:+ chokidar:+ optional: true+resolution: {integrity: sha512-+eIIuRKltZ1hWcaB691aEdsRl4FRJ9qaaIZ2J6U2i4maRbBde8HJZ9m/EJt3i3IrYhdLpnl7QcXyTHzP3eW2jw==}hasBin: true@@ -7534,6 +7654,9 @@ packages:resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==}+ resolution: {integrity: sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==}+resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}@@ -7571,6 +7694,10 @@ packages:resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}engines: {node: '>=16 || 14 >=14.18'}+ resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}+ engines: {node: 18 || 20 || >=22}+resolution: {integrity: sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==}@@ -7656,14 +7783,195 @@ packages:resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-NYEsLHh8DgG/PRH2+G9BTuUdtf9ViS+vdoQ0YA5OQdGsfN4ztiwtDWNtBl9EKeqNMFnIu8IKZ0cLxEQ5r5KVMw==}+ engines: {node: ^18.12 || ^20.9 || >=22.0}+ peerDependencies:+ postcss: ^8.4.38++ resolution: {integrity: sha512-oXM2mdx6IBTRm39797QguYzVEWzbdlFiMNfq88fCCN1Wepw3CYmJ/1/Ifa/KjWo+j5ZURDl2NTldLJIw51IeNQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-l6uATQATZaCa0bckHV+r6dLXfWtUBKXxO3jK+AtxxJJtgMPD+VhhPCCx51I4/5w8U5uHV67g3w7PXj+V3wlMlg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-Sq+Fzj1Eg5/CPf1ERb0wS1Im5cvE2gDXCE+si4HCn1sf+jpQZxDI4DXEp8t77B/ImzDceWE2ebJQFXdqZ6GRJw==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-eTonaQvPZ/3i1ASDHOKkYwAybiM45zFIc7KXils4mQmHLqIswXD9XNOKEVxtTFnsmwYzF66u4LMgSr0abDlh5w==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-cFrJKZvcg/uxB6Ijr4l6qmn3pXQBna9zyrPC+sK0zjbkDUZew+6xDltSF7OeB7rAtzaaMVYSdbod+sZOCWnMOg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-7c3MMjjSZ/qYrx3uc1940GSOzN1Iqjtlqe8uoSg+qdVPYyRb0TILSqqmtlSFuE4mTDECwsm397Ya7iXGzfF7lg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-Kpu5v4Ys6QI59FxmxtNB/iHUVDn9Y9sYw66D6+SZoIk4QTz1prC4aYkhIESu+ieG1iylod1f8MILMs1Em3mmIw==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-BOR1iAM8jnr7zoQSlpeBmCsWV5Uudi/+5j7k05D0O/WP3+OFMPD86c1j/20xiuRtyt45bhxw/7hnhZNhW2mNFA==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-2m1uiuJeTplll+tq4ENOQSzB8LRnSUChBv7oSyFLsJRtUgAAJGP6LLz0/8lkinTgxrmJSPOEhgY1bMXOQ4ZXhQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-X9JjaysZJwlqNkJbUDgOclyG3jZEpAMOfof6PUZjPnPrePnPG62pS17CjdM32uT1Uq1jFvNSff9l7kNbmMSL2A==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-YOn02gC68JijlaXVuKvFSCvQOhTpblkcfDre2hb/Aaa58r2BIaK4AtE/cyZf2wV7YKAG+UlP9DT+By0ry1E4VQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-lIbC0jy3AAwDxEgciZlBullDiMBeBCT+fz5G8RcA9MWqh/hfUkpOI3vNDUNEZHgokaoiv0juB9Y8fGcON7rU/A==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-sn413ofhSQHlZFae//m9FTOfkmiZ+YQXsbosqOWRiVQncU2BA3daX3n0VF3cG6rGLSFVc5Di/yns0dFfh8NFgQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-E5nnB26XjSYz/mGITm6JgiDpAbVuAkzXwLzRZtts19jHDUBFxZ0BkXAehy0uimrOjYJbocby4FVswA/5noOxrQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-pB/SzrIP2l50ZIYu+yQZyMNmnAcwyYb9R1fVWPRxm4zcUFCY2ign7rcntGFuMXDdd9L2pPNUgoODDk91PzRZuQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-NsSQJ8zj8TIDiF0ig44Byo3Jk9e4gNt9x2VIlJudnQQ5DhWAHJPF4Tr1ITwyHio2BUi/I6Iv0HRO7beHYOloYQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-QByrI7hAhsoze992kpbMlJSbZ8FuCEc1OT9EFbZ6HldXNpsdpZr+YXC5di3UEv0+jeZlHbZcoCADgb7a+lPmmQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-bHifyuuSNdKKsnNJ0s8fmfLMlvsQwYVxIoUBnowIVl2ZAdrkYQNGVB4RxjfpvkMjipqvbz0u7feBZybkl/6NJg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-z6bwTV84YW6ZvvNoaNLuzRW4/uWxDKYI1iIDrzk6D2YTL7hICApy+Q1LP6vBEsljX8FM7YSuV9qI79XESd4ddQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-sUcD2cWtyK1AOL/82Fwy1aIVm/wwj5SdZkgZ3QiUzSzQQofrbq15jWJ3BA7Z+yVRwamCjJgZJN0I9IS7c6tgeQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-vsbgFHMFQrJBJKrUFJNZ2pgBeBkC2IvvoHjz1to0/0Xk7sII24T0qFOiJzG6Fu3zJoq/0yI4rKWi7WhApW+EFA==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-AMJjt1ECBffF7CEON/Y0rekRLS6KsePU6PRP08UqYW4UGFRnTXNrByUzYK1h8AC7UWTZdQ9O3Oq9kFIhm0SFEw==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-G6ZyK68AmrPdMB6wyeA37ejnnRG2S8xinJrZJnOv+IaRKf6koPAVbQsiC7MfkmXaGmF1UO+QCijb27wfpxuRNg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-MhyEbfrm+Mlp/36hvZ9mT9DaO7dbncU0CvWI8V93LRkY6IYlu38OPg3FObnuKTUxJ4qA8HpurdQOo5CyqqO76g==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32+resolution: {integrity: sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==}engines: {node: '>=4'}+ resolution: {integrity: sha512-zU9H9oEDrUFKa0JB7w+IYL7Qs9ey1mZyjhbf0KLxwJDdDRtoPvCmaEfknzqfHj44QS9VD6c5sJnBAVYTLRg/Sg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >= 18}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-3QoYmEt4qg/rUWDn6Tc8+ZVPmbp4G1hXDtCNWDx0st8SjtCbRcxRXDDM1QrEiXGG3A45zscSJFb4QH90LViyxg==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32++ resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}+resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}engines: {node: ^10 || ^12 || >=14}+ resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-QecJtfLekJbWVo/dMAA+OSwY79wpRmbqS5TeXvXSX+f0c6pW4/SE6inzZ2qkU7oAMCPqIDkZDvd/bQsSFUnKyw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-z+16RoxK3fUPgwaIgH9NGnK1HKY9XIDpydky5eQGgAFVXTCSezalv9U2jQuNV+Z9qV1fDWNzldcw4eK0SSbqKA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-7Hc+IvlQ7hlaIfQFZnxlRl0jnpWq2qwibORBhQYIb0QbNtuicc5ZxvKkVT71HJ4Py1wSZ/3VR1r8LfkCtoCzhw==}+ engines: {node: '>=12.0.0'}+resolution: {integrity: sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==}engines: {node: '>= 0.8.0'}@@ -7706,9 +8014,6 @@ packages:resolution: {integrity: sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==}- resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==}-resolution: {integrity: sha512-gGXRSXvxQ7UiPgfw8gevrfRWcTlSbOFg+p/N+JVJEK5VhueL2miT6qTymqAmjr1Q5WbOCyJbyrk6JfWKwlFn6A==}engines: {node: '>=12.0.0'}@@ -7731,8 +8036,8 @@ packages:resolution: {integrity: sha512-azINV9dUtzPMFQktvTXciNAfAuVh/L/JCl0vtPCwvOA21uZrC08K/UnmrL+SXGEVc1FwzjW62+xw5S/uaLj6cA==}- resolution: {integrity: sha512-cYQg0JW0w32Ux+XTeZnBEeuWrAY7/HNE6TWnhiHGnnRYlCgyAUPoyh9KzCMa9WhcJlJ1AtQqpEYHc+vbCzA+Aw==}+ resolution: {integrity: sha512-6okWYIKdasTyXICyEtvobmTZAVX57JkzgzIi4iRJlin8kmhG+Xry2dsus+Mun/nGCn6F2U49haHI5mkELXB14g==}resolution: {integrity: sha512-lv7sU9e5Jk8IeUheHata6/UThZ7RK2jnaaNztxfPYUY+VxZyk/ePVaNZ/vwmH8WqGvDz3LrNYt/+gA55NDg6Pg==}@@ -7761,8 +8066,8 @@ packages:resolution: {integrity: sha512-yYELe9Q5q9IQhuvqsZNwA5hfPkMJ8u92bQLIMcsMxf/VADjNtEYptU+inlufAFYcWdHlwNfZOEnOOQrZrcyJCQ==}- resolution: {integrity: sha512-uBi6kmc9f3SZ3PXxqcHiUZLmIXgfgWooKWXcwSGwQd2Zi5Rb0bT14+8CJjJgI8AB+nndLaNgHGrcc6bPIB665g==}+ resolution: {integrity: sha512-kFfq5mMzrS7+wrl5pLJzZEzemx34OQ0w4SARfhy/3yxTlhbstsudDwJzhf1hP02yHzbjoVMSXUj/Sz6RNfMyXg==}resolution: {integrity: sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==}@@ -7989,6 +8294,10 @@ packages:resolution: {integrity: sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==}engines: {node: '>=11.0.0'}+ resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}+ engines: {node: '>=11.0.0'}+resolution: {integrity: sha512-3A6sD0WYP7+QrjbfNA2FN3FsOaGGFoekCVgTyypy53gPxhbkCIjtO6YWgdrfM+n/8sI8JeXZOIxsHjMTNxQ4nQ==}engines: {node: ^14.0.0 || >=16.0.0}@@ -8015,6 +8324,11 @@ packages:engines: {node: '>=10'}hasBin: true+ resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}+ engines: {node: '>=10'}+ hasBin: true+resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}engines: {node: '>= 18'}@@ -8323,6 +8637,12 @@ packages:resolution: {integrity: sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==}+ resolution: {integrity: sha512-I3f053GBLIiS5Fg6OMFhq/c+yW+5Hc2+1fgq7gElDMMSqwlRb3tBf2ef6ucLStYRpId4q//bQO1FjcyNyy4yDQ==}+ engines: {node: ^18.12.0 || ^20.9.0 || >=22.0}+ peerDependencies:+ postcss: ^8.4.32+resolution: {integrity: sha512-vCyKEcCFNXJJ3TE7iP6uqyTG/9xlhhWvJ/LGzmt2YGkEG+PUeIaU0443TMSRbs8yQean2gqGMW8O5CtgJKIlWg==}engines: {node: '>=10'}@@ -8343,6 +8663,11 @@ packages:resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==}+ engines: {node: '>=16'}+ hasBin: true+resolution: {integrity: sha512-zSUTIck02fSga6rc0RZP3b7J7wgHXwLea8ZjgLA3Vgnb8QeOl3Wou2/j5QkzSGeoz6HusP/coYuJl33aQxQZpg==}@@ -8582,8 +8907,8 @@ packages:resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==}+ resolution: {integrity: sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==}resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}@@ -8591,6 +8916,10 @@ packages:resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}+ resolution: {integrity: sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==}+ engines: {node: '>=18.17'}+resolution: {integrity: sha512-O0+af1Gs50lyH1nUu3ZyYS1cRh01Q/kUKatTOkSs7jukXE6/NebucDVxyiDsA9AQ4JC1V1jUH9EO8JX2nMDgGQ==}engines: {node: '>=0.10.0'}@@ -8798,8 +9127,8 @@ packages:resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==}- resolution: {integrity: sha512-kfqDxt5dTB1JhqsCUQVFDj0rmY+4HLwGQIsLPbyrsN9y9WV/1oFDSx3BQ4GfCv9X+jVeQ7rouTqwK53rA/7t8A==}+ resolution: {integrity: sha512-Ezr98sqXW/+OCGoUEXuOKVR+oVFlSdn1tIySEEJdiSAw4IjrW8hQkwARSSBJTSB5Us5dnytDgL0ZDliAYBhaNA==}engines: {node: '>=10.0.0'}@@ -8813,6 +9142,11 @@ packages:resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}engines: {node: '>=12'}+ resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}+ engines: {node: '>=18'}+ deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation+resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}engines: {node: '>=18'}@@ -10649,48 +10983,52 @@ snapshots:'@jridgewell/trace-mapping': 0.3.9optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':+ optional: true++ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optional: true- '@css-inline/[email protected]':+ '@css-inline/[email protected]':optionalDependencies:- '@css-inline/css-inline-android-arm-eabi': 0.14.1- '@css-inline/css-inline-android-arm64': 0.14.1- '@css-inline/css-inline-darwin-arm64': 0.14.1- '@css-inline/css-inline-darwin-x64': 0.14.1- '@css-inline/css-inline-linux-arm-gnueabihf': 0.14.1- '@css-inline/css-inline-linux-arm64-gnu': 0.14.1- '@css-inline/css-inline-linux-arm64-musl': 0.14.1- '@css-inline/css-inline-linux-x64-gnu': 0.14.1- '@css-inline/css-inline-linux-x64-musl': 0.14.1- '@css-inline/css-inline-win32-x64-msvc': 0.14.1+ '@css-inline/css-inline-android-arm-eabi': 0.20.0+ '@css-inline/css-inline-android-arm64': 0.20.0+ '@css-inline/css-inline-darwin-arm64': 0.20.0+ '@css-inline/css-inline-darwin-x64': 0.20.0+ '@css-inline/css-inline-linux-arm-gnueabihf': 0.20.0+ '@css-inline/css-inline-linux-arm64-gnu': 0.20.0+ '@css-inline/css-inline-linux-arm64-musl': 0.20.0+ '@css-inline/css-inline-linux-x64-gnu': 0.20.0+ '@css-inline/css-inline-linux-x64-musl': 0.20.0+ '@css-inline/css-inline-win32-arm64-msvc': 0.20.0+ '@css-inline/css-inline-win32-x64-msvc': 0.20.0'@dabh/[email protected]':dependencies:@@ -11489,25 +11827,36 @@ snapshots:'@emnapi/runtime': 1.8.1'@tybys/wasm-util': 0.9.0- '@nestjs-modules/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])':+ '@nestjs-modules/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:- '@css-inline/css-inline': 0.14.1+ '@css-inline/css-inline': 0.20.0'@nestjs/common': 11.1.12([email protected])([email protected])([email protected])([email protected])'@nestjs/core': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])- glob: 10.3.12+ glob: 13.0.6nodemailer: 7.0.13+ tslib: 2.8.1optionalDependencies:+ '@nestjs/event-emitter': 3.0.1(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])'@types/ejs': 3.1.5'@types/mjml': 4.7.4'@types/pug': 2.0.10- ejs: 3.1.10+ bullmq: 5.71.0+ ejs: 5.0.1handlebars: 4.7.8- liquidjs: 10.24.0- mjml: 4.18.0+ liquidjs: 10.25.1+ nunjucks: 3.2.4([email protected])preview-email: 3.1.1- pug: 3.0.3+ pug: 3.0.4transitivePeerDependencies:- - encoding+ - chokidar+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncss'@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':dependencies:@@ -11521,12 +11870,12 @@ snapshots:'@nestjs/core': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])tslib: 2.8.1- '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])':+ '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])':dependencies:'@nestjs/bull-shared': 11.0.4(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])'@nestjs/common': 11.1.12([email protected])([email protected])([email protected])([email protected])'@nestjs/core': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])- bullmq: 5.67.2+ bullmq: 5.71.0tslib: 2.8.1'@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected])':@@ -11556,7 +11905,7 @@ snapshots:tslib: 2.8.1uid: 2.0.2optionalDependencies:- '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])'@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])':@@ -11571,7 +11920,7 @@ snapshots:tslib: 2.8.1uid: 2.0.2optionalDependencies:- '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])'@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])':@@ -11594,7 +11943,7 @@ snapshots:class-transformer: 0.5.1class-validator: 0.14.3- '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@nestjs/common': 11.1.12([email protected])([email protected])([email protected])([email protected])'@nestjs/core': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])@@ -11603,10 +11952,10 @@ snapshots:rxjs: 7.8.2tslib: 2.8.1optionalDependencies:- ioredis: 5.9.2+ ioredis: 5.9.3nats: 2.29.3- '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])':+ '@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])':dependencies:'@nestjs/common': 11.1.12([email protected])([email protected])([email protected])([email protected])'@nestjs/core': 11.1.7(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])@@ -11615,7 +11964,7 @@ snapshots:rxjs: 7.8.2tslib: 2.8.1optionalDependencies:- ioredis: 5.9.2+ ioredis: 5.9.3nats: 2.29.3'@nestjs/[email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected]([email protected]))([email protected])':@@ -11688,7 +12037,7 @@ snapshots:'@nestjs/core': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])tslib: 2.8.1optionalDependencies:- '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@nestjs/microservices': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])([email protected])([email protected])([email protected])([email protected])'@nestjs/platform-express': 11.1.12(@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))(@nestjs/[email protected])'@nuxt/[email protected]':@@ -11969,9 +12318,6 @@ snapshots:- '@swc/core'- debug- '@one-ini/[email protected]':- optional: true-'@opentelemetry/[email protected]': {}'@phenomnomnominal/[email protected]([email protected])':@@ -12668,6 +13014,9 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ optional: true+'@types/[email protected]':dependencies:'@types/caseless': 0.12.5@@ -12972,7 +13321,7 @@ snapshots:'@vue/shared': 3.5.27estree-walker: 2.0.2magic-string: 0.30.21- postcss: 8.5.6+ postcss: 8.5.8source-map-js: 1.2.1'@vue/[email protected]':@@ -13000,7 +13349,7 @@ snapshots:libqp: 2.1.1optional: trueoptional: true@@ -13393,6 +13742,8 @@ snapshots:+ [email protected]: {}+@@ -13441,6 +13792,10 @@ snapshots:dependencies:balanced-match: 1.0.2+ dependencies:+ balanced-match: 4.0.4+dependencies:fill-range: 7.1.1@@ -13477,13 +13832,13 @@ snapshots:dependencies:cron-parser: 4.9.0- ioredis: 5.9.2+ ioredis: 5.9.3msgpackr: 1.11.5node-abort-controller: 3.1.1- semver: 7.7.3+ semver: 7.7.4tslib: 2.8.1uuid: 11.1.0transitivePeerDependencies:@@ -13525,6 +13880,14 @@ snapshots:+ dependencies:+ browserslist: 4.28.1+ caniuse-lite: 1.0.30001767+ lodash.memoize: 4.1.2+ lodash.uniq: 4.5.0+ optional: true+@@ -13569,15 +13932,19 @@ snapshots:domutils: 3.2.2optional: truedependencies:cheerio-select: 2.1.0dom-serializer: 2.0.0domhandler: 5.0.3domutils: 3.2.2- htmlparser2: 8.0.2+ encoding-sniffer: 0.2.1+ htmlparser2: 9.1.0parse5: 7.3.0parse5-htmlparser2-tree-adapter: 7.1.0+ parse5-parser-stream: 7.1.2+ undici: 6.24.1+ whatwg-mimetype: 4.0.0optional: true@@ -13685,6 +14052,9 @@ snapshots:color-convert: 3.1.3color-string: 2.1.4+ optional: true+@@ -13699,6 +14069,12 @@ snapshots:optional: true+ optional: true++ optional: true+@@ -13708,7 +14084,7 @@ snapshots:optional: trueoptional: true@@ -13739,12 +14115,6 @@ snapshots:- dependencies:- ini: 1.3.8- proto-list: 1.2.4- optional: true-@@ -13836,6 +14206,11 @@ snapshots:+ dependencies:+ postcss: 8.5.8+ optional: true+dependencies:boolbase: 1.0.0@@ -13845,11 +14220,84 @@ snapshots:nth-check: 2.1.1optional: true+ dependencies:+ mdn-data: 2.0.28+ source-map-js: 1.2.1+ optional: true++ dependencies:+ mdn-data: 2.27.1+ source-map-js: 1.2.1+ optional: true+optional: true+ dependencies:+ browserslist: 4.28.1+ css-declaration-sorter: 7.3.1([email protected])+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-calc: 10.1.1([email protected])+ postcss-colormin: 7.0.6([email protected])+ postcss-convert-values: 7.0.9([email protected])+ postcss-discard-comments: 7.0.6([email protected])+ postcss-discard-duplicates: 7.0.2([email protected])+ postcss-discard-empty: 7.0.1([email protected])+ postcss-discard-overridden: 7.0.1([email protected])+ postcss-merge-longhand: 7.0.5([email protected])+ postcss-merge-rules: 7.0.8([email protected])+ postcss-minify-font-values: 7.0.1([email protected])+ postcss-minify-gradients: 7.0.1([email protected])+ postcss-minify-params: 7.0.6([email protected])+ postcss-minify-selectors: 7.0.6([email protected])+ postcss-normalize-charset: 7.0.1([email protected])+ postcss-normalize-display-values: 7.0.1([email protected])+ postcss-normalize-positions: 7.0.1([email protected])+ postcss-normalize-repeat-style: 7.0.1([email protected])+ postcss-normalize-string: 7.0.1([email protected])+ postcss-normalize-timing-functions: 7.0.1([email protected])+ postcss-normalize-unicode: 7.0.6([email protected])+ postcss-normalize-url: 7.0.1([email protected])+ postcss-normalize-whitespace: 7.0.1([email protected])+ postcss-ordered-values: 7.0.2([email protected])+ postcss-reduce-initial: 7.0.6([email protected])+ postcss-reduce-transforms: 7.0.1([email protected])+ postcss-svgo: 7.1.1([email protected])+ postcss-unique-selectors: 7.0.5([email protected])+ optional: true++ dependencies:+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-discard-comments: 7.0.6([email protected])+ postcss-discard-empty: 7.0.1([email protected])+ postcss-normalize-whitespace: 7.0.1([email protected])+ optional: true++ dependencies:+ postcss: 8.5.8+ optional: true++ dependencies:+ cssnano-preset-default: 7.0.11([email protected])+ lilconfig: 3.1.3+ postcss: 8.5.8+ optional: true++ dependencies:+ css-tree: 2.2.1+ optional: true+@@ -13978,7 +14426,7 @@ snapshots:dependencies:levenshtein: 1.0.5- underscore: 1.13.7+ underscore: 1.13.8@@ -14021,11 +14469,6 @@ snapshots:optional: true- dependencies:- domelementtype: 2.3.0- optional: true-dependencies:domelementtype: 2.3.0@@ -14094,20 +14537,15 @@ snapshots:dependencies:safe-buffer: 5.2.1- dependencies:- '@one-ini/wasm': 0.1.1- commander: 10.0.1- minimatch: 9.0.1- semver: 7.7.3- optional: true-dependencies:jake: 10.9.4+ optional: true+@@ -14127,6 +14565,12 @@ snapshots:optional: true+ dependencies:+ iconv-lite: 0.6.3+ whatwg-encoding: 3.1.1+ optional: true+dependencies:once: 1.4.0@@ -14145,6 +14589,9 @@ snapshots:optional: true+ optional: true+optional: true@@ -15134,14 +15581,6 @@ snapshots:dependencies:is-glob: 4.0.3- dependencies:- foreground-child: 3.3.1- jackspeak: 2.3.6- minimatch: 9.0.5- minipass: 7.1.2- path-scurry: 1.11.1-dependencies:foreground-child: 3.3.1@@ -15151,6 +15590,12 @@ snapshots:package-json-from-dist: 1.0.1path-scurry: 1.11.1+ dependencies:+ minimatch: 10.2.4+ minipass: 7.1.3+ path-scurry: 2.0.2+dependencies:fs.realpath: 1.0.0@@ -15304,17 +15749,6 @@ snapshots:relateurl: 0.2.7uglify-js: 3.4.10- dependencies:- camel-case: 3.0.0- clean-css: 4.2.4- commander: 2.20.3- he: 1.2.0- param-case: 2.1.1- relateurl: 0.2.7- uglify-js: 3.19.3- optional: true-dependencies:'@selderee/plugin-htmlparser2': 0.11.0@@ -15324,12 +15758,28 @@ snapshots:selderee: 0.11.0optional: true+ [email protected]([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ '@types/relateurl': 0.2.33+ commander: 14.0.3+ cosmiconfig: 9.0.0([email protected])+ posthtml: 0.16.7+ optionalDependencies:+ cssnano: 7.1.3([email protected])+ postcss: 8.5.8+ relateurl: 0.2.7+ svgo: 4.0.1+ terser: 5.44.1+ transitivePeerDependencies:+ - typescript+ optional: true+dependencies:domelementtype: 2.3.0- domhandler: 3.3.0+ domhandler: 4.3.1domutils: 2.8.0- entities: 2.2.0+ entities: 3.0.1optional: true@@ -15449,7 +15899,7 @@ snapshots:hasown: 2.0.2side-channel: 1.1.0dependencies:'@ioredis/commands': 1.5.0cluster-key-slot: 1.1.2@@ -15560,6 +16010,9 @@ snapshots:+ optional: true+@@ -15701,12 +16154,6 @@ snapshots:- dependencies:- '@isaacs/cliui': 8.0.2- optionalDependencies:- '@pkgjs/parseargs': 0.11.0-dependencies:'@isaacs/cliui': 8.0.2@@ -15992,18 +16439,6 @@ snapshots:- dependencies:- config-chain: 1.1.13- editorconfig: 1.0.4- glob: 10.5.0- js-cookie: 3.0.5- nopt: 7.2.1- optional: true-- optional: true-optional: true@@ -16093,15 +16528,14 @@ snapshots:promise: 7.3.1optional: truedependencies:- cheerio: 1.0.0-rc.12- commander: 6.2.1+ cheerio: 1.0.0+ commander: 12.1.0+ entities: 7.0.1mensch: 0.3.4slick: 1.12.2- web-resource-inliner: 6.0.1- transitivePeerDependencies:- - encoding+ web-resource-inliner: 8.0.0optional: true@@ -16194,6 +16628,9 @@ snapshots:optional: true+ optional: true+@@ -16213,7 +16650,7 @@ snapshots:string-argv: 0.3.2yaml: 2.8.2dependencies:commander: 10.0.1optional: true@@ -16267,10 +16704,16 @@ snapshots:+ optional: true++ optional: true+@@ -16305,6 +16748,8 @@ snapshots:+ [email protected]: {}+dependencies:yallist: 3.1.1@@ -16469,6 +16914,12 @@ snapshots:dependencies:'@types/mdast': 4.0.4+ optional: true++ optional: true+@@ -16715,6 +17166,10 @@ snapshots:dependencies:'@isaacs/brace-expansion': 5.0.0+ dependencies:+ brace-expansion: 5.0.4+dependencies:brace-expansion: 1.1.12@@ -16723,11 +17178,6 @@ snapshots:dependencies:brace-expansion: 2.0.2- dependencies:- brace-expansion: 2.0.2- optional: true-dependencies:brace-expansion: 2.0.2@@ -16736,215 +17186,325 @@ snapshots:+ [email protected]: {}+dependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6chokidar: 3.6.0glob: 10.5.0- html-minifier: 4.0.0- js-beautify: 1.15.4lodash: 4.17.23minimatch: 9.0.5- mjml-core: 4.18.0- mjml-migrate: 4.18.0- mjml-parser-xml: 4.18.0- mjml-validator: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-parser-xml: 5.0.0-beta.2+ mjml-preset-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-validator: 5.0.0-beta.2yargs: 17.7.2transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6- cheerio: 1.0.0-rc.12+ cheerio: 1.0.0+ cssnano: 7.1.3([email protected])+ cssnano-preset-lite: 4.0.4([email protected])detect-node: 2.1.0- html-minifier: 4.0.0- js-beautify: 1.15.4- juice: 10.0.1- lodash: 4.17.23- mjml-migrate: 4.18.0- mjml-parser-xml: 4.18.0- mjml-validator: 4.18.0- transitivePeerDependencies:- - encoding- optional: true-- dependencies:- '@babel/runtime': 7.28.6+ htmlnano: 3.2.0([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])+ juice: 11.1.1lodash: 4.17.23- mjml-core: 4.18.0+ mjml-parser-xml: 5.0.0-beta.2+ mjml-validator: 5.0.0-beta.2+ postcss: 8.5.8+ prettier: 3.8.1transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6- js-beautify: 1.15.4lodash: 4.17.23- mjml-core: 4.18.0- mjml-parser-xml: 4.18.0- yargs: 17.7.2+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6detect-node: 2.1.0@@ -16952,117 +17512,170 @@ snapshots:lodash: 4.17.23optional: truedependencies:'@babel/runtime': 7.28.6- mjml-accordion: 4.18.0- mjml-body: 4.18.0- mjml-button: 4.18.0- mjml-carousel: 4.18.0- mjml-column: 4.18.0- mjml-divider: 4.18.0- mjml-group: 4.18.0- mjml-head: 4.18.0- mjml-head-attributes: 4.18.0- mjml-head-breakpoint: 4.18.0- mjml-head-font: 4.18.0- mjml-head-html-attributes: 4.18.0- mjml-head-preview: 4.18.0- mjml-head-style: 4.18.0- mjml-head-title: 4.18.0- mjml-hero: 4.18.0- mjml-image: 4.18.0- mjml-navbar: 4.18.0- mjml-raw: 4.18.0- mjml-section: 4.18.0- mjml-social: 4.18.0- mjml-spacer: 4.18.0- mjml-table: 4.18.0- mjml-text: 4.18.0- mjml-wrapper: 4.18.0+ mjml-accordion: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-body: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-button: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-carousel: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-column: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-divider: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-group: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-attributes: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-breakpoint: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-font: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-html-attributes: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-preview: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-style: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-head-title: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-hero: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-image: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-navbar: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-raw: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-section: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-social: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-spacer: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-table: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-text: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-wrapper: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6optional: truedependencies:'@babel/runtime': 7.28.6lodash: 4.17.23- mjml-core: 4.18.0- mjml-section: 4.18.0+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-section: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: truedependencies:'@babel/runtime': 7.28.6- mjml-cli: 4.18.0- mjml-core: 4.18.0- mjml-migrate: 4.18.0- mjml-preset-core: 4.18.0- mjml-validator: 4.18.0+ mjml-cli: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-preset-core: 5.0.0-beta.2([email protected])([email protected])([email protected])([email protected])+ mjml-validator: 5.0.0-beta.2transitivePeerDependencies:- - encoding+ - purgecss+ - relateurl+ - srcset+ - svgo+ - terser+ - typescript+ - uncssoptional: true@@ -17221,7 +17834,7 @@ snapshots:- supports-color- typescript- [email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected]):+ [email protected](@nestjs/[email protected]([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected]):dependencies:'@nestjs/common': 11.1.12([email protected])([email protected])([email protected])([email protected])pino: 10.3.1@@ -17271,11 +17884,6 @@ snapshots:- dependencies:- abbrev: 2.0.0- optional: true-@@ -17296,6 +17904,15 @@ snapshots:dependencies:boolbase: 1.0.0+ dependencies:+ a-sync-waterfall: 1.0.1+ asap: 2.0.6+ commander: 5.1.0+ optionalDependencies:+ chokidar: 3.6.0+ optional: true+dependencies:'@napi-rs/wasm-runtime': 0.2.4@@ -17601,6 +18218,11 @@ snapshots:parse5: 7.3.0optional: true+ dependencies:+ parse5: 7.3.0+ optional: true+dependencies:entities: 6.0.1@@ -17632,6 +18254,11 @@ snapshots:lru-cache: 10.4.3minipass: 7.1.2+ dependencies:+ lru-cache: 11.2.7+ minipass: 7.1.3+@@ -17726,17 +18353,218 @@ snapshots:+ dependencies:+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ browserslist: 4.28.1+ caniuse-api: 3.0.0+ colord: 2.9.3+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ browserslist: 4.28.1+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ optional: true++ dependencies:+ postcss: 8.5.8+ optional: true++ dependencies:+ postcss: 8.5.8+ optional: true++ dependencies:+ postcss: 8.5.8+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ stylehacks: 7.0.8([email protected])+ optional: true++ dependencies:+ browserslist: 4.28.1+ caniuse-api: 3.0.0+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ colord: 2.9.3+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ browserslist: 4.28.1+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ cssesc: 3.0.0+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ optional: true++ dependencies:+ postcss: 8.5.8+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ browserslist: 4.28.1+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ cssnano-utils: 5.0.1([email protected])+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true++ dependencies:+ browserslist: 4.28.1+ caniuse-api: 3.0.0+ postcss: 8.5.8+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ optional: true+dependencies:cssesc: 3.0.0util-deprecate: 1.0.2+ dependencies:+ postcss: 8.5.8+ postcss-value-parser: 4.2.0+ svgo: 4.0.1+ optional: true++ dependencies:+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ optional: true++ optional: true+dependencies:nanoid: 3.3.11picocolors: 1.1.1source-map-js: 1.2.1+ dependencies:+ nanoid: 3.3.11+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ htmlparser2: 7.2.0+ optional: true++ dependencies:+ is-json: 2.0.1+ optional: true++ dependencies:+ posthtml-parser: 0.11.0+ posthtml-render: 3.0.0+ optional: true+@@ -17768,7 +18596,7 @@ snapshots:open: 7.4.2p-event: 4.2.0p-wait-for: 3.2.0- pug: 3.0.3+ pug: 3.0.4uuid: 9.0.1optional: true@@ -17786,9 +18614,6 @@ snapshots:asap: 2.0.6optional: true- optional: true-dependencies:'@protobufjs/aspromise': 1.1.2@@ -17846,7 +18671,7 @@ snapshots:pug-runtime: 3.0.1optional: truedependencies:constantinople: 4.0.1doctypes: 1.1.0@@ -17906,9 +18731,9 @@ snapshots:optional: truedependencies:- pug-code-gen: 3.0.3+ pug-code-gen: 3.0.4pug-filters: 4.0.0pug-lexer: 5.0.1pug-linker: 4.0.0@@ -18187,6 +19012,9 @@ snapshots:+ optional: true+dependencies:'@eslint-community/regexpp': 4.12.2@@ -18210,6 +19038,8 @@ snapshots:+ [email protected]: {}+dependencies:debug: 4.4.3@@ -18570,6 +19400,13 @@ snapshots:+ dependencies:+ browserslist: 4.28.1+ postcss: 8.5.8+ postcss-selector-parser: 7.1.1+ optional: true+dependencies:'@types/multipipe': 3.0.5@@ -18591,6 +19428,17 @@ snapshots:+ dependencies:+ commander: 11.1.0+ css-select: 5.2.2+ css-tree: 3.2.1+ css-what: 6.2.2+ csso: 5.0.5+ picocolors: 1.1.1+ sax: 1.6.0+ optional: true+dependencies:'@scarf/scarf': 1.4.0@@ -18851,12 +19699,15 @@ snapshots:has-symbols: 1.1.0which-boxed-primitive: 1.1.1- [email protected]: {}+ [email protected]: {}+ optional: true+dependencies:extend-shallow: 2.0.1@@ -19061,16 +19912,13 @@ snapshots:dependencies:defaults: 1.0.4dependencies:ansi-colors: 4.1.3escape-goat: 3.0.0- htmlparser2: 5.0.1+ htmlparser2: 9.1.0mime: 2.6.0- node-fetch: 2.7.0valid-data-url: 3.0.1- transitivePeerDependencies:- - encodingoptional: true@@ -19079,6 +19927,11 @@ snapshots:+ dependencies:+ iconv-lite: 0.6.3+ optional: true+diff --git a/project/aitoearn-backend/scripts/build-docker.mjs b/project/aitoearn-backend/scripts/build-docker.mjsindex 40b4af24..f84a1865 100644--- a/project/aitoearn-backend/scripts/build-docker.mjs+++ b/project/aitoearn-backend/scripts/build-docker.mjs@@ -1,8 +1,15 @@#!/usr/bin/env node+import { arch } from 'node:os'import { Command } from 'commander'import { $, chalk, fs, path } from 'zx'+function getDefaultPlatform() {+ const a = arch()+ const dockerArch = a === 'x64' ? 'amd64' : a+ return [`linux/${dockerArch}`]+}+async function cleanOutputDir(contextDir, verbose = false) {if (await fs.pathExists(contextDir)) {if (verbose)@@ -208,9 +215,14 @@ async function buildImage(projectName, contextDir, options = {}) {verbose = false,registries = ['registry.fly.io', 'registry.aitoearn.cn'],push = false,- platforms = ['linux/amd64'],+ platforms = getDefaultPlatform(),} = options+ if (platforms.length > 1 && !push) {+ console.error(chalk.red('错误: 多平台构建必须配合 --push 使用(docker buildx 不支持多平台 --load)'))+ process.exit(1)+ }+const platformStr = platforms.join(',')if (verbose) {@@ -231,7 +243,7 @@ async function buildImage(projectName, contextDir, options = {}) {// 为每个 registry 生成 tag 参数const tagArgs = registries.flatMap(registry => ['-t', `${registry}/${projectName}:${tag}`])- const pushArgs = push ? ['--push'] : []+ const pushArgs = push ? ['--push'] : ['--load']try {// 构建镜像并打所有 tag@@ -380,10 +392,11 @@ if (import.meta.url === `file://${process.argv[1]}`) {.option('--context-only', '仅准备 Docker 上下文,不构建镜像', false).option('-r, --registry <registry...>', 'Docker 镜像仓库地址(可多次指定)', ['registry.fly.io', 'registry.aitoearn.cn']).option('-p, --push', '构建后推送镜像到仓库', false)- .option('--platform <platforms...>', '目标平台(可多次指定,如 linux/amd64 linux/arm64)', ['linux/amd64'])+ .option('--platform <platforms...>', '目标平台(可多次指定,如 linux/amd64 linux/arm64),默认当前系统架构').action(async (appName, options) => {try {const finalOptions = { ...options, contextOnly: options.contextOnly }+ const platforms = options.platform || getDefaultPlatform()const result = await prepareContext(appName, finalOptions)@@ -392,7 +405,7 @@ if (import.meta.url === `file://${process.argv[1]}`) {verbose: options.verbose,registries: options.registry,push: options.push,- platforms: options.platform,+ platforms,})}}diff --git a/project/aitoearn-backend/scripts/file-to-env.mjs b/project/aitoearn-backend/scripts/file-to-env.mjsdeleted file mode 100644index de9557be..00000000--- a/project/aitoearn-backend/scripts/file-to-env.mjs+++ /dev/null@@ -1,100 +0,0 @@-#!/usr/bin/env node-import { appendFileSync, existsSync, readFileSync } from 'node:fs'-import { Command } from 'commander'--const program = new Command()--program- .name('env-builder')- .description('一个将文件转换为分块环境变量的CLI工具')- .version('1.0.0')- .description('添加一个文件并将其转换为环境变量')- .argument('<index>', '文件索引 (从0开始的整数)')- .argument('<filePath>', '要转换的文件的路径')- .option('-o, --output <file>', '将环境变量追加到指定文件 (默认为输出到终端)')- .option('-c, --chunk-size <number>', '每个内容块的最大字符数', 50000)- .option('-j, --json', '以 JSON 格式输出环境变量')- .option('-t, --target-path <path>', '目标环境中的文件路径 (默认使用源文件路径)')- .action(async (index, filePath, options) => {- console.log(`开始处理文件: ${filePath} (索引: ${index})`)-- const fileIndex = Number.parseInt(index, 10)- const chunkSize = Number.parseInt(options.chunkSize, 10)-- if (Number.isNaN(fileIndex) || Number.isNaN(chunkSize)) {- console.error('错误: 文件索引和块大小必须是数字。')- process.exit(1)- }-- if (!existsSync(filePath)) {- console.error(`错误: 文件 '${filePath}' 不存在。`)- process.exit(1)- }-- const prefix = `WRITE_FILE_${fileIndex}_`- const envVars = {}-- // 统一使用 envVars 存储环境变量- const pathKey = `${prefix}PATH`- const encodingKey = `${prefix}ENCODING`-- // 使用目标路径或源文件路径- const targetPath = options.targetPath || filePath- envVars[pathKey] = targetPath- envVars[encodingKey] = 'base64'-- if (options.targetPath) {- console.log(` - 目标路径: ${targetPath}`)- }-- const fileBuffer = readFileSync(filePath)- const base64Content = fileBuffer.toString('base64')-- console.log(` - 文件大小: ${fileBuffer.length} 字节`)- console.log(` - Base64 编码后长度: ${base64Content.length} 字符`)-- let chunkIndex = 0- for (let i = 0; i < base64Content.length; i += chunkSize) {- const chunk = base64Content.substring(i, i + chunkSize)- const chunkKey = `${prefix}CONTENT_${chunkIndex}`- envVars[chunkKey] = chunk- chunkIndex++- }-- console.log(` - 内容被分割为 ${chunkIndex} 个块`)-- const exportedVarsCount = 2 + chunkIndex-- // 根据选项决定输出格式- let outputString- if (options.json) {- const jsonOutput = {- env_vars: envVars,- }- outputString = JSON.stringify(jsonOutput, null, 2)- }- else {- const envLines = []- const displayPath = options.targetPath ? `${filePath} -> ${options.targetPath}` : filePath- envLines.push(`\n# --- 文件索引 ${fileIndex}: ${displayPath} ---`)-- for (const [key, value] of Object.entries(envVars)) {- envLines.push(`export ${key}="${value}"`)- }-- envLines.push('')- outputString = envLines.join('\n')- }-- // 统一输出处理- if (options.output) {- appendFileSync(options.output, outputString + (options.json ? '\n' : ''))- const formatType = options.json ? 'JSON 格式' : ''- console.log(`成功将 ${exportedVarsCount} 条环境变量${formatType ? `以 ${formatType}` : ''}追加到文件: ${options.output}`)- }- else {- console.log(options.json ? outputString : outputString.trim())- }- })--program.parse(process.argv)diff --git a/project/aitoearn-backend/scripts/install-ansible.sh b/project/aitoearn-backend/scripts/install-ansible.shdeleted file mode 100755index 2e1750f2..00000000--- a/project/aitoearn-backend/scripts/install-ansible.sh+++ /dev/null@@ -1,109 +0,0 @@-#!/bin/bash--# Ansible CLI 自动安装脚本-# 支持 macOS, Linux (Ubuntu/Debian, CentOS/RHEL) 和通用 pip 安装--set -e--echo "检查 Ansible 安装状态..."--# 检查是否已安装 ansible-if command -v ansible-playbook &> /dev/null; then- ANSIBLE_VERSION=$(ansible-playbook --version | head -n1 | awk '{print $3}')- echo "✅ Ansible 已安装,版本: $ANSIBLE_VERSION"- exit 0-fi--echo "🔧 开始安装 Ansible CLI..."--# 检查 Python 和 pip-if ! command -v python3 &> /dev/null; then- echo "❌ 错误: 未找到 python3,请先安装 Python 3"- exit 1-fi--# 根据操作系统安装 ansible-if [[ "$OSTYPE" == "darwin"* ]]; then- echo "🍎 检测到 macOS 系统"-- # 优先使用 Homebrew- if command -v brew &> /dev/null; then- echo "📦 使用 Homebrew 安装 Ansible..."- brew install ansible- else- echo "⚠️ 未找到 Homebrew,使用 pip3 安装..."- pip3 install --user ansible- fi--elif [[ "$OSTYPE" == "linux-gnu"* ]]; then- echo "🐧 检测到 Linux 系统"-- # Ubuntu/Debian- if command -v apt-get &> /dev/null; then- echo "📦 使用 apt 安装 Ansible..."- sudo apt-get update- sudo apt-get install -y software-properties-common- sudo add-apt-repository --yes --update ppa:ansible/ansible- sudo apt-get install -y ansible-- # CentOS/RHEL/Fedora- elif command -v yum &> /dev/null; then- echo "📦 使用 yum 安装 Ansible..."- sudo yum install -y epel-release- sudo yum install -y ansible-- # 使用 dnf (Fedora 新版本)- elif command -v dnf &> /dev/null; then- echo "📦 使用 dnf 安装 Ansible..."- sudo dnf install -y ansible-- else- echo "⚠️ 未识别的 Linux 发行版,使用 pip3 安装..."- pip3 install --user ansible- fi--else- echo "⚠️ 未识别的操作系统,使用 pip3 安装..."- pip3 install --user ansible-fi--# 验证安装-echo "🔍 验证 Ansible 安装..."-if command -v ansible-playbook &> /dev/null; then- ANSIBLE_VERSION=$(ansible-playbook --version | head -n1 | awk '{print $3}')- echo "✅ Ansible 安装成功!版本: $ANSIBLE_VERSION"-else- echo "❌ Ansible 安装失败,请手动安装"- echo "💡 建议运行: pip3 install --user ansible"- exit 1-fi--# 安装 sshpass (SSH 密码认证支持)-echo "🔧 检查 sshpass 安装状态..."-if ! command -v sshpass &> /dev/null; then- echo "📦 安装 sshpass..."-- if [[ "$OSTYPE" == "darwin"* ]]; then- # macOS- if command -v brew &> /dev/null; then- brew install sshpass- else- echo "⚠️ 未找到 Homebrew,请手动安装 sshpass"- fi- elif [[ "$OSTYPE" == "linux-gnu"* ]]; then- # Linux- if command -v apt-get &> /dev/null; then- sudo apt-get install -y sshpass- elif command -v yum &> /dev/null; then- sudo yum install -y sshpass- elif command -v dnf &> /dev/null; then- sudo dnf install -y sshpass- else- echo "⚠️ 请手动安装 sshpass"- fi- fi-else- echo "✅ sshpass 已安装"-fi--echo "🎉 Ansible CLI 和依赖安装完成!"\ No newline at end of filediff --git a/project/aitoearn-backend/scripts/prepare-opensource.sh b/project/aitoearn-backend/scripts/prepare-opensource.shdeleted file mode 100755index 1c8aa8fa..00000000--- a/project/aitoearn-backend/scripts/prepare-opensource.sh+++ /dev/null@@ -1,151 +0,0 @@-#!/bin/bash-# 准备开源仓库脚本-# 用法: 在内部 monorepo 根目录运行 bash scripts/prepare-opensource.sh-set -euo pipefail--echo "=== 步骤 1: 删除不需要的 apps 和 libs ==="--# 删除 apps-rm -rf apps/aitoearn-admin-server-rm -rf apps/aitoearn-payment-rm -rf apps/aitoearn-task--# 删除 libs-rm -rf libs/aitoearn-admin-client libs/aitoearn-payment-client libs/aitoearn-task-client-rm -rf libs/listmonk libs/ali-green libs/alipay libs/amap libs/ansible-rm -rf libs/maps libs/metric-db libs/one-signal libs/payment-db-rm -rf libs/statistics-db libs/stripe libs/task-db libs/ucloud libs/wise--# 删除独立目录-rm -rf migrations/ scripts/migrations/ tools/ e2e/--echo "=== 步骤 2: 删除 aitoearn-server 功能模块 ==="-rm -rf apps/aitoearn-server/src/core/app-configs/-rm -rf apps/aitoearn-server/src/core/app-release/-rm -rf apps/aitoearn-server/src/core/brand-lib/-rm -rf apps/aitoearn-server/src/core/campaign/-rm -rf apps/aitoearn-server/src/core/feedback/-rm -rf apps/aitoearn-server/src/core/google-maps/-rm -rf apps/aitoearn-server/src/core/maps-test/-rm -rf apps/aitoearn-server/src/core/manager/-rm -rf apps/aitoearn-server/src/core/statistics/-rm -rf apps/aitoearn-server/src/core/uptime/-rm -rf apps/aitoearn-server/src/core/user-event/-rm -rf apps/aitoearn-server/src/core/ai-green/--echo "=== 步骤 3: 删除 aitoearn-server VIP 相关文件 ==="-rm -f apps/aitoearn-server/src/core/user/vip.service.ts-rm -f apps/aitoearn-server/src/core/user/vip-purchase.consumer.ts-rm -f apps/aitoearn-server/src/core/user/vip-renewal.consumer.ts-rm -f apps/aitoearn-server/src/core/credits/monthly-credits-grant.consumer.ts-rm -f apps/aitoearn-server/src/core/notification/mail.service.ts--echo "=== 步骤 4: 删除 aitoearn-ai 功能模块 ==="-rm -rf apps/aitoearn-ai/src/core/ai-availability/-rm -f apps/aitoearn-ai/src/core/agent/agent-analysis.service.ts-rm -f apps/aitoearn-ai/src/core/agent/agent-analysis.consumer.ts-rm -f apps/aitoearn-ai/src/core/agent/agent-week-summary.service.ts-rm -f apps/aitoearn-ai/src/core/agent/agent-week-summary.scheduler.ts-rm -f apps/aitoearn-ai/src/core/agent/mcp/brand-store.mcp.ts--echo "=== 步骤 5: 删除共享代码文件 ==="-# MongoDB schemas-rm -f libs/mongodb/src/schemas/agent-week-summary.schema.ts-rm -f libs/mongodb/src/schemas/app-config.schema.ts-rm -f libs/mongodb/src/schemas/app-release.schema.ts-rm -f libs/mongodb/src/schemas/brand-library.schema.ts-rm -f libs/mongodb/src/schemas/brand-store-review.schema.ts-rm -f libs/mongodb/src/schemas/campaign.schema.ts-rm -f libs/mongodb/src/schemas/campaign-application.schema.ts-rm -f libs/mongodb/src/schemas/feedback.schema.ts-rm -f libs/mongodb/src/schemas/manager.schema.ts-rm -f libs/mongodb/src/schemas/uptime.schema.ts--# MongoDB repositories-rm -f libs/mongodb/src/repositories/agent-week-summary.repository.ts-rm -f libs/mongodb/src/repositories/app-config.repository.ts-rm -f libs/mongodb/src/repositories/app-release.repository.ts-rm -f libs/mongodb/src/repositories/brand-library.repository.ts-rm -f libs/mongodb/src/repositories/brand-store-review.repository.ts-rm -f libs/mongodb/src/repositories/campaign.repository.ts-rm -f libs/mongodb/src/repositories/campaign-application.repository.ts-rm -f libs/mongodb/src/repositories/feedback.repository.ts-rm -f libs/mongodb/src/repositories/manager.repository.ts-rm -f libs/mongodb/src/repositories/uptime.repository.ts-rm -f libs/mongodb/src/repositories/vip.repository.ts-rm -rf libs/mongodb/src/repositories/admin/--# MongoDB enums-rm -f libs/mongodb/src/enums/brand-library.enum.ts-rm -f libs/mongodb/src/enums/app-release.enum.ts-rm -f libs/mongodb/src/enums/campaign.enum.ts-rm -f libs/mongodb/src/enums/feedback.enum.ts--# Common-rm -f libs/common/src/constants/vip.constant.ts-rm -f libs/common/src/enums/vip.enum.ts--# Helpers-rm -rf libs/helpers/src/uptime/--# Queue interfaces-rm -f libs/aitoearn-queue/src/interfaces/vip-data.interface.ts-rm -f libs/aitoearn-queue/src/interfaces/agent-task-analysis.interface.ts-rm -f libs/aitoearn-queue/src/interfaces/user-event-batch-data.interface.ts-rm -f libs/aitoearn-queue/src/interfaces/monthly-credits-grant-data.interface.ts--echo "=== 删除完成 ==="-echo ""-echo "接下来需要手动修改以下文件(详见 docs/opensource-sync-guide.md):"-echo ""-echo " === aitoearn-server ==="-echo " - src/app.module.ts (移除已删除模块的 module imports)"-echo " - src/config.ts (移除 schema 字段)"-echo " - config/config.js (移除环境变量和配置项)"-echo " - package.json (移除 workspace 依赖)"-echo " - src/core/notification/ (移除 OneSignal/MailService)"-echo " - src/core/user/ (移除 VIP 相关, AitoearnTaskClient, UserAccessLog, CreditsService)"-echo " - src/core/channel/ (移除 AitoearnTaskClient, PostData, StatisticsModule)"-echo " - src/core/account/ (移除 AitoearnTaskClient, StatisticsModule)"-echo " - src/core/credits/ (移除 VIP/积分发放/scheduler)"-echo " - src/core/internal/ (移除 VIP endpoints, PromotionPost)"-echo " - src/core/publish-record/ (移除 AitoearnTaskClient)"-echo " - src/common/enums/redlock-key.enum.ts (移除 MonthlyCreditsGrant)"-echo ""-echo " === aitoearn-ai ==="-echo " - src/app.module.ts (移除 AiAvailabilityModule)"-echo " - src/config.ts (移除 aiAvailability, freeForVip, agent analysis)"-echo " - config/config.js (价格归零, 移除 aiAvailability, agent analysis)"-echo " - src/core/agent/ (移除分析/周报/品牌库/BrandStoreMcp)"-echo " - src/core/agent/mcp/*.mcp.ts (移除 UptimeHelperService)"-echo " - src/core/agent/mcp/*.mcp.spec.ts (移除 UptimeHelper mock)"-echo " - src/core/agent/mcp/mcp.utils.ts (从 wrapTool 移除 UptimeHelper)"-echo " - src/core/agent/services/agent-runtime.service.ts (移除 BrandLibrary/Uptime/AiAvailability)"-echo " - src/core/ai/libs/*.service.ts (移除 AiAvailabilityService)"-echo " - src/core/ai/chat/chat.service.ts (移除 freeForVip)"-echo " - src/core/ai/image/image.service.ts (移除 freeForVip)"-echo " - src/core/ai/video/video.service.ts (移除 freeForVip)"-echo " - src/core/ai/models-config/ (移除 AppConfigRepository, 简化为静态配置)"-echo " - src/core/draft-generation/ (移除 BrandLibrary/AiAvailability)"-echo " - src/core/material-adaptation/ (移除 AiAvailability)"-echo " - src/core/internal/ai.controller.ts (移除 saveModelsConfig)"-echo " - src/common/enums/redlock-key.enum.ts (移除 AgentWeekSummaryGeneration)"-echo ""-echo " === libs ==="-echo " - tsconfig.base.json (移除路径别名)"-echo " - libs/mongodb/src/schemas/index.ts (移除已删除 schema)"-echo " - libs/mongodb/src/schemas/user.schema.ts (移除 VipInfo)"-echo " - libs/mongodb/src/repositories/index.ts (移除已删除 repository)"-echo " - libs/mongodb/src/repositories/material.repository.ts (移除 countByBrandLibraryId)"-echo " - libs/mongodb/src/enums/index.ts (移除已删除 enum 导出)"-echo " - libs/mongodb/src/enums/user.enum.ts (移除 VipStatus)"-echo " - libs/mongodb/src/enums/asset.enum.ts (移除 BrandLibrary/GooglePlace)"-echo " - libs/aitoearn-queue/ (移除已删除队列枚举/接口/方法)"-echo " - libs/common/ (移除 VIP enum/constant/ResponseCode/messages)"-echo " - libs/helpers/ (移除 uptime 导出和 module)"-echo " - libs/nest-mcp/ (移除 UptimeHelperService)"-echo " - libs/assets/ (移除 BrandLibrary/GooglePlace 路径映射)"-echo " - libs/aitoearn-server-client/ (移除 VIP 相关方法/接口)"-echo ""-echo "修改完成后运行验证:"-echo " pnpm nx run-many --target=build --projects=aitoearn-server,aitoearn-ai"diff --git a/project/aitoearn-backend/scripts/release.mjs b/project/aitoearn-backend/scripts/release.mjsdeleted file mode 100644index 9bcce1cb..00000000--- a/project/aitoearn-backend/scripts/release.mjs+++ /dev/null@@ -1,341 +0,0 @@-#!/usr/bin/env node-/* eslint-disable no-console */--import { Command } from 'commander'-import { $, chalk, fs, path } from 'zx'--// 默认仓库配置-const DEFAULT_REPO = 'yikart/aitoearn-monorepo'--/**- * 查找项目路径- */-async function findProjectPath(projectName) {- const categories = ['apps', 'tools', 'libs']- for (const category of categories) {- const projectPath = path.resolve(category, projectName)- if (await fs.pathExists(projectPath)) {- return { category, projectPath }- }- }- return null-}--/**- * 读取项目配置- */-async function getProjectConfig(projectName, verbose = false) {- if (verbose)- console.info(chalk.yellow(`读取项目配置: ${projectName}...`))-- const projectInfo = await findProjectPath(projectName)- if (!projectInfo) {- throw new Error(`找不到项目: ${projectName},请检查项目名称是否正确`)- }-- const { category, projectPath } = projectInfo-- // 读取 project.json- const projectJsonPath = path.join(projectPath, 'project.json')- let outputPath = `dist/${category}/${projectName}`- if (await fs.pathExists(projectJsonPath)) {- const projectJson = JSON.parse(await fs.readFile(projectJsonPath, 'utf-8'))- if (projectJson.targets?.build?.options?.outputPath) {- outputPath = projectJson.targets.build.options.outputPath- }- }-- // 读取 package.json 获取描述- const packageJsonPath = path.join(projectPath, 'package.json')- let description = projectName- if (await fs.pathExists(packageJsonPath)) {- const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'))- if (packageJson.description) {- description = packageJson.description- }- }-- const config = {- projectName,- category,- projectPath,- outputPath,- description,- zipFile: `${projectName}.zip`,- }-- if (verbose) {- console.info(chalk.gray(` 分类: ${category}`))- console.info(chalk.gray(` 路径: ${projectPath}`))- console.info(chalk.gray(` 构建输出: ${outputPath}`))- console.info(chalk.gray(` 描述: ${description}`))- }-- return config-}--async function getVersion(verbose = false) {- if (verbose)- console.info(chalk.yellow('生成版本号...'))-- const result = await $`git rev-parse --short HEAD`- const version = result.stdout.trim()-- if (verbose)- console.info(chalk.green(`版本号: ${version}`))-- return version-}--async function buildProject(projectName, _verbose = false) {- console.info(chalk.blue('📦 Step 1: 构建项目...'))-- try {- await $`pnpm nx build ${projectName}`- console.info(chalk.green('✅ 构建完成'))- }- catch (error) {- console.error(chalk.red('❌ 构建失败:'))- console.error(chalk.red(` ${error.message}`))- throw new Error('项目构建失败,脚本终止执行')- }-}--async function createPackage(config, verbose = false) {- console.info(chalk.blue('🗜️ Step 2: 创建发布包...'))-- const distPath = path.resolve(config.outputPath)- const zipPath = path.resolve(config.zipFile)-- // 检查构建产物是否存在- if (!(await fs.pathExists(distPath))) {- throw new Error(`构建产物不存在: ${distPath}`)- }-- // 删除旧的 ZIP 文件- if (await fs.pathExists(zipPath)) {- await fs.remove(zipPath)- if (verbose)- console.info(chalk.gray(` 删除旧的 ZIP 文件: ${zipPath}`))- }-- // 创建 ZIP 包- try {- await $({ cwd: distPath })`zip -r ${zipPath} .`-- // 检查文件大小- const stats = await fs.stat(zipPath)- const sizeMB = (stats.size / 1024 / 1024).toFixed(1)- console.info(chalk.green(`✅ 包创建完成: ${sizeMB}M`))-- if (verbose) {- console.info(chalk.gray(` 位置: ${zipPath}`))- console.info(chalk.gray(` 大小: ${stats.size} bytes`))- }- }- catch (error) {- console.error(chalk.red('❌ 创建 ZIP 包失败:'))- console.error(chalk.red(` ${error.message}`))- throw error- }-}--async function getCommitInfo(verbose = false) {- if (verbose)- console.info(chalk.yellow('获取 commit 信息...'))-- const shaResult = await $`git rev-parse HEAD`- const fullSha = shaResult.stdout.trim()-- const msgResult = await $`git log -1 --pretty=%B`- const message = msgResult.stdout.trim()-- const date = new Date().toISOString()-- if (verbose) {- console.info(chalk.gray(` SHA: ${fullSha}`))- console.info(chalk.gray(` Message: ${message}`))- console.info(chalk.gray(` Date: ${date}`))- }-- return { fullSha, message, date }-}--async function createRelease(config, version, repo, options = {}) {- const { verbose = false, dryRun = false } = options-- console.info(chalk.blue('🏷️ Step 3: 创建 GitHub Release...'))-- const tagName = `${config.projectName}-${version}`- const releaseName = `${config.description} ${version}`- const { date } = await getCommitInfo(verbose)-- // 检查 tag 是否已存在- const tagCheckResult = await $`git tag -l ${tagName}`.quiet()- const tagExists = tagCheckResult.stdout.trim() !== ''-- if (tagExists) {- console.warn(chalk.yellow(`⚠️ Tag ${tagName} 已存在`))-- // 询问是否删除- if (!dryRun) {- console.info(chalk.yellow('删除现有 tag 和 release...'))- try {- await $`gh release delete ${tagName} -y`.quiet()- }- catch {- // Release 可能不存在,忽略错误- }- await $`git tag -d ${tagName}`- await $`git push origin :refs/tags/${tagName}`.quiet()- console.info(chalk.green('✅ 旧 tag 已删除'))- }- }-- // 生成 Release Notes- const releaseNotes = `## ${config.description}--**Commit**: ${version}-**Build Date**: ${date}-`-- if (dryRun) {- console.info(chalk.yellow('\n[Dry Run] 将要创建的 Release:'))- console.info(chalk.gray('─'.repeat(60)))- console.info(chalk.cyan(`Tag: ${tagName}`))- console.info(chalk.cyan(`Title: ${releaseName}`))- console.info(chalk.gray('─'.repeat(60)))- console.info(releaseNotes)- console.info(chalk.gray('─'.repeat(60)))- return- }-- // 创建 Release- try {- // 写入临时文件用于 release notes- const notesFile = 'release-notes.tmp'- await fs.writeFile(notesFile, releaseNotes)-- await $`gh release create ${tagName} ${config.zipFile} --title ${releaseName} --notes-file ${notesFile}`-- // 删除临时文件- await fs.remove(notesFile)-- // 获取 release 信息和 asset ID- const releaseInfo = await $`gh api repos/${repo}/releases/tags/${tagName}`- const releaseData = JSON.parse(releaseInfo.stdout)- const asset = releaseData.assets.find(a => a.name === config.zipFile)-- if (!asset) {- throw new Error('无法找到上传的 asset')- }-- const assetId = asset.id- const apiUrl = `https://api.github.com/repos/${repo}/releases/assets/${assetId}`-- console.info(chalk.green('✅ Release 创建成功!\n'))- console.info(chalk.cyan(`📦 Version: ${version}`))- console.info(chalk.cyan(`🏷️ Tag: ${tagName}`))- console.info(chalk.cyan(`🔗 Release URL: https://github.com/${repo}/releases/tag/${tagName}`))- console.info(chalk.cyan(`📥 Asset ID: ${assetId}`))- console.info(chalk.cyan(`📥 API URL: ${apiUrl}`))- console.info(chalk.gray(` 使用方式: curl -L -H "Authorization: token YOUR_TOKEN" -H "Accept: application/octet-stream" "${apiUrl}" -o ${config.zipFile}`))- }- catch (error) {- console.error(chalk.red('❌ 创建 Release 失败:'))- console.error(chalk.red(` ${error.message}`))- throw error- }-}--async function cleanup(config, verbose = false) {- if (verbose)- console.info(chalk.yellow('\n清理临时文件...'))-- const zipPath = path.resolve(config.zipFile)- if (await fs.pathExists(zipPath)) {- await fs.remove(zipPath)- if (verbose)- console.info(chalk.gray(` 删除: ${zipPath}`))- }-- if (verbose)- console.info(chalk.green('✅ 清理完成'))-}--async function releaseProcess(options = {}) {- const { verbose = false, buildOnly = false, dryRun = false, project, repo = DEFAULT_REPO } = options-- // 参数验证- if (!project) {- console.error(chalk.red('❌ 错误: 必须指定项目名称'))- console.error(chalk.yellow('使用方式: node release.mjs -p <project-name>'))- console.error(chalk.gray('示例: node release.mjs -p opensource-sync'))- process.exit(1)- }-- try {- // 0. 读取项目配置- const config = await getProjectConfig(project, verbose)-- // 1. 生成版本号- const version = await getVersion(verbose)-- // 2. 构建- await buildProject(config.projectName, verbose)-- // 3. 打包- await createPackage(config, verbose)-- if (buildOnly) {- console.info(chalk.green(`\n✅ 构建完成(仅构建模式)`))- console.info(chalk.gray(`ZIP 文件: ${config.zipFile}`))- return- }-- // 4. 创建 Release- await createRelease(config, version, repo, { verbose, dryRun })-- // 5. 清理- if (!dryRun) {- await cleanup(config, verbose)- }-- console.info(chalk.green('\n✅ 发布流程完成!'))- }- catch (error) {- console.error(chalk.red(`\n❌ 发布失败: ${error.message}`))- process.exit(1)- }-}--// CLI-if (import.meta.url === `file://${process.argv[1]}`) {- const program = new Command()-- program- .name('release')- .description('构建并发布项目到 GitHub Release(支持 monorepo 内的任意项目)')- .version('1.0.0')- .requiredOption('-p, --project <name>', '项目名称(如 opensource-sync, apprunner-monitor)')- .option('-v, --verbose', '显示详细日志', false)- .option('--build-only', '仅构建和打包,不发布', false)- .option('--dry-run', '模拟运行,不实际创建 Release', false)- .option('--repo <owner/name>', 'GitHub 仓库', DEFAULT_REPO)- .action(async (options) => {- try {- await releaseProcess(options)- }- catch (error) {- console.error(chalk.red(`错误: ${error.message}`))- process.exit(1)- }- })-- program.parseAsync(process.argv).catch((error) => {- console.error(chalk.red(`错误: ${error.message}`))- process.exit(1)- })-}--export { buildProject, createPackage, createRelease, getProjectConfig, releaseProcess }diff --git a/project/aitoearn-backend/scripts/setup-cloud-space.sh b/project/aitoearn-backend/scripts/setup-cloud-space.shdeleted file mode 100644index b907a173..00000000--- a/project/aitoearn-backend/scripts/setup-cloud-space.sh+++ /dev/null@@ -1,145 +0,0 @@-#!/bin/bash--# ==============================================================================-# 脚本名称: deploy_mlx_stack_v7.sh-# 描述: 无密码版。全自动化安装并配置 MultiloginX, Xvfb, Xpra 的-# 三服务 systemd 堆栈,连接时无需密码。-# 警告: 此配置不安全,请务必使用防火墙限制端口访问。-# 版本: 7.0-# ==============================================================================--set -e-# --- 配置变量 ----XVFB_SERVICE="mlx-xvfb.service"-MLX_APP_SERVICE="mlx-app.service"-XPRA_SERVICE="mlx-xpra.service"--DISPLAY_NUM=":99"-RESOLUTION="1920x1080x24"--# --- 步骤 0: 前置检查和环境设置 ----echo "--- 步骤 0: 正在进行环境检查 ---"-if [ "$(id -u)" -ne 0 ]; then- echo "错误:此脚本需要以 root 权限运行。" >&2- exit 1-fi--if [ -n "$SUDO_USER" ]; then- RUN_USER=$SUDO_USER-else- RUN_USER=$(logname 2>/dev/null || echo "ubuntu")-fi-RUN_GROUP=$(id -gn "$RUN_USER")-echo "所有服务将以用户 '$RUN_USER' (用户组 '$RUN_GROUP') 的身份运行。"-echo ""--# --- 步骤 1: 安装依赖项和 MultiloginX ----echo "--- 步骤 1: 正在安装系统依赖和 MultiloginX ---"-apt update-apt install xfce4 xfce4-goodies xvfb x11-utils xpra xdg-utils -y--MLX_DEB_URL="https://mlxdists.s3.eu-west-3.amazonaws.com/mlx/latest/multiloginx-amd64.deb"-MLX_DEB_FILE="/tmp/mlxdeb.deb"--echo "正在下载最新的 MultiloginX..."-curl -L -f -o "${MLX_DEB_FILE}" "${MLX_DEB_URL}"--echo "正在安装 MultiloginX..."-apt install -y --fix-broken "${MLX_DEB_FILE}"-rm -f "${MLX_DEB_FILE}"-echo "安装步骤完成。"-echo ""--# 获取命令的绝对路径-XVFB_PATH=$(which Xvfb)-MLX_PATH=$(which mlx)-XPRA_PATH=$(which xpra)--# --- 步骤 2: 创建 systemd 服务 (无密码版) ----echo "--- 步骤 2: 正在配置 systemd 服务 ---"--# 1. Xvfb 服务-cat << EOF > "/etc/systemd/system/${XVFB_SERVICE}"-[Unit]-Description=X Virtual Frame Buffer (Xvfb) for MLX-After=network.target--[Service]-Type=simple-ExecStart=${XVFB_PATH} ${DISPLAY_NUM} -screen 0 ${RESOLUTION} -ac-Restart=always-User=${RUN_USER}-Group=${RUN_GROUP}--[Install]-WantedBy=multi-user.target-EOF--# 2. mlx 应用服务-cat << EOF > "/etc/systemd/system/${MLX_APP_SERVICE}"-[Unit]-Description=MLX Application Service-Requires=${XVFB_SERVICE}-After=${XVFB_SERVICE}--[Service]-Type=simple-RemainAfterExit=yes-Environment=DISPLAY=${DISPLAY_NUM}-ExecStart=${MLX_PATH}-User=${RUN_USER}-Group=${RUN_GROUP}--[Install]-WantedBy=multi-user.target-EOF--# 3. Xpra 服务-cat << EOF > "/etc/systemd/system/${XPRA_SERVICE}"-[Unit]-Description=Xpra Session Manager for MLX-Requires=${MLX_APP_SERVICE}-After=${MLX_APP_SERVICE}--[Service]-Type=simple-ExecStart=${XPRA_PATH} start --use-display ${DISPLAY_NUM} --bind-tcp=0.0.0.0:10000 --no-daemon-Restart=always-RestartSec=5-User=${RUN_USER}-Group=${RUN_GROUP}--[Install]-WantedBy=multi-user.target-EOF-echo "所有 systemd 服务文件创建成功。"-echo ""--# --- 步骤 3: 激活服务 ----echo "--- 步骤 3: 正在激活 systemd 服务 ---"-systemctl stop ${XPRA_SERVICE} || true-systemctl stop ${MLX_APP_SERVICE} || true-systemctl stop ${XVFB_SERVICE} || true-rm -f /tmp/.X99-lock /tmp/.X11-unix/X99--systemctl daemon-reload-systemctl enable ${XPRA_SERVICE} ${MLX_APP_SERVICE} ${XVFB_SERVICE}-systemctl restart ${XPRA_SERVICE}--# --- 完成 ----echo ""-echo "======================================================================"-echo " 🎉 部署完成 🎉"-echo "======================================================================"-echo ""-echo "所有服务已启动并设置为开机自启。"-echo "Xpra 服务已在 10000 端口启动,无需密码即可连接。"-echo ""-echo "!! 安全警告 !!"-echo "此配置允许任何人连接。请立即配置防火墙 (例如 ufw),"-echo "只允许您信任的 IP 地址访问 TCP 端口 10000。"-echo "例如: 'sudo ufw allow from YOUR_IP_ADDRESS to any port 10000'"-echo ""-echo "您可以使用以下命令检查主服务状态:"-echo " systemctl status ${XPRA_SERVICE}"-echo "======================================================================"diff --git a/project/aitoearn-web/.claude/rules/default.md b/project/aitoearn-web/.claude/rules/default.mdindex 944cf950..63b53650 100644--- a/project/aitoearn-web/.claude/rules/default.md+++ b/project/aitoearn-web/.claude/rules/default.md@@ -3,14 +3,17 @@## 禁止事项- 使用硬编码货币符号/代码(如 `$`、`USD`、`¥`、`CNY`)→ 用 `appCurrencySymbol` / `appCurrency`(`/src/utils/currency.ts`)+- 使用 `<Input type="number">` 或 `<input type="number">` → 用 `NumberInput`(`/src/components/ui/number-input.tsx`),自动处理清空、小数、格式化## 开发前必查-1. `src/lib/README.md` - 工具方法-2. `src/components/README.md` - 组件-3. `src/utils/README.md` - 工具函数-4. `src/store/README.md` - 全局状态管理(Store)-5. 新增时同步更新对应 README+1. `src/utils/README.md` - 工具函数(格式化、OSS、货币、请求、下载等)+2. `src/lib/README.md` - 工具方法(toast、confirm、cn、VIP、i18n 等)+3. `src/hooks/` - 自定义 Hooks(useIsMobile、useMediaUpload、useKeepTimeCountdown、useVideoThumbnail 等)+4. `src/components/README.md` - 公共组件(MediaPreview、Modal、LoginModal 等)+5. `src/store/README.md` - 全局状态管理(useUserStore、useAccountStore 等)+6. `src/app/config/` - 业务常量与枚举(PlatType、PubType、AccountStatus 等)+7. 新增可复用代码时**必须同步更新对应 README**## 项目特有工具@@ -19,6 +22,7 @@- 货币显示用 `appCurrencySymbol` + `appCurrency`(`/src/utils/currency.ts`),自动适配国内外环境- SEO 元数据用 `getMetadata`(`/src/utils/general.ts`),不要自己拼接 title- 持久化 store 用 `createPersistStore`(`/src/lib/store.ts`)+- 数字输入用 `NumberInput`(`/src/components/ui/number-input.tsx`),禁止使用 `<Input type="number">`- 语言配置:`src/lib/i18n/languageConfig.ts`- 国际化目录:`/src/app/i18n`@@ -129,9 +133,9 @@ API 类型 → src/api/types/### useTransClient 动态加载 namespace 导致闪烁-**原因**:非预加载 namespace 动态加载触发重渲染+**原因**:`settings.ts` 只预加载 `common` 和 `route`,其他 namespace 首次使用时异步 import → 首帧 `t('key')` 返回 key 本身(如 `"setup.title"`)→ 翻译加载后重渲染为真实文本,产生闪烁。-**解决**:拆成两层组件+**场景一:弹窗/条件渲染组件** — 拆成两层组件```tsx// 外层:控制渲染时机(不用 hooks)@@ -151,6 +155,28 @@ const ModalContent = memo(({ onOpenChange }) => {})```+**场景二:有 loading 状态的组件(如依赖 API 数据)** — 外层预加载 namespace + 双重 ready 守卫++当组件本身已有加载态(skeleton / spinner),**必须在外层同时等待 namespace ready**,否则会出现 `skeleton → key文本闪现 → 翻译文本` 的二次闪烁。++```tsx+const MyComponent = memo(({ id }: Props) => {+ const { initialized, data } = useMyData(id)+ // 外层预加载 namespace,子组件再调用时命中缓存,首帧即有翻译+ const { ready: i18nReady } = useTransClient('myNamespace')++ // 双重守卫:数据 + 翻译都就绪前持续显示骨架屏+ if (!initialized || !i18nReady) {+ return <LoadingSkeleton />+ }++ // 此时子组件内 useTransClient('myNamespace') 命中缓存,ready 立即为 true+ return data ? <DataView data={data} /> : <EmptyState />+})+```++**关键原则**:任何有 loading/skeleton 的组件,如果子组件使用了非预加载 namespace,都要在外层用 `useTransClient` 的 `ready` 状态守卫,确保只有一次 skeleton → 内容的干净过渡。+### 新增路由需要加 Middleware 白名单**场景**:新增不需要语言前缀的路由(如 sitemap、API 代理等)diff --git a/project/aitoearn-web/.claude/rules/general.md b/project/aitoearn-web/.claude/rules/general.mdindex 01992fa5..d6dec384 100644--- a/project/aitoearn-web/.claude/rules/general.md+++ b/project/aitoearn-web/.claude/rules/general.md@@ -19,6 +19,85 @@- 使用硬编码颜色(如 `text-gray-900`)→ 用 shadcn/ui 语义化变量- 使用纯黑色(`#000`、`black`、`text-black`)→ 用灰色系语义化变量(`text-muted-foreground`、`text-foreground` 等)- 用 `as any` 绕过 TypeScript 类型错误 → 必须从源头修复类型定义(扩展 interface/type、添加联合类型等)+- 使用 `<Input type="number">` 或 `<input type="number">` → 用 `NumberInput` 组件(`src/components/ui/number-input.tsx`)++## 代码复用(强制)++**核心原则:相同或相似功能的代码必须复用,严禁重复实现。**++### 编码前强制检索流程++每次编写新逻辑前,**必须按顺序检索**以下位置,确认无现有实现后才可编写:++1. **工具函数**:`src/utils/README.md` → `src/lib/README.md` → 对应源文件+2. **自定义 Hooks**:`src/hooks/` 目录下所有 hooks+3. **公共组件**:`src/components/README.md` → 相关组件目录+4. **配置常量**:`src/app/config/` 下的配置文件+5. **Store 方法**:`src/store/README.md` → 对应 store 是否已有类似状态/方法+6. **页面级复用**:当前页面目录下的 store、hooks、utils++**如果找到相似实现,必须复用或扩展,不得另起炉灶。**++### 禁止的重复模式++```tsx+// ❌ 禁止:手写格式化逻辑,项目已有 formatNumber / formatDate / formatTime / formatSeconds+const formatted = value > 10000 ? (value / 10000).toFixed(1) + 'w' : value++// ❌ 禁止:手写货币符号,项目已有 appCurrencySymbol / formatCents+const price = '$' + (amount / 100).toFixed(2)++// ❌ 禁止:手写 OSS URL 拼接,项目已有 getOssUrl / getOssProxyPath+const imgUrl = 'https://oss.xxx.com/' + path++// ❌ 禁止:手写移动端判断,项目已有 useIsMobile hook+const [isMobile, setIsMobile] = useState(window.innerWidth < 768)++// ❌ 禁止:手写视频时长获取,项目已有 getVideoDuration / getVideoInfo+const video = document.createElement('video')++// ❌ 禁止:手写倒计时逻辑,项目已有 useKeepTimeCountdown hook+const [countdown, setCountdown] = useState(60)++// ❌ 禁止:手写 VIP 判断,项目已有 getVipStatusInfo / getVipTier+const isVip = status === 'active_monthly' || status === 'active_yearly'++// ❌ 禁止:手写中文语言判断,项目已有 isChineseLanguage+const isCN = lng === 'zh-CN' || lng === 'zh-TW'++// ❌ 禁止:手写相对时间,项目已有 formatRelativeTime+const timeAgo = Date.now() - time < 60000 ? '刚刚' : ...++// ❌ 禁止:手写确认弹窗,项目已有 confirm()+if (window.confirm('确定删除吗?')) { ... }++// ❌ 禁止:使用原生 type="number",有浏览器行为不一致问题(退格无法清空、spinner 等)+<Input type="number" onChange={e => field.onChange(Number(e.target.value))} />++// ✅ 正确:使用 NumberInput,自动处理清空、小数、格式化+<NumberInput value={field.value} onValueChange={v => field.onChange(v)} decimalScale={2} />+```++### 相似 UI 模式必须抽取复用++- **列表页**:分页逻辑、空状态、加载骨架屏 → 检查是否有类似页面可复用模式+- **表单页**:校验、提交、loading → 检查 `react-hook-form` + `zod` 已有模式+- **弹窗**:使用 `src/components/ui/modal.tsx` 或 `confirm()`,不得自建弹窗容器+- **媒体预览**:使用 `MediaPreview` 组件,不得自建图片/视频预览++### 新建 vs 复用决策++| 场景 | 做法 |+| -------------------- | ----------------------------------------------- |+| 功能与现有完全一致 | **直接引用** |+| 功能与现有 80% 相似 | **扩展现有**(加参数/配置项) |+| 功能与现有 50% 相似 | **抽取公共部分**为新的共享工具/组件 |+| 功能全新、无类似实现 | **允许新建**,但写到合适的公共目录并更新 README |++### 发现重复代码时++- 若在开发过程中发现项目中已存在重复代码,**主动提示用户**是否需要重构合并+- 新增的可复用逻辑(utils / hooks / components),**必须**放到对应公共目录并更新 README## 代码质量diff --git a/project/aitoearn-web/.env b/project/aitoearn-web/.envdeleted file mode 100644index 025b23e9..00000000--- a/project/aitoearn-web/.env+++ /dev/null@@ -1,13 +0,0 @@-# API URL-NEXT_PUBLIC_API_URL="/api"--# OSS URL(自部署通过 nginx 代理到本地 rustfs)-NEXT_PUBLIC_OSS_URL="/oss/"--# OSS URL 代理-NEXT_PUBLIC_OSS_URL_PROXY="/ossProxy/"--# s3 URL 1-NEXT_PUBLIC_S3_URL="https://aitoearn.s3.ap-southeast-1.amazonaws.com/"-# s3 代理-NEXT_PUBLIC_S3_PROXY="/s3Proxy/"\ No newline at end of filediff --git a/project/aitoearn-web/.env.production b/project/aitoearn-web/.env.productionindex 41486de4..3b2d4b81 100644--- a/project/aitoearn-web/.env.production+++ b/project/aitoearn-web/.env.production@@ -1 +1,2 @@NEXT_PUBLIC_EVN=prod+NEXT_PUBLIC_API_URL=/apidiff --git a/project/aitoearn-web/.github/workflows/deploy.yml b/project/aitoearn-web/.github/workflows/deploy.ymldeleted file mode 100644index 8259c69d..00000000--- a/project/aitoearn-web/.github/workflows/deploy.yml+++ /dev/null@@ -1,165 +0,0 @@-name: Deploy--on:- push:- branches:- - main- workflow_dispatch:- inputs:- version:- description: 镜像版本 (留空使用默认生成规则)- required: false- type: string- architectures:- description: 目标平台 (逗号分隔,如 linux/amd64,linux/arm64)- required: false- type: string- default: linux/amd64--permissions:- contents: read--env:- FLY_REGISTRY: registry.fly.io- DOCKER_REGISTRY: registry.aitoearn.cn- APP_NAME: aitoearn-web- INFRASTRUCTURE_REPO: fly-apps--jobs:- build-image:- runs-on: ubuntu-latest- outputs:- version: ${{ steps.version.outputs.version }}-- steps:- - name: Checkout source code- uses: actions/checkout@v4-- - name: Set up Docker Buildx- uses: docker/[email protected]-- - name: Set up flyctl- uses: superfly/flyctl-actions/[email protected]-- - name: Log in to the registry- run: flyctl auth docker- env:- FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}-- - name: Login to Private Registry- uses: docker/login-action@v3- with:- registry: ${{ env.DOCKER_REGISTRY }}- username: ${{ secrets.REGISTRY_USERNAME }}- password: ${{ secrets.REGISTRY_PASSWORD }}-- - name: Generate version- id: version- run: |- if [ -n "${{ github.event.inputs.version }}" ]; then- VERSION="${{ github.event.inputs.version }}"- else- VERSION=$(date +%Y%m%d)-$(git rev-parse --short HEAD)- fi- echo "version=$VERSION" >> $GITHUB_OUTPUT-- - name: Build and push to Fly.io registry- uses: docker/build-push-action@v5- with:- context: .- file: ./Dockerfile- platforms: ${{ github.event.inputs.architectures }}- push: true- tags: ${{ env.FLY_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}- cache-from: type=gha,scope=fly-prod- cache-to: type=gha,mode=max,scope=fly-prod-- - name: Build and push to private registry- uses: docker/build-push-action@v5- with:- context: .- file: ./Dockerfile- platforms: ${{ github.event.inputs.architectures }}- push: true- tags: ${{ env.DOCKER_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}- cache-from: type=gha,scope=private-prod- cache-to: type=gha,mode=max,scope=private-prod- - name: Build summary- run: |- echo "### ✅ 构建成功: ${{ env.APP_NAME }}" >> $GITHUB_STEP_SUMMARY- echo "- **私有镜像**: \`${{ env.DOCKER_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}\`" >> $GITHUB_STEP_SUMMARY- echo "- **Fly.io 镜像**: \`${{ env.FLY_REGISTRY }}/${{ env.APP_NAME }}:${{ steps.version.outputs.version }}\`" >> $GITHUB_STEP_SUMMARY-- # 触发部署- trigger-deployment:- needs: build-image- runs-on: ubuntu-latest- permissions:- id-token: write- contents: read-- steps:- - uses: actions/create-github-app-token@v2- id: generate-token- with:- app-id: ${{ secrets.APP_ID }}- private-key: ${{ secrets.APP_PRIVATE_KEY }}- owner: ${{ github.repository_owner }}- repositories: ${{ env.INFRASTRUCTURE_REPO }}-- - name: Build apps JSON- id: build-apps-json- run: |- APP_NAME="${{ env.APP_NAME }}"- VERSION="${{ needs.build-image.outputs.version }}"- IMAGE="${{ env.FLY_REGISTRY }}/$APP_NAME:$VERSION"-- APPS_JSON="{\"$APP_NAME\":{\"image\":\"$IMAGE\"}}"- echo "apps_json=$APPS_JSON" >> $GITHUB_OUTPUT- echo "📋 Apps JSON: $APPS_JSON"-- - name: Trigger deployment- uses: actions/github-script@v7- with:- github-token: ${{ steps.generate-token.outputs.token }}- script: |- const owner = '${{ github.repository_owner }}';- const repo = '${{ env.INFRASTRUCTURE_REPO }}';- const apps = ${{ steps.build-apps-json.outputs.apps_json }};- const branch = '${{ github.ref_name }}';- const environment = 'prod';-- await github.rest.repos.createDispatchEvent({- owner: owner,- repo: repo,- event_type: 'deploy',- client_payload: {- source_repo: '${{ github.repository }}',- source_branch: branch,- source_commit: '${{ github.sha }}',- apps: apps,- environment: environment,- triggered_by: `workflow_dispatch_${branch}`,- build_url: '${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}'- }- });-- console.log(`✅ 已触发 deploy 事件 (branch: ${branch}, environment: ${environment})`);- console.log('Payload:', {- source_repo: '${{ github.repository }}',- source_branch: branch,- source_commit: '${{ github.sha }}',- apps: apps,- environment: environment- });-- - name: Summary- run: |- echo "## 🚀 已触发部署" >> $GITHUB_STEP_SUMMARY- echo "" >> $GITHUB_STEP_SUMMARY- echo "- **分支**: ${{ github.ref_name }}" >> $GITHUB_STEP_SUMMARY- echo "- **环境**: prod" >> $GITHUB_STEP_SUMMARY- echo "- **提交**: [\`${{ github.sha }}\`](${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }})" >> $GITHUB_STEP_SUMMARY- echo "- **部署目标**: ${{ env.INFRASTRUCTURE_REPO }}" >> $GITHUB_STEP_SUMMARY- echo "- **应用**: ${{ env.APP_NAME }}" >> $GITHUB_STEP_SUMMARY- echo "- **镜像**: \`${{ env.FLY_REGISTRY }}/${{ env.APP_NAME }}:${{ needs.build-image.outputs.version }}\`" >> $GITHUB_STEP_SUMMARYdiff --git a/project/aitoearn-web/.gitignore b/project/aitoearn-web/.gitignoreindex 0829315d..eb65eacd 100644--- a/project/aitoearn-web/.gitignore+++ b/project/aitoearn-web/.gitignore@@ -55,3 +55,4 @@ nultests/.auth/playwright-report/test-results/+.gstack/diff --git a/project/aitoearn-web/deploy/docker-compose.yaml b/project/aitoearn-web/deploy/docker-compose.yamldeleted file mode 100644index 202dc4f6..00000000--- a/project/aitoearn-web/deploy/docker-compose.yaml+++ /dev/null@@ -1,11 +0,0 @@-version: '3.8'--services:- aitoearn-web:- image: next-base-image- container_name: aitoearn-web- ports:- - '3000:3000'- volumes:- - ./standalone:/app- command: node server.jsdiff --git a/project/aitoearn-web/next-sitemap.config.js b/project/aitoearn-web/next-sitemap.config.jsdeleted file mode 100644index 4954b6f1..00000000--- a/project/aitoearn-web/next-sitemap.config.js+++ /dev/null@@ -1,215 +0,0 @@-const { statSync } = require('node:fs')-const path = require('node:path')-// next-sitemap.config.js-const glob = require('glob')-const { HREFLANG_MAP, languages } = require('./src/lib/i18n/hreflangMap.cjs')--const BLOCKLIST_REGEX = /material\/album\/\[id\]/-const HAS_DYNAMIC_SEGMENT = /\[[^/]+?\]/-const siteUrl = 'https://aitoearn.ai'--// 生成多语言alternateRefs(每个语言的根 URL)-const alternateRefs = languages.map(lang => ({- href: `${siteUrl}/${lang}`,- hreflang: HREFLANG_MAP[lang] || lang,-}))-// 添加 x-default,指向站点根(更通用的默认入口)-alternateRefs.push({- href: `${siteUrl}/`,- hreflang: 'x-default',-})--/** @type {import('next-sitemap').IConfig} */-module.exports = {- siteUrl,- generateRobotsTxt: true,- sitemapSize: 7000,-- // 主站 URL 生成(保持你现有逻辑,可继续优化)- transform: async (_, locPath) => {- if (HAS_DYNAMIC_SEGMENT.test(locPath))- return null- if (BLOCKLIST_REGEX.test(locPath))- return null- if (locPath.includes('[lng]'))- return null- return {- loc: locPath,- changefreq: 'monthly',- priority: 0.7,- lastmod: new Date().toISOString(),- }- },-- // 添加多语言支持- alternateRefs,-- additionalPaths: async () => {- // 扩展 glob,支持 js/ts/jsx/tsx 四类 page 文件- const allPageFiles = glob.sync('src/app/**/page.{js,ts,jsx,tsx}', {- cwd: process.cwd(),- ignore: ['**/node_modules/**'],- })-- const pageFiles = allPageFiles- .filter(f => f.includes('[lng]'))- .filter((f) => {- const unix = f.replace(/\\/g, '/')- if (BLOCKLIST_REGEX.test(unix))- return false- const withoutLng = unix.replace('/[lng]', '')- return !HAS_DYNAMIC_SEGMENT.test(withoutLng)- })-- const routeEntries = pageFiles.map((file) => {- let route- = file- .replace(/\\/g, '/')- .replace(/\/page\.(js|tsx)$/, '')- .replace('src/app/[lng]', '') || '/'- if (route !== '/')- route = route.replace(/^\/+/, '/')- const lastmod = statSync(path.resolve(file)).mtime.toISOString()- return { route, lastmod }- })-- const result = []-- for (const lang of languages) {- for (const { route, lastmod } of routeEntries) {- const isRoot = route === '/'- const slug = isRoot ? '' : route.slice(1)- const normalized = slug-- let changefreq = 'monthly'- let priority = isRoot ? 0.8 : 0.7- if (normalized.includes('hotContent')) {- changefreq = 'daily'- priority = 0.9- }- else if (normalized.includes('aiRank')) {- changefreq = 'weekly'- priority = 0.9- }-- result.push({- loc: `/${lang}${slug ? `/${slug}` : ''}`,- changefreq,- priority,- lastmod,- })- }- }-- // 动态任务页面已移除-- return result- },-- // 关键:把子站 sitemap 挂到索引- additionalSitemaps: [- // 'https://blog.aitoearn.ai/sitemap.xml',- 'https://docs.aitoearn.ai/sitemap.xml',- // 'https://hotinfo.aitoearn.ai/sitemap.xml',- // 'https://rank.aitoearn.ai/sitemap.xml',- ],-- // 让 robots.txt 也列出- robotsTxtOptions: {- policies: [- {- userAgent: '*',- allow: '/',- disallow: [- '/api/',- '/_next/static/',- '/_next/image/',- '/cdn-cgi/',- '/admin/',- ],- },- // 允许访问静态资源- {- userAgent: '*',- allow: [- '/_next/static/css/',- '/_next/static/js/',- '/_next/static/media/',- '/_next/static/chunks/',- '/js/',- '/images/',- ],- },- // 欢迎 AI 爬虫- {- userAgent: 'Google-Extended',- allow: '/',- },- {- userAgent: 'GPTBot',- allow: '/',- },- {- userAgent: 'ChatGPT-User',- allow: '/',- },- {- userAgent: 'CCBot',- allow: '/',- },- {- userAgent: 'anthropic-ai',- allow: '/',- },- {- userAgent: 'Claude-Web',- allow: '/',- },- {- userAgent: 'Bard',- allow: '/',- },- {- userAgent: 'Bing-AI',- allow: '/',- },- {- userAgent: 'PerplexityBot',- allow: '/',- },- ],- additionalSitemaps: [- // 'https://blog.aitoearn.ai/sitemap.xml',- 'https://docs.aitoearn.ai/sitemap.xml',- // 'https://hotinfo.aitoearn.ai/sitemap.xml',- // 'https://rank.aitoearn.ai/sitemap.xml',- ],- // 添加自定义内容到 robots.txt(避免重复追加)- transformRobotsTxt: async (_, robotsTxt) => {- const customLines = [- `${siteUrl}/llms.txt`,- `${siteUrl}/llms-zh.txt`,- ]- // 如果已包含 llms 链接则不重复追加- const alreadyHasLlms = customLines.some(line => robotsTxt.includes(line))- if (alreadyHasLlms)- return robotsTxt-- const customContent = `-# LLMs.txt for AI models-# English version-${siteUrl}/llms.txt-# Chinese version-${siteUrl}/llms-zh.txt--# AI Training Policy - We welcome AI crawlers-# Our content can be used for search indexing and AI training-# This helps increase our visibility and reach--# Note: /cdn-cgi/ is Cloudflare's internal path, not part of our site content-# It's disallowed to prevent crawlers from accessing CDN internals-`- return robotsTxt + customContent- },- },-}diff --git a/project/aitoearn-web/next.config.mjs b/project/aitoearn-web/next.config.mjsindex dfed12b4..93fac355 100644--- a/project/aitoearn-web/next.config.mjs+++ b/project/aitoearn-web/next.config.mjs@@ -31,18 +31,9 @@ const nextConfig = {output: 'standalone', // Temporarily disabled to avoid symlink issues on WindowsproductionBrowserSourceMaps: process.env.NEXT_PUBLIC_EVN === 'dev',rewrites: async () => {- const rewrites = [- {- source: `${process.env.NEXT_PUBLIC_OSS_URL_PROXY}:path*`,- destination: `${process.env.NEXT_PUBLIC_OSS_URL}/:path*`,- },- {- source: `${process.env.NEXT_PUBLIC_S3_PROXY}:path*`,- destination: `${process.env.NEXT_PUBLIC_S3_URL}:path*`,- },- ]+ const rewrites = []- // 存在 NEXT_PUBLIC_PROXY_URL 则代理,本地直连 用+ // 存在 NEXT_PUBLIC_PROXY_URL 则代理,本地直连用// 如:NEXT_PUBLIC_PROXY_URL = http://localhost:8080if (process.env.NEXT_PUBLIC_PROXY_URL) {rewrites.push({diff --git a/project/aitoearn-web/package.json b/project/aitoearn-web/package.jsonindex 12319516..64e0cf81 100644--- a/project/aitoearn-web/package.json+++ b/project/aitoearn-web/package.json@@ -3,7 +3,6 @@"version": "0.1.0","private": true,"scripts": {- "postbuild": "next-sitemap","dev": "next dev -p 6060","dev:local": "cross-env NEXT_PUBLIC_API_URL=http://localhost:7001/api next dev","build": "next build",@@ -34,8 +33,7 @@"migrateToLocize": "locize migrate --project-id=01b2e5e8-6243-47d1-b36f-963dbb8bcae3 --api-key=c9805cd1-fd50-4d98-967a-383b39066de8 --path=./app/i18n/locales","downloadLocales": "locize download --project-id=01b2e5e8-6243-47d1-b36f-963dbb8bcae3 --ver=latest --clean=true --path=./app/i18n/locales && npm run i18next-resources-for-ts","syncLocales": "locize sync --project-id=01b2e5e8-6243-47d1-b36f-963dbb8bcae3 --api-key=bd8cb856-d6b3-4c82-a456-862c729a1674 --ver=latest --path=./app/i18n/locales --dry=true",- "i18next-resources-for-ts": "i18next-resources-for-ts interface -i ./src/app/i18n/locales/zh-CN -o ./@types/resources.d.ts",- "prepare": "husky"+ "i18next-resources-for-ts": "i18next-resources-for-ts interface -i ./src/app/i18n/locales/zh-CN -o ./@types/resources.d.ts"},"dependencies": {"@ant-design/colors": "^7.2.1",@@ -104,7 +102,6 @@"lottie-react": "^2.4.1","lucide-react": "^0.561.0","next": "14.2.29",- "next-sitemap": "^4.2.3","next-themes": "^0.4.6","qrcode": "^1.5.4","qs": "^6.14.0",@@ -119,6 +116,7 @@"react-infinite-scroll-component": "^6.1.0","react-markdown": "^10.1.0","react-masonry-css": "^1.0.16",+ "react-number-format": "^5.4.4","react-qrcode-logo": "^4.0.0","react-sortablejs": "^6.1.4","react-transition-group": "^4.4.5",diff --git a/project/aitoearn-web/pm2.json b/project/aitoearn-web/pm2.jsondeleted file mode 100644index 8c1ab879..00000000--- a/project/aitoearn-web/pm2.json+++ /dev/null@@ -1,21 +0,0 @@-{- "apps": [- {- "name": "aitoearn-web",- "cwd": "standalone",- "script": "node server.js",- "instances": "1",- "exec_mode": "cluster",- "env": {- "NODE_ENV": "development",- "PORT": 7000- },- "env_production": {- "NODE_ENV": "production",- "PORT": 7000- },- "log_date_format": "YYYY-MM-DD_HH:mm Z",- "merge_logs": true- }- ]-}diff --git a/project/aitoearn-web/pnpm-lock.yaml b/project/aitoearn-web/pnpm-lock.yamlindex 26337335..12584571 100644--- a/project/aitoearn-web/pnpm-lock.yaml+++ b/project/aitoearn-web/pnpm-lock.yaml@@ -206,9 +206,6 @@ importers:next:specifier: 14.2.29version: 14.2.29(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected])- next-sitemap:- specifier: ^4.2.3- version: 4.2.3([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))next-themes:specifier: ^0.4.6@@ -251,6 +248,9 @@ importers:react-masonry-css:specifier: ^1.0.16version: 1.0.16([email protected])+ react-number-format:+ specifier: ^5.4.4react-qrcode-logo:specifier: ^4.0.0@@ -1076,9 +1076,6 @@ packages:'@clack/[email protected]':resolution: {integrity: sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==}- '@corex/[email protected]':- resolution: {integrity: sha512-N8uEMrMPL0cu/bdboEWpQYb/0i2K5Qn8eCsxzOmxSggJbbQte7ljMRoXm917AbntqTGOzdTu+vP3KOOzoC70HQ==}-'@dprint/[email protected]':resolution: {integrity: sha512-N9fxCxbaBOrDkteSOzaCqwWjso5iAe+WJPsHC021JfHNj2ThInPNEF13ORDKta3llq5D1TlclODCvOvipH7bWQ==}@@ -1508,9 +1505,6 @@ packages:'@microsoft/[email protected]':resolution: {integrity: sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA==}- '@next/[email protected]':- resolution: {integrity: sha512-fbb2C7HChgM7CemdCY+y3N1n8pcTKdqtQLbC7/EQtPdLvlMUT9JX/dBYl8MMZAtYG4uVMyPFHXckb68q/NRwqg==}-'@next/[email protected]':resolution: {integrity: sha512-UzgLR2eBfhKIQt0aJ7PWH7XRPYw7SXz0Fpzdl5THjUnvxy4kfBk9OU4RNPNiETewEEtaBcExNFNn1QWH8wQTjg==}@@ -3699,10 +3693,6 @@ packages:resolution: {integrity: sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==}engines: {node: '>=8.6.0'}- resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}- engines: {node: '>=8.6.0'}-resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}@@ -4692,9 +4682,6 @@ packages:resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}engines: {node: '>=16 || 14 >=14.17'}- resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}-resolution: {integrity: sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==}engines: {node: '>=8'}@@ -4745,13 +4732,6 @@ packages:resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==}- resolution: {integrity: sha512-vjdCxeDuWDzldhCnyFCQipw5bfpl4HmZA7uoo3GAaYGjGgfL4Cxb1CiztPuWGmS+auYs7/8OekRS8C2cjdAsjQ==}- engines: {node: '>=14.18'}- hasBin: true- peerDependencies:- next: '*'-resolution: {integrity: sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==}peerDependencies:@@ -5367,6 +5347,12 @@ packages:peerDependencies:react: '>=16.0.0'+ resolution: {integrity: sha512-wOmoNZoOpvMminhifQYiYSTCLUDOiUbBunrMrMjA+dV52sY+vck1S4UhR6PkgnoCquvvMSeJjErXZ4qSaWCliA==}+ peerDependencies:+ react: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-TcDdsJQe7P0OY7uA7Do4Z0DfIIjjqx81RbBGQY+90T2Ba42pUCx/cSI2UTwPPoH9WwE0StLb8A98mFgKIAI4JQ==}peerDependencies:@@ -7177,8 +7163,6 @@ snapshots:picocolors: 1.1.1sisteransi: 1.0.5- '@corex/[email protected]': {}-'@dprint/[email protected]': {}'@dprint/[email protected]': {}@@ -7693,8 +7677,6 @@ snapshots:'@microsoft/[email protected]': {}- '@next/[email protected]': {}-'@next/[email protected]': {}'@next/[email protected]':@@ -10124,14 +10106,6 @@ snapshots:merge2: 1.4.1micromatch: 4.0.8- dependencies:- '@nodelib/fs.stat': 2.0.5- '@nodelib/fs.walk': 1.2.8- glob-parent: 5.1.2- merge2: 1.4.1- micromatch: 4.0.8-@@ -11365,8 +11339,6 @@ snapshots:dependencies:brace-expansion: 2.0.2- [email protected]: {}-@@ -11411,14 +11383,6 @@ snapshots:- [email protected]([email protected](@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected])):- dependencies:- '@corex/deepmerge': 4.0.43- '@next/env': 13.5.11- fast-glob: 3.3.3- minimist: 1.2.8- next: 14.2.29(@babel/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected])-dependencies:react: 18.3.1@@ -12128,6 +12092,11 @@ snapshots:dependencies:react: 18.3.1+ dependencies:+ react: 18.3.1+ react-dom: 18.3.1([email protected])+dependencies:qrcode-generator: 2.0.4diff --git a/project/aitoearn-web/public/assets/welcome/promotion.mp4 b/project/aitoearn-web/public/assets/welcome/promotion.mp4deleted file mode 100644index 29f91d5c..00000000Binary files a/project/aitoearn-web/public/assets/welcome/promotion.mp4 and /dev/null differdiff --git a/project/aitoearn-web/src/api/ai.ts b/project/aitoearn-web/src/api/ai.tsindex 5ea01140..383c3a92 100644--- a/project/aitoearn-web/src/api/ai.ts+++ b/project/aitoearn-web/src/api/ai.ts@@ -61,7 +61,6 @@ export function generateVideo(data: {prompt: stringimage?: anyimage_tail?: string- mode?: stringsize?: stringduration?: numbermetadata?: Record<string, any>diff --git a/project/aitoearn-web/src/api/credits.ts b/project/aitoearn-web/src/api/credits.tsnew file mode 100644index 00000000..415f0669--- /dev/null+++ b/project/aitoearn-web/src/api/credits.ts@@ -0,0 +1,90 @@+/**+ * Credits API - 用户余额相关接口+ * 包含余额查询和使用记录查询+ */++import http from '@/utils/request'++/** Credits 变动类型 */+export type CreditsType+ = | 'register_bonus'+ | 'purchase'+ | 'vip_monthly'+ | 'ai_service'+ | 'video_style_transfer'+ | 'publish'+ | 'expired'+ | 'manual'++/** 余额响应 */+export interface CreditsBalanceVo {+ /** 当前 Credits 余额(美分) */+ balance: number+}++/** 单条使用记录 */+export interface CreditsRecordVo {+ /** 记录 ID */+ id: string+ /** 用户 ID */+ userId: string+ /** Credits 变动数量(美分) */+ amount: number+ /** 该记录剩余的可用余额(美分) */+ balance: number+ /** Credits 变动类型 */+ type: CreditsType+ /** Credits 变动描述 */+ description?: string+ /** 过期时间,null 表示永久有效 */+ expiredAt?: string | null+ /** 创建时间 */+ createdAt: string+ /** 更新时间 */+ updatedAt: string+}++/** 使用记录列表响应 */+export interface CreditsRecordsVo {+ page: number+ pageSize: number+ totalPages: number+ total: number+ list: CreditsRecordVo[]+}++/** 获取使用记录的参数 */+export interface GetCreditsRecordsParams {+ page?: number+ pageSize?: number+ type?: CreditsType+}++/**+ * 获取用户余额+ */+export function getCreditsBalanceApi() {+ return http.get<CreditsBalanceVo>('user/credits')+}++/**+ * 获取用户余额使用记录+ */+export function getCreditsRecordsApi(params?: GetCreditsRecordsParams) {+ return http.get<CreditsRecordsVo>('user/credits/records', params)+}++/**+ * 美分转美元(保留2位小数)+ */+export function centsToUsd(cents: number): string {+ return cents?.toFixed(2)+}++/**+ * 格式化金额变更(带正负号)+ */+export function formatAmountChange(cents: number): string {+ const usd = centsToUsd(Math.abs(cents))+ return cents >= 0 ? `+${usd}` : `-${usd}`+}diff --git a/project/aitoearn-web/src/api/draftGeneration.ts b/project/aitoearn-web/src/api/draftGeneration.tsindex e15fe9f4..f81cce23 100644--- a/project/aitoearn-web/src/api/draftGeneration.ts+++ b/project/aitoearn-web/src/api/draftGeneration.ts@@ -22,12 +22,25 @@ export interface DraftGenerationResponse {imageUrls?: string[]}+/** 生成任务请求参数 */+export interface DraftGenerationRequest {+ model?: string+ imageModel?: string+ duration?: number+ aspectRatio?: string+ prompt?: string+ imageUrls?: string[]+ imageCount?: number+ imageSize?: string+}+/** 生成任务详情 */export interface DraftGenerationTask {id: stringstatus: DraftTaskStatuspoints: numbererrorMessage?: string+ request?: DraftGenerationRequestresponse?: DraftGenerationResponsecreatedAt: stringupdatedAt: string@@ -63,6 +76,12 @@ export type ImageModelType = string/** 草稿内容类型 */export type DraftContentType = 'video' | 'image_text'+/** 视频草稿类型:draft=完整草稿(含标题描述话题),video=仅生成视频 */+export type VideoDraftType = 'draft' | 'video'++/** 图文草稿类型:draft=完整草稿,image=仅生成图片 */+export type ImageTextDraftType = 'draft' | 'image'+/** 创建 AI 批量生成草稿任务 */export function apiCreateDraftGeneration(data: {quantity: number@@ -74,6 +93,7 @@ export function apiCreateDraftGeneration(data: {duration?: numberaspectRatio?: stringplatforms?: string[]+ draftType?: VideoDraftType}) {return http.post<CreateDraftGenerationVo>('ai/draft-generation/v2', data)}@@ -89,6 +109,7 @@ export function apiCreateImageTextDraft(data: {aspectRatio?: stringimageSize?: stringplatforms?: string[]+ draftType?: ImageTextDraftType}) {return http.post<CreateDraftGenerationVo>('ai/draft-generation/image-text', data)}diff --git a/project/aitoearn-web/src/api/material.ts b/project/aitoearn-web/src/api/material.tsindex 269ebc7d..0a337a3e 100644--- a/project/aitoearn-web/src/api/material.ts+++ b/project/aitoearn-web/src/api/material.ts@@ -1,4 +1,4 @@-import type { DraftMaterial } from '@/app/[lng]/draft-box/types'+import type { PromotionMaterial, PromotionPlan } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'import type { PubType } from '@/app/config/publishConfig'import http from '@/utils/request'@@ -29,7 +29,7 @@ export interface NewMaterialTask {// 创建素材草稿组export function apiCreateMaterialGroup(data: { name: string }) {- return http.post<{ _id: string }>('material/group', {+ return http.post<{ id: string }>('material/group', {...data,type: 'video',})@@ -52,7 +52,7 @@ export function apiUpdateMaterialGroupInfo(// 获取草稿素材组列表export function apiGetMaterialGroupList(pageNo: number, pageSize: number) {- return http.get<{ list: any[], total: number }>(`material/group/list/${pageNo}/${pageSize}`)+ return http.get<{ list: PromotionPlan[], total: number }>(`material/group/list/${pageNo}/${pageSize}`)}// 获取草稿素材组详情@@ -76,6 +76,7 @@ export function apiCreateMaterial(type: PubTypeoption?: Record<string, any>location?: number[]+ accountTypes?: string[]},silent?: boolean,) {@@ -130,7 +131,7 @@ export async function apiGetMaterialList(groupId: string, pageNo: number, pageSiparams.title = filters.titleif (filters?.useCount !== undefined)params.useCount = filters.useCount- const res = await http.get<{ list: DraftMaterial[], total: number }>(`material/list/${pageNo}/${pageSize}`, params)+ const res = await http.get<{ list: PromotionMaterial[], total: number }>(`material/list/${pageNo}/${pageSize}`, params)const list = res?.data?.list// 兼容代码,图文草稿补封面if (list && list.length > 0) {@@ -164,6 +165,7 @@ export function apiUpdateMaterial(desc?: stringlocation?: number[]option?: Record<string, any>+ accountTypes?: string[]},) {return http.put(`material/info/${id}`, data)diff --git a/project/aitoearn-web/src/api/media.ts b/project/aitoearn-web/src/api/media.tsindex 3f87a1f6..574d8385 100644--- a/project/aitoearn-web/src/api/media.ts+++ b/project/aitoearn-web/src/api/media.ts@@ -1,4 +1,4 @@-import type { MediaGroup, MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaGroup, MediaItem } from '@/api/types/media'import http from '@/utils/request'// 创建媒体资源组@@ -41,9 +41,15 @@ export function deleteMedia(id: string) {}// 获取媒体资源列表-export function getMediaList(groupId: string, pageNo: number, pageSize: number) {+export function getMediaList(+ filter: { groupId?: string, materialGroupId?: string },+ pageNo: number,+ pageSize: number,+ type?: 'video' | 'img',+) {return http.get<{ list: MediaItem[], total: number }>(`media/list/${pageNo}/${pageSize}`, {- groupId,+ ...filter,+ ...(type ? { type } : {}),})}diff --git a/project/aitoearn-web/src/api/notification.ts b/project/aitoearn-web/src/api/notification.tsindex 1157a4b3..8b8c9a56 100644--- a/project/aitoearn-web/src/api/notification.ts+++ b/project/aitoearn-web/src/api/notification.ts@@ -14,13 +14,14 @@ export enum NotificationType {TaskReviewApproved = 'task_review_approved',AiReviewSkipped = 'ai_review_skipped',TaskSubmitted = 'task_submitted',+ InteractionAiReviewFailed = 'interaction_ai_review_failed',}export interface NotificationItem {id: stringtitle: stringcontent: string- type: 'system' | 'user' | 'material' | 'other' | 'task_reminder' | 'app_release' | 'user_withdraw' | 'task_punish' | 'agent_result' | 'task_settled' | 'task_review_rejected' | 'task_review_approved' | 'ai_review_skipped' | 'task_submitted'+ type: 'system' | 'user' | 'material' | 'other' | 'task_reminder' | 'app_release' | 'user_withdraw' | 'task_punish' | 'agent_result' | 'task_settled' | 'task_review_rejected' | 'task_review_approved' | 'ai_review_skipped' | 'task_submitted' | 'interaction_ai_review_failed'status: 'read' | 'unread'readAt?: stringcreatedAt: stringdiff --git a/project/aitoearn-web/src/api/open/index.ts b/project/aitoearn-web/src/api/open/index.tsdeleted file mode 100644index 68bb35a5..00000000--- a/project/aitoearn-web/src/api/open/index.ts+++ /dev/null@@ -1,5 +0,0 @@-/**- * 公开 API 模块导出- */--export * from './promotionCode'diff --git a/project/aitoearn-web/src/api/open/promotionCode.ts b/project/aitoearn-web/src/api/open/promotionCode.tsdeleted file mode 100644index d28ac4ab..00000000--- a/project/aitoearn-web/src/api/open/promotionCode.ts+++ /dev/null@@ -1,36 +0,0 @@-/**- * 公开推广码 API- * 用于推广者侧获取素材信息- */--import type { OptimalMaterialVo } from '../types/open/promotionCode'-import type { PlatType } from '@/app/config/platConfig'-import http from '@/utils/request'--/**- * 通过素材组ID获取最优素材(公开接口,无需认证)- * @param groupId 素材组ID(即推广码)- * @param accountType 平台类型,用于筛选匹配的素材- */-export function apiGetOptimalMaterial(groupId: string, accountType: PlatType) {- return http.get<OptimalMaterialVo>('/material/optimal', { groupId, accountType })-}--/**- * 创建公开发布记录(公开接口,无需认证)- * 用于推广者提交作品链接- */-export function apiCreateOpenPublishRecord(params: {- materialGroupId: string- materialId?: string- workLink: string- accountType: PlatType- videoUrl?: string- coverUrl?: string- imgUrlList?: string[]- title?: string- desc?: string- topics?: string[]-}) {- return http.post<{ id: string, success: boolean }>('/task/open/publish-record/create', params)-}diff --git a/project/aitoearn-web/src/api/plat/dataCube.ts b/project/aitoearn-web/src/api/plat/dataCube.tsdeleted file mode 100644index eae01c92..00000000--- a/project/aitoearn-web/src/api/plat/dataCube.ts+++ /dev/null@@ -1,18 +0,0 @@-// 渠道数据-import http from '@/utils/request'--/**- * 获取账号统计数据- * @returns- */-export function apiGetAccountDataCube(accountId: string) {- return http.get<{ code: number, data: any }>(`channel/dataCube/accountDataCube/${accountId}`)-}--/**- * 获取账号增量数据- * @returns- */-export function apiGetAccountDataBulk(accountId: string) {- return http.get<{ code: number, data: any }>(`channel/dataCube/getAccountDataBulk/${accountId}`)-}diff --git a/project/aitoearn-web/src/api/types/draftGeneration.ts b/project/aitoearn-web/src/api/types/draftGeneration.tsindex d9fe8f2d..b91e79be 100644--- a/project/aitoearn-web/src/api/types/draftGeneration.ts+++ b/project/aitoearn-web/src/api/types/draftGeneration.ts@@ -19,7 +19,6 @@ export interface ImageModelInfo {export interface VideoModelPricing {duration: numberprice: number- mode?: stringresolution?: stringaspectRatio?: stringdiscount?: string@@ -29,8 +28,6 @@ export interface VideoModelPricing {export interface VideoModelInfo {name: stringdescription: string- channel: string- modes: string[]resolutions: string[]durations: number[]maxInputImages: numberdiff --git a/project/aitoearn-web/src/api/types/finance.ts b/project/aitoearn-web/src/api/types/finance.tsdeleted file mode 100644index cf46fb72..00000000--- a/project/aitoearn-web/src/api/types/finance.ts+++ /dev/null@@ -1,32 +0,0 @@-/*- * @Author: nevin- * @Date: 2025-03-02 21:06:59- * @LastEditTime: 2025-03-02 22:12:36- * @LastEditors: nevin- * @Description: 财务相关- */--export enum UserWalletRecordType {- TASK_COMMISSION = 'TASK_COMMISSION', // 任务佣金- WITHDRAW = 'WITHDRAW', // 提现-}--export enum UserWalletRecordStatus {- FAIL = -1,- WAIT = 0,- SUCCESS = 1,-}--export interface UserWalletRecord {- id: string- userId: string- dataId: string // 关联数据的ID- type: UserWalletRecordType- balance: number- status: UserWalletRecordStatus- payTime?: string- des?: string- imgUrl?: string // 反馈截图- createdAt: string- updatedAt: string-}diff --git a/project/aitoearn-web/src/api/types/income.ts b/project/aitoearn-web/src/api/types/income.tsnew file mode 100644index 00000000..ce7c6655--- /dev/null+++ b/project/aitoearn-web/src/api/types/income.ts@@ -0,0 +1,52 @@+export enum IncomeType {+ TASK = 'task', // 任务+ TASK_BACK = 'task_back', // 任务回退+ REWARD_BACK = 'reward_back', // 奖励回退+ TASK_WITHDRAW = 'task_withdraw', // 任务提现+}++// 新 API 枚举类型+export enum Currency {+ Cny = 'CNY',+ Unk = 'UNK',+ Usd = 'USD',+}++export enum IncomeStatus {+ Pending = 'pending',+ Withdrawn = 'withdrawn',+}++export enum IncomeTypeEnum {+ RewardBack = 'reward_back',+ Task = 'task',+ TaskBack = 'task_back',+ TaskWithdraw = 'task_withdraw',+}++// 收入记录请求参数+export interface IncomeListRequest {+ currency?: Currency+ page?: number+ pageSize?: number+ status?: IncomeStatus+ type?: IncomeTypeEnum+ [property: string]: any+}++// 订单类型 (根据实际API返回结构)+export interface IncomeRecord {+ _id: string+ id: string+ userId: string+ amount: number+ relId?: string+ type: IncomeType | IncomeTypeEnum+ desc?: string+ metadata?: Record<string, unknown>+ // 提现状态:1=可提现,0=已申请 或 pending/withdrawn+ status?: number | IncomeStatus+ createdAt: Date+ updatedAt: Date+ currency?: Currency+}diff --git a/project/aitoearn-web/src/app/[lng]/material/materialStore/materialStore.types.ts b/project/aitoearn-web/src/api/types/media.tssimilarity index 52%rename from project/aitoearn-web/src/app/[lng]/material/materialStore/materialStore.types.tsrename to project/aitoearn-web/src/api/types/media.tsindex 85a2e7c9..c3e79e76 100644--- a/project/aitoearn-web/src/app/[lng]/material/materialStore/materialStore.types.ts+++ b/project/aitoearn-web/src/api/types/media.ts@@ -1,6 +1,6 @@/**- * materialStore.types.ts - 素材库 Store 类型定义- * 定义素材库页面所有相关的类型+ * media.ts - 媒体资源类型定义+ * 共享的媒体相关接口类型*//**@@ -73,67 +73,3 @@ export interface MediaGroup {thumbUrl: string} | null}--/**- * 筛选类型- */-export type FilterType = 'all' | 'video' | 'img'--/**- * 创建/更新分组的数据类型- */-export interface CreateGroupData {- title: string- desc: string- type: 'video' | 'img'-}--/**- * 更新分组的数据类型- */-export interface UpdateGroupData {- title?: string- desc?: string- type?: 'video' | 'img'-}--/**- * materialStore 状态类型- */-export interface IMaterialStore {- // ===== 数据 =====- /** 分组列表 */- groups: MediaGroup[]- /** 总数 */- total: number- /** 默认图片分组 */- defaultImgGroup: MediaGroup | null- /** 默认视频分组 */- defaultVideoGroup: MediaGroup | null-- // ===== 加载状态 =====- /** 列表加载中 */- isLoading: boolean- /** 提交中(创建/更新) */- isSubmitting: boolean- /** 删除中 */- isDeleting: boolean-- // ===== 分页 =====- /** 当前页码 */- currentPage: number- /** 每页数量 */- pageSize: number-- // ===== 筛选 =====- /** 类型筛选 */- filterType: FilterType- /** 搜索文本 */- searchText: string-- // ===== 弹窗状态 =====- /** 创建/编辑弹窗是否打开 */- createModalOpen: boolean- /** 正在编辑的分组(null 表示创建模式) */- editingGroup: MediaGroup | null-}diff --git a/project/aitoearn-web/src/api/types/open/promotionCode.ts b/project/aitoearn-web/src/api/types/open/promotionCode.tsdeleted file mode 100644index 5a573183..00000000--- a/project/aitoearn-web/src/api/types/open/promotionCode.ts+++ /dev/null@@ -1,31 +0,0 @@-/**- * 公开推广码接口类型定义- * 用于推广者侧获取素材信息- */--import type { PlatType } from '@/app/config/platConfig'--/**- * 素材媒体项- */-export interface MaterialMedia {- url: string- type: 'video' | 'img'- thumbUrl?: string-}--/**- * 最优素材信息(通过 GET /material/optimal?groupId=xxx&accountType=xxx 获取)- */-export interface OptimalMaterialVo {- _id: string- title?: string- desc?: string- topics?: string[]- coverUrl?: string- mediaList?: MaterialMedia[]- useCount: number- option: any- /** 平台类型 */- platform: PlatType-}diff --git a/project/aitoearn-web/src/api/types/uptime.ts b/project/aitoearn-web/src/api/types/uptime.tsdeleted file mode 100644index b8fc05cd..00000000--- a/project/aitoearn-web/src/api/types/uptime.ts+++ /dev/null@@ -1,30 +0,0 @@-export enum UptimeStatus {- NORMAL = 1, // 正常- TIMEOUT = 2, // 超时- UNAVAILABLE = 3, // 不可用-}--export enum UptimeModule {- Agent = 'agent', // Agent- Server = 'server', // 服务器- Ai = 'ai', // Ai- Database = 'database', // 数据库- Network = 'network', // 网络- Other = 'other', // 其他-}--export enum UptimeType {- AgentStatus = 'agentStatus',- AgentMcpStatus = 'agentMcpStatus', // Agent Mcp 状态- NewApiStatus = 'newApiStatus', // NewApi 状态-}--export interface UptimeItem {- id: string- status: UptimeStatus- module: UptimeModule- type: UptimeType- metadata?: Record<string, unknown>- createdAt: string- updatedAt: string-}diff --git a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/components/sections/AIGraderSection.tsx b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/components/sections/AIGraderSection.tsxindex d18ba306..47ebc7ea 100644--- a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/components/sections/AIGraderSection.tsx+++ b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/components/sections/AIGraderSection.tsx@@ -8,6 +8,7 @@import { Sparkles } from 'lucide-react'import Image from 'next/image'import { useRouter } from 'next/navigation'+import { useState } from 'react'import { useTransClient } from '@/app/i18n/client'import { Input } from '@/components/ui/input'@@ -44,13 +45,14 @@ export function AIGraderSection() {const { t } = useTransClient('welcome')const router = useRouter()const token = useUserStore(state => state.token)+ const [searchText, setSearchText] = useState('')const handleSubmit = (e: React.FormEvent | React.MouseEvent) => {e.preventDefault()- // 已登录用户直接跳转+ // 已登录用户直接跳转到首页if (token) {- router.push('/draft-box')+ router.push('/')return}@@ -114,8 +116,9 @@ export function AIGraderSection() {><div className="flex-1"><Input+ value={searchText}+ onChange={e => setSearchText(e.target.value)}placeholder={t('hero.placeholder')}- disabledclassName="!h-10 !border-0 !bg-transparent !shadow-none !ring-0 !pl-2"/></div>diff --git a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/experienceTabs.ts b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/experienceTabs.tsindex 569e2025..c2bec085 100644--- a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/experienceTabs.ts+++ b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/experienceTabs.ts@@ -39,21 +39,9 @@ export const experienceTabs: ExperienceTab[] = [poster: '/assets/welcome/video_create-cover.png',},},- {- id: 'promotion',- number: 3,- titleKey: 'experience.tab1.title',- subtitleKey: 'experience.tab1.subtitle',- descriptionKey: 'experience.tab1.description',- video: {- url: '/assets/welcome/promotion.mp4',- poster: '/assets/welcome/interaction-cover.png',- },- isVertical: true,- },{id: 'interaction',- number: 4,+ number: 3,titleKey: 'experience.tab4.title',subtitleKey: 'experience.tab4.subtitle',descriptionKey: 'experience.tab4.description',diff --git a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/navigation.ts b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/navigation.tsindex 80210748..935c5247 100644--- a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/navigation.ts+++ b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/data/navigation.ts@@ -11,8 +11,6 @@ export interface NavItem {}export const navigation: NavItem[] = [- { type: 'link', labelKey: 'pricing', href: '/pricing' },{ type: 'link', labelKey: 'docs', href: 'https://docs.aitoearn.ai/', external: true },- { type: 'link', labelKey: 'brandPromotion', href: '/brand-promotion' },{ type: 'link', labelKey: 'aiSocial', href: '/ai-social' },]diff --git a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsxindex 57b2c363..16607f37 100644--- a/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/(welcome)/welcome/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import WelcomePageContent from './WelcomePageContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/accounts/components/AccountsTopNav/index.tsx b/project/aitoearn-web/src/app/[lng]/accounts/components/AccountsTopNav/index.tsxindex 9c62d28a..be2e2744 100644--- a/project/aitoearn-web/src/app/[lng]/accounts/components/AccountsTopNav/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/accounts/components/AccountsTopNav/index.tsx@@ -9,7 +9,8 @@'use client'import type { SocialAccount } from '@/api/types/account.type'-import { SquarePen, UserPlus } from 'lucide-react'+import { Bot, SquarePen, UserPlus } from 'lucide-react'+import { useRouter } from 'next/navigation'import { memo, useCallback, useMemo, useState } from 'react'import { useShallow } from 'zustand/react/shallow'import { apiUpdateAccountGroupSortRank } from '@/api/accountSort'@@ -26,6 +27,7 @@ export interface IAccountsTopNavProps {const AccountsTopNav = memo<IAccountsTopNavProps>(({ onNewWork, onAddAccount }) => {const { t } = useTransClient('account')+ const router = useRouter()const [accountSearchText, setAccountSearchText] = useState('')const [collapsedSpaces, setCollapsedSpaces] = useState<Set<string>>(new Set())const [sortLoading, setSortLoading] = useState<string | null>(null)@@ -112,9 +114,14 @@ const AccountsTopNav = memo<IAccountsTopNavProps>(({ onNewWork, onAddAccount })rank: index,}))- await apiUpdateAccountGroupSortRank({ list: updateList })- await getAccountGroup()- toast.success(t('messages.sortSuccess'))+ const res = await apiUpdateAccountGroupSortRank({ list: updateList })+ if (res?.code === 0) {+ await getAccountGroup()+ toast.success(t('messages.sortSuccess'))+ }+ else {+ toast.error(res?.message || t('messages.sortFailed'))+ }}catch (error) {toast.error(t('messages.sortFailed'))@@ -175,6 +182,18 @@ const AccountsTopNav = memo<IAccountsTopNavProps>(({ onNewWork, onAddAccount })<UserPlus className="h-4 w-4" /><span>{t('addAccount')}</span></Button>++ <div className="border-l border-border h-6 mx-1 md:mx-2" />++ {/* Agent创建按钮 */}+ <Button+ variant="outline"+ onClick={() => router.push('/ai-social')}+ className="h-8 md:h-9 gap-1 md:gap-2 px-2 md:px-4 cursor-pointer"+ >+ <Bot className="h-4 w-4" />+ <span>{t('agentCreate')}</span>+ </Button></div>{/* 右侧: 频道选择器(按空间分组) */}diff --git a/project/aitoearn-web/src/app/[lng]/accounts/page.tsx b/project/aitoearn-web/src/app/[lng]/accounts/page.tsxindex a14a3ac9..c44f1a54 100644--- a/project/aitoearn-web/src/app/[lng]/accounts/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/accounts/page.tsx@@ -1,7 +1,7 @@import type { PageParams } from '@/app/globals'import AccountPageCore from '@/app/[lng]/accounts/accountCore'import { useTranslation } from '@/app/i18n'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'export async function generateMetadata({ params }: PageParams) {const { lng } = await paramsdiff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/agentAssetsPageCore.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/agentAssetsPageCore.tsxsimilarity index 100%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/agentAssetsPageCore.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/agentAssetsPageCore.tsxdiff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/AgentAssetCardSkeleton.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/AgentAssetCardSkeleton.tsxsimilarity index 100%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/AgentAssetCardSkeleton.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/AgentAssetCardSkeleton.tsxdiff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/VideoPlaceholder.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/VideoPlaceholder.tsxsimilarity index 100%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/VideoPlaceholder.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/VideoPlaceholder.tsxdiff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/index.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/index.tsxsimilarity index 100%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetCard/index.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetCard/index.tsxdiff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetsHeader/index.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetsHeader/index.tsxsimilarity index 96%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetsHeader/index.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetsHeader/index.tsxindex dbd19630..fd257dcf 100644--- a/project/aitoearn-web/src/app/[lng]/material/agent-assets/components/AgentAssetsHeader/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/agent-assets/components/AgentAssetsHeader/index.tsx@@ -20,9 +20,9 @@ export function AgentAssetsHeader({ total }: AgentAssetsHeaderProps) {const { t } = useTransClient('material')const router = useRouter()- // 返回素材库+ // 返回内容管理const handleBack = useCallback(() => {- router.push('/material')+ router.push('/')}, [router])return (diff --git a/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsx b/project/aitoearn-web/src/app/[lng]/agent-assets/page.tsxsimilarity index 93%rename from project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsxrename to project/aitoearn-web/src/app/[lng]/agent-assets/page.tsxindex 046145f9..0718a427 100644--- a/project/aitoearn-web/src/app/[lng]/material/agent-assets/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/agent-assets/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import { AgentAssetsPageCore } from './agentAssetsPageCore'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/components/AgentFeatures/style.css b/project/aitoearn-web/src/app/[lng]/ai-social/components/AgentFeatures/style.cssindex a51fa17e..89643b6b 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/components/AgentFeatures/style.css+++ b/project/aitoearn-web/src/app/[lng]/ai-social/components/AgentFeatures/style.css@@ -19,7 +19,9 @@background: oklch(0.6 0 0 / 0.3) !important;opacity: 1 !important;border-radius: 9999px !important;- transition: all 0.3s ease !important;+ transition:+ width 0.3s ease,+ background 0.3s ease !important;margin: 0 !important;}diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/components/HomeChat/index.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/components/HomeChat/index.tsxindex 87862638..c610f59c 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/components/HomeChat/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/components/HomeChat/index.tsx@@ -17,6 +17,7 @@ import { ChatInput } from '@/components/Chat/ChatInput'import { useMediaUpload } from '@/hooks/useMediaUpload'import { toast } from '@/lib/toast'import { cn } from '@/lib/utils'+import { useAccountStore } from '@/store/account'import { useAgentStore } from '@/store/agent'import { useUserStore } from '@/store/user'@@ -255,6 +256,13 @@ export const HomeChat = forwardRef<IHomeChatRef, IHomeChatProps>(return}+ // 余额不足检查 - 阈值 50(美分)与 LowBalanceAlertProvider 中的 BALANCE_THRESHOLD 一致+ const creditsBalance = useUserStore.getState().creditsBalance+ if (creditsBalance < 50) {+ useAccountStore.getState().setLowBalanceAlertOpen(true)+ return+ }+// 执行发送逻辑doSend()}, [token, doSend, inputValue, defaultPrompt, medias, lng])diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewCard/index.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewCard/index.tsxindex d9aef0e4..09893336 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewCard/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewCard/index.tsx@@ -5,7 +5,7 @@'use client'-import type { MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaItem } from '@/api/types/media'import { Image as ImageIcon, Play, Video } from 'lucide-react'import Image from 'next/image'import { useVideoThumbnail } from '@/hooks/useVideoThumbnail'diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewList/index.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewList/index.tsxindex aa0ca2a4..dbcc6f44 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewList/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/components/MediaPreviewList/index.tsx@@ -5,7 +5,7 @@'use client'-import type { MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaItem } from '@/api/types/media'import { useTransClient } from '@/app/i18n/client'import { cn } from '@/lib/utils'import { MediaPreviewCard } from '../MediaPreviewCard'diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/index.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/index.tsxindex 335b77ce..809fc36b 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/components/TaskPreview/index.tsx@@ -6,7 +6,7 @@'use client'import type { TaskListItem } from '@/api/agent'-import type { MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaItem } from '@/api/types/media'import type { MediaPreviewItem } from '@/components/common/MediaPreview'import { ArrowRight, Bot, History } from 'lucide-react'import Link from 'next/link'@@ -173,7 +173,7 @@ export function TaskPreview({ limit = 4, className }: ITaskPreviewProps) {case 'tasks':return '/tasks-history'case 'agent':- return '/material/agent-assets'+ return '/agent-assets'default:return '/tasks-history'}diff --git a/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx b/project/aitoearn-web/src/app/[lng]/ai-social/page.tsxindex 1519f76f..d1acd27f 100644--- a/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/ai-social/page.tsx@@ -5,7 +5,7 @@import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import { AiSocialPageContent } from './AiSocialPageContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx b/project/aitoearn-web/src/app/[lng]/auth/login/page.tsxindex dcef6746..b4d936ec 100644--- a/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/auth/login/page.tsx@@ -6,7 +6,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import LoginContent from './components/LoginContent'// SEO 元数据diff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/index.ts b/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/index.tsnew file mode 100644index 00000000..0595d476--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/index.ts@@ -0,0 +1,187 @@+/**+ * 品牌推广模块 Store+ * 管理推广计划列表、弹窗状态+ */++import type {+ IBrandPromotionStoreState,+ PromotionPlan,+} from './types'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import {+ apiCreateMaterialGroup,+ apiDeleteMaterialGroup,+ apiGetMaterialGroupList,+ apiUpdateMaterialGroupInfo,+} from '@/api/material'+import { usePlanTabStore } from '../planTabStore'++// 初始状态+const initialState: IBrandPromotionStoreState = {+ // 推广计划列表状态+ plans: [],+ plansLoading: false,+ plansPagination: {+ current: 1,+ pageSize: 9,+ total: 0,+ hasMore: true,+ },++ // 弹窗状态+ createPlanModalOpen: false,+ editingPlan: null,+ qrCodeDialogOpen: false,+ qrCodePlan: null,++ // 加载状态+ isSubmitting: false,+}++function getInitialState() {+ return lodash.cloneDeep(initialState)+}++export const useBrandPromotionStore = create(+ combine(getInitialState(), (set, get) => {+ const methods = {+ // ==================== 推广计划方法 ====================++ /**+ * 获取推广计划列表+ */+ fetchPlans: async (page: number = 1) => {+ set({ plansLoading: true })+ try {+ const { plansPagination } = get()+ const res = await apiGetMaterialGroupList(page, plansPagination.pageSize)+ const list = (res?.data?.list || []) as PromotionPlan[]+ const total = res?.data?.total || 0++ set({+ plans: list,+ plansPagination: {+ ...plansPagination,+ current: page,+ total,+ hasMore: list.length === plansPagination.pageSize,+ },+ })+ }+ catch {+ // 错误由调用方处理+ }+ finally {+ set({ plansLoading: false })+ }+ },++ /**+ * 创建推广计划+ */+ createPlan: async (data: {+ name: string+ }): Promise<boolean> => {+ set({ isSubmitting: true })+ try {+ const res = await apiCreateMaterialGroup(data)+ if (!res)+ return false+ await methods.fetchPlans(1)+ // 通知 planTabStore 同步+ const resData = res?.data as Record<string, unknown> | undefined+ const newPlanId = resData?.id as string | undefined+ usePlanTabStore.getState().onPlanCreated(newPlanId)+ return true+ }+ catch {+ return false+ }+ finally {+ set({ isSubmitting: false })+ }+ },++ /**+ * 更新推广计划+ */+ updatePlan: async (+ id: string,+ data: { name?: string },+ ): Promise<boolean> => {+ set({ isSubmitting: true })+ try {+ const res = await apiUpdateMaterialGroupInfo(id, data)+ if (res?.code !== 0)+ return false+ const { plansPagination } = get()+ await methods.fetchPlans(plansPagination.current)+ // 通知 planTabStore 同步+ usePlanTabStore.getState().onPlanUpdated(id, data)+ return true+ }+ catch {+ return false+ }+ finally {+ set({ isSubmitting: false })+ }+ },++ /**+ * 删除推广计划+ */+ deletePlan: async (id: string): Promise<boolean> => {+ set({ isSubmitting: true })+ try {+ const res = await apiDeleteMaterialGroup(id)+ if (res?.code !== 0)+ return false+ const { plansPagination } = get()+ await methods.fetchPlans(plansPagination.current)+ // 通知 planTabStore 同步+ usePlanTabStore.getState().onPlanDeleted(id)+ return true+ }+ catch {+ return false+ }+ finally {+ set({ isSubmitting: false })+ }+ },++ // ==================== 弹窗控制 ====================++ openCreatePlanModal: () => {+ set({ createPlanModalOpen: true, editingPlan: null })+ },++ openEditPlanModal: (plan: PromotionPlan) => {+ set({ createPlanModalOpen: true, editingPlan: plan })+ },++ closePlanModal: () => {+ set({ createPlanModalOpen: false, editingPlan: null })+ },++ openQRCodeDialog: (plan: PromotionPlan) => {+ set({ qrCodeDialogOpen: true, qrCodePlan: plan })+ },++ closeQRCodeDialog: () => {+ set({ qrCodeDialogOpen: false, qrCodePlan: null })+ },++ // ==================== 重置 ====================++ reset: () => {+ set(getInitialState())+ },+ }++ return methods+ }),+)diff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/types.ts b/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/types.tsnew file mode 100644index 00000000..8a47b0ae--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/brandPromotionStore/types.ts@@ -0,0 +1,193 @@+/**+ * 品牌推广模块类型定义+ * 包含推广计划、素材、统计数据相关类型+ */++import type { PlatType } from '@/app/config/platConfig'+import type { PubType } from '@/app/config/publishConfig'++// ==================== 推广计划相关类型 ====================++/** 推广计划(原草稿组) */+export interface PromotionPlan {+ id: string+ name: string+ title?: string // 兼容旧数据+ type: PubType+ /** 发布平台 */+ platform?: PlatType+ desc?: string+ createdAt?: string+ updatedAt?: string+ /** 计划内素材数量 */+ mediaCount?: number+ /** 是否为默认计划 */+ isDefault?: boolean+ /** 统计数据 */+ statistics?: PlanStatistics+}++/** 推广计划统计数据 */+export interface PlanStatistics {+ /** 素材数 */+ materialCount: number+ /** 发布数 */+ publishCount: number+ /** 浏览量 */+ viewCount: number+ /** 点赞数 */+ likeCount: number+ /** 评论数 */+ commentCount: number+ /** 分享数 */+ shareCount: number+ /** 收藏数 */+ favoriteCount: number+}++// ==================== 素材相关类型 ====================++/** 媒体资源类型 */+export type MaterialMediaType = 'img' | 'video'++/** 媒体资源 */+export interface MaterialMedia {+ url: string+ type: MaterialMediaType+ content?: string+}++/** 推广素材(原草稿) */+export interface PromotionMaterial {+ id: string+ groupId: string+ title: string+ desc?: string+ coverUrl?: string+ mediaList: MaterialMedia[]+ type?: PubType+ status: 0 | 1 // 0: 生成中, 1: 已生成+ location?: [number, number]+ option?: Record<string, unknown>+ createdAt?: string+ /** 使用次数 */+ useCount?: number+ /** 话题标签 */+ topics?: string[]+ /** AI 生成模型 */+ model?: string+ /** 适用的频道类型 */+ accountTypes?: string[]+}++// ==================== 发布记录相关类型 ====================++/** 发布记录(来自 API 响应) */+export interface PublishRecord {+ id: string+ materialGroupId: string+ dataId: string+ /** 账号 ID */+ accountId: string+ /** 平台类型 */+ accountType: string+ uid: string+ /** 标题 */+ title: string+ /** 描述 */+ desc: string+ /** 封面图 */+ coverUrl: string+ /** 视频链接 */+ videoUrl: string+ /** 作品链接 */+ workLink: string+ /** 发布时间 */+ publishTime: string+ /** 状态 */+ status: number+ /** 创建时间 */+ createdAt: string+ /** 浏览量 */+ viewCount: number+ /** 点赞数 */+ likeCount: number+ /** 评论数 */+ commentCount: number+ /** 分享数 */+ shareCount: number+ /** 收藏数 */+ favoriteCount: number+ /** 数据更新时间 */+ insightUpdatedAt: string+ /** 平台名称(前端补充) */+ platformName?: string+ /** 平台图标(前端补充) */+ platformIcon?: string+}++// ==================== 趋势数据类型 ====================++/** 趋势数据点 */+export interface TrendDataPoint {+ date: string+ value: number+}++/** 趋势数据 */+export interface TrendData {+ viewCount: TrendDataPoint[]+ likeCount: TrendDataPoint[]+ commentCount: TrendDataPoint[]+ shareCount: TrendDataPoint[]+}++// ==================== 分页相关类型 ====================++/** 分页信息 */+export interface Pagination {+ current: number+ pageSize: number+ total: number+ hasMore: boolean+}++// ==================== Store 状态类型 ====================++/** 列表页 Store 状态 */+export interface IBrandPromotionStoreState {+ // 推广计划列表状态+ plans: PromotionPlan[]+ plansLoading: boolean+ plansPagination: Pagination++ // 弹窗状态+ createPlanModalOpen: boolean+ editingPlan: PromotionPlan | null+ qrCodeDialogOpen: boolean+ qrCodePlan: PromotionPlan | null++ // 加载状态+ isSubmitting: boolean+}++/** 列表页 Store 方法 */+export interface IBrandPromotionStoreMethods {+ // 推广计划方法+ fetchPlans: (page?: number) => Promise<void>+ createPlan: (data: { name: string }) => Promise<boolean>+ updatePlan: (id: string, data: { name?: string }) => Promise<boolean>+ deletePlan: (id: string) => Promise<boolean>++ // 弹窗控制+ openCreatePlanModal: () => void+ openEditPlanModal: (plan: PromotionPlan) => void+ closePlanModal: () => void+ openQRCodeDialog: (plan: PromotionPlan) => void+ closeQRCodeDialog: () => void++ // 重置+ reset: () => void+}++export type IBrandPromotionStore = IBrandPromotionStoreState & IBrandPromotionStoreMethodsdiff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/components/CreatePlanModal/index.tsx b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/CreatePlanModal/index.tsxnew file mode 100644index 00000000..98a19d83--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/CreatePlanModal/index.tsx@@ -0,0 +1,142 @@+/**+ * CreatePlanModal - 创建/编辑草稿弹窗+ * 仅包含名称输入+ */++'use client'++import { Loader2 } from 'lucide-react'+import { useCallback, useEffect, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { toast } from '@/lib/toast'+import { useBrandPromotionStore } from '../../brandPromotionStore'++function CreatePlanModal() {+ const { t } = useTransClient('brandPromotion')++ const {+ createPlanModalOpen,+ editingPlan,+ isSubmitting,+ } = useBrandPromotionStore(+ useShallow(state => ({+ createPlanModalOpen: state.createPlanModalOpen,+ editingPlan: state.editingPlan,+ isSubmitting: state.isSubmitting,+ })),+ )++ const closePlanModal = useBrandPromotionStore(state => state.closePlanModal)+ const createPlan = useBrandPromotionStore(state => state.createPlan)+ const updatePlan = useBrandPromotionStore(state => state.updatePlan)++ const isEdit = editingPlan !== null++ // 表单状态+ const [name, setName] = useState('')++ // 初始化/重置表单+ useEffect(() => {+ if (createPlanModalOpen) {+ if (editingPlan) {+ setName(editingPlan.name || editingPlan.title || '')+ }+ else {+ setName('')+ }+ }+ }, [createPlanModalOpen, editingPlan])++ const handleSubmit = useCallback(async () => {+ if (!name.trim())+ return++ if (isEdit && editingPlan) {+ const success = await updatePlan(editingPlan.id, {+ name: name.trim(),+ })+ if (success) {+ toast.success(t('createPlan.updateSuccess'))+ closePlanModal()+ }+ else {+ toast.error(t('createPlan.updateFailed'))+ }+ }+ else {+ const success = await createPlan({+ name: name.trim(),+ })+ if (success) {+ toast.success(t('createPlan.createSuccess'))+ closePlanModal()+ }+ else {+ toast.error(t('createPlan.createFailed'))+ }+ }+ }, [name, isEdit, editingPlan, createPlan, updatePlan, closePlanModal, t])++ return (+ <Dialog+ open={createPlanModalOpen}+ onOpenChange={(open) => {+ if (!open)+ closePlanModal()+ }}+ >+ <DialogContent className="sm:w-[min(500px,95vw)]">+ <DialogHeader>+ <DialogTitle>+ {isEdit ? t('createPlan.editTitle') : t('createPlan.title')}+ </DialogTitle>+ </DialogHeader>++ <div className="space-y-4 py-2">+ {/* 名称 */}+ <div className="space-y-2">+ <Label>{t('createPlan.name')}</Label>+ <Input+ value={name}+ onChange={e => setName(e.target.value)}+ placeholder={t('createPlan.namePlaceholder')}+ maxLength={50}+ />+ </div>+ </div>++ <DialogFooter>+ <Button+ variant="outline"+ onClick={closePlanModal}+ disabled={isSubmitting}+ className="cursor-pointer"+ >+ {t('common.cancel')}+ </Button>+ <Button+ onClick={handleSubmit}+ disabled={isSubmitting || !name.trim()}+ className="cursor-pointer"+ >+ {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {isEdit ? t('common.save') : t('common.confirm')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++export default CreatePlanModaldiff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/PlanListItem.tsx b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/PlanListItem.tsxnew file mode 100644index 00000000..f2492a21--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/PlanListItem.tsx@@ -0,0 +1,77 @@+/**+ * PlanListItem - 更多面板中的计划列表项+ * 显示计划名称、选中状态、编辑/删除操作+ */++'use client'++import type { PromotionPlan } from '../../../brandPromotionStore/types'+import { Check, Pencil, Trash2 } from 'lucide-react'+import { useTransClient } from '@/app/i18n/client'+import { cn } from '@/lib/utils'++interface PlanListItemProps {+ plan: PromotionPlan+ isSelected: boolean+ onSelect: (planId: string) => void+ onEdit: (plan: PromotionPlan) => void+ onDelete: (plan: PromotionPlan) => void+}++function PlanListItem({+ plan,+ isSelected,+ onSelect,+ onEdit,+ onDelete,+}: PlanListItemProps) {+ const { t } = useTransClient('brandPromotion')++ return (+ <div+ className={cn(+ 'flex items-center justify-between px-3 py-2.5 rounded-lg cursor-pointer transition-colors',+ 'hover:bg-accent',+ isSelected && 'bg-accent',+ )}+ onClick={() => onSelect(plan.id)}+ >+ <div className="flex items-center gap-2 min-w-0 flex-1">+ {isSelected && (+ <Check className="h-4 w-4 text-primary shrink-0" />+ )}+ <span className={cn(+ 'text-sm truncate',+ isSelected && 'font-medium text-primary',+ )}+ >+ {plan.name || plan.title}+ </span>+ </div>+ <div className="flex items-center gap-1 shrink-0 ml-2">+ <button+ className="p-1.5 rounded-md hover:bg-muted cursor-pointer transition-colors"+ onClick={(e) => {+ e.stopPropagation()+ onEdit(plan)+ }}+ title={t('planTab.editPlan')}+ >+ <Pencil className="h-3.5 w-3.5 text-muted-foreground" />+ </button>+ <button+ className="p-1.5 rounded-md hover:bg-destructive/10 cursor-pointer transition-colors"+ onClick={(e) => {+ e.stopPropagation()+ onDelete(plan)+ }}+ title={t('planTab.deletePlan')}+ >+ <Trash2 className="h-3.5 w-3.5 text-muted-foreground hover:text-destructive" />+ </button>+ </div>+ </div>+ )+}++export default PlanListItemdiff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/index.tsx b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/index.tsxnew file mode 100644index 00000000..e4c27ffc--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/MorePanel/index.tsx@@ -0,0 +1,229 @@+/**+ * MorePanel - 更多推广计划面板+ * 移动端: Dialog 底部弹出+ * PC 端: Popover 下拉+ * 滚动到底部自动加载更多(IntersectionObserver)+ */++'use client'++import type { PromotionPlan } from '../../../brandPromotionStore/types'+import { Loader2 } from 'lucide-react'+import { useEffect, useRef } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import { useIsMobile } from '@/hooks/useIsMobile'+import confirm from '@/lib/confirm'+import { useBrandPromotionStore } from '../../../brandPromotionStore'+import { usePlanTabStore } from '../../../planTabStore'+import PlanListItem from './PlanListItem'++interface MorePanelProps {+ trigger: React.ReactNode+ onPlanChange?: (planId: string) => void+ syncPlanIdToUrl?: (planId: string) => void+}++function MorePanel({ trigger, onPlanChange, syncPlanIdToUrl }: MorePanelProps) {+ const { t } = useTransClient('brandPromotion')+ const isMobile = useIsMobile()++ const {+ morePlans,+ morePlansLoading,+ morePlansPagination,+ morePanelOpen,+ selectedPlanId,+ } = usePlanTabStore(+ useShallow(state => ({+ morePlans: state.morePlans,+ morePlansLoading: state.morePlansLoading,+ morePlansPagination: state.morePlansPagination,+ morePanelOpen: state.morePanelOpen,+ selectedPlanId: state.selectedPlanId,+ })),+ )++ const openMorePanel = usePlanTabStore(state => state.openMorePanel)+ const closeMorePanel = usePlanTabStore(state => state.closeMorePanel)+ const selectPlan = usePlanTabStore(state => state.selectPlan)+ const loadMoreInPanel = usePlanTabStore(state => state.loadMoreInPanel)+ const onPlanDeleted = usePlanTabStore(state => state.onPlanDeleted)++ const openEditPlanModal = useBrandPromotionStore(state => state.openEditPlanModal)+ const deletePlan = useBrandPromotionStore(state => state.deletePlan)++ const sentinelRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (!morePanelOpen)+ return++ const sentinel = sentinelRef.current+ if (!sentinel)+ return++ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting) {+ loadMoreInPanel()+ }+ },+ { threshold: 0 },+ )++ observer.observe(sentinel)+ return () => observer.disconnect()+ }, [morePanelOpen, morePlansLoading, morePlansPagination.hasMore, loadMoreInPanel])++ const handleSelect = (planId: string) => {+ selectPlan(planId)+ syncPlanIdToUrl?.(planId)+ onPlanChange?.(planId)+ }++ const handleEdit = (plan: PromotionPlan) => {+ closeMorePanel()+ openEditPlanModal(plan)+ }++ const handleDelete = (plan: PromotionPlan) => {+ confirm({+ title: t('plan.deleteConfirmTitle'),+ content: t('plan.deleteConfirmDesc', { name: plan.name || plan.title }),+ okType: 'destructive',+ onOk: async () => {+ const success = await deletePlan(plan.id)+ if (success) {+ onPlanDeleted(plan.id)+ }+ },+ })+ }++ const panelContent = (+ <div className="flex flex-col">+ {/* 标题行 */}+ <div className="flex items-center justify-between mb-3">+ <span className="text-sm font-medium">{t('planTab.moreTitle')}</span>+ <span className="text-xs text-muted-foreground">+ {t('planTab.totalCount', { count: morePlansPagination.total })}+ </span>+ </div>++ {/* 列表 */}+ <div className="space-y-1 max-h-[50vh] overflow-y-auto">+ {morePlans.map(plan => (+ <PlanListItem+ key={plan.id}+ plan={plan}+ isSelected={plan.id === selectedPlanId}+ onSelect={handleSelect}+ onEdit={handleEdit}+ onDelete={handleDelete}+ />+ ))}++ {morePlansLoading && (+ <div className="flex justify-center py-3">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ )}++ {!morePlansPagination.hasMore && morePlans.length > 0 && (+ <div className="text-center text-xs text-muted-foreground py-3">+ {t('planTab.noMore')}+ </div>+ )}++ <div ref={sentinelRef} className="h-1" />+ </div>+ </div>+ )++ if (isMobile) {+ return (+ <>+ <div onClick={openMorePanel}>+ {trigger}+ </div>+ <Dialog+ open={morePanelOpen}+ onOpenChange={(open) => {+ if (!open)+ closeMorePanel()+ }}+ >+ <DialogContent+ className="fixed bottom-0 top-auto left-0 right-0 translate-x-0 translate-y-0 rounded-t-xl rounded-b-none w-full sm:w-full max-h-[70vh]"+ hideCloseButton+ >+ <DialogHeader>+ <DialogTitle>{t('planTab.moreTitle')}</DialogTitle>+ </DialogHeader>+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs text-muted-foreground">+ {t('planTab.totalCount', { count: morePlansPagination.total })}+ </span>+ </div>+ <div className="space-y-1 max-h-[50vh] overflow-y-auto">+ {morePlans.map(plan => (+ <PlanListItem+ key={plan.id}+ plan={plan}+ isSelected={plan.id === selectedPlanId}+ onSelect={handleSelect}+ onEdit={handleEdit}+ onDelete={handleDelete}+ />+ ))}+ {morePlansLoading && (+ <div className="flex justify-center py-3">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ </div>+ )}++ {!morePlansPagination.hasMore && morePlans.length > 0 && (+ <div className="text-center text-xs text-muted-foreground py-3">+ {t('planTab.noMore')}+ </div>+ )}++ <div ref={sentinelRef} className="h-1" />+ </div>+ </DialogContent>+ </Dialog>+ </>+ )+ }++ return (+ <Popover+ open={morePanelOpen}+ onOpenChange={(open) => {+ if (open)+ openMorePanel(); else closeMorePanel()+ }}+ >+ <PopoverTrigger asChild>+ {trigger}+ </PopoverTrigger>+ <PopoverContent align="end" className="w-80" allowInnerScroll>+ {panelContent}+ </PopoverContent>+ </Popover>+ )+}++export default MorePaneldiff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/PlanTabBar.module.scss b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/PlanTabBar.module.scssnew file mode 100644index 00000000..d6006200--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/PlanTabBar.module.scss@@ -0,0 +1,13 @@+/**+ * PlanTabBar 样式+ * 隐藏 Tab 区域的滚动条+ */++.scrollContainer {+ scrollbar-width: none; /* Firefox */+ -ms-overflow-style: none; /* IE/Edge */++ &::-webkit-scrollbar {+ display: none; /* Chrome/Safari */+ }+}diff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/index.tsx b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/index.tsxnew file mode 100644index 00000000..8a25fe74--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/components/PlanTabBar/index.tsx@@ -0,0 +1,165 @@+/**+ * PlanTabBar - 推广计划 Tab 栏+ * 可滚动 Tab + 更多按钮 + 新建按钮+ * 两页面(线下推广 / 草稿箱)复用+ */++'use client'++import { Ellipsis, Plus } from 'lucide-react'+import { usePathname } from 'next/navigation'+import { useCallback, useEffect, useRef } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import { Button } from '@/components/ui/button'+import { Skeleton } from '@/components/ui/skeleton'+import { useIsMobile } from '@/hooks/useIsMobile'+import { cn } from '@/lib/utils'+import { useBrandPromotionStore } from '../../brandPromotionStore'+import { usePlanTabStore } from '../../planTabStore'+import MorePanel from './MorePanel'+import styles from './PlanTabBar.module.scss'++interface PlanTabBarProps {+ onPlanChange?: (planId: string) => void+ /** 是否自动同步 planId 到 URL query 参数(草稿箱使用) */+ syncUrlQuery?: boolean+}++function PlanTabBar({ onPlanChange, syncUrlQuery }: PlanTabBarProps) {+ const { t } = useTransClient('brandPromotion')+ const pathname = usePathname()+ const isMobile = useIsMobile()+ const scrollRef = useRef<HTMLDivElement>(null)+ const activeTabRef = useRef<HTMLButtonElement>(null)++ const {+ tabPlans,+ tabPlansLoading,+ selectedPlanId,+ } = usePlanTabStore(+ useShallow(state => ({+ tabPlans: state.tabPlans,+ tabPlansLoading: state.tabPlansLoading,+ selectedPlanId: state.selectedPlanId,+ })),+ )++ const selectPlan = usePlanTabStore(state => state.selectPlan)+ const openCreatePlanModal = useBrandPromotionStore(state => state.openCreatePlanModal)++ // PC端鼠标滚轮水平滚动+ useEffect(() => {+ const el = scrollRef.current+ if (!el || isMobile)+ return++ const onWheel = (e: WheelEvent) => {+ if (e.deltaY === 0)+ return+ e.preventDefault()+ el.scrollLeft += e.deltaY+ }++ el.addEventListener('wheel', onWheel, { passive: false })+ return () => el.removeEventListener('wheel', onWheel)+ }, [isMobile])++ // 选中 Tab 后自动滚动到容器水平居中位置+ useEffect(() => {+ if (activeTabRef.current && scrollRef.current) {+ const container = scrollRef.current+ const tab = activeTabRef.current+ const scrollLeft = tab.offsetLeft - container.offsetWidth / 2 + tab.offsetWidth / 2+ container.scrollTo({ left: scrollLeft, behavior: 'smooth' })+ }+ }, [selectedPlanId])++ const syncPlanIdToUrl = useCallback((planId: string) => {+ if (syncUrlQuery) {+ window.history.replaceState(null, '', `${pathname}?planId=${planId}`)+ }+ }, [syncUrlQuery, pathname])++ const handleTabClick = (planId: string) => {+ selectPlan(planId)+ syncPlanIdToUrl(planId)+ onPlanChange?.(planId)+ }++ if (tabPlansLoading) {+ return (+ <div className="flex items-center gap-2 px-4 py-2 border-b border-border">+ <Skeleton className="h-8 w-20" />+ <Skeleton className="h-8 w-20" />+ <Skeleton className="h-8 w-20" />+ </div>+ )+ }++ if (tabPlans.length === 0)+ return null++ return (+ <div className="flex items-center border-b border-border bg-background">+ {/* 可滚动 Tab 区域 */}+ <div+ ref={scrollRef}+ className={cn(+ 'flex-1 flex items-center overflow-x-auto min-w-0',+ styles.scrollContainer,+ )}+ >+ {tabPlans.map(plan => (+ <button+ key={plan.id}+ ref={plan.id === selectedPlanId ? activeTabRef : undefined}+ className={cn(+ 'shrink-0 px-4 py-2.5 text-sm cursor-pointer transition-colors whitespace-nowrap',+ 'hover:text-foreground',+ 'border-b-2 border-transparent',+ plan.id === selectedPlanId+ ? 'border-b-primary text-foreground font-medium'+ : 'text-muted-foreground',+ )}+ onClick={() => handleTabClick(plan.id)}+ >+ {plan.name || plan.title}+ </button>+ ))}+ </div>++ {/* 右侧固定按钮区域 */}+ <div className="flex items-center shrink-0 border-l border-border px-1 gap-0.5">+ {/* 更多按钮 */}+ <MorePanel+ trigger={(+ <Button+ variant="ghost"+ size="sm"+ className="cursor-pointer h-8 px-2"+ >+ <Ellipsis className="h-4 w-4" />+ {!isMobile && <span className="ml-1">{t('planTab.more')}</span>}+ </Button>+ )}+ onPlanChange={onPlanChange}+ syncPlanIdToUrl={syncPlanIdToUrl}+ />++ {/* 新建按钮 */}+ <Button+ variant="ghost"+ size="sm"+ className="cursor-pointer h-8 px-2"+ onClick={openCreatePlanModal}+ >+ <Plus className="h-4 w-4" />+ {!isMobile && <span className="ml-1">{t('planTab.newPlan')}</span>}+ </Button>+ </div>+ </div>+ )+}++export default PlanTabBardiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts b/project/aitoearn-web/src/app/[lng]/brand-promotion/planDetailStore.tssimilarity index 51%rename from project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.tsrename to project/aitoearn-web/src/app/[lng]/brand-promotion/planDetailStore.tsindex 6fb264df..9c1aaa9b 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxStore.ts+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/planDetailStore.ts@@ -1,59 +1,68 @@/**- * 草稿箱 Store- * 管理当前草稿组详情、素材列表、弹窗状态、批量操作+ * 品牌推广详情页 Store+ * 管理当前计划详情、素材列表*/-import type { DraftGroup, DraftMaterial, Pagination } from './types'+import type {+ Pagination,+ PromotionMaterial,+ PromotionPlan,+} from './brandPromotionStore/types'+import type { ImageModelType, ImageTextDraftType, VideoDraftType } from '@/api/draftGeneration'import type { MaterialFilterDeleteParams, MaterialListFilters } from '@/api/material'+import type { PlatType } from '@/app/config/platConfig'import lodash from 'lodash'import { create } from 'zustand'import { combine } from 'zustand/middleware'import {+ apiCreateDraftGeneration,+ apiCreateImageTextDraft,apiGetDraftGenerationStats,} from '@/api/draftGeneration'import {apiBatchDeleteMaterials,- apiCreateMaterialGroup,apiDeleteMaterial,apiFilterDeleteMaterials,- apiGetMaterialGroupList,apiGetMaterialInfo,apiGetMaterialList,} from '@/api/material'import { usePublishDialogStorageStore } from '@/components/PublishDialog/usePublishDialogStorageStore'+import { toast } from '@/lib/toast'// Store 状态类型-export interface IDraftBoxStoreState {- // 已初始化的 groupId,用于防止重复请求- initializedGroupId: string | null+export interface IPlanDetailStoreState {+ // 已初始化的 planId,用于防止重复请求+ initializedPlanId: string | null- // 当前草稿组- currentPlan: DraftGroup | null+ // 当前计划+ currentPlan: PromotionPlan | nullplanLoading: boolean// 素材列表- materials: DraftMaterial[]+ materials: PromotionMaterial[]materialsLoading: booleanmaterialsPagination: Pagination// 弹窗状态createMaterialModalOpen: boolean- editingMaterial: DraftMaterial | null+ editingMaterial: PromotionMaterial | null// 草稿详情弹窗状态draftDetailDialogOpen: boolean- selectedDraft: DraftMaterial | null+ selectedDraft: PromotionMaterial | null// 发布弹框状态publishDialogOpen: boolean- publishingDraft: DraftMaterial | null+ publishingDraft: PromotionMaterial | null// 加载状态isSubmitting: boolean// AI 批量生成generatingCount: number+ aiBatchModalOpen: booleangenerationDetailDialogOpen: boolean+ isGeneratingBatch: boolean// 搜索/筛选 & 批量操作materialsFilter: MaterialListFilters@@ -64,8 +73,8 @@ export interface IDraftBoxStoreState {}// 初始状态-const initialState: IDraftBoxStoreState = {- initializedGroupId: null,+const initialState: IPlanDetailStoreState = {+ initializedPlanId: null,currentPlan: null,planLoading: true,@@ -91,7 +100,9 @@ const initialState: IDraftBoxStoreState = {isSubmitting: false,generatingCount: 0,+ aiBatchModalOpen: false,generationDetailDialogOpen: false,+ isGeneratingBatch: false,materialsFilter: {},batchMode: false,@@ -104,16 +115,19 @@ function getInitialState() {return lodash.cloneDeep(initialState)}-export const useDraftBoxStore = create(+export const usePlanDetailStore = create(combine(getInitialState(), (set, get) => {const methods = {- // ==================== 草稿组详情 ====================+ // ==================== 计划详情 ====================- fetchPlanDetail: async (groupId: string) => {+ /**+ * 获取计划详情+ */+ fetchPlanDetail: async (planId: string) => {set({ planLoading: true })try {- const res = await apiGetMaterialInfo(groupId)- const plan = res?.data as DraftGroup+ const res = await apiGetMaterialInfo(planId)+ const plan = res?.data as PromotionPlanset({ currentPlan: plan })return plan}@@ -127,13 +141,16 @@ export const useDraftBoxStore = create(// ==================== 素材列表 ====================- fetchMaterials: async (groupId: string, page: number = 1) => {+ /**+ * 获取素材列表+ */+ fetchMaterials: async (planId: string, page: number = 1) => {set({ materialsLoading: true })try {const { materialsPagination, materialsFilter } = get()- const res = await apiGetMaterialList(groupId, page, materialsPagination.pageSize, materialsFilter)- const resData = res?.data as { list?: DraftMaterial[], total?: number } | undefined- const list = (resData?.list || []) as DraftMaterial[]+ const res = await apiGetMaterialList(planId, page, materialsPagination.pageSize, materialsFilter)+ const resData = res?.data as { list?: any[], total?: number } | undefined+ const list = (resData?.list || []) as PromotionMaterial[]const total = resData?.total || 0set({@@ -154,7 +171,10 @@ export const useDraftBoxStore = create(}},- loadMoreMaterials: async (groupId: string) => {+ /**+ * 加载更多素材(无限滚动)+ */+ loadMoreMaterials: async (planId: string) => {const { materialsLoading, materialsPagination, materials, materialsFilter } = get()if (materialsLoading || !materialsPagination.hasMore)return@@ -162,9 +182,9 @@ export const useDraftBoxStore = create(set({ materialsLoading: true })try {const nextPage = materialsPagination.current + 1- const res = await apiGetMaterialList(groupId, nextPage, materialsPagination.pageSize, materialsFilter)- const resData = res?.data as { list?: DraftMaterial[], total?: number } | undefined- const list = (resData?.list || []) as DraftMaterial[]+ const res = await apiGetMaterialList(planId, nextPage, materialsPagination.pageSize, materialsFilter)+ const resData = res?.data as { list?: any[], total?: number } | undefined+ const list = (resData?.list || []) as PromotionMaterial[]const total = resData?.total || 0set({@@ -185,13 +205,18 @@ export const useDraftBoxStore = create(}},+ /**+ * 删除素材+ */deleteMaterial: async (materialId: string): Promise<boolean> => {set({ isSubmitting: true })try {- await apiDeleteMaterial(materialId)+ const res = await apiDeleteMaterial(materialId)+ if (res?.code !== 0)+ return falseconst { currentPlan, materialsPagination } = get()if (currentPlan) {- await methods.fetchMaterials(currentPlan._id, materialsPagination.current)+ await methods.fetchMaterials(currentPlan.id, materialsPagination.current)}return true}@@ -209,7 +234,7 @@ export const useDraftBoxStore = create(set({ createMaterialModalOpen: true, editingMaterial: null })},- openEditMaterialModal: (material: DraftMaterial) => {+ openEditMaterialModal: (material: PromotionMaterial) => {set({ createMaterialModalOpen: true, editingMaterial: material })},@@ -219,7 +244,7 @@ export const useDraftBoxStore = create(// ==================== 草稿详情弹窗 ====================- openDraftDetailDialog: (material: DraftMaterial) => {+ openDraftDetailDialog: (material: PromotionMaterial) => {set({ draftDetailDialogOpen: true, selectedDraft: material })},@@ -229,7 +254,8 @@ export const useDraftBoxStore = create(// ==================== 发布弹框 ====================- openPublishDialog: (draft: DraftMaterial) => {+ openPublishDialog: (draft: PromotionMaterial) => {+ // 清空上次发布的缓存数据,避免 PublishDialog 触发「是否恢复」确认弹框usePublishDialogStorageStore.getState().clearPubData()set({ publishDialogOpen: true, publishingDraft: draft })},@@ -240,6 +266,14 @@ export const useDraftBoxStore = create(// ==================== AI 批量生成 ====================+ openAiBatchModal: () => {+ set({ aiBatchModalOpen: true })+ },++ closeAiBatchModal: () => {+ set({ aiBatchModalOpen: false })+ },+openGenerationDetailDialog: () => {set({ generationDetailDialogOpen: true })},@@ -248,6 +282,117 @@ export const useDraftBoxStore = create(set({ generationDetailDialogOpen: false })},+ /**+ * 创建 AI 批量生成任务+ */+ createBatchGeneration: async (+ quantity: number,+ modelType: string,+ duration?: number,+ aspectRatio?: string,+ prompt?: string,+ imageUrls?: string[],+ videoUrls?: string[],+ overrideGroupId?: string,+ platforms?: PlatType[],+ draftType?: VideoDraftType,+ ) => {+ const groupId = overrideGroupId || get().currentPlan?.id+ if (!groupId)+ return false++ set({ isGeneratingBatch: true })+ try {+ const res = await apiCreateDraftGeneration({+ quantity,+ groupId,+ model: modelType,+ duration,+ aspectRatio,+ prompt,+ imageUrls,+ videoUrls,+ platforms: platforms?.length ? platforms : undefined,+ draftType,+ })+ if (res?.code === 0) {+ const { generatingCount } = get()+ set({+ generatingCount: generatingCount + quantity,+ })+ return true+ }+ else {+ if (res?.message)+ toast.error(res.message)+ return false+ }+ }+ catch {+ return false+ }+ finally {+ set({ isGeneratingBatch: false })+ }+ },++ /**+ * 创建 AI 图文批量生成任务+ */+ createImageTextBatchGeneration: async (+ quantity: number,+ imageModel: ImageModelType,+ prompt: string,+ imageCount?: number,+ aspectRatio?: string,+ imageUrls?: string[],+ overrideGroupId?: string,+ imageSize?: string,+ platforms?: PlatType[],+ draftType?: ImageTextDraftType,+ ) => {+ const groupId = overrideGroupId || get().currentPlan?.id+ if (!groupId)+ return false++ set({ isGeneratingBatch: true })+ try {+ const res = await apiCreateImageTextDraft({+ quantity,+ groupId,+ prompt,+ imageModel,+ imageCount,+ imageUrls,+ aspectRatio,+ imageSize,+ platforms: platforms?.length ? platforms : undefined,+ draftType,+ })+ if (res?.code === 0) {+ const { generatingCount } = get()+ set({+ generatingCount: generatingCount + quantity,+ })+ return true+ }+ else {+ if (res?.message)+ toast.error(res.message)+ return false+ }+ }+ catch {+ return false+ }+ finally {+ set({ isGeneratingBatch: false })+ }+ },++ /**+ * 获取生成中任务数量(初始化时调用)+ */fetchGeneratingStats: async () => {try {const res = await apiGetDraftGenerationStats()@@ -260,20 +405,29 @@ export const useDraftBoxStore = create(}},+ /**+ * 轮询回调:更新生成中任务数量+ */updateGeneratingCount: (count: number) => {set({ generatingCount: count })},- silentRefreshMaterials: async (groupId: string) => {+ /**+ * 无感刷新素材列表(不触发 loading/骨架屏)+ * 静默请求第1页数据,找出新增的草稿 prepend 到头部+ */+ silentRefreshMaterials: async (planId: string) => {try {const { materialsPagination, materials, materialsFilter } = get()- const res = await apiGetMaterialList(groupId, 1, materialsPagination.pageSize, materialsFilter)- const resData = res?.data as { list?: DraftMaterial[], total?: number } | undefined- const freshList = (resData?.list || []) as DraftMaterial[]+ const res = await apiGetMaterialList(planId, 1, materialsPagination.pageSize, materialsFilter)+ const resData = res?.data as { list?: any[], total?: number } | undefined+ const freshList = (resData?.list || []) as PromotionMaterial[]const total = resData?.total || 0- const existingIds = new Set(materials.map(m => m._id))- const newItems = freshList.filter(item => !existingIds.has(item._id))+ // 构建当前 materials 的 id Set+ const existingIds = new Set(materials.map(m => m.id))+ // 找出新增草稿+ const newItems = freshList.filter(item => !existingIds.has(item.id))if (newItems.length > 0) {set({@@ -305,10 +459,14 @@ export const useDraftBoxStore = create(},})if (currentPlan) {- methods.fetchMaterials(currentPlan._id, 1)+ methods.fetchMaterials(currentPlan.id, 1)}},+ resetMaterialsFilter: () => {+ methods.setMaterialsFilter({})+ },+enterBatchMode: () => {set({ batchMode: true, selectedMaterialIds: [] })},@@ -330,7 +488,7 @@ export const useDraftBoxStore = create(selectAllLoadedMaterials: () => {const { materials } = get()- set({ selectedMaterialIds: materials.map(m => m._id) })+ set({ selectedMaterialIds: materials.map(m => m.id) })},deselectAllMaterials: () => {@@ -343,9 +501,11 @@ export const useDraftBoxStore = create(return falseset({ batchDeleting: true })try {- await apiBatchDeleteMaterials(selectedMaterialIds)+ const res = await apiBatchDeleteMaterials(selectedMaterialIds)+ if (res?.code !== 0)+ return falseset({ batchMode: false, selectedMaterialIds: [] })- await methods.fetchMaterials(currentPlan._id, 1)+ await methods.fetchMaterials(currentPlan.id, 1)return true}catch {@@ -369,9 +529,11 @@ export const useDraftBoxStore = create(if (!currentPlan)return falsetry {- await apiFilterDeleteMaterials({ ...conditions, groupId: currentPlan._id })+ const res = await apiFilterDeleteMaterials({ ...conditions, groupId: currentPlan.id })+ if (res?.code !== 0)+ return falseset({ conditionalDeleteDialogOpen: false })- await methods.fetchMaterials(currentPlan._id, 1)+ await methods.fetchMaterials(currentPlan.id, 1)return true}catch {@@ -379,63 +541,58 @@ export const useDraftBoxStore = create(}},- // ==================== 初始化 ====================+ // ==================== 重置 ====================- /** 自动获取或创建默认草稿箱,然后初始化页面 */- autoInit: async () => {- const { initializedGroupId } = get()-- set({ planLoading: true })- try {- // 获取第一个草稿箱- const res = await apiGetMaterialGroupList(1, 1)- const list = res?.data?.list || []-- let groupId: string+ reset: () => {+ set(getInitialState())+ },- if (list.length > 0) {- groupId = list[0]._id- }- else {- // 没有草稿箱,自动创建一个- const createRes = await apiCreateMaterialGroup({ name: '默认草稿箱' })- if (createRes?.data?._id) {- groupId = createRes.data._id- }- else {- set({ planLoading: false, materialsLoading: false })- return- }- }+ /**+ * 初始化详情页数据+ * @param planId 计划 ID+ * @param force 是否强制重新加载(Tab 切换时使用)+ */+ initDetailPage: async (planId: string, force: boolean = false) => {+ // 如果已经初始化过相同的 planId 且非强制刷新,跳过+ const { initializedPlanId } = get()+ if (!force && initializedPlanId === planId) {+ return+ }- // 防止重复初始化- if (initializedGroupId === groupId) {- set({ planLoading: false })- return- }+ // 重置状态+ set(getInitialState())+ // 标记正在初始化的 planId+ set({ initializedPlanId: planId })- await methods.initDetailPage(groupId, true)- }- catch {- set({ planLoading: false, materialsLoading: false })- }+ // 并行加载数据+ await Promise.all([+ methods.fetchPlanDetail(planId),+ methods.fetchMaterials(planId, 1),+ methods.fetchGeneratingStats(),+ ])},- initDetailPage: async (groupId: string, force: boolean = false) => {- const { initializedGroupId } = get()- if (!force && initializedGroupId === groupId) {+ /**+ * 仅加载「内容管理」所需数据+ * 加载: planDetail + materials + generatingStats+ */+ initContentData: async (planId: string, force: boolean = false) => {+ const { initializedPlanId } = get()+ if (!force && initializedPlanId === planId) {return}+ // 重置状态set(getInitialState())- set({ initializedGroupId: groupId })+ set({ initializedPlanId: planId })await Promise.all([- methods.fetchPlanDetail(groupId),- methods.fetchMaterials(groupId, 1),+ methods.fetchPlanDetail(planId),+ methods.fetchMaterials(planId, 1),methods.fetchGeneratingStats(),])},+}return methodsdiff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/index.ts b/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/index.tsnew file mode 100644index 00000000..eae4a75f--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/index.ts@@ -0,0 +1,236 @@+/**+ * 推广计划 Tab 栏 Store+ * 管理 Tab 列表切换、选中计划持久化、更多面板分页加载+ */++import type { PromotionPlan } from '../brandPromotionStore/types'+import type { IPlanTabStoreState } from './types'+import { apiGetMaterialGroupList } from '@/api/material'+import { createPersistStore } from '@/utils/createPersistStore'++const PAGE_SIZE = 50++const initialState: IPlanTabStoreState = {+ tabPlans: [],+ tabPlansLoading: false,+ selectedPlanId: null,+ morePlans: [],+ morePlansLoading: false,+ morePlansPagination: {+ current: 1,+ pageSize: PAGE_SIZE,+ total: 0,+ hasMore: true,+ },+ morePanelOpen: false,+ initialized: false,+}++export const usePlanTabStore = createPersistStore(+ initialState,+ (set, get) => {+ const methods = {+ /**+ * 初始化 Tab 列表+ * 加载第一页推广计划,恢复或默认选中+ */+ initTabs: async () => {+ const { initialized } = get()+ if (initialized)+ return++ set({ tabPlansLoading: true })+ try {+ const res = await apiGetMaterialGroupList(1, PAGE_SIZE)+ const list = res?.data?.list || []+ const total = res?.data?.total || 0++ const { selectedPlanId } = get()+ // 恢复持久化选中,若不在列表中则选第一个+ let validSelectedId: string | null = null+ if (selectedPlanId && list.some(p => p.id === selectedPlanId)) {+ validSelectedId = selectedPlanId+ }+ else if (list.length > 0) {+ validSelectedId = list[0].id+ }++ set({+ tabPlans: list,+ selectedPlanId: validSelectedId,+ initialized: true,+ morePlansPagination: {+ current: 1,+ pageSize: PAGE_SIZE,+ total,+ hasMore: list.length < total,+ },+ })+ }+ catch {+ set({ initialized: true })+ }+ finally {+ set({ tabPlansLoading: false })+ }+ },++ /**+ * 切换选中计划+ */+ selectPlan: (planId: string) => {+ set({ selectedPlanId: planId, morePanelOpen: false })+ },++ /**+ * 加载「更多」面板数据(指定页)+ */+ fetchMorePlans: async (page: number = 1) => {+ set({ morePlansLoading: true })+ try {+ const res = await apiGetMaterialGroupList(page, PAGE_SIZE)+ const list = res?.data?.list || []+ const total = res?.data?.total || 0++ if (page === 1) {+ set({ morePlans: list })+ }+ else {+ const { morePlans } = get()+ set({ morePlans: [...morePlans, ...list] })+ }++ set({+ morePlansPagination: {+ current: page,+ pageSize: PAGE_SIZE,+ total,+ hasMore: page * PAGE_SIZE < total,+ },+ })+ }+ catch {+ // 静默失败+ }+ finally {+ set({ morePlansLoading: false })+ }+ },++ /**+ * 面板内加载下一页+ */+ loadMoreInPanel: async () => {+ const { morePlansLoading, morePlansPagination } = get()+ if (morePlansLoading || !morePlansPagination.hasMore)+ return+ await methods.fetchMorePlans(morePlansPagination.current + 1)+ },++ /**+ * 创建计划后同步+ * 刷新 tabPlans + 自动选中新计划+ */+ onPlanCreated: async (newPlanId?: string) => {+ try {+ const res = await apiGetMaterialGroupList(1, PAGE_SIZE)+ const list = (res?.data?.list || []) as PromotionPlan[]+ const total = res?.data?.total || 0++ set({+ tabPlans: list,+ morePlansPagination: {+ current: 1,+ pageSize: PAGE_SIZE,+ total,+ hasMore: list.length < total,+ },+ })++ // 自动选中新计划+ if (newPlanId && list.some(p => p.id === newPlanId)) {+ set({ selectedPlanId: newPlanId })+ }+ else if (list.length > 0) {+ set({ selectedPlanId: list[0].id })+ }+ }+ catch {+ // 静默失败+ }+ },++ /**+ * 删除计划后同步+ * 从列表移除 + 自动切换到第一个+ */+ onPlanDeleted: (deletedPlanId: string) => {+ const { tabPlans, selectedPlanId, morePlans } = get()+ const newTabPlans = tabPlans.filter(p => p.id !== deletedPlanId)+ const newMorePlans = morePlans.filter(p => p.id !== deletedPlanId)++ const updates: Partial<IPlanTabStoreState> = {+ tabPlans: newTabPlans,+ morePlans: newMorePlans,+ }++ // 如果删除的是当前选中计划,切换到第一个+ if (selectedPlanId === deletedPlanId) {+ updates.selectedPlanId = newTabPlans.length > 0 ? newTabPlans[0].id : null+ }++ set(updates as IPlanTabStoreState)+ },++ /**+ * 更新计划后同步+ * 就地更新 tabPlans/morePlans 中的名称+ */+ onPlanUpdated: (planId: string, data: { name?: string, desc?: string }) => {+ const { tabPlans, morePlans } = get()++ const updateList = (list: PromotionPlan[]) =>+ list.map(p => (p.id === planId ? { ...p, ...data } : p))++ set({+ tabPlans: updateList(tabPlans),+ morePlans: updateList(morePlans),+ } as Partial<IPlanTabStoreState> as IPlanTabStoreState)+ },++ /**+ * 打开更多面板+ */+ openMorePanel: () => {+ set({ morePanelOpen: true })+ // 打开时加载第一页+ methods.fetchMorePlans(1)+ },++ /**+ * 关闭更多面板+ */+ closeMorePanel: () => {+ set({ morePanelOpen: false })+ },++ /**+ * 重置 Store+ */+ reset: () => {+ set({+ ...initialState,+ selectedPlanId: null,+ } as IPlanTabStoreState)+ },+ }++ return methods+ },+ {+ name: 'plan-tab-store',+ partialize: (state) => {+ return { selectedPlanId: state.selectedPlanId } as typeof state+ },+ },+)diff --git a/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/types.ts b/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/types.tsnew file mode 100644index 00000000..c9870fb5--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/brand-promotion/planTabStore/types.ts@@ -0,0 +1,22 @@+/**+ * 推广计划 Tab 栏 Store 类型定义+ * 管理 Tab 列表、选中状态、更多面板数据+ */++import type { Pagination, PromotionPlan } from '../brandPromotionStore/types'++export interface IPlanTabStoreState {+ /** Tab 栏显示的计划列表 */+ tabPlans: PromotionPlan[]+ tabPlansLoading: boolean+ /** 当前选中计划 ID(持久化) */+ selectedPlanId: string | null+ /** 「更多」面板的完整列表 */+ morePlans: PromotionPlan[]+ morePlansLoading: boolean+ morePlansPagination: Pagination+ /** 更多面板是否展开 */+ morePanelOpen: boolean+ /** 是否已初始化 */+ initialized: boolean+}diff --git a/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts b/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useChatState.tsindex 448a8cb1..135739fe 100644--- a/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts+++ b/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useChatState.ts@@ -11,6 +11,7 @@ import { agentApi } from '@/api/agent'import { toast } from '@/lib/toast'import { useAgentStore } from '@/store/agent'import { getDefaultTaskData } from '@/store/agent/agent.state'+import { useUserStore } from '@/store/user'import { convertMessages, isTaskCompleted } from '../utils'import { useTaskPolling } from './useTaskPolling'@@ -70,6 +71,9 @@ export function useChatState(options: IChatStateOptions): IChatStateReturn {const storeIsGenerating = currentTaskData.isGeneratingconst storeProgress = currentTaskData.progress+ // 获取 Credits 余额+ const fetchCreditsBalance = useUserStore(state => state.fetchCreditsBalance)+// 判断是否为活跃任务const isActiveTask = currentTaskId === taskIdconst isRealtimeGenerating = isActiveTask && storeIsGenerating@@ -192,6 +196,9 @@ export function useChatState(options: IChatStateOptions): IChatStateReturn {}}+ // 获取到 result 后,刷新 Credits 余额+ fetchCreditsBalance()+hasLoadedRef.current = true}else {@@ -208,7 +215,7 @@ export function useChatState(options: IChatStateOptions): IChatStateReturn {}loadTask()- }, [taskId, storeMessages.length, t, setMessages, startPolling])+ }, [taskId, storeMessages.length, t, setMessages, startPolling, fetchCreditsBalance])// 计算最终显示的消息和状态// 优先使用 store 中的消息(支持任务缓存和实时更新)diff --git a/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useTaskPolling.ts b/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useTaskPolling.tsindex f08a5977..a89c10f7 100644--- a/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useTaskPolling.ts+++ b/project/aitoearn-web/src/app/[lng]/chat/[taskId]/hooks/useTaskPolling.ts@@ -6,6 +6,8 @@ import type { IDisplayMessage } from '@/store/agent'*/import { useCallback, useEffect, useRef, useState } from 'react'import { agentApi, TaskStatus } from '@/api/agent'++import { useUserStore } from '@/store/user'import { convertMessages, isTaskCompleted } from '../utils'export interface ITaskPollingOptions {@@ -51,6 +53,9 @@ export function useTaskPolling(options: ITaskPollingOptions): ITaskPollingReturnconst [isPolling, setIsPolling] = useState(false)const pollingTimerRef = useRef<NodeJS.Timeout | null>(null)+ // 获取 Credits 余额+ const fetchCreditsBalance = useUserStore(state => state.fetchCreditsBalance)+/** 开始轮询 */const startPolling = useCallback(() => {setIsPolling(true)@@ -168,6 +173,8 @@ export function useTaskPolling(options: ITaskPollingOptions): ITaskPollingReturnif (isTaskCompleted(mergedMessages)) {// [TaskPolling] Task completed, stopping polling')setIsPolling(false)+ // 任务完成时刷新 Credits 余额+ fetchCreditsBalance()}}@@ -209,6 +216,8 @@ export function useTaskPolling(options: ITaskPollingOptions): ITaskPollingReturnif (isTaskCompleted(mergedMessages)) {// [TaskPolling] Task completed, stopping polling')setIsPolling(false)+ // 任务完成时刷新 Credits 余额+ fetchCreditsBalance()}}}@@ -238,6 +247,7 @@ export function useTaskPolling(options: ITaskPollingOptions): ITaskPollingReturnisActiveTask,pollingInterval,onMessagesUpdate,+ fetchCreditsBalance,getCurrentRawMessages,])diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsxindex e1240b2e..16b9e623 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/DraftBoxCore.tsx@@ -1,30 +1,78 @@/*** 草稿箱核心组件- * 自动获取/创建默认草稿箱并展示内容+ * 通过 PlanTabBar 管理多推广计划切换,展示内容管理模块*/'use client'-import { Loader2 } from 'lucide-react'-import { useEffect } from 'react'+import { Loader2, Plus, Sparkles } from 'lucide-react'+import { useSearchParams } from 'next/navigation'+import { useCallback, useEffect } from 'react'import { useShallow } from 'zustand/react/shallow'+import { useBrandPromotionStore } from '@/app/[lng]/brand-promotion/brandPromotionStore'+import CreatePlanModal from '@/app/[lng]/brand-promotion/components/CreatePlanModal'+import PlanTabBar from '@/app/[lng]/brand-promotion/components/PlanTabBar'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'+import { usePlanTabStore } from '@/app/[lng]/brand-promotion/planTabStore'+import { useTransClient } from '@/app/i18n/client'+import { Button } from '@/components/ui/button'import DraftContentModule from './components/DraftContentModule'-import { useDraftBoxStore } from './draftBoxStore'export default function DraftBoxCore() {- const { planLoading, currentPlan } = useDraftBoxStore(+ const { t } = useTransClient('brandPromotion')+ const searchParams = useSearchParams()+ const urlPlanId = searchParams.get('planId')++ const {+ tabPlans,+ tabPlansLoading,+ selectedPlanId,+ initialized,+ } = usePlanTabStore(useShallow(state => ({- planLoading: state.planLoading,- currentPlan: state.currentPlan,+ tabPlans: state.tabPlans,+ tabPlansLoading: state.tabPlansLoading,+ selectedPlanId: state.selectedPlanId,+ initialized: state.initialized,})),)- const autoInit = useDraftBoxStore(state => state.autoInit)+ const initTabs = usePlanTabStore(state => state.initTabs)++ const openCreatePlanModal = useBrandPromotionStore(+ state => state.openCreatePlanModal,+ )++ const initContentData = usePlanDetailStore(state => state.initContentData)++ // 初始化 Tab 列表+ useEffect(() => {+ initTabs()+ }, [initTabs])++ // URL 参数激活对应 TabuseEffect(() => {- autoInit()- }, [autoInit])+ if (initialized && urlPlanId) {+ usePlanTabStore.getState().selectPlan(urlPlanId)+ }+ }, [initialized, urlPlanId])- if (planLoading && !currentPlan) {+ // 初始化数据+ useEffect(() => {+ if (selectedPlanId) {+ initContentData(selectedPlanId)+ }+ }, [selectedPlanId, initContentData])++ // Tab 切换回调+ const handlePlanChange = useCallback((planId: string) => {+ initContentData(planId, true)+ }, [initContentData])++ const loading = !initialized+ const showEmpty = initialized && tabPlans.length === 0++ if (loading) {return (<div className="flex flex-col h-full"><div className="flex-1 min-h-0">@@ -40,8 +88,45 @@ export default function DraftBoxCore() {)}+ if (showEmpty) {+ return (+ <div className="flex flex-col h-full">+ <div className="flex-1 min-h-0">+ <div className="flex flex-col h-full bg-background">+ <div className="flex-1 flex items-center justify-center p-4">+ <div className="text-center max-w-md">+ <div className="mx-auto w-20 h-20 rounded-full bg-gradient-to-br from-[#c565ef]/10 to-[#55D9ED]/10 flex items-center justify-center mb-6">+ <Sparkles className="h-10 w-10 text-foreground/60" />+ </div>+ <h2 className="text-xl font-semibold text-foreground mb-2">+ {t('empty.title')}+ </h2>+ <p className="text-muted-foreground mb-6">+ {t('empty.description')}+ </p>+ <Button+ size="lg"+ className="cursor-pointer gap-2"+ onClick={openCreatePlanModal}+ >+ <Plus className="h-5 w-5" />+ {t('empty.createButton')}+ </Button>+ </div>+ </div>+ </div>+ </div>+ <CreatePlanModal />+ </div>+ )+ }+return (<div className="flex flex-col h-full">+ {/* Tab 栏 */}+ <div data-testid="draftbox-plan-tabs">+ <PlanTabBar onPlanChange={handlePlanChange} syncUrlQuery />+ </div><div className="flex-1 min-h-0"><div className="flex flex-col h-full bg-background"><div className="flex-1 overflow-auto">@@ -49,6 +134,9 @@ export default function DraftBoxCore() {</div></div></div>++ {/* 创建/编辑推广计划弹窗 */}+ <CreatePlanModal /></div>)}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/AddMediaButton/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/AddMediaButton/index.tsxindex ed3cf162..63d1a95e 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/AddMediaButton/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/AddMediaButton/index.tsx@@ -5,6 +5,7 @@'use client'+import type { BrandImage } from '../index'import { ImageIcon, Upload } from 'lucide-react'import { memo, useCallback, useRef, useState } from 'react'import { useTransClient } from '@/app/i18n/client'@@ -13,7 +14,7 @@ import ImageSelectorPopover from '../ImageSelectorPopover'import styles from './AddMediaButton.module.scss'interface AddMediaButtonProps {- allImages: any[]+ allImages: BrandImage[]selectedIds: string[]maxImages: numberonImagesChange: (ids: string[]) => voiddiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageSelectorPopover/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageSelectorPopover/index.tsxindex 36037680..259164ed 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageSelectorPopover/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageSelectorPopover/index.tsx@@ -5,6 +5,7 @@'use client'+import type { BrandImage } from '../index'import { Check, ImagePlus } from 'lucide-react'import Image from 'next/image'import { memo, useCallback, useRef, useState } from 'react'@@ -17,7 +18,7 @@ import {import { getOssUrl } from '@/utils/oss'interface ImageSelectorPopoverProps {- allImages: any[]+ allImages: BrandImage[]selectedIds: string[]maxImages: numberonImagesChange: (ids: string[]) => voiddiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageStack/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageStack/index.tsxindex 394ccd22..9f296948 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageStack/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ImageStack/index.tsx@@ -7,6 +7,7 @@'use client'+import type { BrandImage } from '../index'import type { VideoModelType } from '@/api/draftGeneration'import type { IUploadedMedia } from '@/components/Chat/MediaUpload'import type { MediaPreviewItem } from '@/components/common/MediaPreview'@@ -21,8 +22,8 @@ import AddMediaButton from '../AddMediaButton'import styles from './ImageStack.module.scss'interface ImageStackProps {- images: any[]- allImages: any[]+ images: BrandImage[]+ allImages: BrandImage[]selectedIds: string[]maxImages: numberonImagesChange: (ids: string[]) => voiddiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/PlatformSelector/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/PlatformSelector/index.tsxindex e65da9d4..90d2ace4 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/PlatformSelector/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/PlatformSelector/index.tsx@@ -15,6 +15,7 @@ import { useTransClient } from '@/app/i18n/client'import { Checkbox } from '@/components/ui/checkbox'import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'+import { useIsMobile } from '@/hooks/useIsMobile'import { cn } from '@/lib/utils'import PlatformLimitsInfo from '../PlatformLimitsInfo'@@ -37,6 +38,7 @@ function getAvailablePlatforms(): [PlatType, { icon: string, name: string }][] {const PlatformSelector = memo(({ selectedPlatforms, onPlatformsChange, pillClass, disabledPlatforms, effectiveLimitsDetailed }: PlatformSelectorProps) => {const { t } = useTransClient('brandPromotion')const [open, setOpen] = useState(false)+ const isMobile = useIsMobile()const availablePlatforms = useMemo(() => getAvailablePlatforms(), [])@@ -157,6 +159,17 @@ const PlatformSelector = memo(({ selectedPlatforms, onPlatformsChange, pillClassside="top"align="start">+ {/* 不兼容警告 banner */}+ {disabledSelectedCount > 0 && (+ <div className="flex items-start gap-1.5 mb-2 p-2 rounded-md bg-amber-50 text-amber-700 text-xs dark:bg-amber-950/30 dark:text-amber-400">+ <TriangleAlert className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />+ <div>+ <div>{t('detail.platformIncompatibleCount', { count: disabledSelectedCount })}</div>+ <div className="text-amber-600/70 dark:text-amber-400/70">{disabledSelectedNames.join(', ')}</div>+ </div>+ </div>+ )}+{/* 标题 + 全选/取消 */}<div className="flex items-center justify-between mb-2"><span className="text-xs font-medium text-foreground">{t('detail.targetPlatforms')}</span>@@ -217,6 +230,18 @@ const PlatformSelector = memo(({ selectedPlatforms, onPlatformsChange, pillClass)if (isDisabled) {+ if (isMobile) {+ return (+ <div key={plat} className="col-span-2">+ {button}+ <div className="px-2 pb-1 text-[10px] text-amber-600/80 dark:text-amber-400/70 leading-tight">+ {disabledReasons.map((reason, i) => (+ <div key={i}>{reason}</div>+ ))}+ </div>+ </div>+ )+ }return (<Tooltip key={plat}><TooltipTrigger asChild>diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ToolBarInline/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ToolBarInline/index.tsxindex 06300b35..0cb64d24 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ToolBarInline/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/ToolBarInline/index.tsx@@ -9,7 +9,7 @@ import type { EffectiveLimitsDetailed } from '../platformLimits'import type { DraftContentType, VideoModelType } from '@/api/draftGeneration'import type { ImageModelPricing, VideoModelInfo } from '@/api/types/draftGeneration'import type { PlatType } from '@/app/config/platConfig'-import { AlertTriangle, ArrowUp, Clock, Coins, ExternalLink, Grid2x2, Image, Layers, Loader2, Lock, Monitor, Ruler, Video } from 'lucide-react'+import { AlertTriangle, ArrowUp, Clock, Coins, ExternalLink, FileText, Grid2x2, Image, Layers, Loader2, Lock, Monitor, Ruler, Video } from 'lucide-react'import { memo, useCallback, useMemo, useState } from 'react'import { useTransClient } from '@/app/i18n/client'import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'@@ -45,9 +45,11 @@ interface ToolBarInlineProps {hasVideos: booleanpromptsExploreUrl: stringpromptsExploreLabel: string+ isDraftMode: booleanselectedPlatforms: PlatType[]effectiveLimitsDetailed: EffectiveLimitsDetaileddisabledPlatforms: Map<PlatType, string[]>+ onDraftModeChange: (isDraft: boolean) => voidonContentTypeChange: (contentType: DraftContentType) => voidonModelTypeChange: (modelType: VideoModelType) => voidonAspectRatioChange: (ratio: string) => void@@ -92,9 +94,11 @@ const ToolBarInline = memo(({hasVideos,promptsExploreUrl,promptsExploreLabel,+ isDraftMode,selectedPlatforms,effectiveLimitsDetailed,disabledPlatforms,+ onDraftModeChange,onContentTypeChange,onModelTypeChange,onAspectRatioChange,@@ -159,7 +163,7 @@ const ToolBarInline = memo(({}, [onImageCountChange])// Popover 状态- const contentTypePopover = useClickPopover()+ const genModePopover = useClickPopover()const modelPopover = useClickPopover()const ratioPopover = useClickPopover()const durationPopover = useClickPopover()@@ -177,18 +181,24 @@ const ToolBarInline = memo(({</span>)}- {/* 内容类型切换 pill */}- <Popover open={contentTypePopover.open} onOpenChange={contentTypePopover.onOpenChange}>+ {/* 生成模式选择 pill(草稿/图片/视频 三选一) */}+ <Popover open={genModePopover.open} onOpenChange={genModePopover.onOpenChange}><PopoverTrigger asChild><button- data-testid="draftbox-ai-content-type"+ data-testid="draftbox-ai-gen-mode"type="button"className={pillClass}>- {isVideoMode- ? <Video className="h-3.5 w-3.5" />- : <Image className="h-3.5 w-3.5" />}- {isVideoMode ? t('detail.contentTypeVideo') : t('detail.contentTypeImageText')}+ {isDraftMode+ ? <FileText className="h-3.5 w-3.5" />+ : isVideoMode+ ? <Video className="h-3.5 w-3.5" />+ : <Image className="h-3.5 w-3.5" />}+ {isDraftMode+ ? `${t('detail.draftModeOn')}(${isVideoMode ? t('detail.contentTypeVideo') : t('detail.contentTypeImageText')})`+ : isVideoMode+ ? t('detail.draftModeOffVideo')+ : t('detail.draftModeOffImage')}</button></PopoverTrigger><PopoverContent@@ -197,37 +207,78 @@ const ToolBarInline = memo(({align="start"><div className="flex flex-col gap-1">+ {/* 草稿模式选项 */}{([- { value: 'video' as const, label: t('detail.contentTypeVideo'), icon: Video },- { value: 'image_text' as const, label: t('detail.contentTypeImageText'), icon: Image },- ]).map(({ value, label, icon: Icon }) => (- <button- key={value}- type="button"- className={cn(- 'flex items-center gap-2 px-3 py-2 rounded-md text-xs cursor-pointer transition-colors text-left',- value === contentType- ? 'bg-primary/10 text-foreground font-medium'- : 'hover:bg-muted text-muted-foreground',- )}- onClick={() => onContentTypeChange(value)}- >- <Icon className="h-3.5 w-3.5" />- {label}- </button>- ))}+ { key: 'draft_image', label: `${t('detail.draftModeOn')}(${t('detail.contentTypeImageText')})`, icon: FileText, isDraft: true, ct: 'image_text' as const },+ { key: 'draft_video', label: `${t('detail.draftModeOn')}(${t('detail.contentTypeVideo')})`, icon: FileText, isDraft: true, ct: 'video' as const },+ ]).map(({ key, label, icon: Icon, isDraft, ct }) => {+ const isActive = isDraftMode && contentType === ct+ return (+ <button+ key={key}+ type="button"+ className={cn(+ 'flex items-center gap-2 px-3 py-2 rounded-md text-xs cursor-pointer transition-colors text-left',+ isActive+ ? 'bg-primary/10 text-foreground font-medium'+ : 'hover:bg-muted text-muted-foreground',+ )}+ onClick={() => {+ onDraftModeChange(true)+ if (contentType !== ct)+ onContentTypeChange(ct)+ genModePopover.onOpenChange(false)+ }}+ >+ <Icon className="h-3.5 w-3.5" />+ {label}+ </button>+ )+ })}+ {/* 分割线 */}+ <div className="border-t border-border my-1" />+ {/* 非草稿模式选项 */}+ {([+ { key: 'image', label: t('detail.draftModeOffImage'), icon: Image, ct: 'image_text' as const },+ { key: 'video', label: t('detail.draftModeOffVideo'), icon: Video, ct: 'video' as const },+ ]).map(({ key, label, icon: Icon, ct }) => {+ const isActive = !isDraftMode && contentType === ct+ return (+ <button+ key={key}+ type="button"+ className={cn(+ 'flex items-center gap-2 px-3 py-2 rounded-md text-xs cursor-pointer transition-colors text-left',+ isActive+ ? 'bg-primary/10 text-foreground font-medium'+ : 'hover:bg-muted text-muted-foreground',+ )}+ onClick={() => {+ onDraftModeChange(false)+ if (contentType !== ct)+ onContentTypeChange(ct)+ genModePopover.onOpenChange(false)+ }}+ >+ <Icon className="h-3.5 w-3.5" />+ {label}+ </button>+ )+ })}</div></PopoverContent></Popover>- {/* 平台选择 pill(内含参数限制 ⓘ) */}- <PlatformSelector- selectedPlatforms={selectedPlatforms}- onPlatformsChange={onPlatformsChange}- pillClass={pillClass}- disabledPlatforms={disabledPlatforms}- effectiveLimitsDetailed={effectiveLimitsDetailed}- />+ {/* 平台选择 pill(内含参数限制 ⓘ)— 仅草稿模式显示 */}+ {isDraftMode && (+ <PlatformSelector+ selectedPlatforms={selectedPlatforms}+ onPlatformsChange={onPlatformsChange}+ pillClass={pillClass}+ disabledPlatforms={disabledPlatforms}+ effectiveLimitsDetailed={effectiveLimitsDetailed}+ />+ )}{/* 模型选择 pill */}<Popover open={modelPopover.open} onOpenChange={modelPopover.onOpenChange}>@@ -256,7 +307,7 @@ const ToolBarInline = memo(({const isActive = key === modelType// 每秒价格:取默认 duration 对应的 pricing 计算const defaultDuration = model.defaults?.duration ?? model.durations[0]- const defaultPricing = model.pricing.find(p => p.duration === defaultDuration && !p.mode) ?? model.pricing.find(p => !p.mode)+ const defaultPricing = model.pricing.find(p => p.duration === defaultDuration) ?? model.pricing[0]const pricePerSecond = defaultPricing && defaultPricing.duration > 0? Math.round((defaultPricing.price / defaultPricing.duration) * 100) / 100: nulldiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/constants.ts b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/constants.tsindex 467a3862..586d8bf2 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/constants.ts+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/constants.ts@@ -25,15 +25,12 @@ export interface VideoModelStaticConfig {maxVideoDuration: number}-/** 允许上传图片的 modes */-const IMAGE_UPLOAD_MODES = new Set(['image2video', 'multi-image2video', 'flf2video', 'lf2video'])-/** 从 API 返回的 VideoModelInfo 动态生成静态配置 */export function getVideoModelConfigFromApi(model: VideoModelInfo): VideoModelStaticConfig {return {supportedRatios: new Set(model.aspectRatios),- maxImages: model.modes.some(m => IMAGE_UPLOAD_MODES.has(m)) ? model.maxInputImages : 0,- maxVideos: model.modes.includes('video2video') ? 1 : 0,+ maxImages: model.maxInputImages > 0 ? model.maxInputImages : 0,+ maxVideos: 1,maxVideoDuration: model.durations.length > 0 ? Math.max(...model.durations) : 8,}}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/index.tsxindex dfa5589f..d5e393b7 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AiBatchGenerateBar/index.tsx@@ -13,12 +13,15 @@ import type { PlatType } from '@/app/config/platConfig'import { RotateCcw, Upload, X } from 'lucide-react'import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useShallow } from 'zustand/react/shallow'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'import { AccountPlatInfoMap, RegionTaskPlatInfoArr, TASK_EXCLUDED_PLATFORMS } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import { useMediaUpload } from '@/hooks/useMediaUpload'import { useGetClientLng } from '@/hooks/useSystem'import { toast } from '@/lib/toast'import { cn } from '@/lib/utils'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'import { getVideoMeta } from '@/utils/media'import { getOssUrl } from '@/utils/oss'import { useDraftBoxConfigStore } from '../../draftBoxConfigStore'@@ -27,6 +30,7 @@ import {DEFAULT_MAX_INPUT_IMAGES,getVideoModelConfigFromApi,getVideoModelStaticConfig,+ IMAGE_TEXT_ASPECT_RATIOS,matchClosestRatio,} from './constants'import ImageStack from './ImageStack'@@ -44,8 +48,14 @@ const PROMPTS_EXPLORE_LNG_MAP: Record<string, string> = {'ko': 'ko-KR',}+/** 品牌图片类型(原 BrandImage,品牌库模块移除后本地保留) */+export interface BrandImage {+ id: string+ url: string+}+/** 模块级常量,避免 selector 每次返回新引用导致无限重渲染 */-const EMPTY_IMAGE_LIST: any[] = []+const EMPTY_IMAGE_LIST: BrandImage[] = []interface AiBatchGenerateBarProps {/** 外部传入 groupId,不从 store 读取 */@@ -60,8 +70,7 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenconst { t } = useTransClient('brandPromotion')const lng = useGetClientLng()- // 图片列表(品牌信息已移除,置空)- const imageList: any[] = []+ const imageList = EMPTY_IMAGE_LIST// 配置 key:按 groupId 隔离const configKey = groupId || '__default__'@@ -76,12 +85,18 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenconst config = getConfig(configKey)- // Store:生成状态(planDetailStore 已移除,暂用空实现)- const isGeneratingBatch = false- const createBatchGeneration = async (..._args: any[]) => false- const createImageTextBatchGeneration = async (..._args: any[]) => false+ // Store:生成状态+ const {+ isGeneratingBatch,+ createBatchGeneration,+ createImageTextBatchGeneration,+ } = usePlanDetailStore(useShallow(state => ({+ isGeneratingBatch: state.isGeneratingBatch,+ createBatchGeneration: state.createBatchGeneration,+ createImageTextBatchGeneration: state.createImageTextBatchGeneration,+ })))- // 默认提示词(品牌信息已移除)+ // 默认提示词const defaultPrompt = ''// 拖拽状态@@ -99,7 +114,8 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenconst [imageCount, setImageCount] = useState(config.imageCount)const [imageSize, setImageSize] = useState(config.imageSize)const [quantity, setQuantity] = useState(config.quantity)- // 计算可用平台+ const [isDraftMode, setIsDraftMode] = useState(config.isDraftMode ?? true)+ // 计算当前区域可用平台const availablePlatforms = useMemo(() =>RegionTaskPlatInfoArr.map(([plat]) => plat), [])@@ -122,6 +138,8 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGen// 追踪上一次的 configKey,用于同步 effect 检测切换const prevConfigKeyRef = useRef(configKey)const isMediaInitializedRef = useRef(false)+ // 防止同一品牌 ID 重复应用默认值+ const lastAppliedBrandIdRef = useRef<string | null>(null)// Pricing 数据const { pricingData, isLoading: isPricingLoading } = usePricingData()@@ -216,6 +234,20 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGen}}, [defaultPrompt, promptValue])+ // imageList 异步加载后自动选中默认图片+ useEffect(() => {+ if (!initialSelectionDone.current && imageList.length > 0) {+ const maxImages = contentType === 'image_text'+ ? (currentImageModelInfo?.maxInputImages ?? DEFAULT_MAX_INPUT_IMAGES)+ : currentVideoModelConfig.maxImages+ const defaultCount = Math.min(5, maxImages, imageList.length)+ const defaultIds = imageList.slice(0, defaultCount).map(img => img.id)+ setSelectedIds(defaultIds)+ updateConfig(configKey, { selectedImageIds: defaultIds })+ initialSelectionDone.current = true+ }+ }, [imageList, modelType, contentType, imageModel, configKey, updateConfig, currentVideoModelConfig])+// 本地上传媒体const {medias: localMedias,@@ -271,16 +303,12 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGen// 是否为视频编辑模式(上传了视频 + 视频内容类型)const isVideoEditMode = hasVideos && contentType === 'video'- // 派生:当前模式(普通 or video2video)的定价数组+ // 派生:当前模型的定价数组const videoPricing: VideoModelPricing[] = useMemo(() => {if (!currentVideoModelInfo?.pricing)return []- if (isVideoEditMode) {- const v2vPricing = currentVideoModelInfo.pricing.filter(p => p.mode === 'video2video')- return v2vPricing.length > 0 ? v2vPricing : currentVideoModelInfo.pricing.filter(p => !p.mode)- }- return currentVideoModelInfo.pricing.filter(p => !p.mode)- }, [currentVideoModelInfo, isVideoEditMode])+ return currentVideoModelInfo.pricing+ }, [currentVideoModelInfo])// 派生:从 pricing 数据的 duration 范围派生时长限制const videoDurationLimits = useMemo(() => {@@ -308,7 +336,6 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenif (duration > videoDurationLimits.max) {setDuration(videoDurationLimits.max)updateConfig(configKey, { duration: videoDurationLimits.max })- toast.info(t('detail.durationAutoAdjusted', { duration: videoDurationLimits.max }))}else if (duration < videoDurationLimits.min) {setDuration(videoDurationLimits.min)@@ -350,6 +377,7 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGensetImageCount(newConfig.imageCount)setImageSize(newConfig.imageSize)setQuantity(newConfig.quantity)+ setIsDraftMode(newConfig.isDraftMode ?? true)// selectedPlatforms 需要区域过滤 + 空时默认全选const storedPlatforms = newConfig.selectedPlatformsif (storedPlatforms.length === 0) {@@ -362,7 +390,7 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenconst storedPrompt = newConfig.promptValue ?? ''setPromptValue(storedPrompt)defaultPromptFilledRef.current = !!storedPrompt- // 从 store 恢复品牌图片选择+ // 从 store 恢复图片选择const storedImageIds = newConfig.selectedImageIds ?? []if (storedImageIds.length > 0) {setSelectedIds(storedImageIds)@@ -372,6 +400,7 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGensetSelectedIds([])initialSelectionDone.current = false}+ lastAppliedBrandIdRef.current = newConfig.linkedBrandId || null// 从 store 恢复持久化的媒体const persistedMedias = newConfig.persistedMedias ?? []if (persistedMedias.length > 0) {@@ -394,8 +423,11 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenisMediaInitializedRef.current = true}, [configKey, _hasHydrated])- // 已选图片对象(品牌图片已移除)- const selectedImages: any[] = []+ // 已选图片对象+ const selectedImages = useMemo(() => {+ const imageMap = new Map(imageList.map(img => [img.id, img]))+ return selectedIds.map(id => imageMap.get(id)).filter(Boolean) as BrandImage[]+ }, [selectedIds, imageList])// 平台兼容性检查const incompatiblePlatforms = useMemo(() => {@@ -437,10 +469,32 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGen// 切换内容类型时清理已上传的媒体资源clearMedias()videoDurationMapRef.current.clear()- // 重置图片选择- setSelectedIds([])- updateConfig(configKey, { selectedImageIds: [] })- }, [configKey, updateConfig, clearMedias])+ // 切换内容类型时校验并重置比例+ if (ct === 'image_text') {+ const supported = IMAGE_TEXT_ASPECT_RATIOS.map(r => r.label)+ if (!supported.includes(aspectRatio)) {+ const defaultRatio = supported.includes('9:16') ? '9:16' : (supported[0] ?? '9:16')+ setAspectRatio(defaultRatio)+ updateConfig(configKey, { aspectRatio: defaultRatio })+ }+ }+ else {+ const supported = currentVideoModelConfig.supportedRatios+ if (!supported.has(aspectRatio)) {+ const defaultRatio = supported.has('9:16') ? '9:16' : ([...supported][0] ?? '9:16')+ setAspectRatio(defaultRatio)+ updateConfig(configKey, { aspectRatio: defaultRatio })+ }+ }+ // 重置店铺图片选择(重新自动选中)+ const maxImages = ct === 'image_text'+ ? (currentImageModelInfo?.maxInputImages ?? DEFAULT_MAX_INPUT_IMAGES)+ : currentVideoModelConfig.maxImages+ const defaultCount = Math.min(5, maxImages, imageList.length)+ const newIds = imageList.slice(0, defaultCount).map(img => img.id)+ setSelectedIds(newIds)+ updateConfig(configKey, { selectedImageIds: newIds })+ }, [configKey, updateConfig, clearMedias, currentVideoModelConfig, currentImageModelInfo, imageList, aspectRatio])const handleImageModelChange = useCallback((im: string) => {setImageModel(im)@@ -498,12 +552,14 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenupdateConfig(configKey, { aspectRatio: defaultRatio })// 根据新模型的 maxImages 重新初始化选中的图片const maxImages = newConfig.maxImages- setSelectedIds([])- updateConfig(configKey, { selectedImageIds: [] })+ const defaultCount = Math.min(maxImages, imageList.length)+ const newIds = imageList.slice(0, defaultCount).map(img => img.id)+ setSelectedIds(newIds)+ updateConfig(configKey, { selectedImageIds: newIds })// 清理超出限制的本地上传图片const currentLocalImages = localMedias.filter(m => m.type === 'image')- if (currentLocalImages.length > 0 && currentLocalImages.length > maxImages) {- const allowedLocal = Math.max(0, maxImages)+ if (currentLocalImages.length > 0 && newIds.length + currentLocalImages.length > maxImages) {+ const allowedLocal = Math.max(0, maxImages - newIds.length)for (let i = currentLocalImages.length - 1; i >= allowedLocal; i--) {const mediaIndex = localMedias.indexOf(currentLocalImages[i]!)if (mediaIndex >= 0)@@ -528,13 +584,18 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGensetDuration(newMaxDuration)updateConfig(configKey, { duration: newMaxDuration })}- }, [aspectRatio, duration, configKey, updateConfig, localMedias, removeLocalMedia, t, pricingData?.videoModels])+ }, [aspectRatio, duration, configKey, updateConfig, imageList, localMedias, removeLocalMedia, t, pricingData?.videoModels])const handlePlatformsChange = useCallback((platforms: PlatType[]) => {setSelectedPlatforms(platforms)updateConfig(configKey, { selectedPlatforms: platforms })}, [configKey, updateConfig])+ const handleDraftModeChange = useCallback((isDraft: boolean) => {+ setIsDraftMode(isDraft)+ updateConfig(configKey, { isDraftMode: isDraft })+ }, [configKey, updateConfig])+// 重置所有配置到默认值const handleReset = useCallback(() => {resetConfig(configKey)@@ -550,20 +611,36 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGensetImageCount(3)setImageSize(firstImageModel?.pricing?.[0]?.resolution ?? '1K')setQuantity(1)+ setIsDraftMode(true)setSelectedPlatforms(availablePlatforms)// 清空媒体clearMedias()videoDurationMapRef.current.clear()- // 直接恢复默认提示词- setPromptValue('')- updateConfig(configKey, { promptValue: '' })- defaultPromptFilledRef.current = false+ // 直接恢复默认提示词(不依赖 effect,避免多次点击时 deps 不变导致 effect 不触发)+ if (defaultPrompt) {+ setPromptValue(defaultPrompt)+ updateConfig(configKey, { promptValue: defaultPrompt })+ defaultPromptFilledRef.current = true+ }+ else {+ setPromptValue('')+ updateConfig(configKey, { promptValue: '' })+ defaultPromptFilledRef.current = false+ }- // 重置图片选中- setSelectedIds([])- initialSelectionDone.current = false- }, [configKey, resetConfig, clearMedias, defaultPlatforms, pricingData])+ // 直接恢复默认图片选中(不依赖 effect)+ if (imageList.length > 0) {+ const maxImages = getVideoModelStaticConfig(firstVideoModel, pricingData?.videoModels).maxImages+ const defaultCount = Math.min(5, maxImages, imageList.length)+ setSelectedIds(imageList.slice(0, defaultCount).map(img => img.id))+ initialSelectionDone.current = true+ }+ else {+ setSelectedIds([])+ initialSelectionDone.current = false+ }+ }, [configKey, resetConfig, clearMedias, defaultPlatforms, defaultPrompt, imageList, pricingData])// 本地上传处理const handleLocalUpload = useCallback(async (files: FileList) => {@@ -700,22 +777,53 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenreturn}+ // 将平台参数限制追加到 prompt,让 AI 感知限制(非草稿模式不需要,因为不生成文案)+ const buildPromptWithLimits = (basePrompt: string): string => {+ if (!isDraftMode)+ return basePrompt+ const limits: string[] = []+ if (effectiveLimitsDetailed.titleMax) {+ limits.push(`标题字数限制:${effectiveLimitsDetailed.titleMax.value}`)+ }+ if (effectiveLimitsDetailed.desMax) {+ limits.push(`描述字数限制:${effectiveLimitsDetailed.desMax.value}`)+ }+ if (effectiveLimitsDetailed.topicMax) {+ limits.push(`话题数量限制:${effectiveLimitsDetailed.topicMax.value}`)+ }+ if (limits.length === 0)+ return basePrompt+ return `${basePrompt}\n\n重要:${limits.join(',')}`+ }+const imageUrls = [...selectedImages.map(img => getOssUrl(img.url)),...localImages.filter(m => m.url).map(m => m.url),]if (contentType === 'image_text') {+ // 图文模式积分验证+ const currentPricing = imagePricing.find(p => p.resolution === imageSize)+ const pricePerImage = currentPricing?.pricePerImage ?? 0+ const totalCredits = Math.ceil(pricePerImage * imageCount * quantity * 100) / 100+ const creditsBalance = useUserStore.getState().creditsBalance+ if (creditsBalance < totalCredits) {+ toast.error(t('detail.insufficientBalance', { total: totalCredits, balance: creditsBalance }))+ useAccountStore.getState().setLowBalanceAlertOpen(true)+ return+ }+const success = await createImageTextBatchGeneration(quantity,imageModel,- promptValue.trim(),+ buildPromptWithLimits(promptValue.trim()),imageCount,aspectRatio,imageUrls.length > 0 ? imageUrls : undefined,groupId,imageSize,effectiveSelectedPlatforms.length > 0 ? effectiveSelectedPlatforms : undefined,+ isDraftMode ? 'draft' : 'image',)if (success) {toast.success(t('detail.imageTextGenerated'))@@ -723,6 +831,15 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGen}}else {+ // 视频模式积分验证(使用 API 驱动的查表积分)+ const totalCredits = videoCredits+ const creditsBalance = useUserStore.getState().creditsBalance+ if (creditsBalance < totalCredits) {+ toast.error(t('detail.insufficientBalance', { total: totalCredits, balance: creditsBalance }))+ useAccountStore.getState().setLowBalanceAlertOpen(true)+ return+ }+const videoUrls = localVideos.filter(v => v.url).map(v => v.url)const success = await createBatchGeneration(@@ -730,25 +847,26 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenmodelType,duration,aspectRatio,- promptValue.trim() || undefined,+ buildPromptWithLimits(promptValue.trim()) || undefined,imageUrls.length > 0 ? imageUrls : undefined,videoUrls.length > 0 ? videoUrls : undefined,groupId,effectiveSelectedPlatforms.length > 0 ? effectiveSelectedPlatforms : undefined,+ isDraftMode ? 'draft' : 'video',)if (success) {toast.success(t('detail.aiBatchGenerate'))onGenerated?.()}}- }, [promptValue, aspectRatio, duration, modelType, selectedImages, localImages, localVideos, hasVideos, quantity, createBatchGeneration, createImageTextBatchGeneration, contentType, imageModel, imageCount, imageSize, imagePricing, videoCredits, isUploading, t, groupId, onGenerated, effectiveSelectedPlatforms])+ }, [promptValue, aspectRatio, duration, modelType, selectedImages, localImages, localVideos, hasVideos, quantity, createBatchGeneration, createImageTextBatchGeneration, contentType, imageModel, imageCount, imageSize, imagePricing, videoCredits, isUploading, t, groupId, onGenerated, effectiveSelectedPlatforms, effectiveLimitsDetailed, isDraftMode])// Prompts 探索页 URL(不同语言对应不同路径)const promptsExploreUrl = useMemo(() => {const lngPath = PROMPTS_EXPLORE_LNG_MAP[lng]return lngPath- ? `https://youmind.com/${lngPath}/seedance-2-0-prompts`- : 'https://youmind.com/seedance-2-0-prompts'+ ? `https://youmind.com/${lngPath}/grok-imagine-prompts`+ : 'https://youmind.com/grok-imagine-prompts'}, [lng])// 动态 Placeholder@@ -859,9 +977,11 @@ const AiBatchGenerateBar = memo(({ groupId, onGenerated, className }: AiBatchGenhasVideos={hasVideos}promptsExploreUrl={promptsExploreUrl}promptsExploreLabel={t('detail.exploreMorePrompts')}+ isDraftMode={isDraftMode}selectedPlatforms={selectedPlatforms}effectiveLimitsDetailed={effectiveLimitsDetailed}disabledPlatforms={incompatiblePlatforms}+ onDraftModeChange={handleDraftModeChange}onContentTypeChange={handleContentTypeChange}onModelTypeChange={handleModelTypeChange}onAspectRatioChange={handleAspectRatioChange}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/AllListSection/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/AllListSection/index.tsxnew file mode 100644index 00000000..35980051--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/AllListSection/index.tsx@@ -0,0 +1,280 @@+/**+ * AllListSection - 全部列表区域+ * 合并草稿、视频、图片三种数据源,瀑布流布局 + IntersectionObserver 无限滚动+ * 根据数据来源分发渲染 DraftCard 或 MediaCard+ */++'use client'++import type { MediaItem } from '@/api/types/media'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import type { MediaPreviewItem } from '@/components/common/MediaPreview'+import { Inbox } from 'lucide-react'+import { memo, useCallback, useEffect, useMemo, useRef } from 'react'+import Masonry from 'react-masonry-css'+import { useShallow } from 'zustand/react/shallow'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'+import { useTransClient } from '@/app/i18n/client'+import { MediaPreview } from '@/components/common/MediaPreview'+import { Skeleton } from '@/components/ui/skeleton'+import { getOssUrl } from '@/utils/oss'+import { useMediaTabStore } from '../ContentTabs/mediaTabStore'+import { LazyImage } from '../LazyImage'+import { MediaCard } from '../MediaCard'++/**+ * 瀑布流断点配置+ */+const MASONRY_BREAKPOINTS = {+ default: 5,+ 1280: 4,+ 1024: 3,+ 768: 3,+ 640: 2,+}++// 骨架屏+function AllCardSkeleton({ index }: { index: number }) {+ const heights = [120, 160, 200, 140, 180, 150, 170, 190]+ const height = heights[index % heights.length]++ return (+ <div className="mb-4">+ <Skeleton className="w-full rounded-xl" style={{ height: `${height}px` }} />+ <div className="pt-2 px-1">+ <Skeleton className="h-4 w-full" />+ </div>+ </div>+ )+}++// 加载更多指示器+const LoadingIndicator = memo(({ label }: { label: string }) => (+ <div className="flex justify-center py-4">+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />+ <span>{label}</span>+ </div>+ </div>+))+LoadingIndicator.displayName = 'LoadingIndicator'++/** 草稿卡片(简化版,用于全部列表,不含批量操作) */+const AllDraftCard = memo(({ material, onClick }: { material: PromotionMaterial, onClick: () => void }) => {+ const coverUrl = material.coverUrl || '/images/placeholder.png'++ return (+ <div+ className="mb-4 cursor-pointer group relative"+ onClick={onClick}+ >+ <div className="relative w-full overflow-hidden rounded-xl">+ <LazyImage+ src={coverUrl}+ alt={material.title || ''}+ width={400}+ height={300}+ className="w-full h-auto transition-transform duration-300 group-hover:scale-105"+ skeletonClassName="rounded-xl"+ placeholderHeight={150}+ style={{ aspectRatio: 'auto' }}+ />+ {material.desc && (+ <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-end p-3 rounded-xl">+ <p className="text-white text-xs line-clamp-4">+ {material.desc}+ </p>+ </div>+ )}+ </div>+ <div className="pt-2 px-1">+ <p className="text-sm font-medium text-foreground line-clamp-2">+ {material.title || ''}+ </p>+ {material.model && (+ <span className="inline-block mt-1 px-1.5 py-0.5 text-xs rounded bg-muted text-muted-foreground">+ {material.model}+ </span>+ )}+ </div>+ </div>+ )+})+AllDraftCard.displayName = 'AllDraftCard'++interface AllListSectionProps {+ materialGroupId: string+}++export const AllListSection = memo(({ materialGroupId }: AllListSectionProps) => {+ const { t } = useTransClient('material')+ const { t: tBrand } = useTransClient('brandPromotion')+ const loadMoreRef = useRef<HTMLDivElement>(null)++ const currentPlan = usePlanDetailStore(state => state.currentPlan)+ const openDraftDetailDialog = usePlanDetailStore(state => state.openDraftDetailDialog)++ const { mergedList, loading, initialized, allExhausted } = useMediaTabStore(+ useShallow(state => ({+ mergedList: state.all.mergedList,+ loading: state.all.loading,+ initialized: state.all.initialized,+ allExhausted: state.all.allExhausted,+ })),+ )++ const fetchAllList = useMediaTabStore(state => state.fetchAllList)+ const loadMoreAll = useMediaTabStore(state => state.loadMoreAll)++ // 媒体预览状态+ const { previewOpen, previewIndex, previewType } = useMediaTabStore(+ useShallow(state => ({+ previewOpen: state.previewOpen,+ previewIndex: state.previewIndex,+ previewType: state.previewType,+ })),+ )+ const openPreview = useMediaTabStore(state => state.openPreview)+ const closePreview = useMediaTabStore(state => state.closePreview)++ // 首次加载+ useEffect(() => {+ if (!initialized && materialGroupId && currentPlan) {+ fetchAllList(materialGroupId, currentPlan.id)+ }+ }, [initialized, materialGroupId, currentPlan, fetchAllList])++ // IntersectionObserver 无限滚动+ useEffect(() => {+ const loadMoreElement = loadMoreRef.current+ if (!loadMoreElement)+ return++ const observer = new IntersectionObserver(+ (entries) => {+ const [entry] = entries+ if (entry.isIntersecting && !allExhausted && !loading && materialGroupId && currentPlan) {+ loadMoreAll(materialGroupId, currentPlan.id)+ }+ },+ { threshold: 0.1 },+ )++ observer.observe(loadMoreElement)+ return () => observer.disconnect()+ }, [allExhausted, loading, materialGroupId, currentPlan, loadMoreAll])++ // 媒体卡片点击 - 打开预览+ const handleMediaClick = useCallback((media: MediaItem) => {+ // 找到在合并列表中同类型媒体的索引(用于预览导航)+ const mediaItems = mergedList.filter(item => item.source === media.type)+ const index = mediaItems.findIndex(item => item.id === media._id)+ if (index !== -1) {+ openPreview(media.type as 'video' | 'img', index)+ }+ }, [mergedList, openPreview])++ // 预览项列表(按当前预览类型过滤)+ const previewItems = useMemo((): MediaPreviewItem[] => {+ return mergedList+ .filter(item => item.source === previewType)+ .map((item) => {+ const media = item.data as MediaItem+ return {+ type: media.type === 'video' ? 'video' as const : 'image' as const,+ src: getOssUrl(media.url),+ title: media.title,+ }+ })+ }, [mergedList, previewType])++ // 初始加载骨架屏+ if (loading && mergedList.length === 0) {+ return (+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ {Array.from({ length: 8 }).map((_, i) => (+ <AllCardSkeleton key={i} index={i} />+ ))}+ </Masonry>+ )+ }++ // 空状态+ if (initialized && mergedList.length === 0) {+ return (+ <div className="flex flex-col items-center justify-center py-12">+ <div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">+ <Inbox className="w-8 h-8 text-muted-foreground" />+ </div>+ <p className="text-sm font-medium text-foreground mb-1">+ {t('mediaManagement.noMedia')}+ </p>+ <p className="text-sm text-muted-foreground">+ {t('mediaManagement.noMediaDesc')}+ </p>+ </div>+ )+ }++ return (+ <>+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ {mergedList.map((item) => {+ if (item.source === 'draft') {+ const material = item.data as PromotionMaterial+ return (+ <AllDraftCard+ key={`draft-${item.id}`}+ material={material}+ onClick={() => openDraftDetailDialog(material)}+ />+ )+ }+ else {+ const media = item.data as MediaItem+ return (+ <MediaCard+ key={`${item.source}-${item.id}`}+ media={media}+ onClick={handleMediaClick}+ />+ )+ }+ })}+ </Masonry>++ {/* 加载触发器 */}+ <div ref={loadMoreRef} />++ {/* 加载更多指示器 */}+ {loading && <LoadingIndicator label={tBrand('common.loading')} />}++ {/* 没有更多数据 */}+ {allExhausted && mergedList.length > 0 && (+ <div className="flex items-center justify-center py-4">+ <span className="text-sm text-muted-foreground">+ {t('mediaManagement.loadedAll')}+ </span>+ </div>+ )}++ {/* 媒体预览弹窗 */}+ <MediaPreview+ open={previewOpen}+ items={previewItems}+ initialIndex={previewIndex}+ onClose={closePreview}+ />+ </>+ )+})++AllListSection.displayName = 'AllListSection'diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/BatchActionBar/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/BatchActionBar/index.tsxindex 4ecb782a..159ef27b 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/BatchActionBar/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/BatchActionBar/index.tsx@@ -8,7 +8,7 @@import { Loader2, Trash2 } from 'lucide-react'import { memo, useCallback } from 'react'import { useShallow } from 'zustand/react/shallow'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import { confirm } from '@/lib/confirm'@@ -17,15 +17,15 @@ import { toast } from '@/lib/toast'const BatchActionBar = memo(() => {const { t } = useTransClient('brandPromotion')- const { selectedMaterialIds, batchDeleting } = useDraftBoxStore(+ const { selectedMaterialIds, batchDeleting } = usePlanDetailStore(useShallow(state => ({selectedMaterialIds: state.selectedMaterialIds,batchDeleting: state.batchDeleting,})),)- const exitBatchMode = useDraftBoxStore(state => state.exitBatchMode)- const batchDeleteMaterials = useDraftBoxStore(state => state.batchDeleteMaterials)+ const exitBatchMode = usePlanDetailStore(state => state.exitBatchMode)+ const batchDeleteMaterials = usePlanDetailStore(state => state.batchDeleteMaterials)const handleDelete = useCallback(() => {const count = selectedMaterialIds.lengthdiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/ConditionalDeleteDialog/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/ConditionalDeleteDialog/index.tsxindex 189f9078..a1263864 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/ConditionalDeleteDialog/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/ConditionalDeleteDialog/index.tsx@@ -10,7 +10,7 @@ import lodash from 'lodash'import { Loader2 } from 'lucide-react'import { memo, useCallback, useEffect, useMemo, useState } from 'react'import { apiGetMaterialList } from '@/api/material'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import {@@ -22,12 +22,13 @@ import {} from '@/components/ui/dialog'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'+import { NumberInput } from '@/components/ui/number-input'import { toast } from '@/lib/toast'// 外层:控制渲染时机const ConditionalDeleteDialog = memo(() => {- const open = useDraftBoxStore(state => state.conditionalDeleteDialogOpen)- const closeDialog = useDraftBoxStore(state => state.closeConditionalDeleteDialog)+ const open = usePlanDetailStore(state => state.conditionalDeleteDialogOpen)+ const closeDialog = usePlanDetailStore(state => state.closeConditionalDeleteDialog)if (!open)return null@@ -47,24 +48,24 @@ ConditionalDeleteDialog.displayName = 'ConditionalDeleteDialog'const ConditionalDeleteDialogContent = memo(({ onOpenChange }: { onOpenChange: (open: boolean) => void }) => {const { t } = useTransClient('brandPromotion')- const currentPlan = useDraftBoxStore(state => state.currentPlan)- const filterDeleteMaterials = useDraftBoxStore(state => state.filterDeleteMaterials)+ const currentPlan = usePlanDetailStore(state => state.currentPlan)+ const filterDeleteMaterials = usePlanDetailStore(state => state.filterDeleteMaterials)const [title, setTitle] = useState('')- const [useCount, setUseCount] = useState('')+ const [useCount, setUseCount] = useState<number | undefined>()const [matchCount, setMatchCount] = useState<number | null>(null)const [querying, setQuerying] = useState(false)const [deleting, setDeleting] = useState(false)- const hasCondition = title.trim() !== '' || useCount !== ''+ const hasCondition = title.trim() !== '' || useCount !== undefined// 构建筛选条件const buildFilters = useCallback((): MaterialListFilters => {const filters: MaterialListFilters = {}if (title.trim())filters.title = title.trim()- if (useCount !== '')- filters.useCount = Number(useCount)+ if (useCount !== undefined)+ filters.useCount = useCountreturn filters}, [title, useCount])@@ -100,7 +101,7 @@ const ConditionalDeleteDialogContent = memo(({ onOpenChange }: { onOpenChange: (return}setQuerying(true)- queryMatchCount(currentPlan._id, filters)+ queryMatchCount(currentPlan.id, filters)}, [title, useCount, currentPlan, buildFilters, queryMatchCount])// 清理 debounce@@ -151,12 +152,12 @@ const ConditionalDeleteDialogContent = memo(({ onOpenChange }: { onOpenChange: (<div className="space-y-2"><Label>{t('draftManage.conditionUseCount')}</Label>- <Input+ <NumberInputdata-testid="draftbox-cond-usecount-input"- type="number"- min={0}value={useCount}- onChange={e => setUseCount(e.target.value)}+ onValueChange={v => setUseCount(v)}+ decimalScale={0}+ allowNegative={false}placeholder={t('draftManage.conditionUseCountPlaceholder')}/></div>diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/ContentTabs/mediaTabStore.ts b/project/aitoearn-web/src/app/[lng]/draft-box/components/ContentTabs/mediaTabStore.tsnew file mode 100644index 00000000..6d816a1f--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/ContentTabs/mediaTabStore.ts@@ -0,0 +1,441 @@+/**+ * mediaTabStore - 媒体 Tab 状态管理+ * 管理视频/图片两个列表的独立状态、分页、预览+ * 以及"全部"Tab 的三路合并数据+ */++import type { MediaItem } from '@/api/types/media'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { apiGetMaterialList } from '@/api/material'+import { getMediaList } from '@/api/media'++const PAGE_SIZE = 20+const ALL_PAGE_SIZE = 20++interface MediaTypeState {+ list: MediaItem[]+ loading: boolean+ total: number+ page: number+ hasMore: boolean+ initialized: boolean+}++const defaultTypeState: MediaTypeState = {+ list: [],+ loading: false,+ total: 0,+ page: 1,+ hasMore: true,+ initialized: false,+}++/** 全部 Tab 统一数据项 */+export interface AllTabItem {+ source: 'draft' | 'video' | 'img'+ id: string+ createdAt: string+ data: PromotionMaterial | MediaItem+}++interface AllTabState {+ mergedList: AllTabItem[]+ loading: boolean+ initialized: boolean+ allExhausted: boolean+ draftPage: number+ draftHasMore: boolean+ draftTotal: number+ videoPage: number+ videoHasMore: boolean+ videoTotal: number+ imgPage: number+ imgHasMore: boolean+ imgTotal: number+}++const defaultAllState: AllTabState = {+ mergedList: [],+ loading: false,+ initialized: false,+ allExhausted: false,+ draftPage: 1,+ draftHasMore: true,+ draftTotal: 0,+ videoPage: 1,+ videoHasMore: true,+ videoTotal: 0,+ imgPage: 1,+ imgHasMore: true,+ imgTotal: 0,+}++/** 将草稿转换为 AllTabItem */+function materialToAllItem(m: PromotionMaterial): AllTabItem {+ return { source: 'draft', id: m.id, createdAt: m.createdAt || '', data: m }+}++/** 将媒体转换为 AllTabItem */+function mediaToAllItem(m: MediaItem, source: 'video' | 'img'): AllTabItem {+ return { source, id: m._id, createdAt: m.createdAt || '', data: m }+}++/** 按 createdAt 降序排序 */+function sortByCreatedAtDesc(items: AllTabItem[]): AllTabItem[] {+ return items.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())+}++export const useMediaTabStore = create(+ combine(+ {+ video: { ...defaultTypeState } as MediaTypeState,+ img: { ...defaultTypeState } as MediaTypeState,+ all: { ...defaultAllState } as AllTabState,+ // 预览状态+ previewOpen: false,+ previewIndex: 0,+ previewType: 'video' as 'video' | 'img',+ },+ (set, get) => ({+ /**+ * 获取媒体列表(首次加载)+ */+ fetchMediaList: async (materialGroupId: string, type: 'video' | 'img') => {+ const state = get()[type]+ if (state.loading)+ return++ set(prev => ({+ [type]: { ...prev[type], loading: true },+ }))++ try {+ const res = await getMediaList({ materialGroupId }, 1, PAGE_SIZE, type)+ if (res?.data) {+ const list = res.data.list || []+ const total = res.data.total || 0+ set({+ [type]: {+ list,+ loading: false,+ total,+ page: 1,+ hasMore: list.length < total,+ initialized: true,+ },+ })+ }+ else {+ set(prev => ({+ [type]: { ...prev[type], loading: false, initialized: true },+ }))+ }+ }+ catch (error) {+ console.error(`Failed to fetch ${type} media list:`, error)+ set(prev => ({+ [type]: { ...prev[type], loading: false, initialized: true },+ }))+ }+ },++ /**+ * 加载更多+ */+ loadMore: async (materialGroupId: string, type: 'video' | 'img') => {+ const state = get()[type]+ if (state.loading || !state.hasMore)+ return++ const nextPage = state.page + 1+ set(prev => ({+ [type]: { ...prev[type], loading: true },+ }))++ try {+ const res = await getMediaList({ materialGroupId }, nextPage, PAGE_SIZE, type)+ if (res?.data) {+ const newList = res.data.list || []+ const total = res.data.total || 0+ const combinedList = [...state.list, ...newList]+ set({+ [type]: {+ list: combinedList,+ loading: false,+ total,+ page: nextPage,+ hasMore: combinedList.length < total,+ initialized: true,+ },+ })+ }+ else {+ set(prev => ({+ [type]: { ...prev[type], loading: false, hasMore: false },+ }))+ }+ }+ catch (error) {+ console.error(`Failed to load more ${type} media:`, error)+ set(prev => ({+ [type]: { ...prev[type], loading: false },+ }))+ }+ },++ /**+ * 获取全部列表(首次加载,三路并行)+ */+ fetchAllList: async (materialGroupId: string, planId: string) => {+ const { all } = get()+ if (all.loading)+ return++ set({ all: { ...get().all, loading: true } })++ try {+ const [draftRes, videoRes, imgRes] = await Promise.all([+ apiGetMaterialList(planId, 1, ALL_PAGE_SIZE),+ getMediaList({ materialGroupId }, 1, ALL_PAGE_SIZE, 'video'),+ getMediaList({ materialGroupId }, 1, ALL_PAGE_SIZE, 'img'),+ ])++ const draftList = draftRes?.data?.list || []+ const draftTotal = draftRes?.data?.total || 0+ const videoList = videoRes?.data?.list || []+ const videoTotal = videoRes?.data?.total || 0+ const imgList = imgRes?.data?.list || []+ const imgTotal = imgRes?.data?.total || 0++ const allItems: AllTabItem[] = [+ ...draftList.map(materialToAllItem),+ ...videoList.map(m => mediaToAllItem(m, 'video')),+ ...imgList.map(m => mediaToAllItem(m, 'img')),+ ]++ const draftHasMore = draftList.length < draftTotal+ const videoHasMore = videoList.length < videoTotal+ const imgHasMore = imgList.length < imgTotal++ set({+ all: {+ mergedList: sortByCreatedAtDesc(allItems),+ loading: false,+ initialized: true,+ allExhausted: !draftHasMore && !videoHasMore && !imgHasMore,+ draftPage: 1,+ draftHasMore,+ draftTotal,+ videoPage: 1,+ videoHasMore,+ videoTotal,+ imgPage: 1,+ imgHasMore,+ imgTotal,+ },+ })+ }+ catch (error) {+ console.error('Failed to fetch all list:', error)+ set({ all: { ...get().all, loading: false, initialized: true } })+ }+ },++ /**+ * 加载更多全部列表+ */+ loadMoreAll: async (materialGroupId: string, planId: string) => {+ const { all } = get()+ if (all.loading || all.allExhausted)+ return++ set({ all: { ...all, loading: true } })++ try {+ const fetches: Promise<any>[] = []+ const fetchTypes: ('draft' | 'video' | 'img')[] = []++ if (all.draftHasMore) {+ fetches.push(apiGetMaterialList(planId, all.draftPage + 1, ALL_PAGE_SIZE))+ fetchTypes.push('draft')+ }+ if (all.videoHasMore) {+ fetches.push(getMediaList({ materialGroupId }, all.videoPage + 1, ALL_PAGE_SIZE, 'video'))+ fetchTypes.push('video')+ }+ if (all.imgHasMore) {+ fetches.push(getMediaList({ materialGroupId }, all.imgPage + 1, ALL_PAGE_SIZE, 'img'))+ fetchTypes.push('img')+ }++ const results = await Promise.all(fetches)++ const current = get().all+ let newDraftPage = current.draftPage+ let newDraftHasMore = current.draftHasMore+ let newDraftTotal = current.draftTotal+ let newVideoPage = current.videoPage+ let newVideoHasMore = current.videoHasMore+ let newVideoTotal = current.videoTotal+ let newImgPage = current.imgPage+ let newImgHasMore = current.imgHasMore+ let newImgTotal = current.imgTotal+ const newItems: AllTabItem[] = []++ results.forEach((res, i) => {+ const type = fetchTypes[i]+ const list = res?.data?.list || []+ const total = res?.data?.total || 0++ if (type === 'draft') {+ newDraftPage += 1+ newDraftTotal = total+ newDraftHasMore = (current.mergedList.filter(item => item.source === 'draft').length + list.length) < total+ newItems.push(...list.map(materialToAllItem))+ }+ else if (type === 'video') {+ newVideoPage += 1+ newVideoTotal = total+ newVideoHasMore = (current.mergedList.filter(item => item.source === 'video').length + list.length) < total+ newItems.push(...list.map((m: MediaItem) => mediaToAllItem(m, 'video')))+ }+ else if (type === 'img') {+ newImgPage += 1+ newImgTotal = total+ newImgHasMore = (current.mergedList.filter(item => item.source === 'img').length + list.length) < total+ newItems.push(...list.map((m: MediaItem) => mediaToAllItem(m, 'img')))+ }+ })++ const mergedList = sortByCreatedAtDesc([...current.mergedList, ...newItems])++ set({+ all: {+ mergedList,+ loading: false,+ initialized: true,+ allExhausted: !newDraftHasMore && !newVideoHasMore && !newImgHasMore,+ draftPage: newDraftPage,+ draftHasMore: newDraftHasMore,+ draftTotal: newDraftTotal,+ videoPage: newVideoPage,+ videoHasMore: newVideoHasMore,+ videoTotal: newVideoTotal,+ imgPage: newImgPage,+ imgHasMore: newImgHasMore,+ imgTotal: newImgTotal,+ },+ })+ }+ catch (error) {+ console.error('Failed to load more all list:', error)+ set({ all: { ...get().all, loading: false } })+ }+ },++ /**+ * 静默刷新全部列表(轮询完成时调用)+ */+ silentRefreshAll: async (materialGroupId: string, planId: string) => {+ const { all } = get()+ if (!all.initialized)+ return++ try {+ const [draftRes, videoRes, imgRes] = await Promise.all([+ apiGetMaterialList(planId, 1, ALL_PAGE_SIZE),+ getMediaList({ materialGroupId }, 1, ALL_PAGE_SIZE, 'video'),+ getMediaList({ materialGroupId }, 1, ALL_PAGE_SIZE, 'img'),+ ])++ const freshDrafts = (draftRes?.data?.list || []).map(materialToAllItem)+ const freshVideos = (videoRes?.data?.list || []).map((m: MediaItem) => mediaToAllItem(m, 'video'))+ const freshImgs = (imgRes?.data?.list || []).map((m: MediaItem) => mediaToAllItem(m, 'img'))++ const current = get().all+ const existingIds = new Set(current.mergedList.map(item => item.id))+ const newItems = [...freshDrafts, ...freshVideos, ...freshImgs].filter(item => !existingIds.has(item.id))++ if (newItems.length > 0) {+ set({+ all: {+ ...current,+ mergedList: sortByCreatedAtDesc([...newItems, ...current.mergedList]),+ draftTotal: draftRes?.data?.total || current.draftTotal,+ videoTotal: videoRes?.data?.total || current.videoTotal,+ imgTotal: imgRes?.data?.total || current.imgTotal,+ },+ })+ }+ }+ catch {+ // 静默失败+ }+ },++ /**+ * 重置所有数据(Plan 切换时调用)+ */+ reset: () => {+ set({+ video: { ...defaultTypeState },+ img: { ...defaultTypeState },+ all: { ...defaultAllState },+ previewOpen: false,+ previewIndex: 0,+ })+ },++ /**+ * 静默刷新已初始化的媒体列表(轮询完成时调用)+ */+ silentRefresh: async (materialGroupId: string) => {+ const state = get()+ const types = (['video', 'img'] as const).filter(t => state[t].initialized)++ await Promise.all(types.map(async (type) => {+ try {+ const current = get()[type]+ const res = await getMediaList({ materialGroupId }, 1, PAGE_SIZE, type)+ if (res?.data) {+ const freshList = res.data.list || []+ const total = res.data.total || 0+ // 构建当前列表的 _id Set+ const existingIds = new Set(current.list.map(m => m._id))+ // 找出新增项+ const newItems = freshList.filter(item => !existingIds.has(item._id))+ if (newItems.length > 0) {+ set({+ [type]: {+ ...current,+ list: [...newItems, ...current.list],+ total,+ },+ })+ }+ }+ }+ catch {+ // 静默失败+ }+ }))+ },++ /**+ * 打开预览+ */+ openPreview: (type: 'video' | 'img', index: number) => {+ set({ previewOpen: true, previewIndex: index, previewType: type })+ },++ /**+ * 关闭预览+ */+ closePreview: () => {+ set({ previewOpen: false })+ },+ }),+ ),+)diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/InlinePlatformSelector/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/InlinePlatformSelector/index.tsxnew file mode 100644index 00000000..5c186335--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/InlinePlatformSelector/index.tsx@@ -0,0 +1,97 @@+/**+ * InlinePlatformSelector - 内联平台图标选择器+ * 用于创建草稿弹窗顶部,一行展示所有可用平台图标+ */++'use client'++import type { PlatType } from '@/app/config/platConfig'+import Image from 'next/image'+import { memo, useCallback, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { RegionTaskPlatInfoArr } from '@/app/config/platConfig'+import { cn } from '@/lib/utils'++interface InlinePlatformSelectorProps {+ selectedPlatforms: PlatType[]+ onPlatformsChange: (platforms: PlatType[]) => void+}++const InlinePlatformSelector = memo(({ selectedPlatforms, onPlatformsChange }: InlinePlatformSelectorProps) => {+ const { t } = useTranslation('brandPromotion')++ const availablePlatforms = useMemo(() =>+ RegionTaskPlatInfoArr.map(([plat, info]) => ({+ plat,+ icon: info.icon,+ name: info.name,+ themeColor: info.themeColor,+ })), [])++ const isAllSelected = selectedPlatforms.length === availablePlatforms.length++ const handleToggle = useCallback((plat: PlatType) => {+ if (selectedPlatforms.includes(plat)) {+ onPlatformsChange(selectedPlatforms.filter(p => p !== plat))+ }+ else {+ onPlatformsChange([...selectedPlatforms, plat])+ }+ }, [selectedPlatforms, onPlatformsChange])++ const handleToggleAll = useCallback(() => {+ if (isAllSelected) {+ onPlatformsChange([])+ }+ else {+ onPlatformsChange(availablePlatforms.map(p => p.plat))+ }+ }, [isAllSelected, availablePlatforms, onPlatformsChange])++ return (+ <div className="flex items-center gap-2">+ <span className="text-xs text-muted-foreground shrink-0">{t('createMaterial.targetPlatforms')}</span>+ <div className="flex flex-wrap items-center gap-2.5 flex-1">+ {availablePlatforms.map(({ plat, icon, name, themeColor }) => {+ const isSelected = selectedPlatforms.includes(plat)+ return (+ <button+ key={plat}+ type="button"+ className={cn(+ 'border-2 rounded-full p-px cursor-pointer transition-all duration-300',+ isSelected+ ? ''+ : 'border-transparent [&>img]:grayscale hover:[&>img]:grayscale-0',+ )}+ style={{+ borderColor: isSelected ? themeColor : 'transparent',+ }}+ title={name}+ onClick={() => handleToggle(plat)}+ >+ <Image+ src={icon}+ alt={name}+ width={38}+ height={38}+ className="rounded-full"+ />+ </button>+ )+ })}+ </div>+ <button+ type="button"+ className="text-xs text-primary hover:underline cursor-pointer shrink-0"+ onClick={handleToggleAll}+ >+ {isAllSelected ? t('createMaterial.deselectAll') : t('createMaterial.selectAll')}+ </button>+ </div>+ )+})++InlinePlatformSelector.displayName = 'InlinePlatformSelector'++export default InlinePlatformSelectordiff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/MobileContent.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/MobileContent.tsxindex f7a87e9b..0e1155e6 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/MobileContent.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/MobileContent.tsx@@ -1,15 +1,15 @@/*** MobileContent - 创建/编辑素材弹窗的移动端布局组件- * 全屏弹窗,布局:媒体上传区 → 标题输入 → 描述输入+ * 全屏弹窗,布局:平台选择 → 媒体上传区 → 标题输入 → 描述输入*/'use client'import type { CreateMaterialModalProps } from './index'import type { IImgFile, IVideoFile } from '@/components/PublishDialog/publishDialog.type'-import { Bot, Play, X } from 'lucide-react'+import { Bot, Play, TriangleAlert, X } from 'lucide-react'import Image from 'next/image'import { useRouter } from 'next/navigation'-import { memo, useCallback, useMemo, useRef, useState } from 'react'+import { memo, useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { ReactSortable } from 'react-sortablejs'import { CSSTransition, TransitionGroup } from 'react-transition-group'@@ -19,6 +19,7 @@ import { useTransClient } from '@/app/i18n/client'import MediaPreview from '@/components/common/MediaPreview'import BrushEditor from '@/components/common/MediaPreview/BrushEditor'import PublishUploadProgress from '@/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress'+import PubParmasMentionInput from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput'import PubParmasTextareaUpload from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload'import PubParmasTextuploadImage from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage'import VideoCoverSeting from '@/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting'@@ -26,7 +27,9 @@ import { formatImg } from '@/components/PublishDialog/PublishDialog.util'import { Button } from '@/components/ui/button'import { DialogTitle } from '@/components/ui/dialog'import { toast } from '@/lib/toast'+import InlinePlatformSelector from './InlinePlatformSelector'import { useCreateMaterialForm } from './useCreateMaterialForm'+import { useMaterialValidation } from './useMaterialValidation'import './uploadItemTransition.css'const MobileContent = memo(@@ -57,6 +60,8 @@ const MobileContent = memo(onSuccess,})+ const { warnings, effectiveLimits } = useMaterialValidation(params, params.selectedPlatforms)+// 预览状态const [previewData, setPreviewData] = useState<IImgFile | IVideoFile | undefined>(undefined)const [imagePreviewOpen, setImagePreviewOpen] = useState(false)@@ -65,16 +70,15 @@ const MobileContent = memo(// 视频封面裁剪const [videoCoverSetingModal, setVideoCoverSetingModal] = useState(false)// 内部图片/视频状态(用于排序等操作后同步回 params)- const textareaRef = useRef<HTMLTextAreaElement>(null)- // 平台配置(素材弹窗统一使用 Tiktok 配置)+ // 平台配置(用于上传类型判断,取 TikTok 作为基准)const platConfig = useMemo(() => {return AccountPlatInfoMap.get(PlatType.Tiktok)! || {}}, [])const imageMax = useMemo(() => {- return platConfig.commonPubParamsConfig?.imagesMax || 10- }, [platConfig])+ return effectiveLimits.imagesMax?.value ?? platConfig.commonPubParamsConfig?.imagesMax ?? 10+ }, [effectiveLimits, platConfig])const videoMax = 1@@ -190,18 +194,6 @@ const MobileContent = memo([updateParams],)- // textarea 自动增高- const handleDesChange = useCallback(- (e: React.ChangeEvent<HTMLTextAreaElement>) => {- updateParams({ des: e.target.value })- // 自动调整高度- const el = e.target- el.style.height = 'auto'- el.style.height = `${el.scrollHeight}px`- },- [updateParams],- )-return (<>{/* 弹窗层 */}@@ -263,8 +255,36 @@ const MobileContent = memo(<div className="w-8" /></div>+ {/* 平台选择器 */}+ <div className="px-4 py-2 border-b border-border shrink-0">+ <InlinePlatformSelector+ selectedPlatforms={params.selectedPlatforms}+ onPlatformsChange={platforms => updateParams({ selectedPlatforms: platforms })}+ />+ </div>+{/* 可滚动内容区 */}<div className="flex-1 overflow-y-auto px-4 py-4">+ {/* 警告区域 */}+ {warnings.length > 0 && (+ <div className="mb-4">+ <div className="rounded-md bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 p-3">+ <div className="flex items-center gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-400 mb-1.5">+ <TriangleAlert className="h-3.5 w-3.5" />+ {t('createMaterial.validationWarnings')}+ </div>+ <ul className="text-xs text-amber-600 dark:text-amber-400/80 space-y-0.5">+ {warnings.map((w, i) => (+ <li key={i}>+ •+ {w}+ </li>+ ))}+ </ul>+ </div>+ </div>+ )}+{/* 媒体上传区 */}<ReactSortableclassName="grid grid-cols-3 gap-2.5"@@ -394,24 +414,32 @@ const MobileContent = memo({/* 标题输入 */}<div className="mt-4 border-t border-border pt-4">- <input- type="text"- value={params.title}- placeholder={t('createMaterial.titlePlaceholder')}- onChange={e => updateParams({ title: e.target.value })}- className="w-full text-base font-medium bg-transparent border-none shadow-none outline-none placeholder:text-muted-foreground/50 focus-visible:ring-0"- />+ <div className="flex items-center gap-2">+ <input+ type="text"+ value={params.title}+ placeholder={t('createMaterial.titlePlaceholder')}+ onChange={e => updateParams({ title: e.target.value })}+ maxLength={effectiveLimits.titleMax?.value}+ className="flex-1 min-w-0 text-base font-medium bg-transparent border-none shadow-none outline-none placeholder:text-muted-foreground/50 focus-visible:ring-0"+ />+ {effectiveLimits.titleMax && (+ <span className={`shrink-0 text-xs tabular-nums ${params.title.length > effectiveLimits.titleMax.value ? 'text-destructive' : 'text-muted-foreground'}`}>+ {params.title.length}+ /+ {effectiveLimits.titleMax.value}+ </span>+ )}+ </div></div>{/* 描述输入 */}<div className="mt-3 border-t border-border pt-3">- <textarea- ref={textareaRef}+ <PubParmasMentionInputvalue={params.des}+ onChange={(value: string) => updateParams({ des: value })}placeholder={tPublish('form.descriptionPlaceholder')}- onChange={handleDesChange}- rows={4}- className="w-full text-sm bg-transparent border-none shadow-none outline-none resize-none placeholder:text-muted-foreground/50 focus-visible:ring-0"+ maxLength={effectiveLimits.desMax?.value ?? 2200}/></div></div>diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/index.tsxindex a0b3e72c..f9aacf80 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/index.tsx@@ -5,8 +5,8 @@*/'use client'-import type { DraftMaterial } from '@/app/[lng]/draft-box/types'-import { Bot } from 'lucide-react'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import { Bot, TriangleAlert } from 'lucide-react'import { useRouter } from 'next/navigation'import { memo } from 'react'import { useTranslation } from 'react-i18next'@@ -23,15 +23,17 @@ import {import { Input } from '@/components/ui/input'import { useIsMobile } from '@/hooks/useIsMobile'import { cn } from '@/lib/utils'+import InlinePlatformSelector from './InlinePlatformSelector'import MobileContent from './MobileContent'import { useCreateMaterialForm } from './useCreateMaterialForm'+import { useMaterialValidation } from './useMaterialValidation'export interface CreateMaterialModalProps {open: boolean/** 素材组 ID(推广计划关联的素材组) */groupId: string | null/** 编辑模式下的素材数据 */- editingMaterial?: DraftMaterial | null+ editingMaterial?: PromotionMaterial | null/** 是否正在提交 */isSubmitting?: boolean/** 关闭弹窗 */@@ -67,6 +69,8 @@ const CreateMaterialModalContent = memo(onSuccess,})+ const { warnings, effectiveLimits } = useMaterialValidation(params, params.selectedPlatforms)+return (<><DialogHeader>@@ -76,6 +80,34 @@ const CreateMaterialModalContent = memo(</DialogHeader><div className="flex flex-col gap-4 py-4 max-h-[70vh]">+ {/* 平台选择器 */}+ <div className="px-1">+ <InlinePlatformSelector+ selectedPlatforms={params.selectedPlatforms}+ onPlatformsChange={platforms => updateParams({ selectedPlatforms: platforms })}+ />+ </div>++ {/* 警告区域 */}+ {warnings.length > 0 && (+ <div className="px-1">+ <div className="rounded-md bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 p-3">+ <div className="flex items-center gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-400 mb-1.5">+ <TriangleAlert className="h-3.5 w-3.5" />+ {t('createMaterial.validationWarnings')}+ </div>+ <ul className="text-xs text-amber-600 dark:text-amber-400/80 space-y-0.5">+ {warnings.map((w, i) => (+ <li key={i}>+ •+ {w}+ </li>+ ))}+ </ul>+ </div>+ </div>+ )}+{/* 使用 PubParmasTextarea 组件 */}<div className="px-1 overflow-y-auto"><PubParmasTextarea@@ -84,6 +116,8 @@ const CreateMaterialModalContent = memo(desValue={params.des}imageFileListValue={params.images}videoFileValue={params.video}+ imagesMaxOverride={effectiveLimits.imagesMax?.value}+ desMaxOverride={effectiveLimits.desMax?.value}onChange={({ value, imgs, video }) => {updateParams({ des: value, images: imgs || [], video })}}@@ -111,7 +145,21 @@ const CreateMaterialModalContent = memo(value={params.title}placeholder={t('createMaterial.titlePlaceholder')}onChange={e => updateParams({ title: e.target.value })}+ maxLength={effectiveLimits.titleMax?.value}/>+ {effectiveLimits.titleMax && (+ <span className={cn(+ 'shrink-0 ml-2 text-xs tabular-nums',+ params.title.length > effectiveLimits.titleMax.value+ ? 'text-destructive'+ : 'text-muted-foreground',+ )}+ >+ {params.title.length}+ /+ {effectiveLimits.titleMax.value}+ </span>+ )}</div>)}/>diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useCreateMaterialForm.ts b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useCreateMaterialForm.tsindex 3b6acfd5..5dbae4a8 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useCreateMaterialForm.ts+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useCreateMaterialForm.ts@@ -3,12 +3,14 @@ import type { MaterialMedia } from '@/api/material'* useCreateMaterialForm - 创建/编辑素材表单逻辑 Hook* 从 CreateMaterialModalContent 中提取的共享表单逻辑,供桌面端和移动端组件复用*/-import type { DraftMaterial } from '@/app/[lng]/draft-box/types'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import type { PlatType } from '@/app/config/platConfig'import type { IImgFile, IVideoFile } from '@/components/PublishDialog/publishDialog.type'import { useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useShallow } from 'zustand/react/shallow'import { apiCreateMaterial, apiUpdateMaterial } from '@/api/material'+import { RegionTaskPlatInfoArr } from '@/app/config/platConfig'import { PubType } from '@/app/config/publishConfig'import { UploadTaskStatusEnum } from '@/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum'import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'@@ -19,11 +21,12 @@ export interface FormParams {des: stringimages: IImgFile[]video?: IVideoFile+ selectedPlatforms: PlatType[]}export interface UseCreateMaterialFormProps {groupId: string | null- editingMaterial?: DraftMaterial | null+ editingMaterial?: PromotionMaterial | nullisSubmitting?: booleanonClose: () => voidonSuccess?: () => void@@ -48,12 +51,16 @@ export function useCreateMaterialForm({})),)+ // 默认全选平台+ const defaultPlatforms = useMemo(() => RegionTaskPlatInfoArr.map(([p]) => p), [])+// 表单参数const [params, setParams] = useState<FormParams>({title: '',des: '',images: [],video: undefined,+ selectedPlatforms: defaultPlatforms,})const isEditing = !!editingMaterial@@ -105,6 +112,9 @@ export function useCreateMaterialForm({des: editingMaterial.desc || '',video,images,+ selectedPlatforms: editingMaterial.accountTypes?.length+ ? editingMaterial.accountTypes as PlatType[]+ : defaultPlatforms,})}else {@@ -113,6 +123,7 @@ export function useCreateMaterialForm({des: '',images: [],video: undefined,+ selectedPlatforms: defaultPlatforms,})}}, [editingMaterial])@@ -267,19 +278,29 @@ export function useCreateMaterialForm({title: params.title.trim(),desc: params.des,type,+ accountTypes: params.selectedPlatforms,}- if (isEditing && editingMaterial?._id) {- await apiUpdateMaterial(editingMaterial._id, {+ if (isEditing && editingMaterial?.id) {+ const res = await apiUpdateMaterial(editingMaterial.id, {coverUrl: materialData.coverUrl,mediaList: materialData.mediaList,title: materialData.title,desc: materialData.desc,+ accountTypes: materialData.accountTypes,})+ if (res?.code !== 0) {+ toast.error(res?.message || t('createMaterial.createFailed'))+ return+ }toast.success(t('createMaterial.createSuccess'))}else {- await apiCreateMaterial(materialData)+ const res = await apiCreateMaterial(materialData)+ if (res?.code !== 0) {+ toast.error(res?.message || t('createMaterial.createFailed'))+ return+ }toast.success(t('createMaterial.createSuccess'))}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useMaterialValidation.ts b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useMaterialValidation.tsnew file mode 100644index 00000000..83123f71--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/CreateMaterialModal/useMaterialValidation.ts@@ -0,0 +1,86 @@+/**+ * useMaterialValidation - 素材平台参数校验 hook+ * 根据选中平台计算参数限制并生成警告信息+ */++import type { FormParams } from './useCreateMaterialForm'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { isAspectRatioInRange } from '@/components/PublishDialog/PublishDialog.util'+import { calcEffectiveLimitsDetailed } from '../AiBatchGenerateBar/platformLimits'++export function useMaterialValidation(params: FormParams, selectedPlatforms: PlatType[]) {+ const { t } = useTranslation('brandPromotion')++ const effectiveLimits = useMemo(+ () => calcEffectiveLimitsDetailed(selectedPlatforms),+ [selectedPlatforms],+ )++ const warnings = useMemo(() => {+ const result: string[] = []+ if (selectedPlatforms.length === 0)+ return result++ // 标题超长+ if (params.title && effectiveLimits.titleMax) {+ if (params.title.length > effectiveLimits.titleMax.value) {+ const platName = AccountPlatInfoMap.get(effectiveLimits.titleMax.limitedBy)?.name ?? effectiveLimits.titleMax.limitedBy+ result.push(t('createMaterial.titleExceeded', { platform: platName, max: effectiveLimits.titleMax.value }))+ }+ }++ // 描述超长+ if (params.des && effectiveLimits.desMax) {+ if (params.des.length > effectiveLimits.desMax.value) {+ const platName = AccountPlatInfoMap.get(effectiveLimits.desMax.limitedBy)?.name ?? effectiveLimits.desMax.limitedBy+ result.push(t('createMaterial.descExceeded', { platform: platName, max: effectiveLimits.desMax.value }))+ }+ }++ // 图片数超限+ if (params.images.length > 0 && effectiveLimits.imagesMax) {+ if (params.images.length > effectiveLimits.imagesMax.value) {+ const platName = AccountPlatInfoMap.get(effectiveLimits.imagesMax.limitedBy)?.name ?? effectiveLimits.imagesMax.limitedBy+ result.push(t('createMaterial.imageExceeded', { platform: platName, max: effectiveLimits.imagesMax.value }))+ }+ }++ // Instagram 比例校验+ if (selectedPlatforms.includes(PlatType.Instagram)) {+ if (params.images.length > 0) {+ for (const img of params.images) {+ if (img.width && img.height && !isAspectRatioInRange(img.width, img.height, 4 / 5, 1.91)) {+ result.push(t('createMaterial.instagramImageAspectRatio'))+ break+ }+ }+ }+ if (params.video?.width && params.video?.height+ && !isAspectRatioInRange(params.video.width, params.video.height, 9 / 16, 4 / 5)) {+ result.push(t('createMaterial.instagramVideoAspectRatio'))+ }+ }++ // Facebook 比例校验+ if (selectedPlatforms.includes(PlatType.Facebook)) {+ if (params.images.length > 0) {+ for (const img of params.images) {+ if (img.width && img.height && !isAspectRatioInRange(img.width, img.height, 4 / 5, 1.91)) {+ result.push(t('createMaterial.facebookImageAspectRatio'))+ break+ }+ }+ }+ if (params.video?.width && params.video?.height+ && !isAspectRatioInRange(params.video.width, params.video.height, 9 / 16, 4 / 5)) {+ result.push(t('createMaterial.facebookVideoAspectRatio'))+ }+ }++ return result+ }, [params.title, params.des, params.images, params.video, effectiveLimits, selectedPlatforms, t])++ return { warnings, effectiveLimits }+}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftContentModule/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftContentModule/index.tsxindex f9fb0ad8..f2696d08 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftContentModule/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftContentModule/index.tsx@@ -1,6 +1,7 @@/*** DraftContentModule - 内容管理核心模块* 可复用的草稿管理区域,包含 AI生成栏、草稿列表、相关弹框+ * 在 brand-promotion 页面和独立 draft-box 页面中复用*/'use client'@@ -8,17 +9,18 @@import type { IPubParams } from '@/components/PublishDialog/publishDialog.type'import { useCallback, useEffect, useMemo } from 'react'import { useShallow } from 'zustand/react/shallow'-import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'+import { AccountPlatInfoMap, isPlatformAvailable } from '@/app/config/platConfig'import { PubType } from '@/app/config/publishConfig'import PublishDialog from '@/components/PublishDialog'import { VideoGrabFrame } from '@/components/PublishDialog/PublishDialog.util'import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'import { useAccountStore } from '@/store/account'-+import { useUserStore } from '@/store/user'import { generateUUID } from '@/utils'-import { useDraftBoxStore } from '../../draftBoxStore'import { useGenerationPolling } from '../../hooks/useGenerationPolling'import AiBatchGenerateBar from '../AiBatchGenerateBar'+import { useMediaTabStore } from '../ContentTabs/mediaTabStore'import { CreateMaterialModal } from '../CreateMaterialModal'import { DraftDetailDialog } from '../DraftDetailDialog'import { DraftListSection } from '../DraftListSection'@@ -32,7 +34,7 @@ function DraftContentModule() {generatingCount,publishDialogOpen,publishingDraft,- } = useDraftBoxStore(+ } = usePlanDetailStore(useShallow(state => ({currentPlan: state.currentPlan,createMaterialModalOpen: state.createMaterialModalOpen,@@ -43,15 +45,20 @@ function DraftContentModule() {})),)- const selectedPlanId = currentPlan?._id || null- const closeMaterialModal = useDraftBoxStore(state => state.closeMaterialModal)- const fetchMaterials = useDraftBoxStore(state => state.fetchMaterials)- const closePublishDialog = useDraftBoxStore(state => state.closePublishDialog)- const silentRefreshMaterials = useDraftBoxStore(state => state.silentRefreshMaterials)- const updateGeneratingCount = useDraftBoxStore(state => state.updateGeneratingCount)+ const selectedPlanId = currentPlan?.id || null+ const closeMaterialModal = usePlanDetailStore(state => state.closeMaterialModal)+ const fetchMaterials = usePlanDetailStore(state => state.fetchMaterials)+ const closePublishDialog = usePlanDetailStore(state => state.closePublishDialog)+ const silentRefreshMaterials = usePlanDetailStore(state => state.silentRefreshMaterials)+ const updateGeneratingCount = usePlanDetailStore(state => state.updateGeneratingCount)const accountList = useAccountStore(state => state.accountList)+ // Plan 切换时重置媒体 Tab 数据+ useEffect(() => {+ useMediaTabStore.getState().reset()+ }, [selectedPlanId])+// AI 批量生成轮询useGenerationPolling({enabled: generatingCount > 0,@@ -59,7 +66,9 @@ function DraftContentModule() {onTaskCompleted: () => {if (selectedPlanId) {silentRefreshMaterials(selectedPlanId)+ useMediaTabStore.getState().silentRefresh(selectedPlanId)}+ useUserStore.getState().fetchCreditsBalance()},onCountUpdate: updateGeneratingCount,})@@ -74,7 +83,7 @@ function DraftContentModule() {return accountList.filter((acc) => {const platConfig = AccountPlatInfoMap.get(acc.type)- return platConfig?.pubTypes.has(targetPubType) && acc.status !== 0+ return platConfig?.pubTypes.has(targetPubType) && acc.status !== 0 && isPlatformAvailable(acc.type)}).map(acc => acc.id)}, [publishingDraft, accountList])@@ -186,8 +195,9 @@ function DraftContentModule() {// 创建草稿成功回调const handleMaterialSuccess = useCallback(() => {if (currentPlan) {- fetchMaterials(currentPlan._id, 1)+ fetchMaterials(currentPlan.id, 1)}+ useUserStore.getState().fetchCreditsBalance()}, [currentPlan, fetchMaterials])return (@@ -195,14 +205,14 @@ function DraftContentModule() {<div className="space-y-6 p-4 md:p-6">{/* AI 批量生成输入栏 */}<AiBatchGenerateBar groupId={selectedPlanId || undefined} />- {/* 草稿列表 */}- <DraftListSection />+ {/* 内容 Tabs:草稿箱 / 视频 / 图片 */}+ <DraftListSection materialGroupId={selectedPlanId || undefined} /></div>{/* 创建草稿弹窗 */}<CreateMaterialModalopen={createMaterialModalOpen}- groupId={currentPlan?._id || null}+ groupId={currentPlan?.id || null}editingMaterial={editingMaterial}onClose={closeMaterialModal}onSuccess={handleMaterialSuccess}@@ -222,6 +232,7 @@ function DraftContentModule() {defaultAccountIds={defaultAccountIds}onPubSuccess={closePublishDialog}/>+</>)}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftDetailDialog.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftDetailDialog.tsxindex 95308da5..1834f938 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftDetailDialog.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftDetailDialog.tsx@@ -6,15 +6,17 @@'use client'-import type { DraftMaterial } from '@/app/[lng]/draft-box/types'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import type { PlatType } from '@/app/config/platConfig'import { Calendar, Edit, Image as ImageIcon, Loader2, Send, Trash2, Video } from 'lucide-react'import NextImage from 'next/image'import { memo, useCallback, useState } from 'react'import { Navigation, Pagination } from 'swiper/modules'import { Swiper, SwiperSlide } from 'swiper/react'import { useShallow } from 'zustand/react/shallow'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { AccountPlatInfoMap } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import {AlertDialog,@@ -50,10 +52,8 @@ function MediaImage({ src, alt }: { src: string, alt: string }) {<div className="relative flex items-center justify-center w-full h-full">{/* Loading 骨架 - 增强效果 */}{!loaded && (- <div className="absolute inset-0 flex flex-col items-center justify-center bg-muted/80 gap-3">- {/* 旋转加载图标 */}+ <div className="absolute inset-0 flex items-center justify-center bg-muted/80"><div className="h-8 w-8 animate-spin rounded-full border-4 border-muted-foreground/30 border-t-primary" />- <span className="text-sm text-muted-foreground">加载中...</span></div>)}<NextImage@@ -73,7 +73,7 @@ function MediaImage({ src, alt }: { src: string, alt: string }) {}// 媒体预览组件 - 使用 Swiper 轮播-const MediaPreview = memo(({ material }: { material: DraftMaterial }) => {+const MediaPreview = memo(({ material }: { material: PromotionMaterial }) => {const mediaList = material.mediaList || []const [currentIndex, setCurrentIndex] = useState(0)const [isHovered, setIsHovered] = useState(false)@@ -177,7 +177,7 @@ const DraftDetailContent = memo(({ onClose }: { onClose: () => void }) => {const { t } = useTransClient('brandPromotion')const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false)- const { selectedDraft, isSubmitting } = useDraftBoxStore(+ const { selectedDraft, isSubmitting } = usePlanDetailStore(useShallow(state => ({selectedDraft: state.selectedDraft,isSubmitting: state.isSubmitting,@@ -189,7 +189,7 @@ const DraftDetailContent = memo(({ onClose }: { onClose: () => void }) => {closeDraftDetailDialog,deleteMaterial,openPublishDialog,- } = useDraftBoxStore(+ } = usePlanDetailStore(useShallow(state => ({openEditMaterialModal: state.openEditMaterialModal,closeDraftDetailDialog: state.closeDraftDetailDialog,@@ -219,7 +219,7 @@ const DraftDetailContent = memo(({ onClose }: { onClose: () => void }) => {if (!selectedDraft)return- const success = await deleteMaterial(selectedDraft._id)+ const success = await deleteMaterial(selectedDraft.id)if (success) {toast.success(t('plan.deleteSuccess'))closeDraftDetailDialog()@@ -309,6 +309,28 @@ const DraftDetailContent = memo(({ onClose }: { onClose: () => void }) => {)}</div>+ {/* 平台图标 */}+ {selectedDraft.accountTypes && selectedDraft.accountTypes.length > 0 && (+ <div className="flex flex-wrap items-center gap-2">+ {selectedDraft.accountTypes.map((type) => {+ const platInfo = AccountPlatInfoMap.get(type as PlatType)+ if (!platInfo)+ return null+ return (+ <NextImage+ key={type}+ src={platInfo.icon}+ alt={platInfo.name}+ width={20}+ height={20}+ className="w-5 h-5"+ unoptimized+ />+ )+ })}+ </div>+ )}+{/* 创建时间 */}{selectedDraft.createdAt && (<div className="flex items-center gap-2 text-sm text-muted-foreground">@@ -386,13 +408,13 @@ DraftDetailContent.displayName = 'DraftDetailContent'// 主组件export const DraftDetailDialog = memo(() => {- const { draftDetailDialogOpen } = useDraftBoxStore(+ const { draftDetailDialogOpen } = usePlanDetailStore(useShallow(state => ({draftDetailDialogOpen: state.draftDetailDialogOpen,})),)- const closeDraftDetailDialog = useDraftBoxStore(state => state.closeDraftDetailDialog)+ const closeDraftDetailDialog = usePlanDetailStore(state => state.closeDraftDetailDialog)// 根据疑难杂症记录 #2,拆成两层组件避免闪烁if (!draftDetailDialogOpen)diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsxindex 205fd542..098a55e2 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListSection.tsx@@ -4,26 +4,35 @@* 图片保持原始比例显示* 创建按钮卡片作为瀑布流前两个元素* 支持搜索筛选、批量删除、条件删除+ * 当传入 materialGroupId 时,集成 Tab(草稿箱/视频/图片)*/'use client'-import type { DraftMaterial } from '@/app/[lng]/draft-box/types'-import { Check, FileText, ListChecks, Plus } from 'lucide-react'-import { memo, useCallback, useEffect, useRef } from 'react'+import type { PromotionMaterial } from '@/app/[lng]/brand-promotion/brandPromotionStore/types'+import type { PlatType } from '@/app/config/platConfig'+import { Check, ListChecks, Plus } from 'lucide-react'+import Image from 'next/image'+import { memo, useCallback, useEffect, useRef, useState } from 'react'import Masonry from 'react-masonry-css'import { useShallow } from 'zustand/react/shallow'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'+import { AccountPlatInfoMap } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'+import { Badge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'import { Skeleton } from '@/components/ui/skeleton'+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'import { cn } from '@/lib/utils'+import { AllListSection } from './AllListSection'import { BatchActionBar } from './BatchActionBar'import { ConditionalDeleteDialog } from './ConditionalDeleteDialog'+import { useMediaTabStore } from './ContentTabs/mediaTabStore'import { DraftListToolbar } from './DraftListToolbar'import { GeneratingCard } from './GeneratingCard'import { LazyImage } from './LazyImage'+import { MediaListSection } from './MediaListSection'/*** 瀑布流断点配置@@ -58,7 +67,7 @@ ManualCreateCard.displayName = 'ManualCreateCard'// 草稿卡片 propsinterface DraftCardProps {- material: DraftMaterial+ material: PromotionMaterialonClick: () => voidbatchMode: booleanselected: boolean@@ -68,6 +77,7 @@ interface DraftCardProps {// 草稿卡片组件(小红书风格)const DraftCard = memo(({ material, onClick, batchMode, selected, onToggleSelect, useCountLabel }: DraftCardProps) => {+ const { t } = useTransClient('brandPromotion')const coverUrl = material.coverUrl || '/images/placeholder.png'const handleClick = useCallback(() => {@@ -113,7 +123,7 @@ const DraftCard = memo(({ material, onClick, batchMode, selected, onToggleSelect<div className="relative w-full overflow-hidden rounded-xl"><LazyImagesrc={coverUrl}- alt={material.title || '草稿'}+ alt={material.title || t('material.draft')}width={400}height={300}className="w-full h-auto transition-transform duration-300 group-hover:scale-105"@@ -139,18 +149,38 @@ const DraftCard = memo(({ material, onClick, batchMode, selected, onToggleSelect{/* 标题和模型标签 */}<div className="pt-2 px-1"><p className="text-sm font-medium text-foreground line-clamp-2">- {material.title || '未命名草稿'}+ {material.title || t('material.untitled')}</p>{material.model && (- <span className="inline-block mt-1 px-1.5 py-0.5 text-[10px] rounded bg-muted text-muted-foreground">+ <span className="inline-block mt-1 px-1.5 py-0.5 text-xs rounded bg-muted text-muted-foreground">{material.model}</span>)}{useCountLabel && (- <span className="inline-block mt-1 ml-1 px-1.5 py-0.5 text-[10px] rounded bg-primary/10 text-primary">+ <span className="inline-block mt-1 ml-1 px-1.5 py-0.5 text-xs rounded bg-primary/10 text-primary">{useCountLabel}</span>)}+ {material.accountTypes && material.accountTypes.length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1.5">+ {material.accountTypes.map((type) => {+ const platInfo = AccountPlatInfoMap.get(type as PlatType)+ if (!platInfo)+ return null+ return (+ <Image+ key={type}+ src={platInfo.icon}+ alt={platInfo.name}+ width={16}+ height={16}+ className="w-4 h-4"+ unoptimized+ />+ )+ })}+ </div>+ )}</div></div>)@@ -175,19 +205,35 @@ function DraftCardSkeleton({ index }: { index: number }) {}// 加载更多指示器-const LoadingIndicator = memo(() => (+const LoadingIndicator = memo(({ label }: { label: string }) => (<div className="flex justify-center py-4"><div className="flex items-center gap-2 text-sm text-muted-foreground"><div className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />- <span>加载中...</span>+ <span>{label}</span></div></div>))LoadingIndicator.displayName = 'LoadingIndicator'-export const DraftListSection = memo(() => {+interface DraftListSectionProps {+ /** 传入时显示 Tab(草稿箱/视频/图片),不传则只显示草稿列表 */+ materialGroupId?: string+}++export const DraftListSection = memo(({ materialGroupId }: DraftListSectionProps) => {const { t } = useTransClient('brandPromotion')+ const { t: tMaterial } = useTransClient('material')++ const showTabs = !!materialGroupId+ const [activeTab, setActiveTab] = useState('all')++ // materialGroupId 变化时,有 Tab 模式默认选中"全部"+ useEffect(() => {+ if (materialGroupId) {+ setActiveTab('all')+ }+ }, [materialGroupId])// 无限滚动加载触发器const loadMoreRef = useRef<HTMLDivElement>(null)@@ -200,7 +246,7 @@ export const DraftListSection = memo(() => {generatingCount,batchMode,selectedMaterialIds,- } = useDraftBoxStore(+ } = usePlanDetailStore(useShallow(state => ({materials: state.materials,materialsLoading: state.materialsLoading,@@ -212,14 +258,44 @@ export const DraftListSection = memo(() => {})),)- const openCreateMaterialModal = useDraftBoxStore(state => state.openCreateMaterialModal)- const loadMoreMaterials = useDraftBoxStore(state => state.loadMoreMaterials)- const openDraftDetailDialog = useDraftBoxStore(state => state.openDraftDetailDialog)- const openGenerationDetailDialog = useDraftBoxStore(state => state.openGenerationDetailDialog)- const toggleMaterialSelection = useDraftBoxStore(state => state.toggleMaterialSelection)+ const openCreateMaterialModal = usePlanDetailStore(state => state.openCreateMaterialModal)+ const loadMoreMaterials = usePlanDetailStore(state => state.loadMoreMaterials)+ const openDraftDetailDialog = usePlanDetailStore(state => state.openDraftDetailDialog)+ const openGenerationDetailDialog = usePlanDetailStore(state => state.openGenerationDetailDialog)+ const toggleMaterialSelection = usePlanDetailStore(state => state.toggleMaterialSelection)++ const { videoTotal, imgTotal, allTotal } = useMediaTabStore(+ useShallow(state => ({+ videoTotal: state.video.total,+ imgTotal: state.img.total,+ allTotal: state.all.draftTotal + state.all.videoTotal + state.all.imgTotal,+ })),+ )++ const fetchMediaList = useMediaTabStore(state => state.fetchMediaList)+ const fetchAllList = useMediaTabStore(state => state.fetchAllList)+ const videoInitialized = useMediaTabStore(state => state.video.initialized)+ const imgInitialized = useMediaTabStore(state => state.img.initialized)+ const allInitialized = useMediaTabStore(state => state.all.initialized)const selectedSet = new Set(selectedMaterialIds)+ // Tab 切换处理+ const handleTabChange = useCallback((value: string) => {+ setActiveTab(value)++ // 首次切换到对应 Tab 时触发加载+ if (value === 'all' && !allInitialized && materialGroupId && currentPlan) {+ fetchAllList(materialGroupId, currentPlan.id)+ }+ if (value === 'video' && !videoInitialized && materialGroupId) {+ fetchMediaList(materialGroupId, 'video')+ }+ if (value === 'img' && !imgInitialized && materialGroupId) {+ fetchMediaList(materialGroupId, 'img')+ }+ }, [allInitialized, videoInitialized, imgInitialized, materialGroupId, currentPlan, fetchAllList, fetchMediaList])+// IntersectionObserver 实现无限滚动useEffect(() => {const loadMoreElement = loadMoreRef.current@@ -230,7 +306,7 @@ export const DraftListSection = memo(() => {(entries) => {const [entry] = entriesif (entry.isIntersecting && materialsPagination.hasMore && !materialsLoading && currentPlan) {- loadMoreMaterials(currentPlan._id)+ loadMoreMaterials(currentPlan.id)}},{ threshold: 0.1 },@@ -243,8 +319,191 @@ export const DraftListSection = memo(() => {}}, [materialsPagination.hasMore, materialsLoading, currentPlan, loadMoreMaterials])+ // 根据 activeTab 获取标题(数量已在 Tab Badge 中展示,此处不再重复)+ const getHeaderTitle = () => {+ switch (activeTab) {+ case 'all':+ return tMaterial('mediaManagement.all')+ case 'video':+ return tMaterial('mediaManagement.video')+ case 'img':+ return tMaterial('mediaManagement.image')+ default:+ return tMaterial('mediaManagement.drafts', '草稿箱')+ }+ }++ // 草稿内容区域+ const draftsContent = (+ <>+ <DraftListToolbar />+ <div>+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ data-testid="draftbox-masonry-list"+ >+ {!batchMode && (+ <ManualCreateCard onClick={openCreateMaterialModal} />+ )}++ {/* 生成中卡片 - 批量模式隐藏 */}+ {!batchMode && generatingCount > 0 && (+ <GeneratingCard count={generatingCount} onClick={openGenerationDetailDialog} />+ )}++ {/* 草稿数据 */}+ {materials.map(material => (+ <DraftCard+ key={material.id}+ material={material}+ onClick={() => openDraftDetailDialog(material)}+ batchMode={batchMode}+ selected={selectedSet.has(material.id)}+ onToggleSelect={() => toggleMaterialSelection(material.id)}+ useCountLabel={material.useCount != null && material.useCount > 0 ? t('material.useCount', { count: material.useCount }) : undefined}+ />+ ))}+ </Masonry>++ {/* 加载触发器 */}+ <div ref={loadMoreRef} />++ {/* 加载更多指示器 */}+ {materialsLoading && <LoadingIndicator label={t('common.loading')} />}++ {/* 没有更多数据 */}+ {!materialsPagination.hasMore && materials.length > 0 && (+ <div className="flex items-center justify-center py-4">+ <span className="text-sm text-muted-foreground">+ {t('common.noMore', '没有更多了')}+ </span>+ </div>+ )}+ </div>+ </>+ )++ // 骨架屏内容+ const skeletonCard = (+ <Card>+ <CardHeader className="pb-4">+ <div className="flex items-center justify-between">+ <CardTitle className="text-base">{t('overview.draftList', { count: materialsPagination.total })}</CardTitle>+ <Button variant="ghost" size="sm" onClick={openGenerationDetailDialog} className="cursor-pointer gap-1.5 text-muted-foreground">+ <ListChecks className="h-3.5 w-3.5" />+ {t('draftManage.generationDetail')}+ </Button>+ </div>+ </CardHeader>+ <CardContent>+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ <ManualCreateCard onClick={openCreateMaterialModal} />+ {Array.from({ length: 8 }).map((_, i) => (+ <DraftCardSkeleton key={i} index={i} />+ ))}+ </Masonry>+ </CardContent>+ </Card>+ )++ // TabsList 组件+ const tabsList = (+ <TabsList className="w-full sm:w-auto">+ <TabsTrigger value="all" className="cursor-pointer gap-1.5 flex-1 sm:flex-initial">+ {tMaterial('mediaManagement.all')}+ {allTotal > 0 && (+ <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] px-1.5 text-xs">+ {allTotal}+ </Badge>+ )}+ </TabsTrigger>+ <TabsTrigger value="drafts" className="cursor-pointer gap-1.5 flex-1 sm:flex-initial">+ {tMaterial('mediaManagement.drafts', '草稿箱')}+ {materialsPagination.total > 0 && (+ <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] px-1.5 text-xs">+ {materialsPagination.total}+ </Badge>+ )}+ </TabsTrigger>+ <TabsTrigger value="video" className="cursor-pointer gap-1.5 flex-1 sm:flex-initial">+ {tMaterial('mediaManagement.video')}+ {videoTotal > 0 && (+ <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] px-1.5 text-xs">+ {videoTotal}+ </Badge>+ )}+ </TabsTrigger>+ <TabsTrigger value="img" className="cursor-pointer gap-1.5 flex-1 sm:flex-initial">+ {tMaterial('mediaManagement.image')}+ {imgTotal > 0 && (+ <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] px-1.5 text-xs">+ {imgTotal}+ </Badge>+ )}+ </TabsTrigger>+ </TabsList>+ )++ // 页面加载时预取全部/视频/图片数据+ useEffect(() => {+ if (materialGroupId && showTabs) {+ if (!allInitialized && currentPlan) {+ fetchAllList(materialGroupId, currentPlan.id)+ }+ if (!videoInitialized) {+ fetchMediaList(materialGroupId, 'video')+ }+ if (!imgInitialized) {+ fetchMediaList(materialGroupId, 'img')+ }+ }+ }, [materialGroupId, showTabs, allInitialized, videoInitialized, imgInitialized, currentPlan, fetchAllList, fetchMediaList])+// 初始加载骨架屏if (materialsLoading && materials.length === 0) {+ if (showTabs) {+ return (+ <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">+ <Card>+ <div className="px-6 pt-6">+ {tabsList}+ </div>+ <CardHeader className="pb-4">+ <div className="flex items-center justify-between">+ <CardTitle className="text-base">{t('overview.draftList', { count: materialsPagination.total })}</CardTitle>+ <Button variant="ghost" size="sm" onClick={openGenerationDetailDialog} className="cursor-pointer gap-1.5 text-muted-foreground">+ <ListChecks className="h-3.5 w-3.5" />+ {t('draftManage.generationDetail')}+ </Button>+ </div>+ </CardHeader>+ <CardContent>+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ <ManualCreateCard onClick={openCreateMaterialModal} />+ {Array.from({ length: 8 }).map((_, i) => (+ <DraftCardSkeleton key={i} index={i} />+ ))}+ </Masonry>+ </CardContent>+ </Card>+ </Tabs>+ )+ }+ return skeletonCard+ }++ // 无 Tab 模式(DraftManageDrawer)+ if (!showTabs) {return (<Card><CardHeader className="pb-4">@@ -256,121 +515,60 @@ export const DraftListSection = memo(() => {</Button></div></CardHeader>- <CardContent>- <Masonry- breakpointCols={MASONRY_BREAKPOINTS}- className="flex -ml-4 w-auto"- columnClassName="pl-4 bg-clip-padding"- >- <ManualCreateCard onClick={openCreateMaterialModal} />- {/* 骨架屏 */}- {Array.from({ length: 8 }).map((_, i) => (- <DraftCardSkeleton key={i} index={i} />- ))}- </Masonry>+ <CardContent className={cn(batchMode && 'pb-16')}>+ {draftsContent}</CardContent>+ {batchMode && <BatchActionBar />}+ <ConditionalDeleteDialog /></Card>)}- // 空状态:加载完成且无草稿- if (!materialsLoading && materials.length === 0) {- return (+ // 有 Tab 模式:TabsList 在 Card 内部+ return (+ <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full"><Card>+ <div className="px-6 pt-6">+ {tabsList}+ </div><CardHeader className="pb-4"><div className="flex items-center justify-between">- <CardTitle className="text-base">{t('overview.draftList', { count: 0 })}</CardTitle>+ <CardTitle className="text-base">{getHeaderTitle()}</CardTitle><Button variant="ghost" size="sm" onClick={openGenerationDetailDialog} className="cursor-pointer gap-1.5 text-muted-foreground"><ListChecks className="h-3.5 w-3.5" />{t('draftManage.generationDetail')}</Button></div></CardHeader>- <CardContent>- <div className="flex flex-col items-center justify-center py-16 gap-4">- <div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted">- <FileText className="h-8 w-8 text-muted-foreground" />- </div>- <div className="text-center">- <p className="text-base font-medium text-muted-foreground">{t('material.emptyTitle')}</p>- <p className="mt-1 text-sm text-muted-foreground/70">{t('material.emptyDesc')}</p>- </div>- <Button onClick={openCreateMaterialModal} className="cursor-pointer mt-2 gap-1.5">- <Plus className="h-4 w-4" />- {t('detail.manualGenerate')}- </Button>- </div>- </CardContent>- </Card>- )- }- return (- <Card>- <CardHeader className="pb-4">- <div className="flex items-center justify-between">- <CardTitle className="text-base">{t('overview.draftList', { count: materialsPagination.total })}</CardTitle>- <Button variant="ghost" size="sm" onClick={openGenerationDetailDialog} className="cursor-pointer gap-1.5 text-muted-foreground">- <ListChecks className="h-3.5 w-3.5" />- {t('draftManage.generationDetail')}- </Button>- </div>- </CardHeader>- <CardContent className={cn(batchMode && 'pb-16')}>- <DraftListToolbar />- <div>- <Masonry- breakpointCols={MASONRY_BREAKPOINTS}- className="flex -ml-4 w-auto"- columnClassName="pl-4 bg-clip-padding"- data-testid="draftbox-masonry-list"- >- {!batchMode && (- <ManualCreateCard onClick={openCreateMaterialModal} />- )}-- {/* 生成中卡片 - 批量模式隐藏 */}- {!batchMode && generatingCount > 0 && (- <GeneratingCard count={generatingCount} onClick={openGenerationDetailDialog} />- )}-- {/* 草稿数据 */}- {materials.map(material => (- <DraftCard- key={material._id}- material={material}- onClick={() => openDraftDetailDialog(material)}- batchMode={batchMode}- selected={selectedSet.has(material._id)}- onToggleSelect={() => toggleMaterialSelection(material._id)}- useCountLabel={material.useCount != null && material.useCount > 0 ? t('material.useCount', { count: material.useCount }) : undefined}- />- ))}- </Masonry>-- {/* 加载触发器 */}- <div ref={loadMoreRef} />-- {/* 加载更多指示器 */}- {materialsLoading && <LoadingIndicator />}-- {/* 没有更多数据 */}- {!materialsPagination.hasMore && materials.length > 0 && (- <div className="flex items-center justify-center py-4">- <span className="text-sm text-muted-foreground">- {t('common.noMore', '没有更多了')}- </span>- </div>- )}- </div>- </CardContent>-- {/* 批量模式底部操作栏 */}- {batchMode && <BatchActionBar />}-- {/* 条件删除弹窗 */}- <ConditionalDeleteDialog />- </Card>+ <TabsContent value="all" className="mt-0">+ <CardContent>+ <AllListSection materialGroupId={materialGroupId} />+ </CardContent>+ </TabsContent>++ <TabsContent value="drafts" className="mt-0">+ <CardContent className={cn(batchMode && 'pb-16')}>+ {draftsContent}+ </CardContent>+ </TabsContent>++ <TabsContent value="video" className="mt-0">+ <CardContent>+ <MediaListSection type="video" materialGroupId={materialGroupId} />+ </CardContent>+ </TabsContent>++ <TabsContent value="img" className="mt-0">+ <CardContent>+ <MediaListSection type="img" materialGroupId={materialGroupId} />+ </CardContent>+ </TabsContent>++ {batchMode && <BatchActionBar />}+ <ConditionalDeleteDialog />+ </Card>+ </Tabs>)})diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListToolbar/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListToolbar/index.tsxindex 641f825d..3560f7a0 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListToolbar/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/DraftListToolbar/index.tsx@@ -10,7 +10,7 @@ import lodash from 'lodash'import { Search, Trash2 } from 'lucide-react'import { memo, useCallback, useMemo, useRef, useState } from 'react'import { useShallow } from 'zustand/react/shallow'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import { Checkbox } from '@/components/ui/checkbox'@@ -24,7 +24,7 @@ const DraftListToolbar = memo(() => {selectedMaterialIds,materials,materialsFilter,- } = useDraftBoxStore(+ } = usePlanDetailStore(useShallow(state => ({batchMode: state.batchMode,selectedMaterialIds: state.selectedMaterialIds,@@ -33,12 +33,12 @@ const DraftListToolbar = memo(() => {})),)- const setMaterialsFilter = useDraftBoxStore(state => state.setMaterialsFilter)- const enterBatchMode = useDraftBoxStore(state => state.enterBatchMode)- const exitBatchMode = useDraftBoxStore(state => state.exitBatchMode)- const selectAllLoadedMaterials = useDraftBoxStore(state => state.selectAllLoadedMaterials)- const deselectAllMaterials = useDraftBoxStore(state => state.deselectAllMaterials)- const openConditionalDeleteDialog = useDraftBoxStore(state => state.openConditionalDeleteDialog)+ const setMaterialsFilter = usePlanDetailStore(state => state.setMaterialsFilter)+ const enterBatchMode = usePlanDetailStore(state => state.enterBatchMode)+ const exitBatchMode = usePlanDetailStore(state => state.exitBatchMode)+ const selectAllLoadedMaterials = usePlanDetailStore(state => state.selectAllLoadedMaterials)+ const deselectAllMaterials = usePlanDetailStore(state => state.deselectAllMaterials)+ const openConditionalDeleteDialog = usePlanDetailStore(state => state.openConditionalDeleteDialog)const [searchValue, setSearchValue] = useState(materialsFilter.title || '')@@ -56,7 +56,7 @@ const DraftListToolbar = memo(() => {const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {const value = e.target.valuesetSearchValue(value)- const { materialsFilter } = useDraftBoxStore.getState()+ const { materialsFilter } = usePlanDetailStore.getState()debouncedRef.current({...materialsFilter,title: value || undefined,@@ -78,7 +78,7 @@ const DraftListToolbar = memo(() => {return (<div className="flex items-center gap-3 mb-4"><div data-testid="draftbox-select-all-checkbox" className="flex items-center gap-2 cursor-pointer" onClick={handleToggleSelectAll}>- <Checkbox checked={allSelected} />+ <Checkbox checked={allSelected} onCheckedChange={handleToggleSelectAll} /><span className="text-sm">{t('draftManage.selectAll')}</span></div><span className="text-sm text-muted-foreground">diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/GenerationDetailDialog/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/GenerationDetailDialog/index.tsxindex 6cdc8d05..754daef3 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/components/GenerationDetailDialog/index.tsx+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/GenerationDetailDialog/index.tsx@@ -5,13 +5,14 @@'use client'-import type { DraftGenerationTask } from '@/api/draftGeneration'+import type { DraftGenerationRequest, DraftGenerationTask } from '@/api/draftGeneration'import { AlertCircle, CheckCircle2, Loader2, Play } from 'lucide-react'import Image from 'next/image'import { memo, useCallback, useEffect, useRef, useState } from 'react'import { apiGetDraftGenerationList } from '@/api/draftGeneration'-import { useDraftBoxStore } from '@/app/[lng]/draft-box/draftBoxStore'+import { usePlanDetailStore } from '@/app/[lng]/brand-promotion/planDetailStore'import { useTransClient } from '@/app/i18n/client'+import { MediaPreview } from '@/components/common/MediaPreview'import { Badge } from '@/components/ui/badge'import {Dialog,@@ -47,15 +48,111 @@ function getStatusVariant(status: DraftGenerationTask['status']): 'default' | 's}}+// 请求参数展示+const RequestParams = memo(({ request, t }: { request: DraftGenerationRequest, t: (key: string, options?: Record<string, unknown>) => string }) => {+ const [previewOpen, setPreviewOpen] = useState(false)+ const [previewIndex, setPreviewIndex] = useState(0)+ const tags: { label: string, value: string }[] = []++ if (request.model) {+ tags.push({ label: t('detail.modelType'), value: request.model })+ }+ if (request.imageModel) {+ tags.push({ label: t('detail.imageModel'), value: request.imageModel })+ }+ if (request.duration) {+ tags.push({ label: t('detail.duration'), value: `${request.duration}s` })+ }+ if (request.aspectRatio) {+ tags.push({ label: t('detail.aspectRatio'), value: request.aspectRatio })+ }+ if (request.imageCount) {+ tags.push({ label: t('detail.imageCount'), value: `${request.imageCount}` })+ }+ if (request.imageSize) {+ tags.push({ label: t('detail.imageResolution'), value: request.imageSize })+ }++ return (+ <div className="mt-2 space-y-1.5">+ {tags.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {tags.map(tag => (+ <span+ key={tag.label}+ className="inline-flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground"+ >+ <span className="opacity-70">{tag.label}</span>+ <span>{tag.value}</span>+ </span>+ ))}+ </div>+ )}+ {request.prompt && (+ <p className="text-xs text-muted-foreground line-clamp-2 break-all">+ <span className="opacity-70">+ {t('detail.promptTitle')}+ :+ </span>+ {request.prompt}+ </p>+ )}+ {request.imageUrls && request.imageUrls.length > 0 && (+ <div className="space-y-1">+ <span className="text-xs text-muted-foreground opacity-70">{t('detail.referenceImages')}</span>+ <div className="flex gap-1.5 flex-wrap">+ {request.imageUrls.map((url, i) => (+ <div+ key={i}+ className="relative w-10 h-10 rounded overflow-hidden bg-muted shrink-0 cursor-pointer"+ onClick={() => { setPreviewIndex(i); setPreviewOpen(true) }}+ >+ <Image+ src={getOssUrl(url)}+ alt={`ref-${i + 1}`}+ fill+ className="object-cover"+ sizes="40px"+ />+ </div>+ ))}+ </div>+ <MediaPreview+ open={previewOpen}+ items={request.imageUrls.map(url => ({ type: 'image' as const, src: getOssUrl(url) }))}+ initialIndex={previewIndex}+ onClose={() => setPreviewOpen(false)}+ />+ </div>+ )}+ </div>+ )+})++RequestParams.displayName = 'RequestParams'+// 任务条目const TaskItem = memo(({ task, t }: { task: DraftGenerationTask, t: (key: string, options?: Record<string, unknown>) => string }) => {+ const [previewOpen, setPreviewOpen] = useState(false)+ const [previewIndex, setPreviewIndex] = useState(0)const response = task.status === 'success' ? task.response : undefined++ // 构建预览项列表和封面+ const hasVideo = !!response?.videoUrl+ const hasImages = (response?.imageUrls?.length ?? 0) > 0const coverSrc = response?.coverUrl? getOssUrl(response.coverUrl): response?.imageUrls?.[0]? getOssUrl(response.imageUrls[0]): undefined+ // 预览项:视频任务只预览视频,图片任务预览所有图片+ const previewItems = response+ ? hasVideo && response.videoUrl+ ? [{ type: 'video' as const, src: getOssUrl(response.videoUrl), title: response.title }]+ : (response.imageUrls || []).map(url => ({ type: 'image' as const, src: getOssUrl(url), title: response.title }))+ : []+return (<div className="flex items-start gap-3 p-3 rounded-lg border border-border/50 bg-muted/20"><div className="mt-0.5">@@ -73,48 +170,83 @@ const TaskItem = memo(({ task, t }: { task: DraftGenerationTask, t: (key: string)}</div>+ {/* 请求参数 */}+ {task.request && <RequestParams request={task.request} t={t} />}+{/* 成功任务 - 渲染 response 内容 */}{response && (- <div className="flex gap-3 mt-2">- {coverSrc && (- <a- href={response.videoUrl ? getOssUrl(response.videoUrl) : coverSrc}- target="_blank"- rel="noopener noreferrer"- className="relative shrink-0 w-20 h-20 rounded-md overflow-hidden bg-muted cursor-pointer block"- >- <Image- src={coverSrc}- alt={response.title || ''}- fill- className="object-cover"- sizes="80px"- />- {response.videoUrl && (+ <div className="mt-2">+ {/* 视频任务:封面 + 文字信息 */}+ {hasVideo && coverSrc && (+ <div className="flex gap-3">+ <div+ className="relative shrink-0 w-20 h-20 rounded-md overflow-hidden bg-muted cursor-pointer"+ onClick={() => { setPreviewIndex(0); setPreviewOpen(true) }}+ >+ <Image+ src={coverSrc}+ alt={response.title || ''}+ fill+ className="object-cover"+ sizes="80px"+ /><div className="absolute inset-0 flex items-center justify-center bg-black/30"><Play className="h-5 w-5 text-white fill-white" /></div>- )}- </a>+ </div>+ <div className="flex-1 min-w-0">+ {response.title && (+ <p className="text-sm font-medium line-clamp-1">{response.title}</p>+ )}+ {response.description && (+ <p className="text-xs text-muted-foreground line-clamp-2 mt-0.5">{response.description}</p>+ )}+ {response.topics?.length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1">+ {response.topics.map(topic => (+ <span key={topic} className="text-xs text-primary">+ #+ {topic}+ </span>+ ))}+ </div>+ )}+ </div>+ </div>)}- <div className="flex-1 min-w-0">- {response.title && (- <p className="text-sm font-medium line-clamp-1">{response.title}</p>- )}- {response.description && (- <p className="text-xs text-muted-foreground line-clamp-2 mt-0.5">{response.description}</p>- )}- {response.topics?.length > 0 && (- <div className="flex flex-wrap gap-1 mt-1">- {response.topics.map(topic => (- <span key={topic} className="text-xs text-primary">- #- {topic}- </span>++ {/* 图片任务:展示所有生成图片 */}+ {!hasVideo && hasImages && (+ <div className="overflow-x-auto">+ <div className="flex gap-1.5">+ {response.imageUrls!.map((url, i) => (+ <div+ key={i}+ className="relative w-20 h-20 rounded-md overflow-hidden bg-muted cursor-pointer"+ onClick={() => { setPreviewIndex(i); setPreviewOpen(true) }}+ >+ <Image+ src={getOssUrl(url)}+ alt={`result-${i + 1}`}+ fill+ className="object-cover"+ sizes="80px"+ />+ </div>))}</div>- )}- </div>+ </div>+ )}++ {/* 预览 */}+ {previewItems.length > 0 && (+ <MediaPreview+ open={previewOpen}+ items={previewItems}+ initialIndex={previewIndex}+ onClose={() => setPreviewOpen(false)}+ />+ )}</div>)}@@ -222,8 +354,8 @@ const GenerationDetailContent = memo(({ onClose }: { onClose: () => void }) => {GenerationDetailContent.displayName = 'GenerationDetailContent'export const GenerationDetailDialog = memo(() => {- const generationDetailDialogOpen = useDraftBoxStore(state => state.generationDetailDialogOpen)- const closeGenerationDetailDialog = useDraftBoxStore(state => state.closeGenerationDetailDialog)+ const generationDetailDialogOpen = usePlanDetailStore(state => state.generationDetailDialogOpen)+ const closeGenerationDetailDialog = usePlanDetailStore(state => state.closeGenerationDetailDialog)// 两层组件模式if (!generationDetailDialogOpen)diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaCard/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaCard/index.tsxnew file mode 100644index 00000000..fed191eb--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaCard/index.tsx@@ -0,0 +1,93 @@+/**+ * MediaCard - 只读媒体卡片+ * 展示视频/图片缩略图,点击打开预览+ * 视频:缩略图 + 播放图标 + 时长+ * 图片:缩略图,保持原始比例+ */++'use client'++import type { MediaItem } from '@/api/types/media'+import { Play } from 'lucide-react'+import { memo, useCallback } from 'react'+import { getOssUrl } from '@/utils/oss'+import { LazyImage } from '../LazyImage'++interface MediaCardProps {+ /** 媒体数据 */+ media: MediaItem+ /** 点击回调 */+ onClick: (media: MediaItem) => void+}++/**+ * 格式化视频时长+ */+function formatDuration(seconds?: number): string {+ if (!seconds)+ return ''+ const mins = Math.floor(seconds / 60)+ const secs = Math.floor(seconds % 60)+ return `${mins}:${secs.toString().padStart(2, '0')}`+}++export const MediaCard = memo(({ media, onClick }: MediaCardProps) => {+ const isVideo = media.type === 'video'+ const thumbUrl = media.thumbUrl ? getOssUrl(media.thumbUrl) : media.url ? getOssUrl(media.url) : '/images/placeholder.png'+ const duration = (media.metadata as any)?.duration++ const handleClick = useCallback(() => {+ onClick(media)+ }, [media, onClick])++ return (+ <div+ className="mb-4 cursor-pointer group relative"+ onClick={handleClick}+ >+ <div className="relative w-full overflow-hidden rounded-xl">+ <LazyImage+ src={thumbUrl}+ alt={media.title || media.desc || '媒体'}+ width={400}+ height={300}+ className="w-full h-auto transition-transform duration-300 group-hover:scale-105"+ skeletonClassName="rounded-xl"+ placeholderHeight={150}+ style={{ aspectRatio: 'auto' }}+ unoptimized+ />++ {/* 视频播放图标 */}+ {isVideo && (+ <div className="absolute inset-0 flex items-center justify-center">+ <div className="w-10 h-10 rounded-full bg-black/50 flex items-center justify-center group-hover:bg-black/70 transition-colors">+ <Play className="w-5 h-5 text-white fill-white ml-0.5" />+ </div>+ </div>+ )}++ {/* 视频时长标签 */}+ {isVideo && duration && (+ <div className="absolute bottom-2 right-2 px-1.5 py-0.5 bg-black/70 rounded text-xs text-white">+ {formatDuration(duration)}+ </div>+ )}++ {/* 悬浮遮罩 */}+ <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors rounded-xl" />+ </div>++ {/* 标题 */}+ {media.title && (+ <div className="pt-2 px-1">+ <p className="text-sm font-medium text-foreground line-clamp-2">+ {media.title}+ </p>+ </div>+ )}+ </div>+ )+})++MediaCard.displayName = 'MediaCard'diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaListSection/index.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaListSection/index.tsxnew file mode 100644index 00000000..018a8b63--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/draft-box/components/MediaListSection/index.tsx@@ -0,0 +1,208 @@+/**+ * MediaListSection - 媒体列表区域+ * 瀑布流布局 + IntersectionObserver 无限滚动展示视频/图片+ * 只读模式,无创建/批量操作+ */++'use client'++import type { MediaItem } from '@/api/types/media'+import type { MediaPreviewItem } from '@/components/common/MediaPreview'+import { ImageIcon, Video } from 'lucide-react'+import { memo, useCallback, useEffect, useMemo, useRef } from 'react'+import Masonry from 'react-masonry-css'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import { MediaPreview } from '@/components/common/MediaPreview'+import { Skeleton } from '@/components/ui/skeleton'+import { getOssUrl } from '@/utils/oss'+import { useMediaTabStore } from '../ContentTabs/mediaTabStore'+import { MediaCard } from '../MediaCard'++/**+ * 瀑布流断点配置+ */+const MASONRY_BREAKPOINTS = {+ default: 5,+ 1280: 4,+ 1024: 3,+ 768: 3,+ 640: 2,+}++interface MediaListSectionProps {+ type: 'video' | 'img'+ materialGroupId: string+}++// 骨架屏+function MediaCardSkeleton({ index }: { index: number }) {+ const heights = [120, 160, 200, 140, 180, 150, 170, 190]+ const height = heights[index % heights.length]++ return (+ <div className="mb-4">+ <Skeleton className="w-full rounded-xl" style={{ height: `${height}px` }} />+ </div>+ )+}++// 加载更多指示器+const LoadingIndicator = memo(() => (+ <div className="flex justify-center py-4">+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />+ </div>+ </div>+))+LoadingIndicator.displayName = 'LoadingIndicator'++export const MediaListSection = memo(({ type, materialGroupId }: MediaListSectionProps) => {+ const { t } = useTransClient('material')+ const loadMoreRef = useRef<HTMLDivElement>(null)++ const { list, loading, hasMore, initialized, total } = useMediaTabStore(+ useShallow(state => ({+ list: state[type].list,+ loading: state[type].loading,+ hasMore: state[type].hasMore,+ initialized: state[type].initialized,+ total: state[type].total,+ })),+ )++ const { previewOpen, previewIndex, previewType } = useMediaTabStore(+ useShallow(state => ({+ previewOpen: state.previewOpen,+ previewIndex: state.previewIndex,+ previewType: state.previewType,+ })),+ )++ const fetchMediaList = useMediaTabStore(state => state.fetchMediaList)+ const loadMore = useMediaTabStore(state => state.loadMore)+ const openPreview = useMediaTabStore(state => state.openPreview)+ const closePreview = useMediaTabStore(state => state.closePreview)++ // 首次加载+ useEffect(() => {+ if (!initialized && materialGroupId) {+ fetchMediaList(materialGroupId, type)+ }+ }, [initialized, materialGroupId, type, fetchMediaList])++ // IntersectionObserver 无限滚动+ useEffect(() => {+ const loadMoreElement = loadMoreRef.current+ if (!loadMoreElement)+ return++ const observer = new IntersectionObserver(+ (entries) => {+ const [entry] = entries+ if (entry.isIntersecting && hasMore && !loading && materialGroupId) {+ loadMore(materialGroupId, type)+ }+ },+ { threshold: 0.1 },+ )++ observer.observe(loadMoreElement)+ return () => observer.disconnect()+ }, [hasMore, loading, materialGroupId, type, loadMore])++ // 点击媒体卡片+ const handleMediaClick = useCallback((media: MediaItem) => {+ const index = list.findIndex(m => m._id === media._id)+ if (index !== -1) {+ openPreview(type, index)+ }+ }, [list, type, openPreview])++ // 预览项列表+ const previewItems = useMemo((): MediaPreviewItem[] => {+ return list.map(media => ({+ type: media.type === 'video' ? 'video' : 'image',+ src: getOssUrl(media.url),+ title: media.title,+ }))+ }, [list])++ // 初始加载骨架屏+ if (loading && list.length === 0) {+ return (+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ {Array.from({ length: 8 }).map((_, i) => (+ <MediaCardSkeleton key={i} index={i} />+ ))}+ </Masonry>+ )+ }++ // 空状态+ if (initialized && list.length === 0) {+ const Icon = type === 'video' ? Video : ImageIcon+ return (+ <div className="flex flex-col items-center justify-center py-12">+ <div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">+ <Icon className="w-8 h-8 text-muted-foreground" />+ </div>+ <p className="text-sm font-medium text-foreground mb-1">+ {type === 'video' ? t('mediaManagement.noVideo') : t('mediaManagement.noImage')}+ </p>+ <p className="text-sm text-muted-foreground">+ {type === 'video' ? t('mediaManagement.noVideoDesc') : t('mediaManagement.noImageDesc')}+ </p>+ </div>+ )+ }++ return (+ <>+ <Masonry+ breakpointCols={MASONRY_BREAKPOINTS}+ className="flex -ml-4 w-auto"+ columnClassName="pl-4 bg-clip-padding"+ >+ {list.map(media => (+ <MediaCard+ key={media._id}+ media={media}+ onClick={handleMediaClick}+ />+ ))}+ </Masonry>++ {/* 加载触发器 */}+ <div ref={loadMoreRef} />++ {/* 加载更多指示器 */}+ {loading && <LoadingIndicator />}++ {/* 没有更多数据 */}+ {!hasMore && list.length > 0 && (+ <div className="flex items-center justify-center py-4">+ <span className="text-sm text-muted-foreground">+ {t('mediaManagement.loadedAll')}+ </span>+ </div>+ )}++ {/* 媒体预览弹窗 - 仅当前 type 匹配时渲染 */}+ {previewType === type && (+ <MediaPreview+ open={previewOpen}+ items={previewItems}+ initialIndex={previewIndex}+ onClose={closePreview}+ />+ )}+ </>+ )+})++MediaListSection.displayName = 'MediaListSection'diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxConfigStore.ts b/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxConfigStore.tsindex d52e2b94..6bada8ad 100644--- a/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxConfigStore.ts+++ b/project/aitoearn-web/src/app/[lng]/draft-box/draftBoxConfigStore.ts@@ -34,6 +34,10 @@ export interface DraftBoxConfig {selectedImageIds: string[]/** AI 生成描述 */promptValue: string+ /** 是否为草稿模式(true=生成完整草稿,false=仅生成视频/图片) */+ isDraftMode: boolean+ /** 关联的品牌 ID,用于检测品牌切换后重新应用默认值 */+ linkedBrandId: string}/** 默认配置(与原 systemStore 一致) */@@ -50,6 +54,8 @@ const DEFAULT_CONFIG: DraftBoxConfig = {persistedMedias: [],selectedImageIds: [],promptValue: '',+ isDraftMode: true,+ linkedBrandId: '',}interface IDraftBoxConfigStore {@@ -91,7 +97,7 @@ export const useDraftBoxConfigStore = createPersistStore(}),{name: 'DraftBoxConfig',- version: 5,+ version: 7,migrate(persistedState: any, version: number) {if (version < 2) {// v1 → v2: 给已有配置补 persistedMedias 字段@@ -123,6 +129,26 @@ export const useDraftBoxConfigStore = createPersistStore(}persistedState.configs = configs}+ if (version < 6) {+ // v5 → v6: 给已有配置补 isDraftMode 字段+ const configs = persistedState.configs ?? {}+ for (const key of Object.keys(configs)) {+ if (configs[key].isDraftMode === undefined) {+ configs[key].isDraftMode = true+ }+ }+ persistedState.configs = configs+ }+ if (version < 7) {+ // v6 → v7: 给已有配置补 linkedBrandId 字段+ const configs = persistedState.configs ?? {}+ for (const key of Object.keys(configs)) {+ if (configs[key].linkedBrandId === undefined) {+ configs[key].linkedBrandId = ''+ }+ }+ persistedState.configs = configs+ }return persistedState},},diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/page.tsx b/project/aitoearn-web/src/app/[lng]/draft-box/page.tsxdeleted file mode 100644index da8b5b69..00000000--- a/project/aitoearn-web/src/app/[lng]/draft-box/page.tsx+++ /dev/null@@ -1,38 +0,0 @@-/**- * 草稿箱页面- * 独立页面展示 AI 批量生成 + 草稿列表 + 相关弹窗- */--import dynamic from 'next/dynamic'-import { useTranslation } from '@/app/i18n'-import { fallbackLng, languages } from '@/lib/i18n/languageConfig'-import { getMetadata } from '@/utils/server-general'--interface PageParams {- params: Promise<{ lng: string }>-}--export async function generateMetadata({ params }: PageParams) {- let { lng } = await params- if (!languages.includes(lng))- lng = fallbackLng- const { t } = await useTranslation(lng, 'common')-- return getMetadata(- {- title: t('header.draftBoxSeoTitle'),- description: t('header.draftBoxSeoDescription'),- keywords: t('header.draftBoxSeoKeywords'),- },- lng,- '/draft-box',- )-}--const DraftBoxCore = dynamic(() => import('./DraftBoxCore'), {- ssr: false,-})--export default function DraftBoxPage() {- return <DraftBoxCore />-}diff --git a/project/aitoearn-web/src/app/[lng]/draft-box/types.ts b/project/aitoearn-web/src/app/[lng]/draft-box/types.tsdeleted file mode 100644index 40b038ae..00000000--- a/project/aitoearn-web/src/app/[lng]/draft-box/types.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * 草稿箱模块类型定义- * 包含草稿组、素材、分页相关类型- */--import type { PlatType } from '@/app/config/platConfig'-import type { PubType } from '@/app/config/publishConfig'--// ==================== 草稿组相关类型 ====================--/** 草稿组(素材组) */-export interface DraftGroup {- _id: string- name: string- title?: string- type: PubType- /** 发布平台 */- platform?: PlatType- desc?: string- createdAt?: string- updatedAt?: string- /** 组内素材数量 */- mediaCount?: number- /** 是否为默认组 */- isDefault?: boolean-}--// ==================== 素材相关类型 ====================--/** 媒体资源类型 */-export type MaterialMediaType = 'img' | 'video'--/** 媒体资源 */-export interface MaterialMedia {- url: string- type: MaterialMediaType- content?: string-}--/** 草稿素材 */-export interface DraftMaterial {- _id: string- groupId: string- title: string- desc?: string- coverUrl?: string- mediaList: MaterialMedia[]- type?: PubType- status: 0 | 1 // 0: 生成中, 1: 已生成- location?: [number, number]- option?: Record<string, unknown>- createdAt?: string- /** 使用次数 */- useCount?: number- /** 话题标签 */- topics?: string[]- /** AI 生成模型 */- model?: string-}--// ==================== 分页相关类型 ====================--/** 分页信息 */-export interface Pagination {- current: number- pageSize: number- total: number- hasMore: boolean-}diff --git a/project/aitoearn-web/src/app/[lng]/layout.tsx b/project/aitoearn-web/src/app/[lng]/layout.tsxindex 4107b533..ed5c22c6 100644--- a/project/aitoearn-web/src/app/[lng]/layout.tsx+++ b/project/aitoearn-web/src/app/[lng]/layout.tsx@@ -1,15 +1,14 @@import { dir } from 'i18next'+import { headers } from 'next/headers'import Script from 'next/script'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import AnnouncementBanner from '@/app/layout/AnnouncementBanner'import LayoutSidebar from '@/app/layout/LayoutSidebar'import { MainContent } from '@/app/layout/MainContent'import MobileNav from '@/app/layout/MobileNav'import { ChannelManager } from '@/components/ChannelManager'import { StructuredData } from '@/components/SEO/StructuredData'import { getHreflang } from '@/lib/i18n/languageConfig'-import { getBaseUrl } from '@/utils/server-general'import { Providers } from '../layout/Providers'import '@/app/var.css'import '../globals.css'@@ -20,7 +19,10 @@ export async function generateMetadata({ params }: { params: Promise<{ lng: strilng = fallbackLngconst { t } = await useTranslation(lng)- const baseUrl = await getBaseUrl()+ const headersList = await headers()+ const host = headersList.get('host') || 'localhost:3000'+ const proto = headersList.get('x-forwarded-proto') || 'https'+ const baseUrl = `${proto}://${host}`// 生成hreflang链接const alternateRefs = languages.map(lang => ({@@ -52,7 +54,11 @@ export default async function RootLayout({params: Promise<{ lng: string }>}>) {const { lng } = await params- const baseUrl = await getBaseUrl()+ const headersList = await headers()+ const host = headersList.get('host') || 'localhost:3000'+ const proto = headersList.get('x-forwarded-proto') || 'https'+ const baseUrl = `${proto}://${host}`+ const autoLoginToken = process.env.AUTO_LOGIN_TOKEN || ''return (<html lang={lng} dir={dir(lng)} suppressHydrationWarning>@@ -93,7 +99,7 @@ export default async function RootLayout({}}/><Script src="https://r.wdfl.co/rw.js" data-rewardful="ded70f" strategy="afterInteractive" />- <Providers lng={lng}>+ <Providers lng={lng} autoLoginToken={autoLoginToken}>{/* 全局频道管理弹框 */}<ChannelManager /><p className="hidden">Impact-Site-Verification: f9836212-462a-482f-9232-8a877970eacf</p>@@ -103,7 +109,7 @@ export default async function RootLayout({{/* 桌面端侧边栏 */}<LayoutSidebar />{/* 主内容区域 - 根据页面类型动态控制 pt-14 */}- <MainContent banner={<AnnouncementBanner />}>{children}</MainContent>+ <MainContent>{children}</MainContent>{/* eslint-disable-next-line next/no-sync-scripts */}<script src="/js/xhs_web_sign.js" />{/* eslint-disable-next-line next/no-sync-scripts */}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumDetailCore.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumDetailCore.tsxdeleted file mode 100644index f54fc51b..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumDetailCore.tsx+++ /dev/null@@ -1,117 +0,0 @@-'use client'--import { PictureOutlined, PlayCircleOutlined, PlusOutlined, SoundOutlined } from '@ant-design/icons'-import { Button, Card, Col, Row, Typography, Upload } from 'antd'-import Image from 'next/image'-import { useRouter } from 'next/navigation'-import { useEffect, useState } from 'react'-import { toast } from '@/lib/toast'-import styles from './albumDetail.module.scss'--const { Title } = Typography--interface Material {- id: string- name: string- url: string- type: 'video' | 'img'- createTime: string-}--interface AlbumDetailCoreProps {- albumId: string-}--export function AlbumDetailCore({ albumId }: AlbumDetailCoreProps) {- const router = useRouter()- const [materials, setMaterials] = useState<Material[]>([])- const [albumInfo, setAlbumInfo] = useState({- name: '视频素材',- type: 'video' as 'video' | 'img',- count: 0,- })-- useEffect(() => {- // 这里应该调用API获取素材库信息和素材列表- // 暂时使用模拟数据- setMaterials([- {- id: '1',- name: '示例视频1',- url: 'https://example.com/video1.mp4',- type: 'video',- createTime: '2024-01-01',- },- // 更多素材...- ])- }, [albumId])-- const handleUpload = (file: File) => {- // 这里应该调用API上传素材- toast.success('上传成功')- return false- }-- const getTypeIcon = (type: string) => {- switch (type) {- case 'video':- return <PlayCircleOutlined />- case 'img':- return <PictureOutlined />- case 'audio':- return <SoundOutlined />- default:- return null- }- }-- return (- <div className={styles.albumDetailContainer}>- <div className={styles.header}>- <div className={styles.titleSection}>- <Title level={2}>{albumInfo.name}</Title>- <span className={styles.typeTag}>{albumInfo.type === 'video' ? '视频' : '图片'}</span>- </div>- <Upload- accept={albumInfo.type === 'video' ? 'video/*' : 'image/*'}- showUploadList={false}- beforeUpload={handleUpload}- >- <Button type="primary" icon={<PlusOutlined />}>- 上传素材- </Button>- </Upload>- </div>-- <Row gutter={[24, 24]}>- {materials.map(material => (- <Col xs={24} sm={12} md={8} lg={6} key={material.id}>- <Card- hoverable- cover={(- <div className={styles.coverWrapper}>- <Image alt={material.name} src={material.url} width={300} height={300} className="w-full h-auto object-cover" unoptimized />- {material.type === 'video' && (- <div className={styles.videoIcon}>- <PlayCircleOutlined />- </div>- )}- </div>- )}- >- <Card.Meta- title={material.name}- description={(- <div className={styles.materialInfo}>- <span>{material.createTime}</span>- <span className={styles.typeIcon}>{getTypeIcon(material.type)}</span>- </div>- )}- />- </Card>- </Col>- ))}- </Row>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumStore/index.ts b/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumStore/index.tsdeleted file mode 100644index a759c496..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/albumStore/index.ts+++ /dev/null@@ -1,502 +0,0 @@-/**- * albumStore - 相册详情页状态管理- * 管理媒体资源的 CRUD 操作和 UI 状态- */--import lodash from 'lodash'-import { create } from 'zustand'-import { combine } from 'zustand/middleware'-import { createMedia, deleteMedia, getMediaList } from '@/api/media'-import { uploadToOss } from '@/api/oss'-import { VideoGrabFrame } from '@/components/PublishDialog/PublishDialog.util'-import { toast } from '@/lib/toast'-import { getOssUrl } from '@/utils/oss'--/**- * 媒体资源类型- */-export interface Media {- _id: string- name: string- url: string- /** 缩略图 URL(视频封面/图片缩略图) */- thumbUrl: string- type: 'video' | 'img'- title: string- desc: string- /** 创建时间 */- createdAt: string-}--/**- * 上传任务类型- */-export interface UploadTask {- /** 任务唯一标识 */- id: string- /** 文件对象 */- file: File- /** 文件名 */- fileName: string- /** 上传进度 0-100 */- progress: number- /** 任务状态 */- status: 'pending' | 'uploading' | 'success' | 'error'- /** 错误信息 */- error?: string-}--/**- * 分组信息类型- */-export interface GroupInfo {- _id: string- title: string- type: 'video' | 'img'- desc: string-}--/**- * albumStore 状态类型- */-export interface IAlbumStore {- // 分组信息- groupInfo: GroupInfo | null-- // 媒体列表- mediaList: Media[]- total: number-- // 状态- isLoading: boolean- isUploading: boolean- isDeleting: boolean- /** 是否正在加载更多 */- isLoadingMore: boolean-- // 分页(无限滚动模式)- currentPage: number- pageSize: number- /** 是否还有更多数据 */- hasMore: boolean-- // 上传队列- uploadQueue: UploadTask[]-- // 预览- previewOpen: boolean- previewIndex: number-}--/**- * 初始状态- */-const initialState: IAlbumStore = {- groupInfo: null,- mediaList: [],- total: 0,- isLoading: false,- isUploading: false,- isDeleting: false,- isLoadingMore: false,- currentPage: 1,- pageSize: 20,- hasMore: true,- uploadQueue: [],- previewOpen: false,- previewIndex: 0,-}--/**- * 获取初始状态的深拷贝- */-function getInitialState(): IAlbumStore {- return lodash.cloneDeep(initialState)-}--/**- * 相册详情 Store- */-export const useAlbumStore = create(- combine({ ...getInitialState() }, (set, get) => {- const methods = {- /**- * 重置 Store 到初始状态- */- reset() {- set(getInitialState())- },-- /**- * 设置分组信息- */- setGroupInfo(groupInfo: GroupInfo) {- set({ groupInfo })- },-- /**- * 设置当前页码并重新加载- */- setCurrentPage(page: number) {- set({ currentPage: page })- },-- /**- * 打开预览- */- openPreview(index: number) {- set({ previewOpen: true, previewIndex: index })- },-- /**- * 关闭预览- */- closePreview() {- set({ previewOpen: false })- },-- /**- * 获取媒体列表(首次加载,重置列表)- */- async fetchMediaList(groupId: string) {- set({ isLoading: true, currentPage: 1, hasMore: true })-- try {- const response: any = await getMediaList(groupId, 1, get().pageSize)-- if (response?.data?.list) {- const list = response.data.list- const total = response.data.total || 0- set({- mediaList: list,- total,- hasMore: list.length < total,- })- }- else {- set({ mediaList: [], total: 0, hasMore: false })- }- }- catch (error) {- console.error('Failed to fetch media list:', error)- toast.error('获取媒体资源列表失败')- set({ mediaList: [], total: 0, hasMore: false })- }- finally {- set({ isLoading: false })- }- },-- /**- * 加载更多(无限滚动)- */- async loadMore(groupId: string) {- const { isLoadingMore, hasMore, currentPage, pageSize, mediaList } = get()- if (isLoadingMore || !hasMore)- return-- const nextPage = currentPage + 1- set({ isLoadingMore: true })-- try {- const response: any = await getMediaList(groupId, nextPage, pageSize)-- if (response?.data?.list) {- const newList = response.data.list- const total = response.data.total || 0- const combinedList = [...mediaList, ...newList]-- set({- mediaList: combinedList,- total,- currentPage: nextPage,- hasMore: combinedList.length < total,- })- }- else {- set({ hasMore: false })- }- }- catch (error) {- console.error('Failed to load more media:', error)- toast.error('加载更多失败')- }- finally {- set({ isLoadingMore: false })- }- },-- /**- * 根据资源组类型获取允许的文件类型- */- getAcceptTypes(): string {- const { groupInfo } = get()- if (!groupInfo)- return 'image/*,video/*'-- switch (groupInfo.type) {- case 'video':- return 'video/*'- case 'img':- return 'image/*'- default:- return 'image/*,video/*'- }- },-- /**- * 验证文件类型是否匹配资源组类型- */- validateFileType(file: File): boolean {- const { groupInfo } = get()- if (!groupInfo)- return true-- const fileType = file.type- switch (groupInfo.type) {- case 'video':- return fileType.startsWith('video/')- case 'img':- return fileType.startsWith('image/')- default:- return true- }- },-- /**- * 上传媒体资源(单个文件,带进度)- */- async uploadMedia(groupId: string, file: File): Promise<boolean> {- const { groupInfo } = get()-- // 验证文件类型- if (!methods.validateFileType(file)) {- const typeMap = {- video: '视频',- img: '图片',- }- toast.error(`此资源组只允许上传${typeMap[groupInfo!.type]}文件`)- return false- }-- set({ isUploading: true })-- try {- // 上传文件到 OSS- const url = await uploadToOss(file)-- // 获取缩略图- let thumbUrl: string- if (file.type.startsWith('video/')) {- // 视频:提取第一帧作为封面- const res = await VideoGrabFrame(URL.createObjectURL(file), 0)- const blob = res.cover.file- const fileName = `${file.name.replace(/\.[^/.]+$/, '')}_cover.png`- const coverFile = new File([blob], fileName, {- type: blob.type || 'image/png',- })- thumbUrl = await uploadToOss(coverFile)- }- else {- // 图片:使用原图作为缩略图- thumbUrl = url- }-- // 创建媒体资源- await createMedia({- groupId,- type: file.type.startsWith('video/') ? 'video' : 'img',- url,- title: file.name,- desc: '',- thumbUrl,- })-- toast.success('上传成功')- await methods.fetchMediaList(groupId)- return true- }- catch (error) {- console.error('Failed to upload media:', error)- toast.error('上传失败')- return false- }- finally {- set({ isUploading: false })- }- },-- /**- * 批量上传媒体资源- */- async uploadMultipleMedia(groupId: string, files: File[]) {- const { groupInfo } = get()-- // 过滤不符合类型的文件- const validFiles = files.filter((file) => {- if (!methods.validateFileType(file)) {- const typeMap = { video: '视频', img: '图片' }- toast.error(`${file.name} 不是${typeMap[groupInfo!.type]}文件,已跳过`)- return false- }- return true- })-- if (validFiles.length === 0)- return-- // 创建上传任务- const tasks: UploadTask[] = validFiles.map(file => ({- id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,- file,- fileName: file.name,- progress: 0,- status: 'pending' as const,- }))-- // 添加到上传队列- set(state => ({- uploadQueue: [...state.uploadQueue, ...tasks],- isUploading: true,- }))-- // 逐个上传- for (const task of tasks) {- // 更新状态为上传中- set(state => ({- uploadQueue: state.uploadQueue.map(t =>- t.id === task.id ? { ...t, status: 'uploading' as const } : t,- ),- }))-- try {- // 上传文件到 OSS(带进度回调)- const url = await uploadToOss(task.file, {- onProgress: (percent: number) => {- set(state => ({- uploadQueue: state.uploadQueue.map(t =>- t.id === task.id ? { ...t, progress: Math.round(percent) } : t,- ),- }))- },- })-- // 获取缩略图- let thumbUrl: string- if (task.file.type.startsWith('video/')) {- const res = await VideoGrabFrame(URL.createObjectURL(task.file), 0)- const blob = res.cover.file- const fileName = `${task.file.name.replace(/\.[^/.]+$/, '')}_cover.png`- const coverFile = new File([blob], fileName, {- type: blob.type || 'image/png',- })- thumbUrl = await uploadToOss(coverFile)- }- else {- thumbUrl = url- }-- // 创建媒体资源- await createMedia({- groupId,- type: task.file.type.startsWith('video/') ? 'video' : 'img',- url,- title: task.file.name,- desc: '',- thumbUrl,- })-- // 更新状态为成功- set(state => ({- uploadQueue: state.uploadQueue.map(t =>- t.id === task.id ? { ...t, status: 'success' as const, progress: 100 } : t,- ),- }))- }- catch (error) {- console.error('Failed to upload file:', task.fileName, error)- // 更新状态为失败- set(state => ({- uploadQueue: state.uploadQueue.map(t =>- t.id === task.id ? { ...t, status: 'error' as const, error: '上传失败' } : t,- ),- }))- }- }-- // 刷新列表- await methods.fetchMediaList(groupId)- set({ isUploading: false })-- // 3秒后清理已完成的任务- setTimeout(() => {- set(state => ({- uploadQueue: state.uploadQueue.filter(t => t.status !== 'success'),- }))- }, 3000)- },-- /**- * 取消上传任务- */- cancelUpload(taskId: string) {- set(state => ({- uploadQueue: state.uploadQueue.filter(t => t.id !== taskId),- }))- },-- /**- * 清空已完成的上传任务- */- clearCompletedUploads() {- set(state => ({- uploadQueue: state.uploadQueue.filter(- t => t.status !== 'success' && t.status !== 'error',- ),- }))- },-- /**- * 删除媒体资源(本地移除,适配无限滚动)- */- async deleteMedia(_groupId: string, mediaId: string): Promise<boolean> {- set({ isDeleting: true })-- try {- await deleteMedia(mediaId)-- // 本地移除该项,不重新加载- set(state => ({- mediaList: state.mediaList.filter(m => m._id !== mediaId),- total: Math.max(0, state.total - 1),- }))-- toast.success('删除成功')- return true- }- catch (error) {- console.error('Failed to delete media:', error)- toast.error('删除失败')- return false- }- finally {- set({ isDeleting: false })- }- },-- /**- * 获取预览项列表(用于 MediaPreview 组件)- */- getPreviewItems() {- const { mediaList } = get()- return mediaList.map(media => ({- type: media.type === 'video' ? 'video' : 'image',- src: getOssUrl(media.url),- title: media.title,- })) as Array<{ type: 'image' | 'video', src: string, title?: string }>- },- }-- return methods- }),-)diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/AlbumHeader/index.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/AlbumHeader/index.tsxdeleted file mode 100644index 6cd2a5b0..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/AlbumHeader/index.tsx+++ /dev/null@@ -1,129 +0,0 @@-/**- * AlbumHeader - 相册页顶部组件- * 包含返回按钮、标题、上传按钮- */--'use client'--import type { GroupInfo } from '../../albumStore'-import { ArrowLeft, Image as ImageIcon, Plus, Video } from 'lucide-react'-import { useRouter } from 'next/navigation'-import { useCallback, useRef } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'--interface AlbumHeaderProps {- /** 分组信息 */- groupInfo: GroupInfo | null- /** 总数量 */- total: number- /** 是否正在上传 */- isUploading?: boolean- /** 允许的文件类型 */- acceptTypes: string- /** 上传多个文件回调 */- onUpload: (files: File[]) => void-}--export function AlbumHeader({- groupInfo,- total,- isUploading,- acceptTypes,- onUpload,-}: AlbumHeaderProps) {- const { t } = useTransClient('material')- const router = useRouter()- const fileInputRef = useRef<HTMLInputElement>(null)-- // 返回素材库- const handleBack = useCallback(() => {- router.push('/material')- }, [router])-- // 触发文件选择- const handleUploadClick = useCallback(() => {- fileInputRef.current?.click()- }, [])-- // 处理文件选择- const handleFileChange = useCallback(- (e: React.ChangeEvent<HTMLInputElement>) => {- const files = e.target.files- if (files && files.length > 0) {- onUpload(Array.from(files))- }- // 清空文件选择,允许重复选择同一文件- e.target.value = ''- },- [onUpload],- )-- // 获取类型显示文本- const getTypeText = () => {- if (!groupInfo)- return t('mediaManagement.mediaResources')- return groupInfo.type === 'video' ? t('mediaManagement.video') : t('mediaManagement.image')- }-- // 获取上传按钮文本- const getUploadText = () => {- if (!groupInfo)- return t('mediaManagement.upload')- return groupInfo.type === 'video'- ? t('mediaManagement.uploadVideo')- : t('mediaManagement.uploadImage')- }-- return (- <header className="sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-card border-b border-border">- <div className="flex items-center gap-3">- <Button variant="ghost" size="icon" onClick={handleBack} className="w-8 h-8">- <ArrowLeft className="w-5 h-5" />- </Button>-- <div className="flex items-center gap-2">- {groupInfo?.type === 'video' ? (- <Video className="w-5 h-5 text-blue-500" />- ) : (- <ImageIcon className="w-5 h-5 text-green-500" />- )}- <h1 className="text-lg font-semibold text-foreground">- {groupInfo?.title || t('mediaManagement.mediaResources')}- </h1>- <span className="text-sm text-muted-foreground">- ·- {getTypeText()}- </span>- </div>-- {total > 0 && (- <span className="text-sm text-muted-foreground">- (- {total}- )- </span>- )}- </div>-- <div className="flex items-center gap-2">- {/* 隐藏的文件输入 */}- <input- ref={fileInputRef}- type="file"- accept={acceptTypes}- onChange={handleFileChange}- className="hidden"- multiple- />-- {/* 上传按钮 */}- <Button onClick={handleUploadClick} disabled={isUploading} loading={isUploading} size="sm">- <Plus className="w-4 h-4 mr-1" />- <span className="hidden sm:inline">{getUploadText()}</span>- <span className="sm:hidden">{t('mediaManagement.upload')}</span>- </Button>- </div>- </header>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/MediaCardSkeleton.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/MediaCardSkeleton.tsxdeleted file mode 100644index fe098e4b..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/MediaCardSkeleton.tsx+++ /dev/null@@ -1,27 +0,0 @@-/**- * MediaCardSkeleton - 媒体卡片骨架屏- * 用于列表加载时的占位显示- */--import { Skeleton } from '@/components/ui/skeleton'--export function MediaCardSkeleton() {- return (- <div className="rounded-xl border border-border bg-card overflow-hidden">- {/* 媒体区域骨架 */}- <div className="relative aspect-square">- <Skeleton className="absolute inset-0" />- {/* 类型图标骨架 */}- <Skeleton className="absolute bottom-2 left-2 w-6 h-6 rounded-full" />- </div>-- {/* 内容区域骨架 */}- <div className="p-3 space-y-2">- {/* 标题骨架 */}- <Skeleton className="h-4 w-3/4" />- {/* 描述骨架 */}- <Skeleton className="h-3 w-1/2" />- </div>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/index.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/index.tsxdeleted file mode 100644index 55f7f67c..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/MediaCard/index.tsx+++ /dev/null@@ -1,139 +0,0 @@-/**- * MediaCard - 媒体卡片组件- * 展示单个媒体资源(图片/视频)- */--'use client'--import type { Media } from '../../albumStore'-import dayjs from 'dayjs'-import { motion } from 'framer-motion'-import { Image as ImageIcon, Play, Trash2, Video } from 'lucide-react'-import Image from 'next/image'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { confirm } from '@/lib/confirm'-import { cn } from '@/lib/utils'-import { getOssUrl } from '@/utils/oss'--interface MediaCardProps {- /** 媒体数据 */- media: Media- /** 点击预览回调 */- onPreview: (media: Media) => void- /** 删除回调 */- onDelete: (id: string) => void- /** 是否正在删除 */- isDeleting?: boolean-}--export function MediaCard({ media, onPreview, onDelete, isDeleting }: MediaCardProps) {- const { t } = useTransClient('material')-- // 处理点击预览- const handleClick = () => {- onPreview(media)- }-- // 处理删除- const handleDelete = async (e: React.MouseEvent) => {- e.stopPropagation()- const confirmed = await confirm({- title: t('mediaManagement.delete'),- content: t('mediaManagement.deleteMediaConfirm'),- okText: t('mediaManagement.delete'),- cancelText: t('mediaManagement.cancel'),- okType: 'destructive',- })- if (confirmed) {- onDelete(media._id)- }- }-- const isVideo = media.type === 'video'- // 优先使用缩略图,其次使用原图- const thumbUrl = getOssUrl(media.thumbUrl || media.url)-- // 格式化创建时间- const formatCreatedAt = () => {- if (!media.createdAt)- return null- return dayjs(media.createdAt).format('YYYY-MM-DD HH:mm')- }-- return (- <motion.div- layout- initial={{ opacity: 0, scale: 0.9 }}- animate={{ opacity: 1, scale: 1 }}- exit={{ opacity: 0, scale: 0.9 }}- transition={{ duration: 0.2 }}- onClick={handleClick}- className={cn(- 'rounded-xl border border-border bg-card overflow-hidden cursor-pointer group',- 'hover:shadow-lg transition-shadow duration-200',- isDeleting && 'opacity-50 pointer-events-none',- )}- >- {/* 媒体预览区域 */}- <div className="relative aspect-square bg-muted overflow-hidden">- {/* 缩略图 */}- <Image- src={thumbUrl}- alt={media.title}- fill- className="object-cover transition-transform duration-300 group-hover:scale-105"- sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"- />-- {/* 视频播放按钮覆盖层 */}- {isVideo && (- <div className="absolute inset-0 flex items-center justify-center bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity">- <div className="w-14 h-14 rounded-full bg-white/90 flex items-center justify-center">- <Play className="w-6 h-6 text-blue-500 ml-1" />- </div>- </div>- )}-- {/* 删除按钮 */}- <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">- <Button- variant="secondary"- size="icon"- className="w-8 h-8 bg-black/50 hover:bg-destructive text-white border-0 backdrop-blur-sm"- onClick={handleDelete}- >- <Trash2 className="w-4 h-4" />- </Button>- </div>-- {/* 类型图标 */}- <div- className={cn(- 'absolute bottom-2 left-2 w-6 h-6 rounded-full flex items-center justify-center backdrop-blur-sm',- isVideo ? 'bg-blue-500/80' : 'bg-green-500/80',- )}- >- {isVideo ? (- <Video className="w-3 h-3 text-white" />- ) : (- <ImageIcon className="w-3 h-3 text-white" />- )}- </div>- </div>-- {/* 标题和时间区域 */}- <div className="p-3">- <h3 className="text-sm font-medium text-foreground truncate">{media.title}</h3>- {media.desc && <p className="text-xs text-muted-foreground truncate mt-1">{media.desc}</p>}- {formatCreatedAt() && (- <p className="text-xs text-muted-foreground mt-1">- {t('mediaManagement.createdAt')}- {' '}- {formatCreatedAt()}- </p>- )}- </div>- </motion.div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadProgress/index.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadProgress/index.tsxdeleted file mode 100644index d54a172f..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadProgress/index.tsx+++ /dev/null@@ -1,167 +0,0 @@-/**- * UploadProgress - 上传进度浮动面板- * 显示批量上传的进度和状态- */--'use client'--import type { UploadTask } from '../../albumStore'-import { AnimatePresence, motion } from 'framer-motion'-import { CheckCircle, ChevronDown, ChevronUp, Loader2, X, XCircle } from 'lucide-react'-import { useState } from 'react'-import { useShallow } from 'zustand/react/shallow'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { Progress } from '@/components/ui/progress'-import { cn } from '@/lib/utils'-import { useAlbumStore } from '../../albumStore'--export function UploadProgress() {- const { t } = useTransClient('material')- const [isCollapsed, setIsCollapsed] = useState(false)-- const { uploadQueue, cancelUpload, clearCompletedUploads } = useAlbumStore(- useShallow(state => ({- uploadQueue: state.uploadQueue,- cancelUpload: state.cancelUpload,- clearCompletedUploads: state.clearCompletedUploads,- })),- )-- // 没有上传任务时不显示- if (uploadQueue.length === 0) {- return null- }-- // 计算统计信息- const completedCount = uploadQueue.filter(t => t.status === 'success').length- const errorCount = uploadQueue.filter(t => t.status === 'error').length- const uploadingCount = uploadQueue.filter(- t => t.status === 'uploading' || t.status === 'pending',- ).length- const totalProgress = uploadQueue.reduce((acc, t) => acc + t.progress, 0) / uploadQueue.length-- // 获取任务状态图标- const getStatusIcon = (task: UploadTask) => {- switch (task.status) {- case 'success':- return <CheckCircle className="w-4 h-4 text-green-500 shrink-0" />- case 'error':- return <XCircle className="w-4 h-4 text-destructive shrink-0" />- case 'uploading':- return <Loader2 className="w-4 h-4 text-primary animate-spin shrink-0" />- default:- return <div className="w-4 h-4 rounded-full border-2 border-muted-foreground/30 shrink-0" />- }- }-- return (- <motion.div- initial={{ opacity: 0, y: 20, scale: 0.95 }}- animate={{ opacity: 1, y: 0, scale: 1 }}- exit={{ opacity: 0, y: 20, scale: 0.95 }}- className="fixed bottom-4 right-4 z-50 w-80 bg-card border border-border rounded-lg shadow-xl overflow-hidden"- >- {/* 头部 */}- <div- className="flex items-center justify-between px-4 py-3 bg-muted/50 cursor-pointer"- onClick={() => setIsCollapsed(!isCollapsed)}- >- <div className="flex items-center gap-2">- {uploadingCount > 0 && <Loader2 className="w-4 h-4 text-primary animate-spin" />}- <span className="font-medium text-sm">{t('mediaManagement.uploadProgress')}</span>- <span className="text-xs text-muted-foreground">- (- {completedCount}- /- {uploadQueue.length}- )- </span>- </div>- <div className="flex items-center gap-1">- {(completedCount > 0 || errorCount > 0) && (- <Button- variant="ghost"- size="icon"- className="w-6 h-6"- onClick={(e) => {- e.stopPropagation()- clearCompletedUploads()- }}- >- <X className="w-3 h-3" />- </Button>- )}- {isCollapsed ? (- <ChevronUp className="w-4 h-4 text-muted-foreground" />- ) : (- <ChevronDown className="w-4 h-4 text-muted-foreground" />- )}- </div>- </div>-- {/* 总进度条 */}- {!isCollapsed && uploadingCount > 0 && (- <div className="px-4 py-2 border-b border-border">- <Progress value={totalProgress} className="h-1" />- </div>- )}-- {/* 任务列表 */}- <AnimatePresence>- {!isCollapsed && (- <motion.div- initial={{ height: 0 }}- animate={{ height: 'auto' }}- exit={{ height: 0 }}- className="overflow-hidden"- >- <div className="max-h-64 overflow-y-auto">- {uploadQueue.map(task => (- <motion.div- key={task.id}- initial={{ opacity: 0, x: -10 }}- animate={{ opacity: 1, x: 0 }}- exit={{ opacity: 0, x: 10 }}- className={cn(- 'flex items-center gap-3 px-4 py-2 border-b border-border last:border-0',- task.status === 'error' && 'bg-destructive/5',- )}- >- {getStatusIcon(task)}- <div className="flex-1 min-w-0">- <p className="text-sm truncate" title={task.fileName}>- {task.fileName}- </p>- {task.status === 'uploading' && (- <Progress value={task.progress} className="h-1 mt-1" />- )}- {task.status === 'error' && task.error && (- <p className="text-xs text-destructive mt-0.5">{task.error}</p>- )}- </div>- {task.status === 'uploading' && (- <span className="text-xs text-muted-foreground shrink-0">- {task.progress}- %- </span>- )}- {(task.status === 'pending' || task.status === 'uploading') && (- <Button- variant="ghost"- size="icon"- className="w-6 h-6 shrink-0"- onClick={() => cancelUpload(task.id)}- >- <X className="w-3 h-3" />- </Button>- )}- </motion.div>- ))}- </div>- </motion.div>- )}- </AnimatePresence>- </motion.div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadSection/index.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadSection/index.tsxdeleted file mode 100644index 7e3f92d1..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/components/UploadSection/index.tsx+++ /dev/null@@ -1,96 +0,0 @@-/**- * AlbumEmptyState - 相册空状态组件- * 当没有媒体资源时显示- */--'use client'--import type { GroupInfo } from '../../albumStore'-import { Image as ImageIcon, Plus, Video } from 'lucide-react'-import { useRef } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'--interface AlbumEmptyStateProps {- /** 分组信息 */- groupInfo: GroupInfo | null- /** 允许的文件类型 */- acceptTypes: string- /** 上传多个文件回调 */- onUpload: (files: File[]) => void- /** 是否正在上传 */- isUploading?: boolean-}--export function AlbumEmptyState({- groupInfo,- acceptTypes,- onUpload,- isUploading,-}: AlbumEmptyStateProps) {- const { t } = useTransClient('material')- const fileInputRef = useRef<HTMLInputElement>(null)-- // 触发文件选择- const handleUploadClick = () => {- fileInputRef.current?.click()- }-- // 处理文件选择- const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const files = e.target.files- if (files && files.length > 0) {- onUpload(Array.from(files))- }- e.target.value = ''- }-- const isVideo = groupInfo?.type === 'video'-- // 获取类型文本用于提示- const getTypeLabel = () => {- return isVideo ? t('mediaManagement.video') : t('mediaManagement.image')- }-- // 获取上传按钮文本- const getUploadButtonText = () => {- return isVideo ? t('mediaManagement.uploadVideo') : t('mediaManagement.uploadImage')- }-- return (- <div className="flex flex-col items-center justify-center py-16 px-4">- {/* 隐藏的文件输入 */}- <input- ref={fileInputRef}- type="file"- accept={acceptTypes}- onChange={handleFileChange}- className="hidden"- multiple- />-- {/* 图标 */}- <div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">- {isVideo ? (- <Video className="w-10 h-10 text-blue-500/50" />- ) : (- <ImageIcon className="w-10 h-10 text-green-500/50" />- )}- </div>-- {/* 标题 */}- <h3 className="text-lg font-medium text-foreground mb-2">{t('mediaManagement.noMedia')}</h3>-- {/* 描述 */}- <p className="text-sm text-muted-foreground text-center max-w-sm mb-6">- {t('mediaManagement.uploadMediaHint', { type: getTypeLabel() })}- </p>-- {/* 上传按钮 */}- <Button onClick={handleUploadClick} disabled={isUploading} loading={isUploading}>- <Plus className="w-4 h-4 mr-2" />- {getUploadButtonText()}- </Button>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/album/[id]/page.tsx b/project/aitoearn-web/src/app/[lng]/material/album/[id]/page.tsxdeleted file mode 100644index ffc2e226..00000000--- a/project/aitoearn-web/src/app/[lng]/material/album/[id]/page.tsx+++ /dev/null@@ -1,247 +0,0 @@-/**- * AlbumPage - 相册详情页- * 展示和管理单个分组内的所有媒体资源(重构版)- * 使用瀑布流布局 + 无限滚动 + 动画效果- */--'use client'--import { Loader2 } from 'lucide-react'-import { useParams, useSearchParams } from 'next/navigation'-import { useCallback, useEffect, useRef } from 'react'-import InfiniteScroll from 'react-infinite-scroll-component'-import Masonry from 'react-masonry-css'-import { useShallow } from 'zustand/react/shallow'-import { useTransClient } from '@/app/i18n/client'-import { MediaPreview } from '@/components/common/MediaPreview'-import { useDocumentTitle } from '@/hooks'-import { useAlbumStore } from './albumStore'-import { AlbumHeader } from './components/AlbumHeader'-import { MediaCard } from './components/MediaCard'-import { MediaCardSkeleton } from './components/MediaCard/MediaCardSkeleton'-import { UploadProgress } from './components/UploadProgress'-import { AlbumEmptyState } from './components/UploadSection'--/**- * 瀑布流断点配置- * 根据屏幕宽度调整列数- */-const MASONRY_BREAKPOINTS = {- default: 5, // > 1280px- 1280: 4, // <= 1280px- 1024: 3, // <= 1024px- 768: 3, // <= 768px- 640: 2, // <= 640px-}--export default function AlbumPage() {- const { t } = useTransClient('material')- const params = useParams()- const searchParams = useSearchParams()- const albumId = params.id as string- const scrollContainerRef = useRef<HTMLDivElement>(null)-- // 从 Store 获取状态和方法- const {- groupInfo,- mediaList,- total,- isLoading,- isUploading,- isDeleting,- isLoadingMore,- hasMore,- previewOpen,- previewIndex,- setGroupInfo,- fetchMediaList,- loadMore,- uploadMultipleMedia,- deleteMedia,- openPreview,- closePreview,- getAcceptTypes,- getPreviewItems,- reset,- } = useAlbumStore(- useShallow(state => ({- groupInfo: state.groupInfo,- mediaList: state.mediaList,- total: state.total,- isLoading: state.isLoading,- isUploading: state.isUploading,- isDeleting: state.isDeleting,- isLoadingMore: state.isLoadingMore,- hasMore: state.hasMore,- previewOpen: state.previewOpen,- previewIndex: state.previewIndex,- setGroupInfo: state.setGroupInfo,- fetchMediaList: state.fetchMediaList,- loadMore: state.loadMore,- uploadMultipleMedia: state.uploadMultipleMedia,- deleteMedia: state.deleteMedia,- openPreview: state.openPreview,- closePreview: state.closePreview,- getAcceptTypes: state.getAcceptTypes,- getPreviewItems: state.getPreviewItems,- reset: state.reset,- })),- )-- // 动态更新页面标题- useDocumentTitle(groupInfo?.title, t('mediaManagement.album'))-- // 初始化:从 URL 参数获取分组信息并加载媒体列表- useEffect(() => {- // 从 URL 参数获取组信息- const title = searchParams.get('title') || ''- const type = (searchParams.get('type') as 'video' | 'img') || 'video'- const desc = searchParams.get('desc') || ''-- if (title) {- setGroupInfo({- _id: albumId,- title,- type,- desc,- })- }-- fetchMediaList(albumId)-- // 组件卸载时重置 Store- return () => {- reset()- }- }, [albumId, searchParams, setGroupInfo, fetchMediaList, reset])-- // 处理上传(多文件)- const handleUpload = useCallback(- async (files: File[]) => {- await uploadMultipleMedia(albumId, files)- },- [albumId, uploadMultipleMedia],- )-- // 处理删除- const handleDelete = useCallback(- async (mediaId: string) => {- await deleteMedia(albumId, mediaId)- },- [albumId, deleteMedia],- )-- // 处理预览- const handlePreview = useCallback(- (media: (typeof mediaList)[0]) => {- const index = mediaList.findIndex(m => m._id === media._id)- if (index !== -1) {- openPreview(index)- }- },- [mediaList, openPreview],- )-- // 处理加载更多- const handleLoadMore = useCallback(() => {- loadMore(albumId)- }, [albumId, loadMore])-- // 获取允许的文件类型- const acceptTypes = getAcceptTypes()-- // 获取预览项列表- const previewItems = getPreviewItems()-- return (- <div className="flex flex-col h-screen bg-background overflow-hidden">- {/* 顶部导航 */}- <AlbumHeader- groupInfo={groupInfo}- total={total}- isUploading={isUploading}- acceptTypes={acceptTypes}- onUpload={handleUpload}- />-- {/* 主内容区 */}- <main- id="album-scroll-container"- ref={scrollContainerRef}- className="flex-1 px-4 py-6 overflow-y-auto"- >- <div className="w-full mx-auto">- {isLoading ? (- // 加载骨架屏- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">- {Array.from({ length: 20 }).map((_, index) => (- <MediaCardSkeleton key={index} />- ))}- </div>- ) : mediaList.length === 0 ? (- // 空状态- <AlbumEmptyState- groupInfo={groupInfo}- acceptTypes={acceptTypes}- onUpload={handleUpload}- isUploading={isUploading}- />- ) : (- // 瀑布流 + 无限滚动- <InfiniteScroll- dataLength={mediaList.length}- next={handleLoadMore}- hasMore={hasMore}- scrollThreshold={0.8}- loader={(- <div className="flex justify-center py-8">- <Loader2 className="w-8 h-8 text-muted-foreground animate-spin" />- </div>- )}- endMessage={- mediaList.length > 0 && (- <div className="flex justify-center py-8 text-muted-foreground text-sm">- {t('mediaManagement.loadedAll')}- {' · '}- {total}- {' '}- {t('mediaManagement.resources')}- </div>- )- }- scrollableTarget="album-scroll-container"- >- <Masonry- breakpointCols={MASONRY_BREAKPOINTS}- className="flex -ml-4 w-auto"- columnClassName="pl-4 bg-clip-padding"- >- {mediaList.map(media => (- <div key={media._id} className="mb-4">- <MediaCard- media={media}- onPreview={handlePreview}- onDelete={handleDelete}- isDeleting={isDeleting}- />- </div>- ))}- </Masonry>- </InfiniteScroll>- )}- </div>- </main>-- {/* 上传进度浮动面板 */}- <UploadProgress />-- {/* 媒体预览弹窗 */}- <MediaPreview- open={previewOpen}- items={previewItems}- initialIndex={previewIndex}- onClose={closePreview}- />- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/AgentAssetGroupCard/index.tsx b/project/aitoearn-web/src/app/[lng]/material/components/AgentAssetGroupCard/index.tsxdeleted file mode 100644index 0e5a3a35..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/AgentAssetGroupCard/index.tsx+++ /dev/null@@ -1,99 +0,0 @@-/**- * AgentAssetGroupCard - Agent 素材分组卡片- * 在素材库首页显示的特殊分组卡片,点击跳转到 Agent 素材详情页- * 特点:- * - 渐变背景 + Bot 图标- * - 无编辑/删除操作- */--'use client'--import { Bot, Sparkles } from 'lucide-react'-import Link from 'next/link'-import { useTransClient } from '@/app/i18n/client'-import { Badge } from '@/components/ui/badge'-import { cn } from '@/lib/utils'--interface AgentAssetGroupCardProps {- /** 资源数量(可选,如果不传则不显示) */- count?: number-}--export function AgentAssetGroupCard({ count }: AgentAssetGroupCardProps) {- const { t } = useTransClient('material')-- return (- <Link- href="/material/agent-assets"- className={cn(- 'block rounded-xl border border-border bg-card overflow-hidden cursor-pointer group',- 'hover:shadow-lg transition-shadow duration-200',- )}- >- {/* 封面区域 - 渐变背景 */}- <div className="relative aspect-[16/10] overflow-hidden">- {/* 渐变背景 - 淡雅灰色系 */}- <div className="absolute inset-0 bg-gradient-to-br from-gray-200 via-gray-300 to-gray-400" />-- {/* 装饰元素 */}- <div className="absolute inset-0 overflow-hidden">- {/* 光晕效果 */}- <div className="absolute -top-10 -right-10 w-32 h-32 bg-white/20 rounded-full blur-2xl" />- <div className="absolute -bottom-10 -left-10 w-32 h-32 bg-white/10 rounded-full blur-2xl" />-- {/* 网格装饰 */}- <div className="absolute inset-0 opacity-10">- <svg className="w-full h-full" xmlns="http://www.w3.org/2000/svg">- <defs>- <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">- <path d="M 20 0 L 0 0 0 20" fill="none" stroke="white" strokeWidth="0.5" />- </pattern>- </defs>- <rect width="100%" height="100%" fill="url(#grid)" />- </svg>- </div>- </div>-- {/* 中心图标 */}- <div className="absolute inset-0 flex flex-col items-center justify-center">- <div className="relative">- <div className="w-16 h-16 rounded-2xl bg-white/60 backdrop-blur-sm flex items-center justify-center mb-2 group-hover:scale-110 transition-transform duration-300">- <Bot className="w-8 h-8 text-gray-600" />- </div>- {/* 闪光图标 */}- <Sparkles className="absolute -top-1 -right-1 w-5 h-5 text-gray-500" />- </div>- </div>-- {/* AI 标签 */}- <Badge className="absolute top-3 left-3 bg-white/60 hover:bg-white/60 text-gray-700 border-0 backdrop-blur-sm">- <Sparkles className="w-3 h-3 mr-1" />- AI- </Badge>-- {/* 资源数量 */}- {count !== undefined && count > 0 && (- <Badge- variant="secondary"- className="absolute bottom-3 right-3 backdrop-blur-sm bg-gray-600/80 hover:bg-gray-600/80 text-white border-0"- >- {count}- {' '}- {t('mediaManagement.resources')}- </Badge>- )}- </div>-- {/* 内容区域 */}- <div className="p-3">- {/* 标题 */}- <h3 className="font-medium text-foreground truncate mb-1">{t('agentAssets.title')}</h3>-- {/* 描述 */}- <p className="text-sm text-muted-foreground line-clamp-2 min-h-[2.5rem]">- {t('agentAssets.description')}- </p>- </div>- </Link>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/CreateGroupModal/index.tsx b/project/aitoearn-web/src/app/[lng]/material/components/CreateGroupModal/index.tsxdeleted file mode 100644index 182aa716..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/CreateGroupModal/index.tsx+++ /dev/null@@ -1,190 +0,0 @@-/**- * CreateGroupModal - 创建/编辑分组弹窗- * 用于创建新分组或编辑已有分组- */--'use client'--import type { CreateGroupData, MediaGroup } from '../../materialStore'-import { Image as ImageIcon, Video } from 'lucide-react'-import { useEffect, useState } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { Input } from '@/components/ui/input'-import { Label } from '@/components/ui/label'-import { Modal } from '@/components/ui/modal'-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select'-import { Textarea } from '@/components/ui/textarea'-import { toast } from '@/lib/toast'--interface CreateGroupModalProps {- /** 是否显示 */- open: boolean- /** 关闭回调 */- onClose: () => void- /** 正在编辑的分组(null 表示创建模式) */- editingGroup: MediaGroup | null- /** 提交回调 */- onSubmit: (data: CreateGroupData) => Promise<boolean>- /** 是否提交中 */- isSubmitting?: boolean-}--export function CreateGroupModal({- open,- onClose,- editingGroup,- onSubmit,- isSubmitting,-}: CreateGroupModalProps) {- const { t } = useTransClient('material')-- // 表单状态- const [title, setTitle] = useState('')- const [desc, setDesc] = useState('')- const [type, setType] = useState<'video' | 'img'>('video')-- // 是否是编辑模式- const isEditMode = !!editingGroup-- // 同步编辑数据- useEffect(() => {- if (open) {- if (editingGroup) {- setTitle(editingGroup.title)- setDesc(editingGroup.desc || '')- setType(editingGroup.type)- }- else {- // 重置表单- setTitle('')- setDesc('')- setType('video')- }- }- }, [open, editingGroup])-- // 处理提交- const handleSubmit = async () => {- // 验证- if (!title.trim()) {- toast.error(t('mediaManagement.groupNamePlaceholder'))- return- }-- const data: CreateGroupData = {- title: title.trim(),- desc: desc.trim(),- type,- }-- const success = await onSubmit(data)- if (success) {- onClose()- }- }-- // 自定义 footer- const footer = (- <div className="flex justify-end gap-3">- <Button variant="outline" onClick={onClose} disabled={isSubmitting}>- {t('mediaManagement.cancel')}- </Button>- <Button- onClick={handleSubmit}- disabled={isSubmitting || !title.trim()}- loading={isSubmitting}- >- {isEditMode ? t('mediaManagement.save') : t('mediaManagement.create')}- </Button>- </div>- )-- return (- <Modal- open={open}- onCancel={onClose}- title={isEditMode ? t('mediaManagement.editGroup') : t('mediaManagement.createGroup')}- footer={footer}- width={480}- destroyOnClose- >- <div className="space-y-4 py-2">- {/* 分组名称 */}- <div className="space-y-2">- <Label htmlFor="title" className="text-sm font-medium">- {t('mediaManagement.groupName')}- <span className="text-destructive ml-1">*</span>- </Label>- <Input- id="title"- value={title}- onChange={e => setTitle(e.target.value)}- placeholder={t('mediaManagement.groupNamePlaceholder')}- maxLength={50}- disabled={isSubmitting}- />- </div>-- {/* 描述 */}- <div className="space-y-2">- <Label htmlFor="desc" className="text-sm font-medium">- {t('mediaManagement.description')}- </Label>- <Textarea- id="desc"- value={desc}- onChange={e => setDesc(e.target.value)}- placeholder={t('mediaManagement.descriptionPlaceholder')}- maxLength={200}- rows={3}- disabled={isSubmitting}- className="resize-none"- />- </div>-- {/* 类型选择 */}- <div className="space-y-2">- <Label className="text-sm font-medium">- {t('mediaManagement.type')}- <span className="text-destructive ml-1">*</span>- </Label>- <Select- value={type}- onValueChange={value => setType(value as 'video' | 'img')}- disabled={isSubmitting || isEditMode}- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="video">- <div className="flex items-center">- <Video className="w-4 h-4 mr-2 text-blue-500" />- {t('mediaManagement.video')}- </div>- </SelectItem>- <SelectItem value="img">- <div className="flex items-center">- <ImageIcon className="w-4 h-4 mr-2 text-green-500" />- {t('mediaManagement.image')}- </div>- </SelectItem>- </SelectContent>- </Select>- {isEditMode && (- <p className="text-xs text-muted-foreground">- {t('mediaManagement.typeCannotChangeAfterCreation')}- </p>- )}- </div>- </div>- </Modal>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/EmptyState/index.tsx b/project/aitoearn-web/src/app/[lng]/material/components/EmptyState/index.tsxdeleted file mode 100644index 08d3f152..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/EmptyState/index.tsx+++ /dev/null@@ -1,42 +0,0 @@-/**- * EmptyState - 空状态组件- * 当没有素材分组时显示- */--'use client'--import { FolderOpen, Plus } from 'lucide-react'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'--interface EmptyStateProps {- /** 创建按钮点击回调 */- onCreateClick: () => void-}--export function EmptyState({ onCreateClick }: EmptyStateProps) {- const { t } = useTransClient('material')-- return (- <div className="flex flex-col items-center justify-center py-16 px-4">- {/* 图标 */}- <div className="w-20 h-20 rounded-full bg-muted flex items-center justify-center mb-6">- <FolderOpen className="w-10 h-10 text-muted-foreground" />- </div>-- {/* 标题 */}- <h3 className="text-lg font-medium text-foreground mb-2">{t('mediaManagement.noGroups')}</h3>-- {/* 描述 */}- <p className="text-sm text-muted-foreground text-center max-w-sm mb-6">- {t('mediaManagement.noGroupsDesc')}- </p>-- {/* 创建按钮 */}- <Button onClick={onCreateClick} className="cursor-pointer">- <Plus className="w-4 h-4 mr-2" />- {t('mediaManagement.createNow')}- </Button>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/GroupCardSkeleton.tsx b/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/GroupCardSkeleton.tsxdeleted file mode 100644index c630ae13..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/GroupCardSkeleton.tsx+++ /dev/null@@ -1,30 +0,0 @@-/**- * GroupCardSkeleton - 分组卡片骨架屏- * 用于列表加载时的占位显示- */--import { Skeleton } from '@/components/ui/skeleton'--export function GroupCardSkeleton() {- return (- <div className="rounded-xl border border-border bg-card overflow-hidden">- {/* 封面区域骨架 */}- <div className="relative aspect-[16/10]">- <Skeleton className="absolute inset-0" />- {/* 类型徽章骨架 */}- <Skeleton className="absolute bottom-3 left-3 w-12 h-5 rounded-full" />- {/* 资源数量骨架 */}- <Skeleton className="absolute bottom-3 right-3 w-16 h-5 rounded-full" />- </div>-- {/* 内容区域骨架 */}- <div className="p-3 space-y-2">- {/* 标题骨架 */}- <Skeleton className="h-5 w-3/4" />- {/* 描述骨架 */}- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-2/3" />- </div>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/index.tsx b/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/index.tsxdeleted file mode 100644index 4f7f7efe..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/MaterialGroupCard/index.tsx+++ /dev/null@@ -1,208 +0,0 @@-/**- * MaterialGroupCard - 素材分组卡片组件- * 展示素材分组的封面、标题、描述、类型和资源数量- */--'use client'--import type { MediaGroup } from '../../materialStore'-import { Edit, Image as ImageIcon, MoreVertical, Trash2, Video } from 'lucide-react'-import Image from 'next/image'-import Link from 'next/link'-import { useTransClient } from '@/app/i18n/client'-import { Badge } from '@/components/ui/badge'-import { Button } from '@/components/ui/button'-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu'-import { confirm } from '@/lib/confirm'-import { cn } from '@/lib/utils'-import { getOssUrl } from '@/utils/oss'--interface MaterialGroupCardProps {- /** 分组数据 */- group: MediaGroup- /** 编辑回调 */- onEdit: (group: MediaGroup) => void- /** 删除回调 */- onDelete: (id: string) => void- /** 是否正在删除 */- isDeleting?: boolean-}--export function MaterialGroupCard({ group, onEdit, onDelete, isDeleting }: MaterialGroupCardProps) {- const { t } = useTransClient('material')-- // 处理编辑- const handleEdit = (e: React.MouseEvent) => {- e.preventDefault()- e.stopPropagation()- onEdit(group)- }-- // 处理删除- const handleDelete = async (e: React.MouseEvent) => {- e.preventDefault()- e.stopPropagation()- const confirmed = await confirm({- title: t('mediaManagement.delete'),- content: t('mediaManagement.deleteConfirm'),- okText: t('mediaManagement.delete'),- cancelText: t('mediaManagement.cancel'),- okType: 'destructive',- })- if (confirmed) {- onDelete(group._id)- }- }-- // 判断是否有封面(视频有 thumbUrl 时也算有封面)- const hasCover = group.cover || group.previewMedia?.thumbUrl- const coverUrl- = group.cover || (group.previewMedia?.thumbUrl ? getOssUrl(group.previewMedia.thumbUrl) : '')- const isVideo = group.type === 'video'- const isDefault = group.isDefault-- // 构建链接 URL- const params = new URLSearchParams({- title: group.title,- type: group.type,- desc: group.desc || '',- })- const href = `/material/album/${group._id}?${params.toString()}`-- // 获取描述文本- const getDescription = () => {- if (isDefault) {- return isVideo- ? t('mediaManagement.defaultVideoGroupDesc')- : t('mediaManagement.defaultImageGroupDesc')- }- return group.desc || t('mediaManagement.noDescription')- }-- return (- <Link- href={href}- className={cn(- 'block rounded-xl border border-border bg-card overflow-hidden cursor-pointer group',- 'hover:shadow-lg transition-shadow duration-200',- isDeleting && 'opacity-50 pointer-events-none',- )}- >- {/* 封面区域 */}- <div className="relative aspect-[16/10] bg-muted overflow-hidden">- {hasCover ? (- // 图片/视频缩略图封面- <Image- src={coverUrl}- alt={group.title}- fill- className="object-cover transition-transform duration-300 group-hover:scale-105"- sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"- />- ) : (- // 无封面占位符- <div- className={cn(- 'absolute inset-0 flex flex-col items-center justify-center',- isVideo- ? 'bg-gradient-to-br from-blue-500/20 to-purple-500/20'- : 'bg-gradient-to-br from-green-500/20 to-teal-500/20',- )}- >- {isVideo ? (- <>- <Video className="w-12 h-12 text-blue-500/60 mb-2" />- <span className="text-sm text-muted-foreground">{t('mediaManagement.video')}</span>- </>- ) : (- <>- <ImageIcon className="w-12 h-12 text-green-500/60 mb-2" />- <span className="text-sm text-muted-foreground">{t('mediaManagement.image')}</span>- </>- )}- </div>- )}-- {/* 默认标签 */}- {isDefault && (- <Badge className="absolute top-3 left-3 bg-amber-500/90 hover:bg-amber-500/90 text-white border-0 backdrop-blur-sm">- {t('mediaManagement.default')}- </Badge>- )}-- {/* 类型徽章 */}- <Badge- className={cn(- 'absolute bottom-3 left-3 backdrop-blur-sm',- isVideo- ? 'bg-blue-500/80 hover:bg-blue-500/80 text-white'- : 'bg-green-500/80 hover:bg-green-500/80 text-white',- )}- >- {isVideo ? <Video className="w-3 h-3 mr-1" /> : <ImageIcon className="w-3 h-3 mr-1" />}- {isVideo ? t('mediaManagement.video') : t('mediaManagement.image')}- </Badge>-- {/* 资源数量 */}- <Badge- variant="secondary"- className="absolute bottom-3 right-3 backdrop-blur-sm bg-black/50 hover:bg-black/50 text-white border-0"- >- {group.count}- {' '}- {t('mediaManagement.resources')}- </Badge>-- {/* 更多操作菜单(非默认组才显示) */}- {!isDefault && (- <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="secondary"- size="icon"- className="w-8 h-8 bg-black/50 hover:bg-black/70 text-white border-0 backdrop-blur-sm"- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- }}- >- <MoreVertical className="w-4 h-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-32">- <DropdownMenuItem onClick={handleEdit}>- <Edit className="w-4 h-4 mr-2" />- {t('mediaManagement.edit')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={handleDelete}- className="text-destructive focus:text-destructive"- >- <Trash2 className="w-4 h-4 mr-2" />- {t('mediaManagement.delete')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- )}- </div>-- {/* 内容区域 */}- <div className="p-3">- {/* 标题 */}- <h3 className="font-medium text-foreground truncate mb-1">{group.title}</h3>-- {/* 描述 */}- <p className="text-sm text-muted-foreground line-clamp-2 min-h-[2.5rem]">- {getDescription()}- </p>- </div>- </Link>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/components/MaterialHeader/index.tsx b/project/aitoearn-web/src/app/[lng]/material/components/MaterialHeader/index.tsxdeleted file mode 100644index cc1b1a25..00000000--- a/project/aitoearn-web/src/app/[lng]/material/components/MaterialHeader/index.tsx+++ /dev/null@@ -1,158 +0,0 @@-/**- * MaterialHeader - 素材库页面顶部组件- * 包含返回按钮、标题、类型筛选、搜索框、创建按钮- */--'use client'--import type { FilterType } from '../../materialStore'-import { ArrowLeft, FolderOpen, Image, Plus, Search, Video } from 'lucide-react'-import { useRouter } from 'next/navigation'-import { useCallback, useEffect, useState } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { Input } from '@/components/ui/input'-import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'-import { cn } from '@/lib/utils'--interface MaterialHeaderProps {- /** 总数量 */- total: number- /** 当前筛选类型 */- filterType: FilterType- /** 筛选类型变化回调 */- onFilterChange: (type: FilterType) => void- /** 搜索文本 */- searchText: string- /** 搜索文本变化回调 */- onSearchChange: (text: string) => void- /** 创建按钮点击回调 */- onCreateClick: () => void- /** 是否加载中 */- isLoading?: boolean-}--export function MaterialHeader({- total,- filterType,- onFilterChange,- searchText,- onSearchChange,- onCreateClick,- isLoading,-}: MaterialHeaderProps) {- const { t } = useTransClient('material')- const router = useRouter()-- // 本地搜索状态(用于防抖)- const [localSearch, setLocalSearch] = useState(searchText)-- // 同步外部搜索文本- useEffect(() => {- setLocalSearch(searchText)- }, [searchText])-- // 防抖搜索- useEffect(() => {- const timer = setTimeout(() => {- if (localSearch !== searchText) {- onSearchChange(localSearch)- }- }, 300)- return () => clearTimeout(timer)- }, [localSearch, searchText, onSearchChange])-- // 返回首页- const handleBack = useCallback(() => {- router.push('/')- }, [router])-- return (- <header className="sticky top-0 z-10 bg-card border-b border-border">- {/* 第一行:标题和操作 */}- <div className="flex items-center justify-between px-4 py-3">- <div className="flex items-center gap-3">- <Button variant="ghost" size="icon" onClick={handleBack} className="w-8 h-8">- <ArrowLeft className="w-5 h-5" />- </Button>- <div className="flex items-center gap-2">- <FolderOpen className="w-5 h-5 text-primary" />- <h1 className="text-lg font-semibold text-foreground">{t('mediaManagement.title')}</h1>- </div>- {total > 0 && (- <span className="text-sm text-muted-foreground">- (- {total}- )- </span>- )}- </div>-- <div className="flex items-center gap-3">- {/* 桌面端筛选 Tabs */}- <Tabs- value={filterType}- onValueChange={value => onFilterChange(value as FilterType)}- className="hidden sm:block"- >- <TabsList className="h-9">- <TabsTrigger value="all" className="text-sm px-3">- {t('mediaManagement.all')}- </TabsTrigger>- <TabsTrigger value="video" className="text-sm px-3">- <Video className="w-4 h-4 mr-1" />- {t('mediaManagement.video')}- </TabsTrigger>- <TabsTrigger value="img" className="text-sm px-3">- <Image className="w-4 h-4 mr-1" />- {t('mediaManagement.image')}- </TabsTrigger>- </TabsList>- </Tabs>-- {/* 创建按钮 */}- <Button onClick={onCreateClick} size="sm">- <Plus className="w-4 h-4 mr-1" />- <span className="hidden sm:inline">{t('mediaManagement.createGroup')}</span>- <span className="sm:hidden">{t('mediaManagement.create')}</span>- </Button>- </div>- </div>-- {/* 第二行:移动端筛选 + 搜索 */}- <div className="px-4 pb-3 flex flex-col sm:flex-row gap-3">- {/* 移动端筛选 Tabs */}- <Tabs- value={filterType}- onValueChange={value => onFilterChange(value as FilterType)}- className="sm:hidden"- >- <TabsList className="w-full grid grid-cols-3">- <TabsTrigger value="all">{t('mediaManagement.all')}</TabsTrigger>- <TabsTrigger value="video">- <Video className="w-4 h-4 mr-1" />- {t('mediaManagement.video')}- </TabsTrigger>- <TabsTrigger value="img">- <Image className="w-4 h-4 mr-1" />- {t('mediaManagement.image')}- </TabsTrigger>- </TabsList>- </Tabs>-- {/* 搜索框 */}- <div className="relative flex-1 max-w-md">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />- <Input- type="text"- placeholder={t('mediaManagement.searchPlaceholder')}- value={localSearch}- onChange={e => setLocalSearch(e.target.value)}- className={cn('pl-9 h-9', isLoading && 'opacity-50')}- disabled={isLoading}- />- </div>- </div>- </header>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/materialPageCore.tsx b/project/aitoearn-web/src/app/[lng]/material/materialPageCore.tsxdeleted file mode 100644index 52bce05a..00000000--- a/project/aitoearn-web/src/app/[lng]/material/materialPageCore.tsx+++ /dev/null@@ -1,210 +0,0 @@-/**- * MaterialPageCore - 素材库核心页面- * 素材分组和管理的核心功能页面(重构版)- */--'use client'--import type { CreateGroupData, MediaGroup } from './materialStore'-import { useCallback, useEffect } from 'react'-import { useShallow } from 'zustand/react/shallow'-import { Pagination } from '@/components/ui/pagination'-import { AgentAssetGroupCard } from './components/AgentAssetGroupCard'-import { CreateGroupModal } from './components/CreateGroupModal'-import { EmptyState } from './components/EmptyState'-import { MaterialGroupCard } from './components/MaterialGroupCard'-import { GroupCardSkeleton } from './components/MaterialGroupCard/GroupCardSkeleton'-import { MaterialHeader } from './components/MaterialHeader'-import { useMaterialStore } from './materialStore'--export function MaterialPageCore() {- // 从 Store 获取状态和方法- const {- groups,- total,- isLoading,- isSubmitting,- isDeleting,- currentPage,- pageSize,- filterType,- searchText,- createModalOpen,- editingGroup,- fetchGroups,- setFilterType,- setSearchText,- setCurrentPage,- openCreateModal,- openEditModal,- closeCreateModal,- createGroup,- updateGroup,- deleteGroup,- } = useMaterialStore(- useShallow(state => ({- groups: state.groups,- total: state.total,- isLoading: state.isLoading,- isSubmitting: state.isSubmitting,- isDeleting: state.isDeleting,- currentPage: state.currentPage,- pageSize: state.pageSize,- filterType: state.filterType,- searchText: state.searchText,- createModalOpen: state.createModalOpen,- editingGroup: state.editingGroup,- fetchGroups: state.fetchGroups,- setFilterType: state.setFilterType,- setSearchText: state.setSearchText,- setCurrentPage: state.setCurrentPage,- openCreateModal: state.openCreateModal,- openEditModal: state.openEditModal,- closeCreateModal: state.closeCreateModal,- createGroup: state.createGroup,- updateGroup: state.updateGroup,- deleteGroup: state.deleteGroup,- })),- )-- // 计算总页数- const totalPages = Math.max(1, Math.ceil(total / pageSize))-- // 初始化加载- useEffect(() => {- fetchGroups()- }, [fetchGroups])-- // 处理搜索(防抖后触发)- const handleSearchChange = useCallback(- (text: string) => {- setSearchText(text)- // 搜索时重置到第一页- if (currentPage !== 1) {- setCurrentPage(1)- }- else {- fetchGroups()- }- },- [setSearchText, currentPage, setCurrentPage, fetchGroups],- )-- // 处理分页- const handlePageChange = useCallback(- (page: number) => {- if (page < 1 || page > totalPages)- return- setCurrentPage(page)- },- [totalPages, setCurrentPage],- )-- // 处理编辑- const handleEdit = useCallback(- (group: MediaGroup) => {- openEditModal(group)- },- [openEditModal],- )-- // 处理删除- const handleDelete = useCallback(- async (id: string) => {- await deleteGroup(id)- },- [deleteGroup],- )-- // 处理创建/更新提交- const handleSubmit = useCallback(- async (data: CreateGroupData) => {- if (editingGroup) {- return await updateGroup(editingGroup._id, data)- }- else {- return await createGroup(data)- }- },- [editingGroup, createGroup, updateGroup],- )-- return (- <div className="flex flex-col min-h-screen bg-background">- {/* 顶部导航 */}- <MaterialHeader- total={total}- filterType={filterType}- onFilterChange={setFilterType}- searchText={searchText}- onSearchChange={handleSearchChange}- onCreateClick={openCreateModal}- isLoading={isLoading}- />-- {/* 主内容区 */}- <main className="flex-1 px-4 py-6">- <div className="w-full mx-auto">- {isLoading ? (- // 加载骨架屏- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">- {Array.from({ length: pageSize }).map((_, index) => (- <GroupCardSkeleton key={index} />- ))}- </div>- ) : groups.length === 0 ? (- // 空状态- <EmptyState onCreateClick={openCreateModal} />- ) : (- // 分组卡片网格- <>- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">- {/* Agent 素材分组卡片 - 仅在第一页且无类型筛选时显示 */}- {currentPage === 1 && filterType === 'all' && <AgentAssetGroupCard />}- {groups.map(group => (- <MaterialGroupCard- key={group._id}- group={group}- onEdit={handleEdit}- onDelete={handleDelete}- isDeleting={isDeleting}- />- ))}- </div>-- {/* 分页器 */}- {totalPages > 1 && (- <div className="mt-8">- <Pagination- current={currentPage}- pageSize={pageSize}- total={total}- onChange={handlePageChange}- showTotal={(totalCount, [_start, _end]) => (- <span className="text-sm text-muted-foreground">- {currentPage}- {' '}- /- {totalPages}- </span>- )}- className="w-full"- />- </div>- )}- </>- )}- </div>- </main>-- {/* 创建/编辑弹窗 */}- <CreateGroupModal- open={createModalOpen}- onClose={closeCreateModal}- editingGroup={editingGroup}- onSubmit={handleSubmit}- isSubmitting={isSubmitting}- />- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/material/materialStore/index.ts b/project/aitoearn-web/src/app/[lng]/material/materialStore/index.tsdeleted file mode 100644index 3848527c..00000000--- a/project/aitoearn-web/src/app/[lng]/material/materialStore/index.ts+++ /dev/null@@ -1,285 +0,0 @@-/**- * materialStore - 素材库页面状态管理- * 管理素材分组的 CRUD 操作和 UI 状态- */--import type {- CreateGroupData,- FilterType,- IMaterialStore,- MediaGroup,- UpdateGroupData,-} from './materialStore.types'-import lodash from 'lodash'-import { create } from 'zustand'-import { combine } from 'zustand/middleware'-import {- createMediaGroup,- deleteMediaGroup,- getMediaGroupList,- updateMediaGroupInfo,-} from '@/api/media'-import { toast } from '@/lib/toast'-import { getOssUrl } from '@/utils/oss'--// 导出类型-export type { CreateGroupData, FilterType, IMaterialStore, MediaGroup, UpdateGroupData }--/**- * 初始状态- */-const initialState: IMaterialStore = {- // 数据- groups: [],- total: 0,- defaultImgGroup: null,- defaultVideoGroup: null,-- // 加载状态- isLoading: false,- isSubmitting: false,- isDeleting: false,-- // 分页- currentPage: 1,- pageSize: 12,-- // 筛选- filterType: 'all',- searchText: '',-- // 弹窗状态- createModalOpen: false,- editingGroup: null,-}--/**- * 获取初始状态的深拷贝- */-function getInitialState(): IMaterialStore {- return lodash.cloneDeep(initialState)-}--/**- * 素材库 Store- */-export const useMaterialStore = create(- combine({ ...getInitialState() }, (set, get) => {- const methods = {- /**- * 重置 Store 到初始状态- */- reset() {- set(getInitialState())- },-- /**- * 设置筛选类型并重新加载- */- setFilterType(filterType: FilterType) {- set({ filterType, currentPage: 1 })- methods.fetchGroups()- },-- /**- * 设置搜索文本(不自动加载,由组件控制防抖)- */- setSearchText(searchText: string) {- set({ searchText })- },-- /**- * 设置当前页码并重新加载- */- setCurrentPage(page: number) {- set({ currentPage: page })- methods.fetchGroups()- },-- /**- * 打开创建弹窗- */- openCreateModal() {- set({ createModalOpen: true, editingGroup: null })- },-- /**- * 打开编辑弹窗- */- openEditModal(group: MediaGroup) {- set({ createModalOpen: true, editingGroup: group })- },-- /**- * 关闭创建/编辑弹窗- */- closeCreateModal() {- set({ createModalOpen: false, editingGroup: null })- },-- /**- * 处理分组数据,提取封面和资源数量- */- processGroups(list: MediaGroup[]): MediaGroup[] {- return list.map((group) => {- const mediaList = group.mediaList-- // 查找第一个媒体作为预览- let previewMedia = null- if (mediaList && mediaList.list && mediaList.list.length > 0) {- previewMedia = mediaList.list[0]- }-- return {- ...group,- // 使用缩略图作为封面(thumbUrl 优先)- cover: previewMedia ? getOssUrl(previewMedia.thumbUrl || previewMedia.url) : undefined,- // 使用 mediaList 的 total 作为资源数量- count: mediaList ? mediaList.total : 0,- // 保存预览媒体信息(包含 thumbUrl)- previewMedia: previewMedia- ? {- type: previewMedia.type,- url: previewMedia.url,- thumbUrl: previewMedia.thumbUrl,- }- : null,- }- })- },-- /**- * 获取分组列表- */- async fetchGroups() {- const { currentPage, pageSize, filterType } = get()- set({ isLoading: true })-- try {- const typeParam = filterType === 'all' ? undefined : filterType- const response = await getMediaGroupList(currentPage, pageSize, typeParam)-- if (response?.data) {- const processedGroups = methods.processGroups(response.data.list || [])- set({- groups: processedGroups,- total: response.data.total || 0,- })- }- }- catch (error) {- console.error('Failed to fetch groups:', error)- toast.error('获取素材分组失败')- }- finally {- set({ isLoading: false })- }- },-- /**- * 创建分组- */- async createGroup(data: CreateGroupData): Promise<boolean> {- set({ isSubmitting: true })-- try {- await createMediaGroup(data)- methods.closeCreateModal()- // 重置到第一页并刷新- set({ currentPage: 1 })- await methods.fetchGroups()- toast.success('创建成功')- return true- }- catch (error) {- console.error('Failed to create group:', error)- toast.error('创建失败')- return false- }- finally {- set({ isSubmitting: false })- }- },-- /**- * 更新分组- */- async updateGroup(id: string, data: UpdateGroupData): Promise<boolean> {- set({ isSubmitting: true })-- try {- await updateMediaGroupInfo(id, data)- methods.closeCreateModal()- await methods.fetchGroups()- toast.success('更新成功')- return true- }- catch (error) {- console.error('Failed to update group:', error)- toast.error('更新失败')- return false- }- finally {- set({ isSubmitting: false })- }- },-- /**- * 删除分组- */- async deleteGroup(id: string): Promise<boolean> {- set({ isDeleting: true })-- try {- await deleteMediaGroup(id)- // 如果当前页没有数据了,回退到上一页- const { groups, currentPage } = get()- if (groups.length === 1 && currentPage > 1) {- set({ currentPage: currentPage - 1 })- }- await methods.fetchGroups()- toast.success('删除成功')- return true- }- catch (error) {- console.error('Failed to delete group:', error)- toast.error('删除失败')- return false- }- finally {- set({ isDeleting: false })- }- },-- /**- * 获取默认分组(图片和视频)- * 用于首页快捷入口- */- async fetchDefaultGroups() {- try {- // 获取分组列表(第一页足够获取默认分组)- const response = await getMediaGroupList(1, 50)- if (response?.data?.list) {- const groups = response.data.list- // 优先查找标记为默认的分组,否则取第一个对应类型的分组- const defaultImg- = groups.find(g => g.isDefault && g.type === 'img')- || groups.find(g => g.type === 'img')- const defaultVideo- = groups.find(g => g.isDefault && g.type === 'video')- || groups.find(g => g.type === 'video')- set({- defaultImgGroup: defaultImg || null,- defaultVideoGroup: defaultVideo || null,- })- }- }- catch (error) {- console.error('Failed to fetch default groups:', error)- }- },- }-- return methods- }),-)diff --git a/project/aitoearn-web/src/app/[lng]/material/page.tsx b/project/aitoearn-web/src/app/[lng]/material/page.tsxdeleted file mode 100644index 1faca2cf..00000000--- a/project/aitoearn-web/src/app/[lng]/material/page.tsx+++ /dev/null@@ -1,30 +0,0 @@-import type { PageParams } from '@/app/globals'-import * as React from 'react'-import { MaterialPageCore } from '@/app/[lng]/material/materialPageCore'-import { useTranslation } from '@/app/i18n'-import { getMetadata } from '@/utils/server-general'--export async function generateMetadata({ params }: PageParams) {- const { lng } = await params- const { t } = await useTranslation(lng, 'material')- return await getMetadata(- {- title: t('meta.title'),- description: t('meta.description'),- keywords: t('meta.keywords'),- },- lng,- '/material',- )-}--export default async function Page({ params }: PageParams) {- const { lng } = await params- const { t } = await useTranslation(lng, 'material')-- return (- <>- <MaterialPageCore />- </>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/page.tsx b/project/aitoearn-web/src/app/[lng]/page.tsxindex 0a695536..6952f769 100644--- a/project/aitoearn-web/src/app/[lng]/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/page.tsx@@ -1,9 +1,37 @@/**- * 首页 - 重定向到内容管理+ * 首页 - 内容管理*/-import { redirect } from 'next/navigation'+import dynamic from 'next/dynamic'+import { useTranslation } from '@/app/i18n'+import { fallbackLng, languages } from '@/lib/i18n/languageConfig'+import { getMetadata } from '@/utils/general'-export default async function HomePage() {- redirect('/draft-box')+interface PageParams {+ params: Promise<{ lng: string }>+}++export async function generateMetadata({ params }: PageParams) {+ let { lng } = await params+ if (!languages.includes(lng))+ lng = fallbackLng+ const { t } = await useTranslation(lng, 'common')++ return getMetadata(+ {+ title: t('header.draftBoxSeoTitle'),+ description: t('header.draftBoxSeoDescription'),+ keywords: t('header.draftBoxSeoKeywords'),+ },+ lng,+ '/',+ )+}++const DraftBoxCore = dynamic(() => import('./draft-box/DraftBoxCore'), {+ ssr: false,+})++export default function HomePage() {+ return <DraftBoxCore />}diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/1.png b/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/1.pngdeleted file mode 100644index b9151ba3..00000000Binary files a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/1.png and /dev/null differdiff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/2.png b/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/2.pngdeleted file mode 100644index 2a27a33a..00000000Binary files a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/2.png and /dev/null differdiff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/3.png b/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/3.pngdeleted file mode 100644index c2476cd3..00000000Binary files a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/3.png and /dev/null differdiff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/4.png b/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/4.pngdeleted file mode 100644index afe035b2..00000000Binary files a/project/aitoearn-web/src/app/[lng]/promo/[code]/assets/4.png and /dev/null differdiff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/AiToEarnIntro.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/components/AiToEarnIntro.tsxdeleted file mode 100644index 50b40fa6..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/AiToEarnIntro.tsx+++ /dev/null@@ -1,101 +0,0 @@-/**- * AiToEarnIntro - AiToEarn 平台介绍组件- * 展示平台核心功能,参考 welcome 页面设计风格- */--'use client'--import { MapPin, Sparkles, Target } from 'lucide-react'-import { memo } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Card } from '@/components/ui/card'--export const AiToEarnIntro = memo(() => {- const { t } = useTransClient('promo')-- // 核心功能列表- const features = [- {- icon: MapPin,- title: t('intro.features.offlineMarketing'),- desc: t('intro.features.offlineMarketingDesc'),- },- {- icon: Target,- title: t('intro.features.payForResults'),- desc: t('intro.features.payForResultsDesc'),- },- {- icon: Sparkles,- title: t('intro.features.aiAssist'),- desc: t('intro.features.aiAssistDesc'),- },- ]-- return (- <Card className="relative overflow-hidden border-border/50 p-0">- {/* 装饰光晕 */}- <div className="pointer-events-none absolute -right-20 -top-20 h-40 w-40 rounded-full bg-[#c565ef]/5 blur-3xl" />- <div className="pointer-events-none absolute -bottom-20 -left-20 h-40 w-40 rounded-full bg-[#55D9ED]/5 blur-3xl" />-- {/* 头部区域 */}- <div className="relative p-6">- {/* Badge */}- <div className="mb-4 inline-flex items-center gap-2 rounded-full border border-[#c565ef]/10 bg-gradient-to-r from-[#c565ef]/5 to-[#55D9ED]/5 px-3 py-1.5 backdrop-blur-sm">- <div className="flex h-5 w-5 items-center justify-center rounded-md bg-gradient-to-br from-[#c565ef] to-[#55D9ED]">- <span className="text-xs font-bold text-white">A</span>- </div>- <span className="text-sm font-medium text-foreground/80">AiToEarn</span>- </div>-- {/* 标题区域 */}- <h2 className="text-xl font-bold md:text-2xl">- <span className="bg-gradient-to-r from-[#c565ef] to-[#55D9ED] bg-clip-text text-transparent">- {t('intro.title')}- </span>- </h2>- <p className="mt-1 text-sm text-muted-foreground">- {t('intro.subtitle')}- </p>-- {/* 分隔线 */}- <div className="my-4 h-px bg-gradient-to-r from-transparent via-[#c565ef]/20 to-transparent" />-- {/* 主标题 */}- <div className="rounded-lg bg-gradient-to-r from-[#c565ef]/5 to-[#55D9ED]/5 p-4">- <h3 className="text-base font-semibold leading-relaxed">- {t('intro.heroTitle')}- </h3>- <p className="mt-1 text-sm leading-relaxed text-muted-foreground">- {t('intro.heroSubtitle')}- </p>- </div>- </div>-- {/* 核心功能 */}- <div className="space-y-3 px-6 pb-6">- {features.map((feature, index) => {- const Icon = feature.icon- return (- <div- key={index}- className="group flex items-start gap-3 rounded-xl border border-transparent bg-muted/30 p-3 transition-all duration-300 hover:-translate-y-0.5 hover:border-border/50 hover:bg-muted/50 hover:shadow-md"- >- <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[#c565ef]/10 to-[#55D9ED]/10">- <Icon className="h-5 w-5 text-foreground/70" />- </div>- <div className="flex-1">- <span className="text-sm font-medium">{feature.title}</span>- <p className="mt-0.5 text-xs text-muted-foreground">- {feature.desc}- </p>- </div>- </div>- )- })}- </div>- </Card>- )-})--AiToEarnIntro.displayName = 'AiToEarnIntro'diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/MaterialPreviewCard.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/components/MaterialPreviewCard.tsxdeleted file mode 100644index 73cc1f17..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/MaterialPreviewCard.tsx+++ /dev/null@@ -1,163 +0,0 @@-/**- * MaterialPreviewCard - 素材预览卡片组件- * 显示推荐的发布素材预览- */--'use client'--import type { OptimalMaterialVo } from '@/api/types/open/promotionCode'-import { Eye, Image as ImageIcon, Play, Video } from 'lucide-react'-import Image from 'next/image'-import { memo, useState } from 'react'-import { useTransClient } from '@/app/i18n/client'-import MediaPreview from '@/components/common/MediaPreview'-import { Badge } from '@/components/ui/badge'-import { Card } from '@/components/ui/card'-import { getOssUrl } from '@/utils/oss'--interface MaterialPreviewCardProps {- material: OptimalMaterialVo-}--export const MaterialPreviewCard = memo(({ material }: MaterialPreviewCardProps) => {- const { t } = useTransClient('promo')- const [previewOpen, setPreviewOpen] = useState(false)- const [previewIndex, setPreviewIndex] = useState(0)-- // 判断是否有视频- const hasVideo = material.mediaList?.some(m => m.type === 'video')-- // 获取封面URL- const coverUrl = material.coverUrl- ? getOssUrl(material.coverUrl)- : material.mediaList?.[0]?.thumbUrl- ? getOssUrl(material.mediaList[0].thumbUrl)- : material.mediaList?.[0]?.url- ? getOssUrl(material.mediaList[0].url)- : undefined-- // 处理媒体点击- const handleMediaClick = (index: number) => {- setPreviewIndex(index)- setPreviewOpen(true)- }-- // 准备预览数据- const previewItems- = material.mediaList?.map(m => ({- type: m.type as 'video' | 'image',- src: getOssUrl(m.url) || '',- title: material.title,- })) || []-- return (- <>- <Card className="p-0">- {/* Header */}- <div className="p-6 pb-4">- <div className="flex items-start justify-between">- <div>- <h3 className="flex items-center gap-2 text-lg font-semibold">- {hasVideo ? <Video className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}- {t('material.title')}- </h3>- <p className="mt-1 text-sm text-muted-foreground">{t('material.description')}</p>- </div>- {material.useCount > 0 && (- <Badge variant="secondary">- {t('material.usedCount').replace('{{count}}', String(material.useCount))}- </Badge>- )}- </div>- </div>-- {/* Content */}- <div className="space-y-4 px-6 pb-6">- {/* 封面/缩略图 */}- {coverUrl && (- <div- className="relative aspect-video w-full cursor-pointer overflow-hidden rounded-lg bg-muted"- onClick={() => handleMediaClick(0)}- >- <Image- src={coverUrl}- alt={material.title || t('material.preview')}- fill- className="object-cover transition-transform hover:scale-105"- />- {hasVideo && (- <div className="absolute inset-0 flex items-center justify-center bg-black/30">- <div className="flex h-12 w-12 items-center justify-center rounded-full bg-white/90">- <Play className="h-6 w-6 text-primary" fill="currentColor" />- </div>- </div>- )}- <div className="absolute bottom-2 right-2">- <Badge- variant="secondary"- className="flex items-center gap-1 bg-black/60 text-white"- >- <Eye className="h-3 w-3" />- {t('material.clickToPreview')}- </Badge>- </div>- </div>- )}-- {/* 标题和描述 */}- {material.title && (- <div className="space-y-1">- <h4 className="font-medium">{material.title}</h4>- {material.desc && (- <p className="text-sm text-muted-foreground line-clamp-3">{material.desc}</p>- )}- </div>- )}-- {/* 多媒体缩略图 */}- {material.mediaList && material.mediaList.length > 1 && (- <div className="grid grid-cols-4 gap-2">- {material.mediaList.slice(0, 4).map((media, index) => (- <div- key={index}- className="relative aspect-square cursor-pointer overflow-hidden rounded-md bg-muted"- onClick={() => handleMediaClick(index)}- >- <Image- src={getOssUrl(media.thumbUrl || media.url) || ''}- alt={`${t('material.preview')} ${index + 1}`}- fill- className="object-cover transition-transform hover:scale-105"- />- {media.type === 'video' && (- <div className="absolute inset-0 flex items-center justify-center bg-black/30">- <Play className="h-4 w-4 text-white" fill="currentColor" />- </div>- )}- {index === 3 && material.mediaList!.length > 4 && (- <div className="absolute inset-0 flex items-center justify-center bg-black/60 text-white">- +- {material.mediaList!.length - 4}- </div>- )}- </div>- ))}- </div>- )}- </div>- </Card>-- {/* 媒体预览弹窗 */}- {previewItems.length > 0 && (- <MediaPreview- open={previewOpen}- onClose={() => setPreviewOpen(false)}- items={previewItems}- initialIndex={previewIndex}- />- )}- </>- )-})--MaterialPreviewCard.displayName = 'MaterialPreviewCard'diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PlatformSelectStep.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PlatformSelectStep.tsxdeleted file mode 100644index 64696c09..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PlatformSelectStep.tsx+++ /dev/null@@ -1,118 +0,0 @@-/**- * PlatformSelectStep - 平台选择步骤组件- * 用于用户选择发布内容的目标平台- */--'use client'--import Image from 'next/image'-import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'-import { cn } from '@/lib/utils'--interface PlatformSelectStepProps {- selectedPlatform: PlatType | null- onSelect: (platform: PlatType) => void- onConfirm: () => void-}--// 支持的平台-const supportedPlatforms = [PlatType.Tiktok, PlatType.Douyin]--const accountTypeToPlatType: Record<string, PlatType> = {- [PlatType.Tiktok]: PlatType.Tiktok,- [PlatType.Douyin]: PlatType.Douyin,-}--export function PlatformSelectStep({- selectedPlatform,- onSelect,- onConfirm,-}: PlatformSelectStepProps) {- const { t } = useTransClient('promo')-- return (- <Card className="border-primary/10 p-0 shadow-lg">- <CardHeader className="pb-4 text-center">- <CardTitle className="text-xl md:text-2xl">- {t('platformSelect.title')}- </CardTitle>- <CardDescription>- {t('platformSelect.description')}- </CardDescription>- </CardHeader>- <CardContent className="space-y-6">- {/* 平台选择网格 */}- <div className="grid grid-cols-2 gap-3 md:gap-4">- {supportedPlatforms.map((platform) => {- const platType = accountTypeToPlatType[platform]- const platInfo = AccountPlatInfoMap.get(platType)- if (!platInfo)- return null-- const isSelected = selectedPlatform === platform-- return (- <button- key={platform}- type="button"- onClick={() => onSelect(platform)}- className={cn(- 'group relative flex cursor-pointer flex-col items-center gap-2 rounded-xl border-2 p-4 transition-all md:gap-3 md:p-6',- isSelected- ? 'scale-105 border-primary bg-primary/5 shadow-md'- : 'border-border bg-card hover:border-primary/50 hover:bg-primary/5',- )}- >- {/* 平台图标 */}- <div- className={cn(- 'flex h-12 w-12 items-center justify-center rounded-xl transition-all md:h-16 md:w-16',- isSelected ? 'scale-110' : 'group-hover:scale-105',- )}- >- <Image- src={platInfo.icon}- alt={platInfo.name}- width={48}- height={48}- className="h-10 w-10 object-contain md:h-12 md:w-12"- />- </div>-- {/* 平台名称 */}- <span- className={cn(- 'text-sm font-medium transition-colors md:text-base',- isSelected ? 'text-primary' : 'text-foreground',- )}- >- {platInfo.name}- </span>-- {/* 选中指示器 */}- {isSelected && (- <div className="absolute -top-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground md:h-6 md:w-6 md:text-xs">- ✓- </div>- )}- </button>- )- })}- </div>-- {/* 确认按钮 */}- <Button- onClick={onConfirm}- disabled={!selectedPlatform}- className="w-full"- size="lg"- >- {t('platformSelect.confirm')}- </Button>- </CardContent>- </Card>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PublishResultStep.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PublishResultStep.tsxdeleted file mode 100644index 4258132c..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/components/PublishResultStep.tsx+++ /dev/null@@ -1,293 +0,0 @@-/**- * PublishResultStep - 发布结果步骤组件- * 显示发布成功或失败的结果,并提供作品链接提交功能- */--'use client'--import { CheckCircle2, CircleAlert, HelpCircle, Home, Link2, Loader2, RefreshCw, XCircle } from 'lucide-react'-import Image from 'next/image'-import { memo, useCallback, useMemo, useState } from 'react'-import { apiCreateOpenPublishRecord } from '@/api/open/promotionCode'-import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'--import { useTransClient } from '@/app/i18n/client'-import { MediaPreview } from '@/components/common/MediaPreview'-import { Button } from '@/components/ui/button'-import { Card } from '@/components/ui/card'-import { Input } from '@/components/ui/input'-import { Label } from '@/components/ui/label'-import guideImage1 from '../assets/1.png'-import guideImage2 from '../assets/2.png'-import guideImage3 from '../assets/3.png'-import guideImage4 from '../assets/4.png'--interface PublishResultStepProps {- result: {- success: boolean- message?: string- flowId?: string- }- materialGroupId?: string- materialId?: string- accountType?: PlatType- videoUrl?: string- coverUrl?: string- imgUrlList?: string[]- title?: string- desc?: string- topics?: string[]- /** 是否需要提交作品链接,默认 true(抖音需要,TikTok 不需要) */- requireWorkLink?: boolean- onRetry: () => void- onGoHome: () => void-}--export const PublishResultStep = memo(({- result,- materialGroupId,- materialId,- accountType = PlatType.Tiktok,- videoUrl,- coverUrl,- imgUrlList,- title,- desc,- topics,- requireWorkLink = true,- onRetry,- onGoHome,-}: PublishResultStepProps) => {- const { t } = useTransClient('promo')-- // 获取平台信息- const platInfo = useMemo(() => {- return AccountPlatInfoMap.get(accountType as unknown as PlatType)- }, [accountType])-- // 作品链接相关状态- const [workLink, setWorkLink] = useState('')- const [submitStatus, setSubmitStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle')- const [submitError, setSubmitError] = useState('')- const [showGuide, setShowGuide] = useState(false)-- // 教程图片列表- const guideImages = [- { type: 'image' as const, src: guideImage1.src, title: '步骤1' },- { type: 'image' as const, src: guideImage2.src, title: '步骤2' },- { type: 'image' as const, src: guideImage3.src, title: '步骤3' },- { type: 'image' as const, src: guideImage4.src, title: '步骤4' },- ]-- // 提交作品链接- const handleSubmitWorkLink = useCallback(async () => {- if (!workLink.trim() || !materialGroupId || !accountType)- return-- setSubmitStatus('loading')- setSubmitError('')-- try {- const res = await apiCreateOpenPublishRecord({- materialGroupId,- materialId,- workLink: workLink.trim(),- accountType,- videoUrl,- coverUrl,- imgUrlList,- title,- desc,- topics,- })-- if (res?.code === 0 && res.data?.success) {- setSubmitStatus('success')- }- else {- setSubmitStatus('error')- setSubmitError(res?.message || t('result.submitFailed'))- }- }- catch (error) {- console.error('Submit work link failed:', error)- setSubmitStatus('error')- setSubmitError(t('result.submitFailed'))- }- }, [workLink, materialGroupId, materialId, accountType, videoUrl, coverUrl, imgUrlList, title, desc, topics, t])-- if (result.success) {- return (- <Card className="p-0">- {/* Header - 根据提交状态显示不同内容 */}- <div className="p-6 pb-4">- <div className="flex flex-col items-center text-center">- {submitStatus === 'success' || !requireWorkLink ? (- <>- <CheckCircle2 className="mb-4 h-16 w-16 text-green-500" />- <h3 className="text-xl font-semibold">- {!requireWorkLink ? t('result.successTitle') : t('result.linkSubmitSuccessTitle')}- </h3>- {!requireWorkLink && platInfo && (- <div className="mt-2 flex items-center justify-center gap-2 text-sm text-muted-foreground">- <Image src={platInfo.icon} alt={platInfo.name} width={20} height={20} />- <p>{t('result.platformSuccessDescription', { platform: platInfo.name })}</p>- </div>- )}- </>- ) : (- <>- <CircleAlert className="mb-4 h-16 w-16 text-amber-500" />- <h3 className="text-xl font-semibold">{t('result.pendingTitle')}</h3>- <p className="mt-2 text-sm text-muted-foreground">{t('result.pendingDescription')}</p>- </>- )}- </div>- </div>-- {/* Content */}- <div className="px-6 pb-4">- {/* 在链接提交成功或不需要提交链接时显示结果信息 */}- {(submitStatus === 'success' || !requireWorkLink) && (- <div className="rounded-lg bg-muted p-4 text-center">- <p className="text-sm text-muted-foreground">- {result.message || t('result.defaultSuccessMessage')}- </p>- {result.flowId && (- <p className="mt-2 text-xs text-muted-foreground">- {t('result.flowId')}- :- {result.flowId}- </p>- )}- </div>- )}-- {/* 作品链接提交区域 - 仅在需要提交链接时显示 */}- {requireWorkLink && materialGroupId && accountType && submitStatus !== 'success' && (- <div className="mt-4 space-y-3">- <Label htmlFor="workLink" className="flex items-center gap-2 text-sm font-medium">- <Link2 className="h-4 w-4" />- {t('result.workLinkLabel')}- </Label>- <Input- id="workLink"- value={workLink}- onChange={e => setWorkLink(e.target.value)}- placeholder={t('result.workLinkPlaceholder')}- disabled={submitStatus === 'loading'}- />- {submitStatus === 'error' && submitError && (- <p className="text-sm text-destructive">{submitError}</p>- )}- <Button- onClick={handleSubmitWorkLink}- disabled={!workLink.trim() || submitStatus === 'loading'}- className="w-full cursor-pointer"- >- {submitStatus === 'loading'- ? (- <>- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- {t('result.submitting')}- </>- )- : t('result.submitWorkLink')}- </Button>-- {/* 如何获取作品链接按钮 */}- <Button- variant="outline"- onClick={() => setShowGuide(true)}- className="w-full cursor-pointer border-amber-500 text-amber-600 hover:bg-amber-50 hover:text-amber-700 dark:border-amber-400 dark:text-amber-400 dark:hover:bg-amber-950 dark:hover:text-amber-300"- >- <HelpCircle className="mr-2 h-4 w-4" />- {t('result.howToGetLink')}- </Button>- </div>- )}-- {/* 提交成功提示 */}- {submitStatus === 'success' && (- <div className="mt-4 space-y-3">- <div className="rounded-lg bg-green-50 p-4 text-center dark:bg-green-900/20">- <p className="flex items-center justify-center gap-2 text-sm text-green-600 dark:text-green-400">- <CheckCircle2 className="h-4 w-4" />- {t('result.submitSuccess')}- </p>- </div>- {/* 显示已提交的链接 */}- <div className="rounded-lg bg-muted p-4">- <p className="mb-2 text-sm font-medium">{t('result.submittedLink')}</p>- <a- href={workLink}- target="_blank"- rel="noopener noreferrer"- className="flex items-center gap-2 break-all text-sm text-primary hover:underline"- >- <Link2 className="h-4 w-4 shrink-0" />- {workLink}- </a>- </div>- </div>- )}- </div>-- {/* Footer */}- <div className="flex gap-2 p-6 pt-0">- <Button variant="outline" onClick={onRetry} className="cursor-pointer">- <RefreshCw className="mr-2 h-4 w-4" />- {t('result.publishAgain')}- </Button>- <Button onClick={onGoHome} className="flex-1 cursor-pointer">- <Home className="mr-2 h-4 w-4" />- {t('result.goHome')}- </Button>- </div>-- {/* 教程图片预览 */}- <MediaPreview- open={showGuide}- items={guideImages}- onClose={() => setShowGuide(false)}- />- </Card>- )- }-- return (- <Card className="p-0">- {/* Header */}- <div className="p-6 pb-4">- <div className="flex flex-col items-center text-center">- <XCircle className="mb-4 h-16 w-16 text-destructive" />- <h3 className="text-xl font-semibold">{t('result.failedTitle')}</h3>- <p className="mt-2 text-sm text-muted-foreground">{t('result.failedDescription')}</p>- </div>- </div>-- {/* Content */}- <div className="px-6 pb-4">- <div className="rounded-lg bg-destructive/10 p-4 text-center">- <p className="text-sm text-destructive">- {result.message || t('result.defaultFailedMessage')}- </p>- </div>- </div>-- {/* Footer */}- <div className="flex gap-2 p-6 pt-0">- <Button variant="outline" onClick={onGoHome} className="cursor-pointer">- <Home className="mr-2 h-4 w-4" />- {t('result.goHome')}- </Button>- <Button onClick={onRetry} className="flex-1 cursor-pointer">- <RefreshCw className="mr-2 h-4 w-4" />- {t('result.retry')}- </Button>- </div>- </Card>- )-})--PublishResultStep.displayName = 'PublishResultStep'diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsxdeleted file mode 100644index e71b135a..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/page.tsx+++ /dev/null@@ -1,43 +0,0 @@-/**- * 推广码发布页面- * 用于推广者通过推广码进入后发布内容- */--import type { Metadata } from 'next'-import { useTranslation } from '@/app/i18n'-import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'-import PromoPageCore from './promoPageCore'--// 生成 SEO 元数据-export async function generateMetadata({- params,-}: {- params: Promise<{ lng: string, code: string }>-}): Promise<Metadata> {- let { lng } = await params- if (!languages.includes(lng))- lng = fallbackLng- const { t } = await useTranslation(lng, 'promo')-- return getMetadata(- {- title: t('meta.title'),- description: t('meta.description'),- keywords: 'promotion, publish, social media, AiToEarn',- },- lng,- `/promo`,- )-}--// 页面组件-export default async function PromoPage({- params,-}: {- params: Promise<{ lng: string, code: string }>-}) {- const { lng, code } = await params-- return <PromoPageCore lng={lng} code={code} />-}diff --git a/project/aitoearn-web/src/app/[lng]/promo/[code]/promoPageCore.tsx b/project/aitoearn-web/src/app/[lng]/promo/[code]/promoPageCore.tsxdeleted file mode 100644index 8c9cae36..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/[code]/promoPageCore.tsx+++ /dev/null@@ -1,740 +0,0 @@-/**- * PromoPageCore - 推广码发布页面核心组件- * 推广者通过推广码(素材组ID)进入后选择平台发布内容- */--'use client'--import type { OptimalMaterialVo } from '@/api/types/open/promotionCode'-import { AlertCircle, Loader2, RefreshCw } from 'lucide-react'-import { useRouter, useSearchParams } from 'next/navigation'-import { useCallback, useEffect, useRef, useState } from 'react'-import { apiGetOptimalMaterial } from '@/api/open/promotionCode'-import { apiDouyinPublishCreate } from '@/api/plat/douyin'-import { apiGetInstagramNoUserAuthUrl } from '@/api/plat/instagram'-import { apiPubCreate } from '@/api/plat/publish'-import { apiGetTikTokNoUserAuthUrl } from '@/api/plat/tiktok'-import { getUtcDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'-import { PlatType } from '@/app/config/platConfig'-import { PubType } from '@/app/config/publishConfig'-import { useTransClient } from '@/app/i18n/client'-import { Button } from '@/components/ui/button'-import { Card } from '@/components/ui/card'-import { Skeleton } from '@/components/ui/skeleton'-import { generateUUID, parseTopicString } from '@/utils'-import { AiToEarnIntro } from './components/AiToEarnIntro'-import { PlatformSelectStep } from './components/PlatformSelectStep'-import { PublishResultStep } from './components/PublishResultStep'--interface PromoPageCoreProps {- lng: string- code: string-}--// 页面状态枚举-type PageStep- = | 'loading' // 加载中- | 'error' // 错误- | 'platform_select' // 平台选择- | 'publishing' // 发布中- | 'redirecting' // 跳转中(倒计时)- | 'platform_not_supported' // 平台不支持- | 'result' // 发布结果--// 获取/保存选中平台的 key-const getSelectedPlatformKey = (code: string) => `promo_platform_${code}`--// 保存选中的平台(授权前保存,授权回调后使用)-// 使用 sessionStorage,仅在当前会话中有效-function saveSelectedPlatform(code: string, platform: PlatType) {- try {- sessionStorage.setItem(getSelectedPlatformKey(code), platform)- }- catch {- // 忽略存储错误- }-}--// 获取保存的平台-function getSavedPlatform(code: string): PlatType | null {- try {- const platform = sessionStorage.getItem(getSelectedPlatformKey(code))- return platform as PlatType | null- }- catch {- return null- }-}--// 清除保存的平台-function clearSavedPlatform(code: string) {- try {- sessionStorage.removeItem(getSelectedPlatformKey(code))- }- catch {- // 忽略错误- }-}--// 根据 accountId 前缀推断平台类型-// accountId 格式: {platform}_{id},如 tiktok_xxx, instagram_xxx, douyin_xxx-function inferPlatformFromAccountId(accountId: string): PlatType | null {- // 按第一个下划线分割,取平台前缀- const underscoreIndex = accountId.indexOf('_')- if (underscoreIndex === -1)- return null-- const platformPrefix = accountId.substring(0, underscoreIndex).toLowerCase()-- switch (platformPrefix) {- case 'tiktok':- return PlatType.Tiktok- // case 'instagram': // 暂时隐藏 Instagram- // return PlatType.INSTAGRAM- case 'douyin':- return PlatType.Douyin- default:- return null- }-}--export default function PromoPageCore({ lng, code }: PromoPageCoreProps) {- const { t } = useTransClient('promo')- const router = useRouter()- const searchParams = useSearchParams()-- // 页面状态- const [step, setStep] = useState<PageStep>('loading')- const [errorMessage, setErrorMessage] = useState<string>('')-- // 数据状态- const [material, setMaterial] = useState<OptimalMaterialVo | null>(null)-- // 发布状态- const [publishResult, setPublishResult] = useState<{- success: boolean- message?: string- flowId?: string- } | null>(null)-- // 跳转倒计时状态- const [redirectCountdown, setRedirectCountdown] = useState<number | null>(null)- const [redirectUrl, setRedirectUrl] = useState<string | null>(null)-- // TikTok 是否需要提交作品链接(TikTok 不需要)- const [requireWorkLink, setRequireWorkLink] = useState(true)-- // 当前发布的平台类型- const [currentPlatform, setCurrentPlatform] = useState<PlatType | null>(null)-- // 用户选择的平台(根据语言环境设置默认值:中文选抖音,其他选TikTok)- const [selectedPlatform, setSelectedPlatform] = useState<PlatType | null>(- lng.startsWith('zh') ? PlatType.Douyin : PlatType.Tiktok,- )-- // 防止 OAuth 回调重复处理- const oauthProcessedRef = useRef(false)-- // 抖音发布逻辑- const handleDouyinPublish = useCallback(async (materialData: OptimalMaterialVo) => {- setCurrentPlatform(PlatType.Douyin)- setStep('publishing')-- try {- const hasVideo = materialData?.mediaList?.some(m => m.type === 'video')- const { topics, cleanedString } = parseTopicString(materialData?.desc || '')- const topicsAll = [...new Set((materialData.topics ?? []).concat(topics))]-- const publishParams: {- title?: string- desc?: string- materialGroupId?: string- materialId?: string- videoUrl?: string- coverUrl?: string- imgUrlList?: string[]- topics: string[]- } = {- title: materialData?.title || '',- desc: cleanedString,- materialGroupId: code,- materialId: materialData?._id,- topics: topicsAll,- }-- if (hasVideo) {- const videoMedia = materialData?.mediaList?.find(m => m.type === 'video')- publishParams.videoUrl = videoMedia?.url- publishParams.coverUrl = materialData?.coverUrl- }- else if (materialData?.mediaList && materialData.mediaList.length > 0) {- publishParams.imgUrlList = materialData.mediaList- .filter(m => m.type === 'img')- .map(m => m.url)- publishParams.coverUrl = materialData.coverUrl || publishParams.imgUrlList[0]- }-- const res = await apiDouyinPublishCreate(publishParams)-- if (res?.code === 0) {- if (res.data) {- window.location.href = res.data- }-- setPublishResult({- success: true,- message: t('publish.success'),- })- setStep('result')- }- else {- setPublishResult({- success: false,- message: res?.message || t('publish.failed'),- })- setStep('result')- }- }- catch (error) {- console.error('Publish failed:', error)- setPublishResult({- success: false,- message: t('publish.failed'),- })- setStep('result')- }- }, [code, t])-- // TikTok 授权流程- const startTikTokAuth = useCallback(async () => {- setCurrentPlatform(PlatType.Tiktok)- setStep('publishing')- try {- const res = await apiGetTikTokNoUserAuthUrl({- promotionCode: code,- })-- if (res?.code === 0 && res.data?.url) {- setRedirectUrl(res.data.url)- setRedirectCountdown(2)- setStep('redirecting')- }- else {- setPublishResult({- success: false,- message: res?.message || t('publish.authFailed'),- })- setStep('result')- }- }- catch (error) {- console.error('TikTok auth failed:', error)- setPublishResult({- success: false,- message: t('publish.authFailed'),- })- setStep('result')- }- }, [code, t])-- // Instagram 授权流程- const startInstagramAuth = useCallback(async () => {- setCurrentPlatform(PlatType.Instagram)- setStep('publishing')- try {- const res = await apiGetInstagramNoUserAuthUrl({- materialGroupId: code,- })-- if (res?.code === 0 && res.data?.url) {- setRedirectUrl(res.data.url)- setRedirectCountdown(2)- setStep('redirecting')- }- else {- setPublishResult({- success: false,- message: res?.message || t('publish.authFailed'),- })- setStep('result')- }- }- catch (error) {- console.error('Instagram auth failed:', error)- setPublishResult({- success: false,- message: t('publish.authFailed'),- })- setStep('result')- }- }, [code, t])-- // TikTok 发布(直接发布,已有 accountId)- const doTikTokPublish = useCallback(async (materialData: OptimalMaterialVo) => {- const accountId = searchParams.get('accountId')- if (!accountId)- return-- setCurrentPlatform(PlatType.Tiktok)- setStep('publishing')- setRequireWorkLink(false)-- try {- const hasVideo = materialData?.mediaList?.some(m => m.type === 'video')- const title = materialData?.title || ''- const { topics, cleanedString } = parseTopicString(materialData?.desc || '')- const topicsAll = [...new Set((materialData.topics ?? []).concat(topics))]-- const publishType = hasVideo ? PubType.VIDEO : PubType.ImageText- const videoMedia = hasVideo ? materialData?.mediaList?.find(m => m.type === 'video') : null- const photoImages = !hasVideo- ? materialData?.mediaList?.filter(m => m.type === 'img').map(m => m.url) || []- : undefined-- const publishTime = getUtcDays(new Date()).format()- const res = await apiPubCreate({- accountId,- flowId: generateUUID(),- accountType: PlatType.Tiktok,- type: publishType,- title,- desc: cleanedString,- materialGroupId: code,- materialId: materialData?._id,- videoUrl: hasVideo ? videoMedia?.url : undefined,- imgUrlList: !hasVideo ? photoImages : undefined,- coverUrl: materialData?.coverUrl,- publishTime,- topics: topicsAll,- option: materialData?.option?.tiktok || {- tiktok: {- privacy_level: 'PUBLIC_TO_EVERYONE',- comment_disabled: false,- duet_disabled: false,- stitch_disabled: false,- brand_organic_toggle: false,- brand_content_toggle: false,- brand_disclosure_enabled: false,- },- },- })-- if (res?.code === 0) {- clearSavedPlatform(code) // 发布成功后清除保存的平台- setPublishResult({- success: true,- message: t('publish.success'),- })- setStep('result')- }- else {- setPublishResult({- success: false,- message: res?.message || t('publish.failed'),- })- setStep('result')- }- }- catch (error) {- console.error('TikTok publish failed:', error)- setPublishResult({- success: false,- message: t('publish.failed'),- })- setStep('result')- }- }, [code, searchParams, t])-- // Instagram 发布(直接发布,已有 accountId)- const doInstagramPublish = useCallback(async (materialData: OptimalMaterialVo) => {- const accountId = searchParams.get('accountId')- if (!accountId)- return-- setCurrentPlatform(PlatType.Instagram)- setStep('publishing')- setRequireWorkLink(false)-- try {- const hasVideo = materialData?.mediaList?.some(m => m.type === 'video')- const title = materialData?.title || ''- const { topics, cleanedString } = parseTopicString(materialData?.desc || '')- const topicsAll = [...new Set((materialData.topics ?? []).concat(topics))]-- const publishType = hasVideo ? PubType.VIDEO : PubType.ImageText- const videoMedia = hasVideo ? materialData?.mediaList?.find(m => m.type === 'video') : null- const photoImages = !hasVideo- ? materialData?.mediaList?.filter(m => m.type === 'img').map(m => m.url) || []- : undefined-- const publishTime = getUtcDays(new Date()).format()- const res = await apiPubCreate({- accountId,- flowId: generateUUID(),- accountType: PlatType.Instagram,- type: publishType,- title,- desc: cleanedString,- materialGroupId: code,- materialId: materialData?._id,- videoUrl: hasVideo ? videoMedia?.url : undefined,- imgUrlList: !hasVideo ? photoImages : undefined,- coverUrl: materialData?.coverUrl,- publishTime,- topics: topicsAll,- option: materialData?.option?.instagram || {- instagram: {- content_category: publishType === PubType.VIDEO ? 'reel' : 'post',- },- },- })-- if (res?.code === 0) {- clearSavedPlatform(code) // 发布成功后清除保存的平台- setPublishResult({- success: true,- message: t('publish.success'),- })- setStep('result')- }- else {- setPublishResult({- success: false,- message: res?.message || t('publish.failed'),- })- setStep('result')- }- }- catch (error) {- console.error('Instagram publish failed:', error)- setPublishResult({- success: false,- message: t('publish.failed'),- })- setStep('result')- }- }, [code, searchParams, t])-- // 获取素材信息(公开接口,无需登录)- const fetchMaterial = useCallback(async (accountType: PlatType) => {- try {- setStep('loading')-- const res = await apiGetOptimalMaterial(code, accountType)-- if (res?.code === 0 && res.data) {- const materialData = res.data- setMaterial(materialData)- return materialData- }- else if (res?.code === 0 && !res.data) {- setErrorMessage(t('error.noDraft'))- setStep('error')- }- else {- setErrorMessage(t('error.invalidCode'))- setStep('error')- }- }- catch (error) {- console.error('Failed to fetch material:', error)- setErrorMessage(t('error.taskNotFound'))- setStep('error')- }- return null- }, [code, t])-- // OAuth 回调处理(有 accountId 参数时自动获取素材并发布)- const handleOAuthCallback = useCallback(async () => {- const accountId = searchParams.get('accountId')- if (!accountId || oauthProcessedRef.current)- return false-- // 优先从 accountId 前缀推断平台类型(解决跨标签页 sessionStorage 不共享的问题)- // fallback 到 sessionStorage 中保存的平台- const inferredPlatform = inferPlatformFromAccountId(accountId)- const platform = inferredPlatform || getSavedPlatform(code)-- if (!platform)- return false-- // 标记为已处理,防止 React Strict Mode 或依赖变化导致的重复执行- oauthProcessedRef.current = true- setSelectedPlatform(platform)- setCurrentPlatform(platform)-- // 先获取素材- const materialData = await fetchMaterial(platform)- if (!materialData)- return true // 已处理但素材获取失败,fetchMaterial 内部已设置错误状态-- // 直接发布- if (platform === PlatType.Tiktok) {- await doTikTokPublish(materialData)- }- // 暂时隐藏 Instagram- // else if (platform === PlatType.INSTAGRAM) {- // await doInstagramPublish(materialData)- // }- return true- }, [searchParams, code, fetchMaterial, doTikTokPublish, doInstagramPublish])-- // 重新发布(返回平台选择)- const handleRetry = useCallback(() => {- setPublishResult(null)- setSelectedPlatform(null)- setStep('platform_select')- }, [])-- // 平台选择处理- const handlePlatformSelect = useCallback((platform: PlatType) => {- setSelectedPlatform(platform)- }, [])-- // 确认平台选择并开始发布- const handleConfirmPlatform = useCallback(async () => {- if (!selectedPlatform)- return-- const accountId = searchParams.get('accountId')- // 暂时隐藏 Instagram: 原为 selectedPlatform === PlatType.TIKTOK || selectedPlatform === PlatType.INSTAGRAM- const needsOAuth = selectedPlatform === PlatType.Tiktok-- if (needsOAuth && !accountId) {- // 保存选中的平台到 localStorage,授权回调后使用- saveSelectedPlatform(code, selectedPlatform)-- if (selectedPlatform === PlatType.Tiktok) {- await startTikTokAuth()- }- // 暂时隐藏 Instagram- // else if (selectedPlatform === PlatType.INSTAGRAM) {- // await startInstagramAuth()- // }- return- }-- // 先获取素材- const materialData = await fetchMaterial(selectedPlatform)- if (!materialData)- return-- // 抖音直接发布- if (selectedPlatform === PlatType.Douyin) {- await handleDouyinPublish(materialData)- }- else {- // 其他平台暂不支持- setStep('platform_not_supported')- }- }, [selectedPlatform, searchParams, code, startTikTokAuth, startInstagramAuth, fetchMaterial, handleDouyinPublish])-- // 初始化- useEffect(() => {- const accountId = searchParams.get('accountId')- if (accountId) {- // OAuth 回调:获取素材并自动发布- handleOAuthCallback()- }- else {- // 正常流程:直接展示平台选择- setStep('platform_select')- }- }, [searchParams, handleOAuthCallback])-- // 跳转倒计时逻辑- useEffect(() => {- if (redirectCountdown === null)- return-- if (redirectCountdown > 0) {- const timer = setTimeout(() => {- setRedirectCountdown(redirectCountdown - 1)- }, 1000)- return () => clearTimeout(timer)- }-- if (redirectCountdown === 0 && redirectUrl) {- window.location.href = redirectUrl- }- }, [redirectCountdown, redirectUrl])-- // 加载状态- if (step === 'loading') {- return (- <div className="min-h-screen bg-gradient-to-br from-background via-background to-primary/5 px-0 py-4 md:p-8">- <div className="mx-auto max-w-2xl space-y-4 px-4 md:px-0">- <Card className="p-0 shadow-lg">- <div className="p-4 md:p-6">- <Skeleton className="h-8 w-48" />- <Skeleton className="mt-2 h-4 w-full" />- </div>- <div className="space-y-4 px-4 pb-4 md:px-6 md:pb-6">- <Skeleton className="h-24 w-full" />- <Skeleton className="h-12 w-full" />- </div>- </Card>- </div>- </div>- )- }-- // 错误状态- if (step === 'error') {- return (- <div className="min-h-screen bg-gradient-to-br from-background via-background to-destructive/5 px-0 py-4 md:p-8">- <div className="mx-auto max-w-2xl px-4 md:px-0">- <Card className="p-0 shadow-lg border-destructive/10">- <div className="p-6 text-center md:p-8">- <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10 md:h-20 md:w-20">- <AlertCircle className="h-8 w-8 text-destructive md:h-10 md:w-10" />- </div>- <h3 className="text-lg font-semibold md:text-xl">- {t('error.title')}- </h3>- <p className="mt-2 text-sm text-muted-foreground">- {errorMessage}- </p>- <Button- onClick={() => {- const accountId = searchParams.get('accountId')- if (accountId) {- oauthProcessedRef.current = false- handleOAuthCallback()- }- else {- setStep('platform_select')- }- }}- className="mt-6 cursor-pointer"- >- <RefreshCw className="mr-2 h-4 w-4" />- {t('error.retry')}- </Button>- </div>- </Card>- </div>- </div>- )- }-- // 获取发布中状态的文案- const getPublishingText = () => {- switch (currentPlatform) {- case PlatType.Douyin:- return {- title: t('autoPublish.publishingDouyin'),- desc: t('autoPublish.douyinPublishingDesc'),- }- case PlatType.Instagram:- return {- title: t('autoPublish.publishingInstagram'),- desc: t('autoPublish.instagramPublishingDesc'),- }- default:- return {- title: t('autoPublish.publishingTikTok'),- desc: t('autoPublish.tiktokPublishingDesc'),- }- }- }-- // 获取跳转授权的文案- const getRedirectingText = () => {- switch (currentPlatform) {- case PlatType.Instagram:- return t('autoPublish.redirectingToInstagram')- default:- return t('autoPublish.redirectingToTikTok')- }- }-- return (- <div className="min-h-screen bg-gradient-to-br from-background via-background to-primary/5 px-0 py-4 md:p-8">- <div className="mx-auto max-w-2xl space-y-4 px-4 md:space-y-6 md:px-0">- {/* 平台选择 */}- {step === 'platform_select' && (- <PlatformSelectStep- selectedPlatform={selectedPlatform}- onSelect={handlePlatformSelect}- onConfirm={handleConfirmPlatform}- />- )}-- {/* 发布中状态 */}- {step === 'publishing' && (- <Card className="p-0 shadow-lg border-primary/10">- <div className="p-4 text-center md:p-6">- <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 md:h-20 md:w-20">- <Loader2 className="h-8 w-8 animate-spin text-primary md:h-10 md:w-10" />- </div>- <h3 className="text-lg font-semibold md:text-xl">- {getPublishingText().title}- </h3>- <p className="mt-2 text-sm text-muted-foreground">- {getPublishingText().desc}- </p>- </div>- </Card>- )}-- {/* 跳转授权倒计时 */}- {step === 'redirecting' && (- <Card className="p-0 shadow-lg border-primary/10">- <div className="p-4 text-center md:p-6">- <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 md:h-20 md:w-20">- <Loader2 className="h-8 w-8 animate-spin text-primary md:h-10 md:w-10" />- </div>- <h3 className="text-lg font-semibold md:text-xl">- {getRedirectingText()}- </h3>- <p className="mt-2 text-3xl font-bold text-primary">- {redirectCountdown}- s- </p>- </div>- </Card>- )}-- {/* 平台不支持状态 */}- {step === 'platform_not_supported' && (- <Card className="p-0 shadow-lg border-destructive/10">- <div className="p-4 text-center md:p-6">- <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10 md:h-20 md:w-20">- <AlertCircle className="h-8 w-8 text-destructive md:h-10 md:w-10" />- </div>- <h3 className="text-lg font-semibold md:text-xl">- {t('autoPublish.platformNotSupported')}- </h3>- <p className="mt-2 text-sm text-muted-foreground">- {t('autoPublish.platformNotSupportedDesc')}- </p>- </div>- </Card>- )}-- {/* 发布结果 */}- {step === 'result' && publishResult && (- <PublishResultStep- result={publishResult}- materialGroupId={code}- materialId={material?._id}- accountType={currentPlatform || selectedPlatform || undefined}- videoUrl={material?.mediaList?.find(m => m.type === 'video')?.url}- coverUrl={material?.coverUrl}- imgUrlList={material?.mediaList?.filter(m => m.type === 'img').map(m => m.url)}- title={material?.title}- desc={material?.desc}- topics={material?.topics}- requireWorkLink={requireWorkLink}- onRetry={handleRetry}- onGoHome={() => router.push(`/${lng}`)}- />- )}-- {/* 平台介绍 - 仅在发布后显示 */}- {step === 'result' && <AiToEarnIntro />}- </div>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/promo/page.tsx b/project/aitoearn-web/src/app/[lng]/promo/page.tsxdeleted file mode 100644index 453439bd..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/page.tsx+++ /dev/null@@ -1,43 +0,0 @@-/**- * TikTok OAuth 回调页面- * 处理 TikTok 授权后的重定向- */--import type { Metadata } from 'next'-import { useTranslation } from '@/app/i18n'-import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'-import PromoCallbackCore from './promoCallbackCore'--// 生成 SEO 元数据-export async function generateMetadata({- params,-}: {- params: Promise<{ lng: string }>-}): Promise<Metadata> {- let { lng } = await params- if (!languages.includes(lng))- lng = fallbackLng- const { t } = await useTranslation(lng, 'promo')-- return getMetadata(- {- title: t('meta.title'),- description: t('meta.description'),- keywords: t('meta.keywords'),- },- lng,- `/promo`,- )-}--// 页面组件-export default async function PromoCallbackPage({- params,-}: {- params: Promise<{ lng: string }>-}) {- const { lng } = await params-- return <PromoCallbackCore lng={lng} />-}diff --git a/project/aitoearn-web/src/app/[lng]/promo/promoCallbackCore.tsx b/project/aitoearn-web/src/app/[lng]/promo/promoCallbackCore.tsxdeleted file mode 100644index 1c2e4f55..00000000--- a/project/aitoearn-web/src/app/[lng]/promo/promoCallbackCore.tsx+++ /dev/null@@ -1,62 +0,0 @@-/**- * PromoCallbackCore - OAuth 回调核心组件- * 处理 TikTok/Instagram 授权后的重定向逻辑- */--'use client'--import { Loader2 } from 'lucide-react'-import { useRouter, useSearchParams } from 'next/navigation'-import { useEffect, useRef } from 'react'-import { useTransClient } from '@/app/i18n/client'-import { Card } from '@/components/ui/card'--interface PromoCallbackCoreProps {- lng: string-}--export default function PromoCallbackCore({ lng }: PromoCallbackCoreProps) {- const { t } = useTransClient('promo')- const router = useRouter()- const searchParams = useSearchParams()- const processedRef = useRef(false)-- useEffect(() => {- if (processedRef.current)- return- processedRef.current = true-- const accountId = searchParams.get('accountId')- // 兼容 TikTok (promotionCode) 和 Instagram (materialGroupId) 两种回调参数- const promotionCode = searchParams.get('promotionCode') || searchParams.get('materialGroupId')-- if (!promotionCode || !accountId) {- router.replace(`/${lng}`)- return- }-- // 跳转到推广页面,带上 accountId- const targetUrl = accountId- ? `/${lng}/promo/${promotionCode}?accountId=${accountId}`- : `/${lng}/promo/${promotionCode}`-- router.replace(targetUrl)- }, [lng, router, searchParams])-- return (- <div className="min-h-screen bg-gradient-to-br from-background via-background to-primary/5 px-0 py-4 md:p-8">- <div className="mx-auto max-w-2xl px-4 md:px-0">- <Card className="p-0 shadow-lg border-primary/10">- <div className="p-4 text-center md:p-6">- <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 md:h-20 md:w-20">- <Loader2 className="h-8 w-8 animate-spin text-primary md:h-10 md:w-10" />- </div>- <h3 className="text-lg font-semibold md:text-xl">- {t('callback.processing')}- </h3>- </div>- </Card>- </div>- </div>- )-}diff --git a/project/aitoearn-web/src/app/[lng]/tasks-history/TasksHistoryPageContent.tsx b/project/aitoearn-web/src/app/[lng]/tasks-history/TasksHistoryPageContent.tsxnew file mode 100644index 00000000..4948af49--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/tasks-history/TasksHistoryPageContent.tsx@@ -0,0 +1,343 @@+/**+ * 任务记录页内容组件 - Tasks History Content+ * 客户端组件,包含所有交互逻辑+ * 支持搜索任务标题和收藏筛选功能+ */+'use client'++import type { TaskListItem } from '@/api/agent'+import { ArrowLeft, FileText, FileVideo, History, RefreshCw, Search, Star, X } from 'lucide-react'+import { useParams, useRouter } from 'next/navigation'+import { useCallback, useEffect, useRef, useState } from 'react'+import { agentApi } from '@/api/agent'+import { useTransClient } from '@/app/i18n/client'+import { TaskCardSkeleton } from '@/components/Chat'+import TaskHistoryList from '@/components/Chat/TaskHistoryList'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Pagination } from '@/components/ui/pagination'+import UserLogsModal from '@/components/UserLogsModal'+import VideoHistoryModal from '@/components/VideoHistoryModal'+import { toast } from '@/lib/toast'+import { cn } from '@/lib/utils'++export function TasksHistoryPageContent() {+ const { t } = useTransClient('chat')+ const router = useRouter()+ const { lng } = useParams()++ // 状态+ const [tasks, setTasks] = useState<TaskListItem[]>([])+ const [isLoading, setIsLoading] = useState(true)+ const [page, setPage] = useState(1)+ const [total, setTotal] = useState(0)+ const [logsModalOpen, setLogsModalOpen] = useState(false)+ const [videoHistoryModalOpen, setVideoHistoryModalOpen] = useState(false)++ // 搜索和筛选状态+ const [searchKeyword, setSearchKeyword] = useState('')+ const [favoriteOnly, setFavoriteOnly] = useState(false)+ const debounceTimerRef = useRef<NodeJS.Timeout | null>(null)++ // 每页 16 条+ const pageSize = 16++ const totalPages = Math.max(1, Math.ceil(total / pageSize || 1))++ // 判断是否有筛选条件+ const hasFilters = searchKeyword.trim() || favoriteOnly++ /** 加载任务列表(分页) */+ const loadTasks = useCallback(+ async (pageNum: number, keyword?: string, onlyFavorites?: boolean) => {+ setIsLoading(true)+ try {+ const result = await agentApi.getTaskList({+ page: pageNum,+ pageSize,+ keyword: keyword?.trim() || undefined,+ favoriteOnly: onlyFavorites || undefined,+ })+ if (result && result.code === 0 && result.data) {+ const newTasks = result.data.list || []+ setTasks(newTasks)+ setTotal(result.data.total || 0)+ setPage(pageNum)+ }+ }+ catch (error) {+ console.error('Load task list failed:', error)+ toast.error(t('message.error'))+ }+ finally {+ setIsLoading(false)+ }+ },+ [pageSize, t],+ )++ /** 初始加载 */+ useEffect(() => {+ loadTasks(1, searchKeyword, favoriteOnly)+ }, []) // eslint-disable-line react-hooks/exhaustive-deps++ /** 搜索防抖处理 */+ const handleSearchChange = (value: string) => {+ setSearchKeyword(value)++ // 清除之前的定时器+ if (debounceTimerRef.current) {+ clearTimeout(debounceTimerRef.current)+ }++ // 设置 500ms 防抖+ debounceTimerRef.current = setTimeout(() => {+ loadTasks(1, value, favoriteOnly)+ }, 500)+ }++ /** 清除搜索 */+ const handleClearSearch = () => {+ setSearchKeyword('')+ if (debounceTimerRef.current) {+ clearTimeout(debounceTimerRef.current)+ }+ loadTasks(1, '', favoriteOnly)+ }++ /** 切换收藏筛选 */+ const handleToggleFavoriteOnly = () => {+ const newValue = !favoriteOnly+ setFavoriteOnly(newValue)+ loadTasks(1, searchKeyword, newValue)+ }++ /** 清除所有筛选 */+ const handleClearFilters = () => {+ setSearchKeyword('')+ setFavoriteOnly(false)+ if (debounceTimerRef.current) {+ clearTimeout(debounceTimerRef.current)+ }+ loadTasks(1, '', false)+ }++ /** 刷新列表,保持当前筛选条件 */+ const handleRefresh = () => {+ loadTasks(1, searchKeyword, favoriteOnly)+ }++ /** 分页切换 */+ const handlePageChange = (nextPage: number) => {+ if (nextPage < 1 || nextPage > totalPages)+ return+ loadTasks(nextPage, searchKeyword, favoriteOnly)+ }++ /** 返回首页 */+ const handleBack = () => {+ router.push(`/ai-social`)+ }++ /** 打开日志弹窗 */+ const handleOpenLogs = () => {+ setLogsModalOpen(true)+ }++ /** 打开视频历史弹窗 */+ const handleOpenVideoHistory = () => {+ setVideoHistoryModalOpen(true)+ }++ return (+ <div className="flex flex-col min-h-screen bg-background">+ {/* 顶部导航 */}+ <header className="sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-card border-b border-border">+ <div className="flex items-center gap-3">+ <Button variant="ghost" size="icon" onClick={handleBack} className="w-8 h-8">+ <ArrowLeft className="w-5 h-5" />+ </Button>+ <div className="flex items-center gap-2">+ <History className="w-5 h-5 text-primary" />+ <h1 className="text-lg font-semibold text-foreground">{t('history.title')}</h1>+ </div>+ {total > 0 && (+ <span className="text-sm text-muted-foreground">+ (+ {total}+ )+ </span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ onClick={handleOpenLogs}+ className="w-8 h-8"+ title={t('history.logs')}+ >+ <FileText className="w-4 h-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={handleOpenVideoHistory}+ className="w-8 h-8"+ title={t('history.videoHistory')}+ >+ <FileVideo className="w-4 h-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={handleRefresh}+ disabled={isLoading}+ className="w-8 h-8"+ >+ <RefreshCw className={cn('w-4 h-4', isLoading && 'animate-spin')} />+ </Button>+ </div>+ </header>++ {/* 搜索和筛选区域 */}+ <div className="sticky top-[57px] z-10 px-4 py-3 bg-card border-b border-border">+ <div className="flex items-center gap-3 max-w-6xl mx-auto">+ {/* 搜索框 */}+ <div className="relative flex-1">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />+ <Input+ type="text"+ placeholder={t('history.searchPlaceholder')}+ value={searchKeyword}+ onChange={e => handleSearchChange(e.target.value)}+ className="pl-9 pr-9 border-0 bg-muted/50 focus-visible:ring-0 focus-visible:bg-muted"+ />+ {searchKeyword && (+ <button+ type="button"+ onClick={handleClearSearch}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground cursor-pointer"+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>++ {/* 筛选按钮区域 */}+ <div className="flex items-center gap-2 shrink-0">+ {/* 收藏筛选按钮 */}+ <Button+ variant={favoriteOnly ? 'default' : 'outline'}+ size="sm"+ onClick={handleToggleFavoriteOnly}+ className="gap-1.5 cursor-pointer"+ >+ <Star className={cn('w-4 h-4', favoriteOnly && 'fill-current')} />+ <span className="hidden sm:inline">{t('history.favoriteOnly')}</span>+ </Button>++ {/* 清除筛选按钮 */}+ {hasFilters && (+ <Button+ variant="ghost"+ size="sm"+ onClick={handleClearFilters}+ className="text-muted-foreground hover:text-foreground cursor-pointer hidden sm:flex"+ >+ {t('history.clearFilters')}+ </Button>+ )}+ </div>+ </div>+ </div>++ {/* 任务列表 */}+ <main className="flex-1 px-4 py-6">+ <div className="w-full max-w-6xl mx-auto">+ {isLoading ? (+ // 加载骨架屏+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">+ {Array.from({ length: pageSize }).map((_, index) => (+ <TaskCardSkeleton key={index} />+ ))}+ </div>+ ) : tasks.length === 0 ? (+ // 空状态 - 根据筛选条件显示不同提示+ <div className="flex flex-col items-center justify-center py-16">+ {favoriteOnly ? (+ // 收藏筛选的空状态+ <>+ <Star className="w-16 h-16 text-muted-foreground/30 mb-4" />+ <p className="text-muted-foreground mb-4">{t('history.emptyFavorites')}</p>+ <Button onClick={handleClearFilters} className="cursor-pointer">+ {t('history.clearFilters')}+ </Button>+ </>+ ) : searchKeyword.trim() ? (+ // 搜索的空状态+ <>+ <Search className="w-16 h-16 text-muted-foreground/30 mb-4" />+ <p className="text-muted-foreground mb-4">{t('history.emptySearch')}</p>+ <Button onClick={handleClearSearch} className="cursor-pointer">+ {t('history.clearFilters')}+ </Button>+ </>+ ) : (+ // 无任何筛选的空状态+ <>+ <History className="w-16 h-16 text-muted-foreground/30 mb-4" />+ <p className="text-muted-foreground mb-4">{t('history.empty')}</p>+ <Button onClick={handleBack} className="cursor-pointer">+ {t('home.startChat')}+ </Button>+ </>+ )}+ </div>+ ) : (+ // 任务卡片网格 + 分页器+ <>+ <div>+ <TaskHistoryList+ tasks={tasks}+ isLoading={isLoading}+ onRefresh={() => loadTasks(page, searchKeyword, favoriteOnly)}+ />+ </div>++ {/* 分页器(使用项目内的 Pagination 组件) */}+ {totalPages > 1 && (+ <div className="mt-8">+ <Pagination+ current={page}+ pageSize={pageSize}+ total={total}+ onChange={handlePageChange}+ showTotal={(totalCount, [_start, _end]) => (+ <span className="text-sm text-muted-foreground">+ {page}+ {' '}+ /+ {totalPages}+ </span>+ )}+ className="w-full"+ />+ </div>+ )}+ </>+ )}+ </div>+ </main>++ {/* 用户日志弹窗 */}+ <UserLogsModal open={logsModalOpen} onClose={() => setLogsModalOpen(false)} />++ {/* 视频历史弹窗 */}+ <VideoHistoryModal+ open={videoHistoryModalOpen}+ onClose={() => setVideoHistoryModalOpen(false)}+ />+ </div>+ )+}diff --git a/project/aitoearn-web/src/app/[lng]/tasks-history/page.tsx b/project/aitoearn-web/src/app/[lng]/tasks-history/page.tsxnew file mode 100644index 00000000..26b8fea0--- /dev/null+++ b/project/aitoearn-web/src/app/[lng]/tasks-history/page.tsx@@ -0,0 +1,38 @@+/**+ * 任务记录页 - Tasks History+ * 功能:显示所有任务记录,支持分页加载和删除+ */++import type { Metadata } from 'next'+import { useTranslation } from '@/app/i18n'+import { fallbackLng, languages } from '@/app/i18n/settings'+import { getMetadata } from '@/utils/general'++import { TasksHistoryPageContent } from './TasksHistoryPageContent'++// SEO 元数据+export async function generateMetadata({+ params,+}: {+ params: Promise<{ lng: string }>+}): Promise<Metadata> {+ let { lng } = await params+ if (!languages.includes(lng))+ lng = fallbackLng+ const { t } = await useTranslation(lng, 'chat')++ return getMetadata(+ {+ title: t('history.meta.title'),+ description: t('history.meta.description'),+ keywords: t('history.meta.keywords'),+ },+ lng,+ '/tasks-history',+ )+}++// 默认导出+export default function TasksHistoryPage() {+ return <TasksHistoryPageContent />+}diff --git a/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsxindex 9eb0a5c8..18cbc479 100644--- a/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/data-deletion/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsxindex 7e05e1f8..ddd34248 100644--- a/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/data-protection-agreement/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import DataProtectionContent from './DataProtectionContent'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsxindex a6c4483b..cfa238f6 100644--- a/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/extension-privacy-policy/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsxindex e3518458..2d09e532 100644--- a/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/plugin-guide/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import PluginGuideContent from './PluginGuideContent'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsxindex 0bc20c5d..27e365bc 100644--- a/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/privacy-policy/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx b/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsxindex 5db67bb6..42b70432 100644--- a/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx+++ b/project/aitoearn-web/src/app/[lng]/websit/terms-of-service/page.tsx@@ -5,7 +5,7 @@import type { Metadata } from 'next'import { useTranslation } from '@/app/i18n'import { fallbackLng, languages } from '@/app/i18n/settings'-import { getMetadata } from '@/utils/server-general'+import { getMetadata } from '@/utils/general'import styles from '../websit.module.scss'export async function generateMetadata({diff --git a/project/aitoearn-web/src/app/auto-login/route.ts b/project/aitoearn-web/src/app/auto-login/route.tsdeleted file mode 100644index 4ad867d3..00000000--- a/project/aitoearn-web/src/app/auto-login/route.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * auto-login API Route - 读取 init 服务生成的自动登录 token- */--import { readFileSync } from 'fs'-import { NextResponse } from 'next/server'--export const dynamic = 'force-dynamic'--export function GET() {- const tokenPath = process.env.AUTO_LOGIN_TOKEN_PATH- if (!tokenPath) return NextResponse.json({ token: null })- try {- const token = readFileSync(tokenPath, 'utf-8').trim()- return NextResponse.json({ token })- } catch {- return NextResponse.json({ token: null })- }-}diff --git a/project/aitoearn-web/src/app/config/platConfig.ts b/project/aitoearn-web/src/app/config/platConfig.tsindex a7ec77d4..45d86231 100644--- a/project/aitoearn-web/src/app/config/platConfig.ts+++ b/project/aitoearn-web/src/app/config/platConfig.ts@@ -107,7 +107,7 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([{name: 'bilibili',icon: bilibiliSvg,- url: 'https://cp.kuaishou.com/profile',+ url: 'https://www.bilibili.com',pubTypes: new Set([PubType.VIDEO]),commonPubParamsConfig: {topicMax: 10,@@ -268,10 +268,18 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([])export const AccountPlatInfoArr = Array.from(AccountPlatInfoMap)-// ========== 平台排序 ==========+// ========== 区域平台配置 ==========++/** 判断平台是否可用(所有平台均可用) */+export function isPlatformAvailable(_platType: PlatType): boolean {+ return true+}++/** 隐藏的平台(向后兼容,空集合) */+export const ABROAD_HIDDEN_PLATFORMS = new Set<PlatType>()-/** 完整平台列表 */-export const RegionSortedPlatInfoArr = [...AccountPlatInfoArr]+/** 所有平台列表(无区域排序) */+export const RegionSortedPlatInfoArr = AccountPlatInfoArr// ========== 任务推广相关配置 ==========@@ -294,7 +302,7 @@ export const TaskPlatInfoArr = AccountPlatInfoArr.filter(([platType]) => !TASK_EXCLUDED_PLATFORMS.has(platType),)-/** 可用的任务推广平台列表 */+/** 当前区域可用的任务推广平台列表 */export const RegionTaskPlatInfoArr = AccountPlatInfoArr.filter(([platType]) => !TASK_EXCLUDED_PLATFORMS.has(platType),)diff --git a/project/aitoearn-web/src/app/config/promotionConfig.ts b/project/aitoearn-web/src/app/config/promotionConfig.tsdeleted file mode 100644index e69de29b..00000000diff --git a/project/aitoearn-web/src/app/globals.css b/project/aitoearn-web/src/app/globals.cssindex ab71b8b9..7e3619db 100644--- a/project/aitoearn-web/src/app/globals.css+++ b/project/aitoearn-web/src/app/globals.css@@ -164,6 +164,9 @@ button {body {@apply bg-background text-foreground text-sm;}+ *:focus-visible {+ @apply outline-2 outline-offset-2 outline-ring;+ }}body > div {diff --git a/project/aitoearn-web/src/app/i18n/locales/de/account.json b/project/aitoearn-web/src/app/i18n/locales/de/account.jsonindex 8f3de86f..69550108 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/account.json@@ -305,9 +305,9 @@"channelManager": {"myChannels": "Meine Kanäle","title": "Kanalverwaltung",- "description": "Verwalten Sie Ihre Kanäle und Bereichsgruppen",+ "description": "Verwalten Sie Ihre Kanäle und Gruppen","platforms": "Plattformen",- "allChannels": "Alle Kanäle",+ "allChannels": "Meine Kanäle","availablePlatforms": "Verfügbare Plattformen","connectNewChannel": "Kanal verbinden","backToChannels": "Zurück zu Meine Kanäle",@@ -333,15 +333,15 @@"syncFailed": "Kontosynchronisierung fehlgeschlagen","tabs": {"channels": "Kanäle",- "spaces": "Bereiche"+ "spaces": "Gruppen"},- "searchPlaceholder": "Kanäle oder Bereiche suchen...",- "createSpace": "Bereich erstellen",- "createSpaceNamePlaceholder": "Bereichsnamen eingeben",- "createSpaceSuccess": "Bereich erfolgreich erstellt",- "createSpaceFailed": "Bereich konnte nicht erstellt werden",- "editSpaceSuccess": "Bereich erfolgreich bearbeitet",- "editSpaceFailed": "Bereich konnte nicht bearbeitet werden",+ "searchPlaceholder": "Kanäle oder Gruppen suchen...",+ "createSpace": "Gruppe erstellen",+ "createSpaceNamePlaceholder": "Gruppennamen eingeben",+ "createSpaceSuccess": "Gruppe erfolgreich erstellt",+ "createSpaceFailed": "Gruppe konnte nicht erstellt werden",+ "editSpaceSuccess": "Gruppe erfolgreich bearbeitet",+ "editSpaceFailed": "Gruppe konnte nicht bearbeitet werden","deleteChannelSuccess": "Kanal erfolgreich gelöscht","deleteChannelFailed": "Kanal konnte nicht gelöscht werden","sortSuccess": "Sortierung erfolgreich",@@ -350,9 +350,9 @@"moveDown": "Nach unten","noChannels": "Keine Kanäle","deleteConfirm": "Löschen bestätigen",- "deleteSpaceConfirm": "Bereichslöschung bestätigen",- "deleteSpaceSuccess": "Bereich erfolgreich gelöscht",- "deleteSpaceFailed": "Bereich konnte nicht gelöscht werden",+ "deleteSpaceConfirm": "Gruppenlöschung bestätigen",+ "deleteSpaceSuccess": "Gruppe erfolgreich gelöscht",+ "deleteSpaceFailed": "Gruppe konnte nicht gelöscht werden","channelCount": "{{count}} Kanäle","sorting": "Sortierung...","deleting": "Löschen...",diff --git a/project/aitoearn-web/src/app/i18n/locales/de/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/de/affiliates.jsondeleted file mode 100644index e726a286..00000000--- a/project/aitoearn-web/src/app/i18n/locales/de/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "title": "Treten Sie Friends of AiToEarn bei",- "seo": {- "title": "Partnerprogramm - 30% wiederkehrende Provision verdienen",- "description": "Treten Sie dem AiToEarn-Partnerprogramm bei und verdienen Sie 30% Provision auf die Zahlungen jeder Empfehlung für 12 Monate. Teilen Sie Ihren einzigartigen Link und verfolgen Sie Ihre Einnahmen.",- "keywords": "Partnerprogramm, Empfehlungsprovision, Online verdienen, passives Einkommen, 30% Provision, AiToEarn Partner"- },- "describe": "Empfehlen Sie zahlende Benutzer zur Registrierung bei aitoearn.ai und erhalten Sie 30% Provision auf ihre ersten 12 Zahlungen innerhalb von 12 Monaten, insgesamt $716,4!",- "keywords": "AiToEarn Affiliate, Affiliate-Marketing, Geld verdienen, teilen und verdienen, Empfehlungsverdienste",- "subtitle": "Erhalten Sie eine <strong>30% Provision</strong> auf die ersten 12 Zahlungen innerhalb der ersten 12 Monate für zahlende Kunden, die Sie an aitoearn.ai verweisen ($199×12×30% = $716.4)!",- "productIntro": {- "badge": "Github 10k+ Star Open-Source-Projekt",- "headline": "Automatisierte KI-Workflow-Engine",- "features": {- "oneClick": {- "title": "Ein-Klick-Aufgabenausführung",- "description": "Beschreiben Sie Ihren Bedarf, Agent orchestriert intelligent optimale KI-Tool-Kombinationen"- },- "multiModal": {- "title": "Multi-Modale Integration",- "description": "Kombiniert nahtlos Textgenerierung, Bilderstellung, Videoverarbeitung und Übersetzung"- },- "zeroCurve": {- "title": "Null-Lernkurve",- "description": "Vom Konzept zum Endprodukt - 10-fache Effizienzsteigerung ohne manuellen Tool-Wechsel"- }- },- "sections": {- "models": {- "title": "🎯 Premium-KI-Modelle",- "items": [- "<strong>Flaggschiff-LLMs:</strong> Claude Opus 4.5, GPT-5.1, Gemini 3.0 - neueste hochmoderne Modelle",- "<strong>Professionelle Video-Tools:</strong> Sora-2, Veo-3.1 für fortgeschrittene Videogenerierung und -bearbeitung",- "<strong>Hochwertige Bilderstellung:</strong> Nano Banana Pro, GPT-Image für professionelle Visuals"- ]- },- "distribution": {- "title": "📱 Omni-Channel-Verteilung",- "items": [- "<strong>Social-Media-Matrix:</strong> Instagram, TikTok, YouTube, Bilibili, Douyin + 20+ Plattformen",- "<strong>Intelligente Inhaltsanpassung:</strong> Optimiert automatisch Formate für beste Performance jeder Plattform",- "<strong>Massenverwaltung:</strong> Multi-Account-Handling mit Ein-Klick-Veröffentlichung"- ]- },- "processing": {- "title": "⚡ Professionelle Videoverarbeitung",- "items": [- "<strong>KI-gestützte Bearbeitung:</strong> Identifiziert automatisch Highlights für ansprechende Kurzinhalte",- "<strong>Mehrsprachige Sprachausgabe:</strong> Echtzeit-Übersetzung mit natürlicher, fließender Erzählung",- "<strong>Stil-Transformation:</strong> Sofortige Videostil-Änderungen für personalisierte visuelle Erlebnisse"- ]- },- "revolution": {- "title": "🌟 Content-Creation-Revolution",- "description": "Verwandeln Sie Content-Erstellung von manueller Arbeit in intelligente Steuerung. Ob Sie Creator, Marketer oder Unternehmen sind - erschließen Sie unbegrenztes kreatives Potenzial mit Aitoearn Agent."- }- }- },- "totalEarnings": "Gesamtverdienst",- "pending": "Ausstehend",- "pendingTooltip": "Ihr ausstehendes Einkommen wird am {{date}} auf Ihr Konto überwiesen. ",- "viewIncome": "Klicken Sie hier, um das Einkommen anzuzeigen",- "settled": "Abgerechnet",- "referralLink": {- "title": "Ihr Empfehlungslink",- "copy": "Kopieren",- "copied": "Kopiert!",- "copySuccess": "Empfehlungslink kopiert!",- "copyError": "Fehler beim Kopieren des Links",- "description": "Teilen Sie diesen Link mit Ihren Freunden und verdienen Sie 30% Provision auf ihre ersten 12 Zahlungen!"- },- "goToPublish": "Gehen Sie zu AiToEarn veröffentlichen",- "oneClickPromotion": {- "button": "Ein-Klick AiToEarn bewerben & {{amount}} verdienen",- "description": "KI erstellt automatisch Werbevideo mit Ihrem Empfehlungslink und veröffentlicht es auf allen Ihren Kanälen"- },- "stats": {- "totalReferrals": "Gesamte Empfehlungen",- "paidReferrals": "Bezahlte Empfehlungen",- "conversionRate": "Konversionsrate"- },- "commissions": {- "title": "Monatliche Provisionsdetails",- "settled": "Abgerechnet",- "pending": "Ausstehend",- "noData": "Noch keine Provisionen. Beginnen Sie, Ihren Empfehlungslink zu teilen!"- },- "howItWorks": {- "title": "So funktioniert es",- "step1": "Teilen Sie Ihren einzigartigen Empfehlungslink mit Freunden und Kontakten",- "step2": "Wenn sie sich anmelden und eine Zahlung tätigen, verdienen Sie 30% Provision",- "step3": "Verdienen Sie Provision auf ihre ersten 12 Zahlungen innerhalb von 12 Monaten",- "step4": "Provisionen werden monatlich abgerechnet und können auf Ihr Wallet ausgezahlt werden"- },- "loading": {- "failed": "Fehler beim Laden der Daten"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/de/brandPromotion.jsonindex cddf9be8..fd8a7f78 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/brandPromotion.json@@ -29,6 +29,20 @@"imageCountExceeded": "Bilderanzahl überschreitet das Plattformlimit (max. {{max}})"},"platformIncompatibleCount": "{{count}} inkompatibel",- "timeLimitedModelTip": "Zeitlich begrenzte Modelle sind nicht garantiert verfügbar. Falls nicht nutzbar, versuchen Sie es später erneut oder wechseln Sie zu einem anderen Modell."+ "timeLimitedModelTip": "Zeitlich begrenzte Modelle sind nicht garantiert verfügbar. Falls nicht nutzbar, versuchen Sie es später erneut oder wechseln Sie zu einem anderen Modell.",+ "draftModeOn": "Entwurf erstellen",+ "draftModeOffVideo": "Video erstellen",+ "draftModeOffImage": "Bild erstellen",+ "modelType": "Modell",+ "duration": "Videolänge",+ "aspectRatio": "Verhältnis",+ "promptTitle": "Benutzerdefinierter Prompt",+ "referenceImages": "Referenzbilder",+ "imageModel": "Bildmodell",+ "imageCount": "Bilderanzahl",+ "imageResolution": "Auflösung"+ },+ "publishRecord": {+ "untitled": "Unbenannt"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/common.json b/project/aitoearn-web/src/app/i18n/locales/de/common.jsonindex 5146eac1..3c3d5800 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/common.json@@ -89,7 +89,8 @@"draftBox": "Inhaltsverwaltung","draftBoxSeoTitle": "Content-Management - KI-Batch-Erstellung & Entwurfseditor","draftBoxSeoDescription": "Alle Ihre Content-Entwürfe an einem Ort verwalten. Mit KI Social-Media-Posts generieren, Entwürfe vor der Veröffentlichung bearbeiten.",- "draftBoxSeoKeywords": "Content-Management, Entwurfseditor, KI-Content-Generierung, Batch-Erstellung, Social-Media-Entwürfe, AiToEarn"+ "draftBoxSeoKeywords": "Content-Management, Entwurfseditor, KI-Content-Generierung, Batch-Erstellung, Social-Media-Entwürfe, AiToEarn",+ "agentAssets": "Agent-Materialien"},"tasks": "Marktplatz","signIn": {@@ -128,20 +129,23 @@"networkError": "Netzwerkfehler, bitte später erneut versuchen!","contact": "Brauchen Sie Hilfe? Kontaktieren Sie den Support:","uptime": {- "seoTitle": "Servicestatus - Echtzeit-Systemüberwachung",- "pageKeywords": "Servicestatus, Systemüberwachung, Verfügbarkeits-Tracker, Server-Status, API-Status, AiToEarn-Status",- "pageTitle": "Dienststatus",- "pageDescription": "Überwachen Sie den Echtzeitstatus und die Verfügbarkeit der AiToEarn-Dienste. Prüfen Sie den Betriebsstatus von Agent, Server, KI, Datenbank und Netzwerkmodulen.",+ "seoTitle": "KI-Modellstatus - Echtzeit-Verfügbarkeitsüberwachung",+ "pageKeywords": "KI-Modellstatus, Modellverfügbarkeit, Verfügbarkeits-Tracker, KI-Service-Status, Modellüberwachung, AiToEarn-Status",+ "pageTitle": "KI-Modellstatus",+ "pageDescription": "Überwachen Sie die Echtzeit-Verfügbarkeit und Betriebszeit der KI-Modelle. Prüfen Sie den Betriebsstatus jedes Modells und Anbieters.","loading": "Laden...","noData": "Keine Daten","uptimePercentage": "Verfügbarkeit:","normal": "Normal","timeout": "Zeitüberschreitung","unavailable": "Nicht verfügbar",+ "provider": "Anbieter",+ "operation": "Vorgang",+ "latency": "Latenz",+ "errorType": "Fehler","filter": {"title": "Filter",- "module": "Modul",- "type": "Typ",+ "model": "Modell","timeRange": "Zeitraum","all": "Alle","last7Days": "Letzte 7 Tage",@@ -151,20 +155,7 @@"apply": "Anwenden"},"copy": "Kopieren",- "copied": "Kopiert",- "module": {- "Agent": "Agent",- "Server": "Server",- "Ai": "KI",- "Database": "Datenbank",- "Network": "Netzwerk",- "Other": "Sonstiges"- },- "type": {- "AgentStatus": "Agent-Status",- "AgentMcpStatus": "Agent-MCP-Status",- "NewApiStatus": "NewApi-Status"- }+ "copied": "Kopiert"},"websit": {"termsOfService": {@@ -275,5 +266,6 @@"abroadContent": "{{platform}} ist nur auf der internationalen Seite verfügbar. Zur internationalen Seite weiterleiten?","ok": "Weiter","cancel": "Abbrechen"- }+ },+ "noMore": "Keine weiteren Daten"}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/material.json b/project/aitoearn-web/src/app/i18n/locales/de/material.jsonindex 491e3e2f..17a6de6a 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/material.json@@ -51,6 +51,10 @@"upload": "Hochladen","deleteMediaConfirm": "Sind Sie sicher, dass Sie dieses Medium löschen möchten?","noMedia": "Keine Medienressourcen",+ "noVideo": "Noch keine Videos",+ "noImage": "Noch keine Bilder",+ "noVideoDesc": "Generierte Videos werden hier angezeigt",+ "noImageDesc": "Generierte Bilder werden hier angezeigt","uploadMediaHint": "Klicken Sie auf die Schaltfläche unten, um {{type}} hochzuladen","searchPlaceholder": "Gruppen suchen...","default": "Standard",@@ -69,7 +73,8 @@"selectImage": "Bild auswählen","selectedCount": "{{count}} ausgewählt","confirm": "Bestätigen",- "noMediaDesc": "Keine Medien in dieser Gruppe"+ "noMediaDesc": "Keine Medien in dieser Gruppe",+ "drafts": "Entwürfe"},"aiGenerate": {"title": "KI-Tools",diff --git a/project/aitoearn-web/src/app/i18n/locales/de/plugin.json b/project/aitoearn-web/src/app/i18n/locales/de/plugin.jsonindex 8a241ec7..7a241fe1 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "Das AiToEarn-Browser-Plugin ist speziell für den intelligenten Betrieb von Xiaohongshu entwickelt. Bitte klicken Sie auf die Schaltfläche unten, um es herunterzuladen und zu installieren.","downloadButton": "Jetzt herunterladen","chromeWebStore": "Chrome Web Store",- "githubRelease": "GitHub Release","chinaDownload": "China-Download","activeDescription": "Ihr Browser-Plugin ist aktiviert. Sie können jetzt die Veröffentlichungsfunktion nutzen!","platformAccounts": "Plattform-Konten",@@ -96,6 +95,6 @@"title": "Nur für Desktop","description": "Die Browser-Erweiterung ist auf mobilen Geräten nicht verfügbar. Bitte verwenden Sie einen Desktop-Browser, um die Erweiterung zu installieren und zu nutzen.","goToPC": "Bitte am PC besuchen",- "introduction": "Browser-Erweiterung für die AiToEarn-Plattform. Arbeitet mit AiToEarn Web zusammen, um die Veröffentlichung von Xiaohongshu-Inhalten zu automatisieren — Videos, Bilderkarussells, Titel, Hashtags und mehr, alles mit einem Klick. Integrierter AI Agent, angetrieben von Claude Opus 4.6 — einem der fortschrittlichsten KI-Modelle der Welt — hilft Ihnen, Browseraufgaben durch natürliche Konversation zu automatisieren. Installieren Sie die Erweiterung, um alle AiToEarn-Plattformfunktionen freizuschalten, einschließlich Ein-Klick-Veröffentlichung, Echtzeit-Fortschrittsverfolgung und KI-gesteuerte Automatisierung."+ "introduction": "AiToEarn-Plattform Browser-Erweiterung. Arbeitet mit AiToEarn Web zusammen, um Interaktionen auf Xiaohongshu, TikTok und anderen Plattformen zu automatisieren — Folgen, Liken, Lesezeichen, Kommentieren und mehr."}}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/promo.json b/project/aitoearn-web/src/app/i18n/locales/de/promo.jsondeleted file mode 100644index 6bd4db27..00000000--- a/project/aitoearn-web/src/app/i18n/locales/de/promo.json+++ /dev/null@@ -1,7 +0,0 @@-{- "meta": {- "title": "Schnell veröffentlichen - Inhalte per Promotion-Code teilen",- "description": "Veröffentlichen Sie Werbeinhalte auf Ihren Social-Media-Konten mit einem Promotion-Code. Wählen Sie Ihre Plattform, passen Sie Ihren Beitrag an und verdienen Sie Belohnungen auf AiToEarn.",- "keywords": "Promotion-Code, Social-Media-Veröffentlichung, Inhalte teilen, Markenpromotion, Belohnungen verdienen, AiToEarn"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/task.json b/project/aitoearn-web/src/app/i18n/locales/de/task.jsonindex 000d24ef..b3952dd7 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/task.json@@ -13,6 +13,7 @@"menu.aiContent": "AI Content","menu.aiInteraction": "AI Interact","menu.myChannel": "My Channel",+ "menu.mySettings": "Einstellungen","menu.myBrand": "My Agent","menu.contentTrading": "Content Trading","menu.aiAgent": "AI Agent",@@ -26,6 +27,20 @@"filter.allCountries": "Alle Länder","filter.allStatuses": "Alle Status","filter.search": "Aufgaben suchen…",+ "filter.searchPlaceholder": "Stichwort suchen…",+ "filter.taskType": "Aufgabentyp",+ "filter.allTypes": "Alle",+ "filter.promotion": "Promotion",+ "filter.interaction": "Interaktion",+ "filter.country": "Land/Region",+ "filter.dateRange": "Veröffentlichungsdatum",+ "filter.startDate": "Startdatum",+ "filter.endDate": "Enddatum",+ "filter.advancedFilter": "Erweiterte Filter",+ "filter.confirm": "Filter anwenden",+ "filter.selectDateRange": "Datumsbereich wählen",+ "filter.clear": "Löschen",+ "filter.reset": "Zurücksetzen","card.publishTime": "Veröffentlicht","banner.title": "Want to promote your brand?",@@ -33,6 +48,7 @@"banner.publishNow": "Publish Now","card.perArticle": "Earn per post",+ "card.perInteraction": "Earn per task","card.goCheck": "Details","card.inviting": "Inviting","card.soldOut": "Sold Out",@@ -79,6 +95,7 @@"status.del": "Widerrufen","statusHint.doing": "Bitte erfüllen Sie die Aufgabenanforderungen und reichen Sie Ihre Arbeit ein",+ "statusHint.doing_interaction": "Bitte schließen Sie die Interaktionsaufgabe ab und reichen Sie Screenshots ein","statusHint.waiting": "Ihre Arbeit wird veröffentlicht, bitte warten","statusHint.pending": "Arbeit eingereicht, wartet auf Überprüfung","statusHint.approved": "Überprüfung bestanden, wartet auf Abrechnung",@@ -106,6 +123,7 @@"detail.platform": "Platform","detail.deadline": "Deadline","detail.submissionTime": "Einreichungszeit",+ "detail.submittedWorkLink": "Eingereichte Arbeit","detail.recruits": "Max Recruits","detail.currentRecruits": "Recruited","detail.interactionReq": "Interaction Requirements",@@ -203,13 +221,18 @@"create.districtPlaceholder": "Bezirk","create.validation.placeRequired": "Standortanforderung ist aktiviert, bitte geben Sie einen Ort ein","create.validation.countryRequired": "Standortanforderung ist aktiviert, bitte wählen Sie ein Land",+ "create.validation.cpmRewardMin": "CPM-Preis muss größer als 0 sein",+ "create.validation.cpeRewardMin": "CPE-Preis muss größer als 0 sein","create.collectNotSupported": "Diese Plattform unterstützt keine Favoriten","detail.rewardPerPost": "Belohnung pro Beitrag",+ "detail.rewardPerInteraction": "Belohnung pro Interaktion","detail.recruitProgress": "Rekrutierungsfortschritt","detail.taskType": "Aufgabentyp","detail.taskType.promotion": "Promotion","detail.taskType.interaction": "Interaktion",+ "detail.taskType.promotionTip": "Benutzer nehmen Aufgaben an und veröffentlichen Videos gemäß den Anforderungen",+ "detail.taskType.interactionTip": "Benutzer nehmen Aufgaben an und liken, kommentieren und sammeln Werke gemäß den Anforderungen","detail.scope.online": "Online","detail.scope.offline": "Offline","detail.location": "Standort",@@ -265,6 +288,13 @@"stats.noTitle": "Kein Titel","stats.fetchFailed": "Statistikdaten konnten nicht abgerufen werden","stats.publishTime": "Veröffentlicht",+ "stats.trendTitle": "7-Tage-Interaktionstrend",+ "stats.trendViews": "Aufrufe",+ "stats.trendLikes": "Likes",+ "stats.trendComments": "Kommentare",+ "stats.trendShares": "Geteilt",+ "stats.trendFavorites": "Favoriten",+ "stats.trendNoData": "Noch keine Trenddaten","seo.homeTitle": "Bezahlte Promotion-Aufgaben - Mit Social Media verdienen","seo.myTasksTitle": "Meine Aufgaben - Veröffentlichte & Angenommene Promotions verfolgen",@@ -290,7 +320,7 @@"detail.interactionHint": "Bitte führen Sie zuerst die folgenden Aktionen aus: {{actions}}, und laden Sie dann Screenshots hoch","detail.interactionAction.like": "Gefällt mir","detail.interactionAction.collect": "Sammeln",- "detail.interactionAction.forward": "Weiterleiten",+ "detail.interactionAction.comment": "Kommentieren","create.insufficientBalance.title": "Unzureichendes Guthaben","create.insufficientBalance.description": "Diese Aufgabe erfordert {{symbol}}{{required}}, Ihr aktuelles Guthaben beträgt {{symbol}}{{current}}, Differenz {{symbol}}{{deficit}}. Möchten Sie {{symbol}}{{rechargeAmount}} aufladen?",@@ -309,7 +339,7 @@"create.interaction.actions": "Interaktionsaktionen","create.interaction.actionLike": "Gefällt mir","create.interaction.actionCollect": "Sammeln",- "create.interaction.actionForward": "Weiterleiten",+ "create.interaction.actionComment": "Kommentieren","create.interaction.quantity": "Anzahl Interaktionen","create.interaction.quantityHint": "Wie viele Personen für diese Interaktion rekrutiert werden","create.interaction.quantityMin": "Mindestens 1 Person",@@ -321,6 +351,7 @@"create.interaction.validation.actionsRequired": "Bitte wählen Sie mindestens eine Interaktionsaktion","create.interaction.validation.rewardMin": "Mindestens {{symbol}}{{min}} pro Person","create.interaction.validation.quantityMin": "Mindestens 1 Person erforderlich",+ "create.interaction.validation.unsupportedPlatform": "Bitte geben Sie einen unterstützten Plattform-Link ein (Unterstützt: Xiaohongshu, TikTok, YouTube, Twitter, Facebook, Instagram, Bilibili, Douyin)","detail.submitByLink": "Link einreichen","detail.publishFromPlatform": "Von Plattform veröffentlichen",@@ -351,5 +382,27 @@"dispute.confirm": "Möchten Sie diesen Einspruch wirklich einreichen? Die Aufgabe wird in den Einspruchsprüfungsstatus versetzt.","dispute.confirmTitle": "Einspruch bestätigen","dispute.reasonRequired": "Bitte geben Sie einen Einspruchsgrund an",- "dispute.screenshotRequired": "Bitte laden Sie mindestens einen Screenshot als Beweis hoch"+ "dispute.screenshotRequired": "Bitte laden Sie mindestens einen Screenshot als Beweis hoch",++ "detail.cpmReward": "Pro 1K Aufrufe",+ "detail.cpeReward": "Pro 1K Interaktionen",+ "detail.engagementRule": "Interaktionsregel: Like×1 + Sammeln×3 + Kommentar×5",+ "detail.cpmRewardLabel": "Pro 1K Aufrufe",+ "detail.cpeRewardLabel": "Pro 1K Interaktionen",+ "detail.cpmRewardUnit": "/ 1K Aufrufe",+ "detail.cpeRewardUnit": "/ 1K Interaktionen",+ "card.cpmReward": "Pro 1K Aufrufe",+ "card.cpeReward": "Pro 1K Interaktionen",++ "detail.interactionLink": "Interaktionslink",+ "detail.interactionTip": "Sie müssen dieses Werk {{actions}}",++ "time.justNow": "Gerade eben",+ "time.minutesAgo": "vor {{minutes}} Min.",+ "time.hoursAgo": "vor {{hours}} Std.",+ "time.daysAgo": "vor {{days}} Tagen",+ "format.tenThousand": "{{value}}w",+ "create.defaultTaskTitle": "{{platform}} Promotion",+ "workPerformance.dataUpdateTime": "Die Werkdaten werden täglich um 2:00 Uhr UTC aktualisiert",+ "userTasks.settle.rule": "Abrechnungsregel: Nach Genehmigung des Werks erfasst das System 7 Tage lang Daten und rechnet dann automatisch ab"}diff --git a/project/aitoearn-web/src/app/i18n/locales/de/welcome.json b/project/aitoearn-web/src/app/i18n/locales/de/welcome.jsonindex 2c0cece9..46590236 100644--- a/project/aitoearn-web/src/app/i18n/locales/de/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/de/welcome.json@@ -12,7 +12,7 @@"pricing": "Preise","docs": "Dokumentation","brandPromotion": "Produkt",- "aiSocial": "KI Social",+ "aiSocial": "KI Veröffentlichung","login": "Anmelden","getDemo": "Kostenlos starten"},diff --git a/project/aitoearn-web/src/app/i18n/locales/en/account.json b/project/aitoearn-web/src/app/i18n/locales/en/account.jsonindex 52b0b72e..583f5130 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/account.json@@ -302,14 +302,15 @@"web": "Web","app": "App"},+ "agentCreate": "Agent Create","channelManager": {"browserPlugin": "Browser Plugin","xhsMobileNotSupported": "Sorry, Rednote requires a browser plugin. Please use AiToEarn on PC to operate Rednote.","myChannels": "My Channels","title": "Channel Manager",- "description": "Manage your channels and space groups",+ "description": "Manage your channels and groups","platforms": "Platforms",- "allChannels": "All Channels",+ "allChannels": "My Channels","availablePlatforms": "Available Platforms","connectNewChannel": "Connect Channel","backToChannels": "Back to My Channels",@@ -335,15 +336,15 @@"syncFailed": "Account sync failed","tabs": {"channels": "Channels",- "spaces": "Spaces"+ "spaces": "Groups"},- "searchPlaceholder": "Search channels or spaces...",- "createSpace": "Create Space",- "createSpaceNamePlaceholder": "Enter space name",- "createSpaceSuccess": "Space created successfully",- "createSpaceFailed": "Failed to create space",- "editSpaceSuccess": "Space edited successfully",- "editSpaceFailed": "Failed to edit space",+ "searchPlaceholder": "Search channels or groups...",+ "createSpace": "Create Group",+ "createSpaceNamePlaceholder": "Enter group name",+ "createSpaceSuccess": "Group created successfully",+ "createSpaceFailed": "Failed to create group",+ "editSpaceSuccess": "Group edited successfully",+ "editSpaceFailed": "Failed to edit group","deleteChannelSuccess": "Channel deleted successfully","deleteChannelFailed": "Failed to delete channel","sortSuccess": "Sort successful",@@ -352,9 +353,9 @@"moveDown": "Move down","noChannels": "No channels","deleteConfirm": "Confirm delete",- "deleteSpaceConfirm": "Confirm Delete Space",- "deleteSpaceSuccess": "Space deleted successfully",- "deleteSpaceFailed": "Failed to delete space",+ "deleteSpaceConfirm": "Confirm Delete Group",+ "deleteSpaceSuccess": "Group deleted successfully",+ "deleteSpaceFailed": "Failed to delete group","channelCount": "{{count}} channels","sorting": "Sorting...","deleting": "Deleting...",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/en/affiliates.jsondeleted file mode 100644index bc702102..00000000--- a/project/aitoearn-web/src/app/i18n/locales/en/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "title": "Join Friends of AiToEarn",- "seo": {- "title": "Affiliate Program - Earn 30% Recurring Commission",- "description": "Join the AiToEarn affiliate program and earn 30% commission on every referral's payments for 12 months. Share your unique link, track earnings in real-time, and build passive income with AI content tools.",- "keywords": "affiliate program, referral commission, earn money online, passive income, 30% commission, referral program, content creator affiliate, AiToEarn affiliate"- },- "describe": "Refer paying users to register at aitoearn.ai and earn 30% commission on their first 12 payments within 12 months, totaling $716.4!",- "keywords": "AiToEarn affiliate, affiliate marketing, earn money, share and earn, referral earnings",- "subtitle": "Receive a <strong>30% commission</strong> on the first 12 payments within the first 12 months for paying customers you refer to aitoearn.ai ($199×12×30% = $716.4)!",- "productIntro": {- "badge": "Github 10k+ Star open-sourced project",- "headline": "Automated AI Workflow Engine",- "features": {- "oneClick": {- "title": "One-Click Task Execution",- "description": "Describe your need, Agent intelligently orchestrates optimal AI tool combinations"- },- "multiModal": {- "title": "Multi-Modal Integration",- "description": "Seamlessly combines text generation, image creation, video processing, and translation"- },- "zeroCurve": {- "title": "Zero-Learning Curve",- "description": "From concept to final product - 10x efficiency boost without manual tool switching"- }- },- "sections": {- "models": {- "title": "🎯 Premium AI Models",- "items": [- "<strong>Flagship LLMs:</strong> Claude Opus 4.5, GPT-5.1, Gemini 3.0 - latest cutting-edge models",- "<strong>Professional Video Tools:</strong> Sora-2, Veo-3.1 for advanced video generation and editing",- "<strong>High-Quality Image Creation:</strong> Nano Banana Pro, GPT-Image for professional-grade visuals"- ]- },- "distribution": {- "title": "📱 Omni-Channel Distribution",- "items": [- "<strong>Social Media Matrix:</strong> Instagram, TikTok, YouTube, Bilibili, Douyin + 20+ platforms",- "<strong>Smart Content Adaptation:</strong> Auto-optimizes formats for each platform's best performance",- "<strong>Bulk Management:</strong> Multi-account handling with one-click publishing"- ]- },- "processing": {- "title": "⚡ Professional Video Processing",- "items": [- "<strong>AI-Powered Editing:</strong> Automatically identifies highlights for engaging short-form content",- "<strong>Multi-Language Voiceover:</strong> Real-time translation with natural, fluent narration",- "<strong>Style Transformation:</strong> Instant video style changes for personalized visual experiences"- ]- },- "revolution": {- "title": "🌟 Content Creation Revolution",- "description": "Transform content creation from manual labor to intelligent direction. Whether you're a creator, marketer, or business - unlock unlimited creative potential with Aitoearn Agent."- }- }- },- "totalEarnings": "Total Earnings",- "pending": "Pending",- "pendingTooltip": "Your pending income will be settled to your account on {{date}}. ",- "viewIncome": "Click to view income",- "settled": "Settled",- "referralLink": {- "title": "Your Referral Link",- "copy": "Copy",- "copied": "Copied!",- "copySuccess": "Referral link copied!",- "copyError": "Failed to copy link",- "description": "Share this link with your friends and earn 30% commission on their first 12 payments!"- },- "goToPublish": "Go to Publish AiToEarn",- "oneClickPromotion": {- "button": "One-Click Promote AiToEarn & Earn {{amount}}",- "description": "AI automatically creates promotional video with your referral link and publishes to all your channels"- },- "stats": {- "totalReferrals": "Total Referrals",- "paidReferrals": "Paid Referrals",- "conversionRate": "conversion rate"- },- "commissions": {- "title": "Monthly Commission Details",- "settled": "Settled",- "pending": "Pending",- "noData": "No commissions yet. Start sharing your referral link!"- },- "howItWorks": {- "title": "How It Works",- "step1": "Share your unique referral link with friends and contacts",- "step2": "When they sign up and make a payment, you earn 30% commission",- "step3": "Earn commission on their first 12 payments within 12 months",- "step4": "Commissions are settled monthly and can be withdrawn to your wallet"- },- "loading": {- "failed": "Failed to load data"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/en/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/en/brandPromotion.jsonindex fc9bcb4d..f349af72 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/brandPromotion.json@@ -106,7 +106,6 @@"videoEditMode": "Video Edit","ratioLockedByVideo": "Ratio follows input video","durationLockedByVideo": "Duration matches input video",- "durationAutoAdjusted": "Duration auto-adjusted to {{duration}}s","dropToUpload": "Drop files here to upload","resetConfig": "Reset","targetPlatforms": "Target Platforms",@@ -131,7 +130,10 @@"imageCountExceeded": "Image count exceeds the platform limit (max {{max}})"},"platformIncompatibleCount": "{{count}} incompatible",- "timeLimitedModelTip": "Time-limited models are not guaranteed to be available. If unavailable, please try again later or switch to another model."+ "timeLimitedModelTip": "Time-limited models are not guaranteed to be available. If unavailable, please try again later or switch to another model.",+ "draftModeOn": "Generate Draft",+ "draftModeOffVideo": "Generate Video",+ "draftModeOffImage": "Generate Image"},"tabs": {"overview": "Overview",@@ -155,6 +157,8 @@"downloadQRCode": "Download QR Code","draftSummary": "Draft Summary","draftList": "{{count}} Drafts",+ "videoList": "{{count}} Videos",+ "imageList": "{{count}} Images","viewMore": "View More","publishRecordSummary": "Publish Records","backToTop": "Back to Top",@@ -220,12 +224,15 @@"shareCount": "Shares","favoriteCount": "Favorites","dataUpdatedAt": "Data Updated",- "noWorkLink": "No work link"+ "noWorkLink": "No work link",+ "untitled": "Untitled"},"material": {"emptyTitle": "No Materials","emptyDesc": "Create materials or use Agent to batch generate","useCount": "Used {{count}} times",+ "draft": "Draft",+ "untitled": "Untitled Draft","generating": "Generating","completed": "Completed"},@@ -293,7 +300,18 @@"titlePlaceholder": "Enter draft title","pleaseUploadMedia": "Please upload image or video","titleRequired": "Please enter a title",- "descRequired": "Please enter a description"+ "descRequired": "Please enter a description",+ "targetPlatforms": "Target Platforms",+ "selectAll": "Select All",+ "deselectAll": "Deselect All",+ "titleExceeded": "Title exceeds {{platform}} limit of {{max}} characters",+ "descExceeded": "Description exceeds {{platform}} limit of {{max}} characters",+ "imageExceeded": "Images exceed {{platform}} limit of {{max}}",+ "validationWarnings": "Compatibility Warnings",+ "instagramImageAspectRatio": "Instagram image aspect ratio must be between 4:5 and 1.91:1",+ "instagramVideoAspectRatio": "Instagram video aspect ratio must be between 9:16 and 4:5",+ "facebookImageAspectRatio": "Facebook image aspect ratio must be between 4:5 and 1.91:1",+ "facebookVideoAspectRatio": "Facebook video aspect ratio must be between 9:16 and 4:5"},"planTab": {"more": "More",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/common.json b/project/aitoearn-web/src/app/i18n/locales/en/common.jsonindex c1e3f2c2..bbe9c52e 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/common.json@@ -91,7 +91,8 @@"draftBoxSeoTitle": "Content Management - AI Batch Creation & Draft Editor","draftBoxSeoDescription": "Manage all your content drafts in one place. Use AI to batch generate social media posts, edit drafts before publishing, and organize content for multi-platform distribution with AiToEarn.","draftBoxSeoKeywords": "content management, draft editor, AI content generation, batch content creation, social media drafts, content scheduling, AiToEarn",- "brandPromotion": "AI Check-in"+ "brandPromotion": "AI Check-in",+ "agentAssets": "Agent Assets"},"tasks": "Marketplace","signIn": {@@ -130,20 +131,23 @@"networkError": "Network error, please try again later!","contact": "Need help? Contact support:","uptime": {- "seoTitle": "Service Status - Real-Time System Health Monitor",- "pageKeywords": "service status, system monitoring, uptime tracker, server health, API status, AiToEarn status, real-time monitoring",- "pageTitle": "Service Status",- "pageDescription": "Monitor the real-time status and uptime of AiToEarn services. Check the operational status of Agent, Server, AI, Database, and Network modules.",+ "seoTitle": "AI Model Status - Real-Time Model Availability Monitor",+ "pageKeywords": "AI model status, model availability, uptime tracker, AI service health, model monitoring, AiToEarn status",+ "pageTitle": "AI Model Status",+ "pageDescription": "Monitor the real-time availability and uptime of AI models. Check the operational status of each model and provider.","loading": "Loading...","noData": "No data","uptimePercentage": "Uptime:","normal": "Normal","timeout": "Timeout","unavailable": "Unavailable",+ "provider": "Provider",+ "operation": "Operation",+ "latency": "Latency",+ "errorType": "Error","filter": {"title": "Filters",- "module": "Module",- "type": "Type",+ "model": "Model","timeRange": "Time Range","all": "All","last7Days": "Last 7 Days",@@ -153,20 +157,7 @@"apply": "Apply"},"copy": "Copy",- "copied": "Copied",- "module": {- "Agent": "Agent",- "Server": "Server",- "Ai": "AI",- "Database": "Database",- "Network": "Network",- "Other": "Other"- },- "type": {- "AgentStatus": "Agent Status",- "AgentMcpStatus": "Agent MCP Status",- "NewApiStatus": "NewApi Status"- }+ "copied": "Copied"},"websit": {"termsOfService": {@@ -277,5 +268,6 @@"abroadContent": "{{platform}} is only available on the international site. Redirect to the international site?","ok": "Go","cancel": "Cancel"- }+ },+ "noMore": "No more data"}diff --git a/project/aitoearn-web/src/app/i18n/locales/en/material.json b/project/aitoearn-web/src/app/i18n/locales/en/material.jsonindex df1561f5..3bbbad97 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/material.json@@ -51,6 +51,10 @@"upload": "Upload","deleteMediaConfirm": "Are you sure to delete this media?","noMedia": "No media resources",+ "noVideo": "No videos yet",+ "noImage": "No images yet",+ "noVideoDesc": "Generated videos will appear here",+ "noImageDesc": "Generated images will appear here","uploadMediaHint": "Click the button below to upload {{type}}","searchPlaceholder": "Search groups...","default": "Default",@@ -69,7 +73,8 @@"selectImage": "Select Image","selectedCount": "{{count}} selected","confirm": "Confirm",- "noMediaDesc": "No media in this group"+ "noMediaDesc": "No media in this group",+ "drafts": "Drafts"},"aiGenerate": {"title": "AI Tools",diff --git a/project/aitoearn-web/src/app/i18n/locales/en/notification.json b/project/aitoearn-web/src/app/i18n/locales/en/notification.jsonindex a82adb05..8356d0aa 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/notification.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/notification.json@@ -70,6 +70,7 @@"task_review_approved": "Task Review","ai_review_skipped": "AI Review","task_submitted": "Task Submission",+ "interaction_ai_review_failed": "AI Review","other": "Other Notification"},"taskStatus": {diff --git a/project/aitoearn-web/src/app/i18n/locales/en/plugin.json b/project/aitoearn-web/src/app/i18n/locales/en/plugin.jsonindex c827954f..fcfc5889 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "The AiToEarn browser plugin is specifically designed for the intelligent operation of Xiaohongshu. Please click the button below to download and install.","downloadButton": "Download Now","chromeWebStore": "Chrome Web Store",- "githubRelease": "GitHub Release","chinaDownload": "China Download","activeDescription": "Your browser plugin is activated. You can start using the publish feature!","platformAccounts": "Platform Accounts",@@ -96,6 +95,6 @@"title": "Desktop Only","description": "The browser extension is not available on mobile devices. Please use a desktop browser to install and use the extension.","goToPC": "Please visit on PC",- "introduction": "Browser extension for the AiToEarn platform. Works with AiToEarn web to automate Xiaohongshu content publishing — videos, image carousels, titles, hashtags, and more, all in one click. Built-in AI Agent, powered by Claude Opus 4.6 — one of the world's most advanced AI models — helps you automate browser tasks through natural conversation. Install to unlock full AiToEarn platform features including one-click publishing, real-time progress tracking, and AI-powered automation."+ "introduction": "AiToEarn platform browser extension. Works with AiToEarn web to automate interactions on Xiaohongshu, TikTok and other platforms — follow, like, bookmark, comment and more."}}diff --git a/project/aitoearn-web/src/app/i18n/locales/en/promo.json b/project/aitoearn-web/src/app/i18n/locales/en/promo.jsondeleted file mode 100644index 1882877b..00000000--- a/project/aitoearn-web/src/app/i18n/locales/en/promo.json+++ /dev/null@@ -1,124 +0,0 @@-{- "meta": {- "title": "Quick Publish - Share Content via Promotion Code",- "description": "Publish promotional content to your social media accounts using a promotion code. Select your platform, customize your post, and share brand content to earn rewards on AiToEarn.",- "keywords": "promotion code, social media publishing, content sharing, brand promotion, earn rewards, quick publish, AiToEarn"- },- "platformSelect": {- "title": "Select Platform",- "description": "Please select a platform to publish your content",- "confirm": "Confirm"- },- "error": {- "title": "Error",- "invalidCode": "Invalid promotion code",- "taskNotFound": "Task not found or expired",- "noAccountSelected": "Please select an account to publish",- "noDraft": "Unable to publish. No draft exists for this promotion. Please contact the store owner.",- "retry": "Retry"- },- "taskType": {- "video": "Video",- "article": "Article",- "promotion": "Promotion",- "interaction": "Interaction"- },- "taskCard": {- "reward": "Reward",- "deadline": "Deadline",- "noDeadline": "No deadline",- "recruits": "Recruits",- "area": "Area",- "platforms": "Supported Platforms",- "noDescription": "No description",- "proceedToPublish": "Start Publishing",- "loginToPublish": "Login to Publish"- },- "material": {- "title": "Recommended Material",- "description": "Using the following material can achieve better promotion results",- "preview": "Preview",- "clickToPreview": "Click to preview",- "usedCount": "Used {{count}} times"- },- "account": {- "title": "Select Publishing Account",- "description": "Select an account to publish this content",- "loading": "Loading account list...",- "noAccount": "No available accounts",- "noMatchingAccount": "No accounts match the task requirements. Please add accounts for the required platforms first",- "requiredPlatforms": "Required platforms",- "back": "Back",- "publish": "Confirm Publish"- },- "publish": {- "publishing": "Publishing",- "pleaseWait": "Publishing content, please wait...",- "success": "Published successfully",- "failed": "Publish failed, please try again later",- "authFailed": "Authorization failed, please try again"- },- "result": {- "successTitle": "Published Successfully",- "successDescription": "Your content has been submitted for publishing",- "defaultSuccessMessage": "Content has been submitted to the publish queue. Please check the publish status later",- "flowId": "Flow ID",- "publishAgain": "Publish Again",- "goHome": "Go Home",- "failedTitle": "Publish Failed",- "failedDescription": "An error occurred during publishing",- "defaultFailedMessage": "Publish failed. Please check your network connection and try again",- "retry": "Retry",- "workLinkLabel": "Work Link",- "workLinkPlaceholder": "Please paste your published work link",- "submitWorkLink": "Submit Work Link",- "submitting": "Submitting...",- "submitSuccess": "Submitted successfully! Thank you for participating",- "submittedLink": "Submitted Work Link",- "submitFailed": "Submit failed, please try again",- "linkSubmitSuccessTitle": "Link Submitted",- "linkSubmitSuccessDescription": "Thank you for participating, we will review it soon",- "pendingTitle": "Pending Work Link Submission",- "pendingDescription": "Please paste your work link below after publishing on Douyin",- "howToGetLink": "How to get the work link?",- "platformSuccessDescription": "Your content has been successfully published to {{platform}}"- },- "intro": {- "title": "AI Operations Assistant for Solo Entrepreneurs",- "subtitle": "Let AI Be Your Operations Team",- "heroTitle": "No Need to Hire a Team",- "heroSubtitle": "AiToEarn helps you complete the entire process from content creation to promotion",- "features": {- "offlineMarketing": "Offline Check-in Marketing",- "offlineMarketingDesc": "Turn customers into your brand ambassadors",- "payForResults": "Pay for Results",- "payForResultsDesc": "Zero risk, only pay for real results",- "aiAssist": "AI-Powered Throughout",- "aiAssistDesc": "From ideas to publishing, AI handles everything"- }- },- "autoPublish": {- "publishing": "Publishing...",- "publishingDouyin": "Opening Douyin...",- "publishingTikTok": "Publishing...",- "publishingInstagram": "Publishing...",- "douyinPublishingDesc": "Please complete the publishing in Douyin App",- "tiktokPublishingDesc": "Processing your content, please wait...",- "instagramPublishingDesc": "Processing your content, please wait...",- "platformNotSupported": "Platform Not Supported",- "platformNotSupportedDesc": "The platform for this task does not support auto-publishing yet. Please use other methods to publish",- "tiktokComingSoon": "TikTok Coming Soon",- "tiktokComingSoonDesc": "Auto-publishing for TikTok is coming soon. Stay tuned!",- "openingApp": "Opening Douyin...",- "openingAppDesc": "Please complete the publishing in Douyin App",- "redirectingToTikTok": "Redirecting to TikTok authorization",- "redirectingToInstagram": "Redirecting to Instagram authorization",- "adapting": "AI is optimizing content...",- "adaptingDesc": "Adapting content for the target platform, please wait",- "alreadyPublished": "You have successfully published",- "cooldownRemaining": "You can publish again in {{minutes}} minutes"- },- "callback": {- "processing": "Processing authorization..."- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/en/route.json b/project/aitoearn-web/src/app/i18n/locales/en/route.jsonindex 84935851..c6c71538 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/route.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/route.json@@ -17,7 +17,7 @@"addChannel": "Add Channel","sidebar.more": "More","uptime": "Status",- "aiSocial": "AI social media",+ "aiSocial": "AI Publish","taskSquare": "Gold Rush Square","myTasks": "My Tasks","createTask": "Create Task"diff --git a/project/aitoearn-web/src/app/i18n/locales/en/task.json b/project/aitoearn-web/src/app/i18n/locales/en/task.jsonindex 5e434a34..9761f106 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/task.json@@ -10,9 +10,10 @@"menu.draftBox": "Content Management","menu.offlinePromo": "AI Check-in","menu.myTasks": "My Tasks",- "menu.aiContent": "AI Content",+ "menu.aiContent": "AI Publish","menu.aiInteraction": "AI Interact","menu.myChannel": "My Channel",+ "menu.mySettings": "Settings","menu.myBrand": "My Agent","menu.contentTrading": "Content Trading","menu.aiAgent": "AI Agent",@@ -27,6 +28,20 @@"filter.allCountries": "All Countries","filter.allStatuses": "All Statuses","filter.search": "Search tasks...",+ "filter.searchPlaceholder": "Search keywords...",+ "filter.taskType": "Task Type",+ "filter.allTypes": "All",+ "filter.promotion": "Promotion",+ "filter.interaction": "Interaction",+ "filter.country": "Country/Region",+ "filter.dateRange": "Date Range",+ "filter.startDate": "Start Date",+ "filter.endDate": "End Date",+ "filter.advancedFilter": "Advanced Filters",+ "filter.confirm": "Apply Filters",+ "filter.selectDateRange": "Select date range",+ "filter.clear": "Clear",+ "filter.reset": "Reset","card.publishTime": "Published","banner.title": "Want to promote your brand?",@@ -37,6 +52,8 @@"banner.statsSettlement": "Fast Settlement","card.perArticle": "Earn per post",+ "card.perInteraction": "Earn per task",+ "card.baseReward": "Base Reward","card.goCheck": "Details","card.inviting": "Inviting","card.soldOut": "Sold Out",@@ -83,6 +100,7 @@"status.del": "Revoked","statusHint.doing": "Please complete the task requirements and submit your work",+ "statusHint.doing_interaction": "Please complete the interaction task and submit screenshots","statusHint.waiting": "Your work is being published, please wait","statusHint.pending": "Work submitted, waiting for review","statusHint.approved": "Review passed, waiting for settlement",@@ -110,6 +128,7 @@"detail.platform": "Platform","detail.deadline": "Deadline","detail.submissionTime": "Submission Time",+ "detail.submittedWorkLink": "Submitted Work","detail.recruits": "Max Recruits","detail.currentRecruits": "Recruited","detail.interactionReq": "Interaction Requirements",@@ -155,7 +174,10 @@"create.selectBrand": "Select Brand","create.prompt": "Prompt","create.promptPlaceholder": "Describe the promotion content you want...",- "create.pricePerArticle": "Price Per Post",+ "create.pricingMode": "Pricing Mode",+ "create.pricingModeFixed": "Fixed Price",+ "create.pricingModeCpmCpe": "CPM/CPE Settlement",+ "create.pricePerArticle": "Fixed Price","create.priceMin": "Min {{symbol}}{{min}}","create.quantity": "Number of Posts","create.quantityMin": "Min 1 post",@@ -167,16 +189,22 @@"create.costFormula": "Price × Quantity","create.interactionHint": "Set interaction goals for creators. Leave empty for no requirement","create.customPricing": "Custom Settlement Pricing (Optional)",- "create.customPricingHint": "Leave empty to use platform default pricing, unit is per 1000 views/engagement points",+ "create.selectPlatformFirst": "Please select a platform first",+ "create.customPricingPlatformLimit": "Only {{platforms}} supports custom settlement pricing","create.cpmReward": "CPM Price (per 1K views)","create.cpeReward": "CPE Price (per 1K engagement)",- "create.pricingPlaceholder": "Use default",+ "create.cpmPlaceholder": "Enter CPM price",+ "create.cpePlaceholder": "Enter CPE price",+ "create.cpmDesc": "Price per 1,000 views",+ "create.cpeDesc": "Price per 1,000 engagement points (Rule: Like×1 + Collect×3 + Comment×5)",+ "create.pricingReference": "Ref: {{symbol}}{{value}}",+ "create.pricingAutoFill": "Use reference","create.totalPayment": "Total Payment","create.priceUnit": "/post","create.sectionContent": "Content Settings","create.sectionPricing": "Pricing & Quantity","create.validation.titleRequired": "Please enter a task title",- "create.validation.priceMin": "Minimum {{symbol}}{{min}} per post",+ "create.validation.priceMin": "Fixed price minimum {{symbol}}{{min}}","create.validation.quantityMin": "Minimum 1 post","create.validation.platformRequired": "Please select a platform","create.platformPlaceholder": "Search and select a platform...",@@ -188,7 +216,7 @@"create.draftBoxEmpty": "No draft boxes","create.draftBoxPreview": "Preview draft box","create.draftBoxMediaCount": "{{count}} materials",- "create.draftBoxHint": "We recommend preparing promotional materials in the draft box. Users can refer to and use them to improve content quality",+ "create.draftBoxHint": "We recommend preparing promotional materials in the draft box for creators to use. If not set, creators can create content freely.","create.validation.titleMax": "Task title max 50 characters","create.validation.descriptionMax": "Task description max 1000 characters","create.validation.draftRequired": "Please select a draft box",@@ -210,6 +238,8 @@"create.districtPlaceholder": "District","create.validation.placeRequired": "Location requirement is enabled, please enter a place","create.validation.countryRequired": "Location is enabled, please select a country",+ "create.validation.cpmRewardMin": "CPM price must be greater than 0",+ "create.validation.cpeRewardMin": "CPE price must be greater than 0","create.publishSuccess": "Published successfully","create.publishFailed": "Publish failed","create.collectNotSupported": "This platform does not support collects",@@ -221,10 +251,13 @@"detail.loginToAccept": "Login to accept task","detail.rewardPerPost": "Reward Per Post",+ "detail.rewardPerInteraction": "Reward Per Interaction","detail.recruitProgress": "Recruit Progress","detail.taskType": "Task Type","detail.taskType.promotion": "Promotion","detail.taskType.interaction": "Interaction",+ "detail.taskType.promotionTip": "Users accept tasks and publish videos as required",+ "detail.taskType.interactionTip": "Users accept tasks and like, comment, and collect works as required","detail.scope.online": "Online","detail.scope.offline": "Offline","detail.location": "Location",@@ -280,6 +313,26 @@"stats.noTitle": "No Title","stats.fetchFailed": "Failed to fetch task statistics","stats.publishTime": "Published",+ "stats.trendTitle": "7-Day Engagement Trend",+ "stats.trendViews": "Views",+ "stats.trendLikes": "Likes",+ "stats.trendComments": "Comments",+ "stats.trendShares": "Shares",+ "stats.trendFavorites": "Favorites",+ "stats.trendNoData": "No trend data yet",++ "workPerformance.title": "Work Performance",+ "workPerformance.estimatedEarnings": "Estimated Earnings",+ "workPerformance.estimatedCost": "Estimated Cost",+ "workPerformance.cpmFormula": "{{views}} views × {{price}}/1K",+ "workPerformance.cpeFormula": "Engagement {{score}} × {{price}}/1K",+ "workPerformance.viewDetails": "View Details",+ "workPerformance.noData": "No data yet",+ "workPerformance.updatedAt": "Updated {{time}}",+ "workPerformance.engagementScore": "Engagement Score",+ "workPerformance.settleAmount": "Amount",+ "workPerformance.settlementRule": "Settlement rule: After the work is approved, the system collects data for 7 days and then settles automatically",+ "workPerformance.dataUpdateTime": "Work data is updated daily at 2:00 AM UTC","userTasks.title": "Accepted Users","userTasks.empty": "No users have accepted this task yet",@@ -292,6 +345,8 @@"userTasks.aiVerify.passed": "Passed","userTasks.aiVerify.failed": "Failed","userTasks.aiVerify.skipped": "Skipped",+ "userTasks.aiVerify.reason": "AI Analysis",+ "userTasks.aiVerify.matchScore": "Match Score","userTasks.settle": "Settlement","userTasks.settle.cpm": "CPM","userTasks.settle.reward": "Reward",@@ -300,7 +355,9 @@"userTasks.settle.settled": "Settled","userTasks.settle.failed": "Failed","userTasks.settle.expired": "Expired",+ "userTasks.settle.rule": "Settlement rule: After the work is approved, the system collects data for 7 days and then settles automatically","userTasks.rejectionReason": "Rejection Reason",+ "userTasks.screenshots": "Screenshots","userTasks.manualReview": "Manual Review Required","userTasks.autoRejectReview": "Auto-rejected, publisher can review","userTasks.approve": "Approve",@@ -340,7 +397,7 @@"detail.interactionHint": "Please complete the following actions first: {{actions}}, then upload screenshots","detail.interactionAction.like": "Like","detail.interactionAction.collect": "Collect",- "detail.interactionAction.forward": "Forward",+ "detail.interactionAction.comment": "Comment","create.insufficientBalance.title": "Insufficient Balance","create.insufficientBalance.description": "This task requires {{symbol}}{{required}}, your current balance is {{symbol}}{{current}}, deficit {{symbol}}{{deficit}}. Would you like to recharge {{symbol}}{{rechargeAmount}}?",@@ -359,7 +416,7 @@"create.interaction.actions": "Interaction Actions","create.interaction.actionLike": "Like","create.interaction.actionCollect": "Collect",- "create.interaction.actionForward": "Forward",+ "create.interaction.actionComment": "Comment","create.interaction.quantity": "Number of Interactions","create.interaction.quantityHint": "How many people to recruit for this interaction","create.interaction.quantityMin": "Min 1 person",@@ -371,6 +428,7 @@"create.interaction.validation.actionsRequired": "Please select at least one interaction action","create.interaction.validation.rewardMin": "Minimum {{symbol}}{{min}} per person","create.interaction.validation.quantityMin": "At least 1 person required",+ "create.interaction.validation.unsupportedPlatform": "Please enter a supported platform link (Supported: Xiaohongshu, TikTok, YouTube, Twitter, Facebook, Instagram, Bilibili, Douyin)","verifyCode.AI_THEME_MISMATCH": "AI determined content is not relevant to the task (score: {{matchScore}}/100, threshold: {{threshold}})","verifyCode.AI_CANNOT_ANALYZE": "AI could not analyze the content, manual review required",@@ -446,5 +504,54 @@"stats.interactionRequired": "Required: ≥{{count}}, current: {{current}}","create.cpmCpeDeposit": "CPM/CPE Deposit",- "create.cpmCpeDepositHint": "CPM/CPE tasks require a deposit of $50 per post. Settlement is capped at the deposit amount. Any remaining deposit will be refunded."+ "create.cpmCpeDepositHint": "CPM/CPE tasks require a deposit of $50 per post. Settlement is capped at the deposit amount. Any remaining deposit will be refunded.",++ "create.tabPromotionDesc": "Publish your promotion needs and let creators pick up tasks to create and publish video content",+ "create.tabInteractionDesc": "Publish interaction needs and let users like, bookmark, and comment on your content",+ "create.confirmDialog.title": "Confirm Task Publication",+ "create.confirmDialog.notSet": "Not set",+ "create.confirmDialog.taskTitle": "Task Title",+ "create.confirmDialog.platform": "Platform",+ "create.confirmDialog.draftBox": "Draft Box",+ "create.confirmDialog.pricePerArticle": "Fixed Price",+ "create.confirmDialog.quantity": "Number of Posts",+ "create.confirmDialog.totalCost": "Total Cost",+ "create.confirmDialog.location": "Location",+ "create.confirmDialog.cpmReward": "CPM Price",+ "create.confirmDialog.cpeReward": "CPE Price",+ "create.confirmDialog.articles": "posts",+ "create.pricingTypeCpm": "CPM (Pay per views)",+ "create.pricingTypeCpe": "CPE (Pay per engagement)",+ "create.cpmCpeDataPeriod": "Only data from 7 days after content submission is counted",+ "create.priceMinFree": "Can be set to free",+ "create.confirmDialog.interactionActions": "Interaction Actions",+ "create.confirmDialog.rewardPerPerson": "Reward Per Person",+ "create.confirmDialog.interactionQuantity": "Number of People",+ "create.confirmDialog.people": "people",++ "detail.cpmReward": "Per 1K Views",+ "detail.cpeReward": "Per 1K Engagements",+ "detail.engagementRule": "Engagement Rule: Like×1 + Collect×3 + Comment×5",+ "detail.cpmRewardLabel": "Per 1K Views",+ "detail.cpeRewardLabel": "Per 1K Engagements",+ "detail.cpmRewardUnit": "/ 1K Views",+ "detail.cpeRewardUnit": "/ 1K Engagements",+ "card.cpmReward": "Per 1K Views",+ "card.cpeReward": "Per 1K Engagements",++ "detail.interactionLink": "Interaction Link",+ "detail.interactionTip": "You need to {{actions}} this work",++ "action.delete": "Delete Task",+ "action.deleteConfirm": "Confirm delete this task?",+ "action.deleteConfirmContent": "The task must be stopped with no active user tasks. The remaining balance will be refunded after deletion.",+ "toast.deleteSuccess": "Deleted successfully",+ "toast.deleteFailed": "Delete failed",++ "time.justNow": "Just now",+ "time.minutesAgo": "{{minutes}}m ago",+ "time.hoursAgo": "{{hours}}h ago",+ "time.daysAgo": "{{days}}d ago",+ "format.tenThousand": "{{value}}w",+ "create.defaultTaskTitle": "{{platform}} promotion"}diff --git a/project/aitoearn-web/src/app/i18n/locales/en/welcome.json b/project/aitoearn-web/src/app/i18n/locales/en/welcome.jsonindex e4be4778..34fbe2d1 100644--- a/project/aitoearn-web/src/app/i18n/locales/en/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/en/welcome.json@@ -12,7 +12,7 @@"pricing": "Pricing","docs": "Docs","brandPromotion": "Product",- "aiSocial": "AI social media",+ "aiSocial": "AI Publish","login": "Login","getDemo": "Start Free"},diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/account.json b/project/aitoearn-web/src/app/i18n/locales/fr/account.jsonindex 03670337..47dd1223 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/account.json@@ -305,9 +305,9 @@"channelManager": {"myChannels": "Mes chaînes","title": "Gestionnaire de chaînes",- "description": "Gérez vos chaînes et groupes d'espaces",+ "description": "Gérez vos chaînes et groupes","platforms": "Plateformes",- "allChannels": "Toutes les chaînes",+ "allChannels": "Mes chaînes","availablePlatforms": "Plateformes disponibles","connectNewChannel": "Connecter une chaîne","backToChannels": "Retour à Mes chaînes",@@ -333,15 +333,15 @@"syncFailed": "Échec de la synchronisation du compte","tabs": {"channels": "Chaînes",- "spaces": "Espaces"+ "spaces": "Groupes"},- "searchPlaceholder": "Rechercher des chaînes ou des espaces...",- "createSpace": "Créer un espace",- "createSpaceNamePlaceholder": "Entrez le nom de l'espace",- "createSpaceSuccess": "Espace créé avec succès",- "createSpaceFailed": "Échec de la création de l'espace",- "editSpaceSuccess": "Espace modifié avec succès",- "editSpaceFailed": "Échec de la modification de l'espace",+ "searchPlaceholder": "Rechercher des chaînes ou des groupes...",+ "createSpace": "Créer un groupe",+ "createSpaceNamePlaceholder": "Entrez le nom du groupe",+ "createSpaceSuccess": "Groupe créé avec succès",+ "createSpaceFailed": "Échec de la création du groupe",+ "editSpaceSuccess": "Groupe modifié avec succès",+ "editSpaceFailed": "Échec de la modification du groupe","deleteChannelSuccess": "Chaîne supprimée avec succès","deleteChannelFailed": "Échec de la suppression de la chaîne","sortSuccess": "Tri réussi",@@ -350,9 +350,9 @@"moveDown": "Descendre","noChannels": "Aucune chaîne","deleteConfirm": "Confirmer la suppression",- "deleteSpaceConfirm": "Confirmer la suppression de l'espace",- "deleteSpaceSuccess": "Espace supprimé avec succès",- "deleteSpaceFailed": "Échec de la suppression de l'espace",+ "deleteSpaceConfirm": "Confirmer la suppression du groupe",+ "deleteSpaceSuccess": "Groupe supprimé avec succès",+ "deleteSpaceFailed": "Échec de la suppression du groupe","channelCount": "{{count}} chaînes","sorting": "Tri en cours...","deleting": "Suppression en cours...",diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/fr/affiliates.jsondeleted file mode 100644index e5d22c1b..00000000--- a/project/aitoearn-web/src/app/i18n/locales/fr/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "seo": {- "title": "Programme d'affiliation - Gagnez 30% de commission récurrente",- "description": "Rejoignez le programme d'affiliation AiToEarn et gagnez 30% de commission sur les paiements de chaque filleul pendant 12 mois. Partagez votre lien unique et suivez vos revenus en temps réel.",- "keywords": "programme d'affiliation, commission de parrainage, gagner en ligne, revenu passif, 30% commission, AiToEarn affilié"- },- "title": "Rejoignez Friends of AiToEarn",- "describe": "Recommandez des utilisateurs payants pour s'inscrire sur aitoearn.ai et gagnez 30% de commission sur leurs 12 premiers paiements en 12 mois, soit un total de 716,4 $ !",- "keywords": "Affiliation AiToEarn, marketing d'affiliation, gagner de l'argent, partager et gagner, revenus de parrainage",- "subtitle": "Recevez une <strong>commission de 30%</strong> sur les 12 premiers paiements dans les 12 premiers mois pour les clients payants que vous recommandez à aitoearn.ai ($199×12×30% = $716.4) !",- "productIntro": {- "badge": "Projet open source Github 10k+ Star",- "headline": "Moteur de workflow IA automatisé",- "features": {- "oneClick": {- "title": "Exécution de tâches en un clic",- "description": "Décrivez votre besoin, l'Agent orchestre intelligemment les combinaisons d'outils IA optimales"- },- "multiModal": {- "title": "Intégration multi-modale",- "description": "Combine de manière transparente la génération de texte, la création d'images, le traitement vidéo et la traduction"- },- "zeroCurve": {- "title": "Courbe d'apprentissage zéro",- "description": "Du concept au produit final - gain d'efficacité x10 sans changement manuel d'outil"- }- },- "sections": {- "models": {- "title": "🎯 Modèles IA premium",- "items": [- "<strong>LLM phares :</strong> Claude Opus 4.5, GPT-5.1, Gemini 3.0 - derniers modèles de pointe",- "<strong>Outils vidéo professionnels :</strong> Sora-2, Veo-3.1 pour la génération et l'édition vidéo avancées",- "<strong>Création d'images de haute qualité :</strong> Nano Banana Pro, GPT-Image pour des visuels de qualité professionnelle"- ]- },- "distribution": {- "title": "📱 Distribution omnicanale",- "items": [- "<strong>Matrice de médias sociaux :</strong> Instagram, TikTok, YouTube, Bilibili, Douyin + 20+ plateformes",- "<strong>Adaptation intelligente du contenu :</strong> Optimise automatiquement les formats pour les meilleures performances de chaque plateforme",- "<strong>Gestion en masse :</strong> Gestion multi-comptes avec publication en un clic"- ]- },- "processing": {- "title": "⚡ Traitement vidéo professionnel",- "items": [- "<strong>Montage assisté par IA :</strong> Identifie automatiquement les moments forts pour un contenu court engageant",- "<strong>Voix off multilingue :</strong> Traduction en temps réel avec narration naturelle et fluide",- "<strong>Transformation de style :</strong> Changements instantanés de style vidéo pour des expériences visuelles personnalisées"- ]- },- "revolution": {- "title": "🌟 Révolution de la création de contenu",- "description": "Transformez la création de contenu du travail manuel à la direction intelligente. Que vous soyez créateur, marketeur ou entreprise - libérez un potentiel créatif illimité avec Aitoearn Agent."- }- }- },- "totalEarnings": "Gains totaux",- "pending": "En attente",- "pendingTooltip": "Vos revenus en attente seront réglés sur votre compte le {{date}}. ",- "viewIncome": "Cliquez pour voir les revenus",- "settled": "Réglé",- "referralLink": {- "title": "Votre lien de parrainage",- "copy": "Copier",- "copied": "Copié !",- "copySuccess": "Lien de parrainage copié !",- "copyError": "Échec de la copie du lien",- "description": "Partagez ce lien avec vos amis et gagnez 30% de commission sur leurs 12 premiers paiements !"- },- "goToPublish": "Aller publier AiToEarn",- "oneClickPromotion": {- "button": "Promouvoir AiToEarn en un clic et gagner {{amount}}",- "description": "L'IA crée automatiquement une vidéo promotionnelle avec votre lien de parrainage et la publie sur toutes vos chaînes"- },- "stats": {- "totalReferrals": "Total des parrainages",- "paidReferrals": "Parrainages payants",- "conversionRate": "Taux de conversion"- },- "commissions": {- "title": "Détails des commissions mensuelles",- "settled": "Réglé",- "pending": "En attente",- "noData": "Pas encore de commissions. Commencez à partager votre lien de parrainage !"- },- "howItWorks": {- "title": "Comment ça marche",- "step1": "Partagez votre lien de parrainage unique avec vos amis et contacts",- "step2": "Lorsqu'ils s'inscrivent et effectuent un paiement, vous gagnez 30% de commission",- "step3": "Gagnez une commission sur leurs 12 premiers paiements en 12 mois",- "step4": "Les commissions sont réglées mensuellement et peuvent être retirées sur votre portefeuille"- },- "loading": {- "failed": "Échec du chargement des données"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/fr/brandPromotion.jsonindex 02a9d92e..1304d825 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/brandPromotion.json@@ -29,6 +29,20 @@"imageCountExceeded": "Le nombre d'images dépasse la limite de la plateforme (max {{max}})"},"platformIncompatibleCount": "{{count}} incompatible(s)",- "timeLimitedModelTip": "Les modèles à durée limitée ne sont pas garantis disponibles. Si indisponible, réessayez plus tard ou passez à un autre modèle."+ "timeLimitedModelTip": "Les modèles à durée limitée ne sont pas garantis disponibles. Si indisponible, réessayez plus tard ou passez à un autre modèle.",+ "draftModeOn": "Générer un brouillon",+ "draftModeOffVideo": "Générer une vidéo",+ "draftModeOffImage": "Générer une image",+ "modelType": "Modèle",+ "duration": "Durée vidéo",+ "aspectRatio": "Ratio",+ "promptTitle": "Prompt personnalisé",+ "referenceImages": "Images de référence",+ "imageModel": "Modèle d'image",+ "imageCount": "Nombre d'images",+ "imageResolution": "Résolution"+ },+ "publishRecord": {+ "untitled": "Sans titre"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/common.json b/project/aitoearn-web/src/app/i18n/locales/fr/common.jsonindex be9c268e..f8cd6b59 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/common.json@@ -89,7 +89,8 @@"draftBox": "Gestion de contenu","draftBoxSeoTitle": "Gestion de contenu - Création par lots IA et éditeur de brouillons","draftBoxSeoDescription": "Gérez tous vos brouillons de contenu en un seul endroit. Utilisez l'IA pour générer des publications par lots et organisez la distribution multi-plateformes avec AiToEarn.",- "draftBoxSeoKeywords": "gestion de contenu, éditeur de brouillons, génération de contenu IA, création par lots, brouillons réseaux sociaux, AiToEarn"+ "draftBoxSeoKeywords": "gestion de contenu, éditeur de brouillons, génération de contenu IA, création par lots, brouillons réseaux sociaux, AiToEarn",+ "agentAssets": "Ressources Agent"},"tasks": "Marché","signIn": {@@ -128,20 +129,23 @@"networkError": "Erreur réseau, veuillez réessayer plus tard !","contact": "Besoin d'aide ? Contactez le support :","uptime": {- "seoTitle": "État du service - Surveillance système en temps réel",- "pageKeywords": "état du service, surveillance système, suivi disponibilité, état serveur, état API, AiToEarn statut",- "pageTitle": "État des services",- "pageDescription": "Surveillez l'état en temps réel et la disponibilité des services AiToEarn. Vérifiez le statut opérationnel des modules Agent, Serveur, IA, Base de données et Réseau.",+ "seoTitle": "Statut des modèles IA - Surveillance de disponibilité en temps réel",+ "pageKeywords": "statut modèle IA, disponibilité modèle, suivi disponibilité, santé service IA, surveillance modèle, AiToEarn statut",+ "pageTitle": "Statut des modèles IA",+ "pageDescription": "Surveillez la disponibilité en temps réel et le temps de fonctionnement des modèles IA. Vérifiez le statut opérationnel de chaque modèle et fournisseur.","loading": "Chargement...","noData": "Aucune donnée","uptimePercentage": "Disponibilité :","normal": "Normal","timeout": "Délai dépassé","unavailable": "Indisponible",+ "provider": "Fournisseur",+ "operation": "Opération",+ "latency": "Latence",+ "errorType": "Erreur","filter": {"title": "Filtres",- "module": "Module",- "type": "Type",+ "model": "Modèle","timeRange": "Période","all": "Tout","last7Days": "7 derniers jours",@@ -151,20 +155,7 @@"apply": "Appliquer"},"copy": "Copier",- "copied": "Copié",- "module": {- "Agent": "Agent",- "Server": "Serveur",- "Ai": "IA",- "Database": "Base de données",- "Network": "Réseau",- "Other": "Autre"- },- "type": {- "AgentStatus": "Statut Agent",- "AgentMcpStatus": "Statut MCP Agent",- "NewApiStatus": "Statut NewApi"- }+ "copied": "Copié"},"websit": {"termsOfService": {@@ -275,5 +266,6 @@"abroadContent": "{{platform}} n'est disponible que sur le site international. Rediriger vers le site international ?","ok": "Aller","cancel": "Annuler"- }+ },+ "noMore": "Plus de données"}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/material.json b/project/aitoearn-web/src/app/i18n/locales/fr/material.jsonindex 70663d1c..55277e5b 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/material.json@@ -51,6 +51,10 @@"upload": "Télécharger","deleteMediaConfirm": "Êtes-vous sûr de vouloir supprimer ce média ?","noMedia": "Aucune ressource média",+ "noVideo": "Pas encore de vidéos",+ "noImage": "Pas encore d'images",+ "noVideoDesc": "Les vidéos générées apparaîtront ici",+ "noImageDesc": "Les images générées apparaîtront ici","uploadMediaHint": "Cliquez sur le bouton ci-dessous pour télécharger {{type}}","searchPlaceholder": "Rechercher des groupes...","default": "Par défaut",@@ -69,7 +73,8 @@"selectImage": "Sélectionner une image","selectedCount": "{{count}} sélectionné(s)","confirm": "Confirmer",- "noMediaDesc": "Aucun média dans ce groupe"+ "noMediaDesc": "Aucun média dans ce groupe",+ "drafts": "Brouillons"},"aiGenerate": {"title": "Outils IA",diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/plugin.json b/project/aitoearn-web/src/app/i18n/locales/fr/plugin.jsonindex e9de23f9..59adaf9c 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "Le plugin de navigateur AiToEarn est spécialement conçu pour l'opération intelligente de Xiaohongshu. Veuillez cliquer sur le bouton ci-dessous pour télécharger et installer.","downloadButton": "Télécharger maintenant","chromeWebStore": "Chrome Web Store",- "githubRelease": "GitHub Release","chinaDownload": "Téléchargement Chine","activeDescription": "Votre plugin de navigateur est activé. Vous pouvez commencer à utiliser la fonction de publication !","platformAccounts": "Comptes de plateforme",@@ -96,6 +95,6 @@"title": "Bureau uniquement","description": "L'extension de navigateur n'est pas disponible sur les appareils mobiles. Veuillez utiliser un navigateur de bureau pour installer et utiliser l'extension.","goToPC": "Veuillez visiter sur PC",- "introduction": "Extension de navigateur pour la plateforme AiToEarn. Fonctionne avec AiToEarn web pour automatiser la publication de contenu Xiaohongshu — vidéos, carrousels d'images, titres, hashtags et plus encore, le tout en un clic. Agent IA intégré, propulsé par Claude Opus 4.6 — l'un des modèles d'IA les plus avancés au monde — vous aide à automatiser les tâches du navigateur par conversation naturelle. Installez pour débloquer toutes les fonctionnalités de la plateforme AiToEarn, y compris la publication en un clic, le suivi en temps réel et l'automatisation alimentée par l'IA."+ "introduction": "Extension de navigateur pour la plateforme AiToEarn. Fonctionne avec AiToEarn web pour automatiser les interactions sur Xiaohongshu, TikTok et d'autres plateformes — suivre, aimer, ajouter aux favoris, commenter et plus encore."}}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/promo.json b/project/aitoearn-web/src/app/i18n/locales/fr/promo.jsondeleted file mode 100644index 7a9b8c62..00000000--- a/project/aitoearn-web/src/app/i18n/locales/fr/promo.json+++ /dev/null@@ -1,7 +0,0 @@-{- "meta": {- "title": "Publication rapide - Partager du contenu via code promo",- "description": "Publiez du contenu promotionnel sur vos comptes de réseaux sociaux avec un code promo. Sélectionnez votre plateforme, personnalisez votre publication et gagnez des récompenses sur AiToEarn.",- "keywords": "code promo, publication réseaux sociaux, partage de contenu, promotion de marque, gagner des récompenses, AiToEarn"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/task.json b/project/aitoearn-web/src/app/i18n/locales/fr/task.jsonindex 20f2fdfd..722c0a48 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/task.json@@ -13,6 +13,7 @@"menu.aiContent": "AI Content","menu.aiInteraction": "AI Interact","menu.myChannel": "My Channel",+ "menu.mySettings": "Paramètres","menu.myBrand": "My Agent","menu.contentTrading": "Content Trading","menu.aiAgent": "AI Agent",@@ -26,6 +27,20 @@"filter.allCountries": "Tous les pays","filter.allStatuses": "Tous les statuts","filter.search": "Rechercher des tâches…",+ "filter.searchPlaceholder": "Rechercher par mot-clé…",+ "filter.taskType": "Type de tâche",+ "filter.allTypes": "Tous",+ "filter.promotion": "Promotion",+ "filter.interaction": "Interaction",+ "filter.country": "Pays/Région",+ "filter.dateRange": "Date de publication",+ "filter.startDate": "Date de début",+ "filter.endDate": "Date de fin",+ "filter.advancedFilter": "Filtres avancés",+ "filter.confirm": "Appliquer",+ "filter.selectDateRange": "Sélectionner une plage",+ "filter.clear": "Effacer",+ "filter.reset": "Réinitialiser","card.publishTime": "Publié","banner.title": "Want to promote your brand?",@@ -33,6 +48,7 @@"banner.publishNow": "Publish Now","card.perArticle": "Earn per post",+ "card.perInteraction": "Earn per task","card.goCheck": "Details","card.inviting": "Inviting","card.soldOut": "Sold Out",@@ -79,6 +95,7 @@"status.del": "Révoqué","statusHint.doing": "Veuillez compléter les exigences et soumettre votre travail",+ "statusHint.doing_interaction": "Veuillez compléter la tâche d'interaction et soumettre des captures d'écran","statusHint.waiting": "Votre travail est en cours de publication, veuillez patienter","statusHint.pending": "Travail soumis, en attente de vérification","statusHint.approved": "Vérification réussie, en attente de règlement",@@ -106,6 +123,7 @@"detail.platform": "Platform","detail.deadline": "Deadline","detail.submissionTime": "Date de soumission",+ "detail.submittedWorkLink": "Oeuvre soumise","detail.recruits": "Max Recruits","detail.currentRecruits": "Recruited","detail.interactionReq": "Interaction Requirements",@@ -203,13 +221,18 @@"create.districtPlaceholder": "District","create.validation.placeRequired": "L'exigence de localisation est activée, veuillez saisir un lieu","create.validation.countryRequired": "La localisation est activée, veuillez sélectionner un pays",+ "create.validation.cpmRewardMin": "Le prix CPM doit être supérieur à 0",+ "create.validation.cpeRewardMin": "Le prix CPE doit être supérieur à 0","create.collectNotSupported": "Cette plateforme ne prend pas en charge les favoris","detail.rewardPerPost": "Récompense par article",+ "detail.rewardPerInteraction": "Récompense par interaction","detail.recruitProgress": "Progression du recrutement","detail.taskType": "Type de tâche","detail.taskType.promotion": "Promotion","detail.taskType.interaction": "Interaction",+ "detail.taskType.promotionTip": "Les utilisateurs acceptent des tâches et publient des vidéos selon les exigences",+ "detail.taskType.interactionTip": "Les utilisateurs acceptent des tâches et aiment, commentent et collectent des œuvres selon les exigences","detail.scope.online": "En ligne","detail.scope.offline": "Hors ligne","detail.location": "Emplacement",@@ -265,6 +288,13 @@"stats.noTitle": "Sans titre","stats.fetchFailed": "Échec de la récupération des statistiques","stats.publishTime": "Publié",+ "stats.trendTitle": "Tendance d'interaction sur 7 jours",+ "stats.trendViews": "Vues",+ "stats.trendLikes": "J'aime",+ "stats.trendComments": "Commentaires",+ "stats.trendShares": "Partages",+ "stats.trendFavorites": "Favoris",+ "stats.trendNoData": "Pas encore de données de tendance","seo.homeTitle": "Tâches de promotion payantes - Gagnez avec les réseaux sociaux","seo.myTasksTitle": "Mes tâches - Suivre les promotions publiées et acceptées",@@ -290,7 +320,7 @@"detail.interactionHint": "Veuillez d'abord effectuer les actions suivantes : {{actions}}, puis téléchargez les captures d'écran","detail.interactionAction.like": "J'aime","detail.interactionAction.collect": "Collecter",- "detail.interactionAction.forward": "Partager",+ "detail.interactionAction.comment": "Commenter","create.insufficientBalance.title": "Solde insuffisant","create.insufficientBalance.description": "La création de cette tâche nécessite {{symbol}}{{required}}, votre solde actuel est de {{symbol}}{{current}}, le déficit est de {{symbol}}{{deficit}}. Souhaitez-vous recharger {{symbol}}{{rechargeAmount}} ?",@@ -309,7 +339,7 @@"create.interaction.actions": "Actions d'interaction","create.interaction.actionLike": "J'aime","create.interaction.actionCollect": "Collecter",- "create.interaction.actionForward": "Transférer",+ "create.interaction.actionComment": "Commenter","create.interaction.quantity": "Nombre d'interactions","create.interaction.quantityHint": "Combien de personnes recruter pour cette interaction","create.interaction.quantityMin": "Minimum 1 personne",@@ -321,6 +351,7 @@"create.interaction.validation.actionsRequired": "Veuillez sélectionner au moins une action d'interaction","create.interaction.validation.rewardMin": "Minimum {{symbol}}{{min}} par personne","create.interaction.validation.quantityMin": "Au moins 1 personne requise",+ "create.interaction.validation.unsupportedPlatform": "Veuillez entrer un lien de plateforme prise en charge (Supporté : Xiaohongshu, TikTok, YouTube, Twitter, Facebook, Instagram, Bilibili, Douyin)","detail.submitByLink": "Soumettre le lien","detail.publishFromPlatform": "Publier depuis la plateforme",@@ -351,5 +382,27 @@"dispute.confirm": "Êtes-vous sûr de vouloir soumettre cette contestation ? La tâche passera en statut d'examen de contestation.","dispute.confirmTitle": "Confirmer la contestation","dispute.reasonRequired": "Veuillez fournir une raison de contestation",- "dispute.screenshotRequired": "Veuillez télécharger au moins une capture d'écran comme preuve"+ "dispute.screenshotRequired": "Veuillez télécharger au moins une capture d'écran comme preuve",++ "detail.cpmReward": "Pour 1K vues",+ "detail.cpeReward": "Pour 1K interactions",+ "detail.engagementRule": "Règle d'interaction : Like×1 + Collecte×3 + Commentaire×5",+ "detail.cpmRewardLabel": "Pour 1K vues",+ "detail.cpeRewardLabel": "Pour 1K interactions",+ "detail.cpmRewardUnit": "/ 1K vues",+ "detail.cpeRewardUnit": "/ 1K interactions",+ "card.cpmReward": "Pour 1K vues",+ "card.cpeReward": "Pour 1K interactions",++ "detail.interactionLink": "Lien d'interaction",+ "detail.interactionTip": "Vous devez {{actions}} cette œuvre",++ "time.justNow": "À l'instant",+ "time.minutesAgo": "il y a {{minutes}} min",+ "time.hoursAgo": "il y a {{hours}} h",+ "time.daysAgo": "il y a {{days}} j",+ "format.tenThousand": "{{value}}w",+ "create.defaultTaskTitle": "Promotion {{platform}}",+ "workPerformance.dataUpdateTime": "Les données des œuvres sont mises à jour quotidiennement à 2h00 UTC",+ "userTasks.settle.rule": "Règle de règlement : après approbation de l'œuvre, le système collecte les données pendant 7 jours puis effectue le règlement automatiquement"}diff --git a/project/aitoearn-web/src/app/i18n/locales/fr/welcome.json b/project/aitoearn-web/src/app/i18n/locales/fr/welcome.jsonindex 3578329c..5ce0e53d 100644--- a/project/aitoearn-web/src/app/i18n/locales/fr/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/fr/welcome.json@@ -12,7 +12,7 @@"pricing": "Tarifs","docs": "Documentation","brandPromotion": "Produit",- "aiSocial": "IA Social",+ "aiSocial": "IA Publication","login": "Connexion","getDemo": "Commencer gratuitement"},diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/account.json b/project/aitoearn-web/src/app/i18n/locales/ja/account.jsonindex dc25b16e..22808944 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/account.json@@ -305,9 +305,9 @@"channelManager": {"myChannels": "マイチャンネル","title": "チャンネル管理",- "description": "チャンネルとスペースグループを管理",+ "description": "チャンネルとグループを管理","platforms": "プラットフォーム",- "allChannels": "すべてのチャンネル",+ "allChannels": "マイチャンネル","availablePlatforms": "利用可能なプラットフォーム","connectNewChannel": "チャンネルを接続","backToChannels": "マイチャンネルに戻る",@@ -333,15 +333,15 @@"syncFailed": "アカウントの同期に失敗しました","tabs": {"channels": "チャンネル",- "spaces": "スペース"+ "spaces": "グループ"},- "searchPlaceholder": "チャンネルまたはスペースを検索...",- "createSpace": "スペースを作成",- "createSpaceNamePlaceholder": "スペース名を入力",- "createSpaceSuccess": "スペースが正常に作成されました",- "createSpaceFailed": "スペースの作成に失敗しました",- "editSpaceSuccess": "スペースが正常に編集されました",- "editSpaceFailed": "スペースの編集に失敗しました",+ "searchPlaceholder": "チャンネルまたはグループを検索...",+ "createSpace": "グループを作成",+ "createSpaceNamePlaceholder": "グループ名を入力",+ "createSpaceSuccess": "グループが正常に作成されました",+ "createSpaceFailed": "グループの作成に失敗しました",+ "editSpaceSuccess": "グループが正常に編集されました",+ "editSpaceFailed": "グループの編集に失敗しました","deleteChannelSuccess": "チャンネルが正常に削除されました","deleteChannelFailed": "チャンネルの削除に失敗しました","sortSuccess": "並べ替えが成功しました",@@ -350,9 +350,9 @@"moveDown": "下へ移動","noChannels": "チャンネルがありません","deleteConfirm": "削除の確認",- "deleteSpaceConfirm": "スペースの削除を確認",- "deleteSpaceSuccess": "スペースが正常に削除されました",- "deleteSpaceFailed": "スペースの削除に失敗しました",+ "deleteSpaceConfirm": "グループの削除を確認",+ "deleteSpaceSuccess": "グループが正常に削除されました",+ "deleteSpaceFailed": "グループの削除に失敗しました","channelCount": "{{count}}チャンネル","sorting": "並べ替え中...","deleting": "削除中...",diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/ja/affiliates.jsondeleted file mode 100644index 2e30b570..00000000--- a/project/aitoearn-web/src/app/i18n/locales/ja/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "title": "Friends of AiToEarnに参加",- "seo": {- "title": "アフィリエイトプログラム - 30%の継続報酬を獲得",- "description": "AiToEarnアフィリエイトプログラムに参加して、紹介者の支払いごとに12ヶ月間30%のコミッションを獲得。専用リンクを共有し、リアルタイムで収益を追跡。",- "keywords": "アフィリエイト, 紹介コミッション, オンライン収入, 不労所得, 30%コミッション, 紹介プログラム, クリエイターアフィリエイト, AiToEarn"- },- "describe": "aitoearn.aiに有料ユーザーを紹介し、12ヶ月以内の最初の12回の支払いに対して30%のコミッションを獲得、合計$716.4!",- "keywords": "AiToEarnアフィリエイト, アフィリエイトマーケティング, お金を稼ぐ, シェアして稼ぐ, 紹介収益",- "subtitle": "aitoearn.aiに紹介した有料顧客の最初の12ヶ月以内の最初の12回の支払いに対して<strong>30%のコミッション</strong>を受け取ります($199×12×30% = $716.4)!",- "productIntro": {- "badge": "Github 10k+ Starオープンソースプロジェクト",- "headline": "自動化されたAIワークフローエンジン",- "features": {- "oneClick": {- "title": "ワンクリックタスク実行",- "description": "ニーズを説明すると、エージェントが最適なAIツールの組み合わせをインテリジェントに編成"- },- "multiModal": {- "title": "マルチモーダル統合",- "description": "テキスト生成、画像作成、動画処理、翻訳をシームレスに組み合わせ"- },- "zeroCurve": {- "title": "ゼロ学習曲線",- "description": "コンセプトから最終製品まで - 手動でのツール切り替えなしで効率10倍向上"- }- },- "sections": {- "models": {- "title": "🎯 プレミアムAIモデル",- "items": [- "<strong>フラッグシップLLM:</strong> Claude Opus 4.5、GPT-5.1、Gemini 3.0 - 最新の最先端モデル",- "<strong>プロフェッショナル動画ツール:</strong> Sora-2、Veo-3.1による高度な動画生成と編集",- "<strong>高品質画像作成:</strong> Nano Banana Pro、GPT-Imageによるプロフェッショナルグレードのビジュアル"- ]- },- "distribution": {- "title": "📱 オムニチャネル配信",- "items": [- "<strong>ソーシャルメディアマトリックス:</strong> Instagram、TikTok、YouTube、Bilibili、Douyin + 20+プラットフォーム",- "<strong>スマートコンテンツ適応:</strong> 各プラットフォームの最高のパフォーマンスのためにフォーマットを自動最適化",- "<strong>一括管理:</strong> ワンクリック公開によるマルチアカウント処理"- ]- },- "processing": {- "title": "⚡ プロフェッショナル動画処理",- "items": [- "<strong>AI駆動編集:</strong> 魅力的なショートフォームコンテンツのためにハイライトを自動識別",- "<strong>多言語ボイスオーバー:</strong> 自然で流暢なナレーションによるリアルタイム翻訳",- "<strong>スタイル変換:</strong> パーソナライズされた視覚体験のための即座の動画スタイル変更"- ]- },- "revolution": {- "title": "🌟 コンテンツ作成革命",- "description": "コンテンツ作成を手作業からインテリジェントな方向性へ変革。クリエイター、マーケター、ビジネスのいずれであっても - Aitoearn Agentで無限の創造的可能性を解き放ちます。"- }- }- },- "totalEarnings": "総収益",- "pending": "保留中",- "pendingTooltip": "保留中の収入は{{date}}にアカウントに決済されます。",- "viewIncome": "クリックして収入を確認",- "settled": "決済済み",- "referralLink": {- "title": "あなたの紹介リンク",- "copy": "コピー",- "copied": "コピーしました!",- "copySuccess": "紹介リンクをコピーしました!",- "copyError": "リンクのコピーに失敗しました",- "description": "このリンクを友達と共有して、最初の12回の支払いに対して30%のコミッションを獲得しましょう!"- },- "goToPublish": "AiToEarn公開ページへ",- "oneClickPromotion": {- "button": "ワンクリックでAiToEarnを宣伝して{{amount}}を稼ぐ",- "description": "AIがあなたの紹介リンク付きのプロモーション動画を自動作成し、すべてのチャンネルに公開します"- },- "stats": {- "totalReferrals": "総紹介数",- "paidReferrals": "有料紹介数",- "conversionRate": "コンバージョン率"- },- "commissions": {- "title": "月次コミッション詳細",- "settled": "決済済み",- "pending": "保留中",- "noData": "まだコミッションがありません。紹介リンクの共有を始めましょう!"- },- "howItWorks": {- "title": "仕組み",- "step1": "友達や連絡先とあなた専用の紹介リンクを共有",- "step2": "彼らがサインアップして支払いを行うと、30%のコミッションを獲得",- "step3": "12ヶ月以内の最初の12回の支払いに対してコミッションを獲得",- "step4": "コミッションは毎月決済され、ウォレットに引き出すことができます"- },- "loading": {- "failed": "データの読み込みに失敗しました"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/ja/brandPromotion.jsonindex 7a58a6ba..f4c6d192 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/brandPromotion.json@@ -29,6 +29,20 @@"imageCountExceeded": "画像数がプラットフォームの上限を超えています(最大 {{max}} 枚)"},"platformIncompatibleCount": "{{count}} 件非対応",- "timeLimitedModelTip": "期間限定モデルの利用は保証されていません。利用できない場合は、後で再試行するか、他のモデルに切り替えてください。"+ "timeLimitedModelTip": "期間限定モデルの利用は保証されていません。利用できない場合は、後で再試行するか、他のモデルに切り替えてください。",+ "draftModeOn": "下書き生成",+ "draftModeOffVideo": "動画生成",+ "draftModeOffImage": "画像生成",+ "modelType": "モデル",+ "duration": "動画の長さ",+ "aspectRatio": "比率",+ "promptTitle": "カスタムプロンプト",+ "referenceImages": "参考画像",+ "imageModel": "画像モデル",+ "imageCount": "画像数",+ "imageResolution": "解像度"+ },+ "publishRecord": {+ "untitled": "無題"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/common.json b/project/aitoearn-web/src/app/i18n/locales/ja/common.jsonindex 9b8982b9..880d533b 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/common.json@@ -89,7 +89,8 @@"draftBox": "コンテンツ管理","draftBoxSeoTitle": "コンテンツ管理 - AIバッチ作成と下書きエディタ","draftBoxSeoDescription": "すべてのコンテンツ下書きを一か所で管理。AIで一括生成、投稿前に編集、AiToEarnでマルチプラットフォーム配信を整理。",- "draftBoxSeoKeywords": "コンテンツ管理, 下書きエディタ, AIコンテンツ生成, 一括作成, SNS下書き, コンテンツスケジュール, AiToEarn"+ "draftBoxSeoKeywords": "コンテンツ管理, 下書きエディタ, AIコンテンツ生成, 一括作成, SNS下書き, コンテンツスケジュール, AiToEarn",+ "agentAssets": "Agent素材"},"tasks": "マーケットプレイス","signIn": {@@ -128,20 +129,23 @@"networkError": "ネットワークエラーです。後でもう一度お試しください!","contact": "お困りですか?サポートにお問い合わせください:","uptime": {- "seoTitle": "サービスステータス - リアルタイムシステム監視",- "pageKeywords": "サービスステータス, システム監視, 稼働率追跡, サーバー状態, APIステータス, AiToEarnステータス, リアルタイム監視",- "pageTitle": "サービス状況",- "pageDescription": "AiToEarnサービスのリアルタイム状況と稼働時間を監視します。Agent、Server、AI、Database、Networkモジュールの運用状況をご確認ください。",+ "seoTitle": "AIモデルステータス - リアルタイムモデル可用性監視",+ "pageKeywords": "AIモデルステータス, モデル可用性, 稼働率追跡, AIサービス状態, モデル監視, AiToEarnステータス",+ "pageTitle": "AIモデルステータス",+ "pageDescription": "AIモデルのリアルタイム可用性と稼働時間を監視します。各モデルとプロバイダーの運用状況をご確認ください。","loading": "読み込み中...","noData": "データがありません","uptimePercentage": "稼働率:","normal": "正常","timeout": "タイムアウト","unavailable": "利用不可",+ "provider": "プロバイダー",+ "operation": "操作",+ "latency": "レイテンシー",+ "errorType": "エラー","filter": {"title": "フィルター",- "module": "モジュール",- "type": "タイプ",+ "model": "モデル","timeRange": "期間","all": "すべて","last7Days": "過去7日間",@@ -151,20 +155,7 @@"apply": "適用"},"copy": "コピー",- "copied": "コピーしました",- "module": {- "Agent": "Agent",- "Server": "Server",- "Ai": "AI",- "Database": "Database",- "Network": "Network",- "Other": "その他"- },- "type": {- "AgentStatus": "Agentステータス",- "AgentMcpStatus": "Agent MCPステータス",- "NewApiStatus": "NewApiステータス"- }+ "copied": "コピーしました"},"websit": {"termsOfService": {@@ -275,5 +266,6 @@"abroadContent": "{{platform}} は国際サイトでのみ利用可能です。国際サイトに移動しますか?","ok": "移動","cancel": "キャンセル"- }+ },+ "noMore": "これ以上データはありません"}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/material.json b/project/aitoearn-web/src/app/i18n/locales/ja/material.jsonindex 05567e2e..f7e25a7c 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/material.json@@ -51,6 +51,10 @@"upload": "アップロード","deleteMediaConfirm": "このメディアを削除してもよろしいですか?","noMedia": "メディアリソースがありません",+ "noVideo": "動画はまだありません",+ "noImage": "画像はまだありません",+ "noVideoDesc": "生成された動画はここに表示されます",+ "noImageDesc": "生成された画像はここに表示されます","uploadMediaHint": "下のボタンをクリックして{{type}}をアップロード","searchPlaceholder": "グループを検索...","default": "デフォルト",@@ -69,7 +73,8 @@"selectImage": "画像を選択","selectedCount": "{{count}}件選択中","confirm": "確認",- "noMediaDesc": "このグループにメディアがありません"+ "noMediaDesc": "このグループにメディアがありません",+ "drafts": "下書き"},"aiGenerate": {"title": "AIツール",diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/plugin.json b/project/aitoearn-web/src/app/i18n/locales/ja/plugin.jsonindex 9418eb8d..c5d9f9ef 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "AiToEarnブラウザプラグインは小紅書のスマート運用のために特別に設計されています。下のボタンをクリックしてダウンロードしてインストールしてください。","downloadButton": "今すぐダウンロード","chromeWebStore": "Chrome ウェブストア",- "githubRelease": "GitHub リリース","chinaDownload": "中国ダウンロード","activeDescription": "ブラウザプラグインが有効になりました。公開機能をご利用いただけます!","platformAccounts": "プラットフォームアカウント",@@ -96,6 +95,6 @@"title": "デスクトップ専用","description": "ブラウザ拡張機能はモバイルデバイスでは利用できません。拡張機能のインストールと使用にはデスクトップブラウザをご利用ください。","goToPC": "PCでアクセスしてください",- "introduction": "AiToEarnプラットフォーム用ブラウザ拡張機能。AiToEarn Webと連携し、小紅書のコンテンツ公開を自動化します — 動画、画像カルーセル、タイトル、ハッシュタグなど、すべてワンクリックで完了。内蔵AIエージェントは、世界最先端のAIモデルの一つであるClaude Opus 4.6を搭載し、自然な会話でブラウザタスクの自動化をサポートします。インストールすると、ワンクリック公開、リアルタイム進捗追跡、AI自動化など、AiToEarnプラットフォームの全機能が利用可能になります。"+ "introduction": "AiToEarnプラットフォーム用ブラウザ拡張機能。AiToEarn Webと連携し、小紅書、TikTokなどのプラットフォームでのインタラクションを自動化します — フォロー、いいね、ブックマーク、コメントなど。"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/promo.json b/project/aitoearn-web/src/app/i18n/locales/ja/promo.jsondeleted file mode 100644index 000b322d..00000000--- a/project/aitoearn-web/src/app/i18n/locales/ja/promo.json+++ /dev/null@@ -1,7 +0,0 @@-{- "meta": {- "title": "クイック投稿 - プロモーションコードでコンテンツを共有",- "description": "プロモーションコードを使用してSNSアカウントにプロモーションコンテンツを投稿。プラットフォームを選択、投稿をカスタマイズして、AiToEarnで報酬を獲得。",- "keywords": "プロモーションコード, SNS投稿, コンテンツ共有, ブランドプロモーション, 報酬獲得, クイック投稿, AiToEarn"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/task.json b/project/aitoearn-web/src/app/i18n/locales/ja/task.jsonindex 930fab70..09fb9fd0 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/task.json@@ -13,6 +13,7 @@"menu.aiContent": "AI Content","menu.aiInteraction": "AI Interact","menu.myChannel": "My Channel",+ "menu.mySettings": "設定","menu.myBrand": "My Agent","menu.contentTrading": "Content Trading","menu.aiAgent": "AI Agent",@@ -26,6 +27,20 @@"filter.allCountries": "すべての国","filter.allStatuses": "すべてのステータス","filter.search": "タスクを検索…",+ "filter.searchPlaceholder": "キーワード検索…",+ "filter.taskType": "タスクタイプ",+ "filter.allTypes": "すべて",+ "filter.promotion": "プロモーション",+ "filter.interaction": "インタラクション",+ "filter.country": "国/地域",+ "filter.dateRange": "公開日",+ "filter.startDate": "開始日",+ "filter.endDate": "終了日",+ "filter.advancedFilter": "詳細フィルター",+ "filter.confirm": "フィルター適用",+ "filter.selectDateRange": "日付範囲を選択",+ "filter.clear": "クリア",+ "filter.reset": "リセット","card.publishTime": "公開日","banner.title": "Want to promote your brand?",@@ -33,6 +48,7 @@"banner.publishNow": "Publish Now","card.perArticle": "Earn per post",+ "card.perInteraction": "Earn per task","card.goCheck": "Details","card.inviting": "Inviting","card.soldOut": "Sold Out",@@ -79,6 +95,7 @@"status.del": "取り消し","statusHint.doing": "タスク要件を完了し、作品を提出してください",+ "statusHint.doing_interaction": "インタラクションタスクを完了し、スクリーンショットを提出してください","statusHint.waiting": "作品を公開中です。お待ちください","statusHint.pending": "作品が提出されました。審査をお待ちください","statusHint.approved": "審査通過、精算をお待ちください",@@ -106,6 +123,7 @@"detail.platform": "Platform","detail.deadline": "Deadline","detail.submissionTime": "提出日時",+ "detail.submittedWorkLink": "提出した作品","detail.recruits": "Max Recruits","detail.currentRecruits": "Recruited","detail.interactionReq": "Interaction Requirements",@@ -203,13 +221,18 @@"create.districtPlaceholder": "地区","create.validation.placeRequired": "位置要件が有効です。場所を入力してください","create.validation.countryRequired": "位置要件が有効です。国を選択してください",+ "create.validation.cpmRewardMin": "CPM価格は0より大きくしてください",+ "create.validation.cpeRewardMin": "CPE価格は0より大きくしてください","create.collectNotSupported": "このプラットフォームはお気に入りに対応していません","detail.rewardPerPost": "1件あたりの報酬",+ "detail.rewardPerInteraction": "1回あたりの報酬","detail.recruitProgress": "募集状況","detail.taskType": "タスク種別","detail.taskType.promotion": "プロモーション","detail.taskType.interaction": "インタラクション",+ "detail.taskType.promotionTip": "ユーザーがタスクを受け入れ、要件に従って動画を公開します",+ "detail.taskType.interactionTip": "ユーザーがタスクを受け入れ、要件に従っていいね、コメント、お気に入りを行います","detail.scope.online": "オンライン","detail.scope.offline": "オフライン","detail.location": "場所",@@ -265,6 +288,13 @@"stats.noTitle": "タイトルなし","stats.fetchFailed": "統計データの取得に失敗しました","stats.publishTime": "公開日時",+ "stats.trendTitle": "7日間インタラクショントレンド",+ "stats.trendViews": "再生数",+ "stats.trendLikes": "いいね数",+ "stats.trendComments": "コメント数",+ "stats.trendShares": "シェア数",+ "stats.trendFavorites": "お気に入り数",+ "stats.trendNoData": "トレンドデータはまだありません","seo.homeTitle": "有料プロモーションタスク - SNSで稼ぐ","seo.myTasksTitle": "マイタスク - 公開・受諾したプロモーションを追跡",@@ -290,7 +320,7 @@"detail.interactionHint": "まず以下の操作を完了してください:{{actions}}、その後スクリーンショットをアップロードしてください","detail.interactionAction.like": "いいね","detail.interactionAction.collect": "お気に入り",- "detail.interactionAction.forward": "転送",+ "detail.interactionAction.comment": "コメント","create.insufficientBalance.title": "残高不足","create.insufficientBalance.description": "このタスクの作成には {{symbol}}{{required}} が必要です。現在の残高は {{symbol}}{{current}}、不足額は {{symbol}}{{deficit}} です。{{symbol}}{{rechargeAmount}} をチャージしますか?",@@ -309,7 +339,7 @@"create.interaction.actions": "インタラクション項目","create.interaction.actionLike": "いいね","create.interaction.actionCollect": "お気に入り",- "create.interaction.actionForward": "転送",+ "create.interaction.actionComment": "コメント","create.interaction.quantity": "インタラクション人数","create.interaction.quantityHint": "このインタラクションに何人募集するか","create.interaction.quantityMin": "最低1人",@@ -321,6 +351,7 @@"create.interaction.validation.actionsRequired": "少なくとも1つのインタラクション項目を選択してください","create.interaction.validation.rewardMin": "1人あたりの報酬は最低 {{symbol}}{{min}}","create.interaction.validation.quantityMin": "最低1人必要です",+ "create.interaction.validation.unsupportedPlatform": "対応プラットフォームのリンクを入力してください(対応:小紅書、TikTok、YouTube、Twitter、Facebook、Instagram、Bilibili、Douyin)","detail.submitByLink": "リンクを提出","detail.publishFromPlatform": "プラットフォームから公開",@@ -351,5 +382,27 @@"dispute.confirm": "異議を提出しますか?提出後、タスクは異議審査状態になります。","dispute.confirmTitle": "異議申立の確認","dispute.reasonRequired": "異議の理由を入力してください",- "dispute.screenshotRequired": "証拠として少なくとも1枚のスクリーンショットをアップロードしてください"+ "dispute.screenshotRequired": "証拠として少なくとも1枚のスクリーンショットをアップロードしてください",++ "detail.cpmReward": "1K再生あたり",+ "detail.cpeReward": "1Kエンゲージメントあたり",+ "detail.engagementRule": "エンゲージメントルール:いいね×1 + お気に入り×3 + コメント×5",+ "detail.cpmRewardLabel": "1K再生あたり",+ "detail.cpeRewardLabel": "1Kエンゲージメントあたり",+ "detail.cpmRewardUnit": "/ 1K再生",+ "detail.cpeRewardUnit": "/ 1Kエンゲージメント",+ "card.cpmReward": "1K再生あたり",+ "card.cpeReward": "1Kエンゲージメントあたり",++ "detail.interactionLink": "インタラクションリンク",+ "detail.interactionTip": "この作品に{{actions}}する必要があります",++ "time.justNow": "たった今",+ "time.minutesAgo": "{{minutes}}分前",+ "time.hoursAgo": "{{hours}}時間前",+ "time.daysAgo": "{{days}}日前",+ "format.tenThousand": "{{value}}万",+ "create.defaultTaskTitle": "{{platform}}プロモーション",+ "workPerformance.dataUpdateTime": "作品データはUTC午前2時に毎日更新されます",+ "userTasks.settle.rule": "決済ルール:作品が承認された後、システムは7日間データを収集し、自動的に決済します"}diff --git a/project/aitoearn-web/src/app/i18n/locales/ja/welcome.json b/project/aitoearn-web/src/app/i18n/locales/ja/welcome.jsonindex b8182a19..697bd88b 100644--- a/project/aitoearn-web/src/app/i18n/locales/ja/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/ja/welcome.json@@ -12,7 +12,7 @@"pricing": "料金","docs": "ドキュメント","brandPromotion": "製品",- "aiSocial": "AIソーシャル",+ "aiSocial": "AI配信","login": "ログイン","getDemo": "無料で始める"},diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/account.json b/project/aitoearn-web/src/app/i18n/locales/ko/account.jsonindex 20fcf491..5750d50c 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/account.json@@ -305,9 +305,9 @@"channelManager": {"myChannels": "내 채널","title": "채널 관리자",- "description": "채널 및 스페이스 그룹 관리",+ "description": "채널 및 그룹 관리","platforms": "플랫폼",- "allChannels": "모든 채널",+ "allChannels": "내 채널","availablePlatforms": "사용 가능한 플랫폼","connectNewChannel": "채널 연결","backToChannels": "내 채널로 돌아가기",@@ -333,15 +333,15 @@"syncFailed": "계정 동기화 실패","tabs": {"channels": "채널",- "spaces": "스페이스"+ "spaces": "그룹"},- "searchPlaceholder": "채널 또는 스페이스 검색...",- "createSpace": "스페이스 만들기",- "createSpaceNamePlaceholder": "스페이스 이름 입력",- "createSpaceSuccess": "스페이스가 성공적으로 생성되었습니다",- "createSpaceFailed": "스페이스 생성에 실패했습니다",- "editSpaceSuccess": "스페이스가 성공적으로 수정되었습니다",- "editSpaceFailed": "스페이스 수정에 실패했습니다",+ "searchPlaceholder": "채널 또는 그룹 검색...",+ "createSpace": "그룹 만들기",+ "createSpaceNamePlaceholder": "그룹 이름 입력",+ "createSpaceSuccess": "그룹이 성공적으로 생성되었습니다",+ "createSpaceFailed": "그룹 생성에 실패했습니다",+ "editSpaceSuccess": "그룹이 성공적으로 수정되었습니다",+ "editSpaceFailed": "그룹 수정에 실패했습니다","deleteChannelSuccess": "채널이 성공적으로 삭제되었습니다","deleteChannelFailed": "채널 삭제에 실패했습니다","sortSuccess": "정렬 완료",@@ -350,9 +350,9 @@"moveDown": "아래로 이동","noChannels": "채널 없음","deleteConfirm": "삭제 확인",- "deleteSpaceConfirm": "스페이스 삭제 확인",- "deleteSpaceSuccess": "스페이스가 성공적으로 삭제되었습니다",- "deleteSpaceFailed": "스페이스 삭제에 실패했습니다",+ "deleteSpaceConfirm": "그룹 삭제 확인",+ "deleteSpaceSuccess": "그룹이 성공적으로 삭제되었습니다",+ "deleteSpaceFailed": "그룹 삭제에 실패했습니다","channelCount": "{{count}}개 채널","sorting": "정렬 중...","deleting": "삭제 중...",diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/ko/affiliates.jsondeleted file mode 100644index a74b8824..00000000--- a/project/aitoearn-web/src/app/i18n/locales/ko/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "seo": {- "title": "제휴 프로그램 - 30% 반복 수수료 획득",- "description": "AiToEarn 제휴 프로그램에 참여하여 12개월 동안 추천인 결제마다 30% 수수료를 획득하세요. 고유 링크를 공유하고 실시간으로 수익을 추적하세요.",- "keywords": "제휴 프로그램, 추천 수수료, 온라인 수익, 수동 소득, 30% 수수료, AiToEarn 제휴"- },- "title": "Friends of AiToEarn 가입",- "describe": "aitoearn.ai에 유료 사용자를 추천하고 12개월 내 첫 12회 결제에 대해 30% 커미션을 받으세요, 총 $716.4!",- "keywords": "AiToEarn 제휴, 제휴 마케팅, 돈 벌기, 공유하고 벌기, 추천 수익",- "subtitle": "aitoearn.ai에 추천한 유료 고객의 첫 12개월 내 첫 12회 결제에 대해 <strong>30% 커미션</strong>을 받으세요 ($199×12×30% = $716.4)!",- "productIntro": {- "badge": "Github 10k+ Star 오픈소스 프로젝트",- "headline": "자동화된 AI 워크플로우 엔진",- "features": {- "oneClick": {- "title": "원클릭 작업 실행",- "description": "필요사항을 설명하면 에이전트가 최적의 AI 도구 조합을 지능적으로 구성"- },- "multiModal": {- "title": "멀티모달 통합",- "description": "텍스트 생성, 이미지 생성, 비디오 처리 및 번역을 원활하게 결합"- },- "zeroCurve": {- "title": "제로 학습 곡선",- "description": "개념에서 최종 제품까지 - 수동 도구 전환 없이 효율성 10배 향상"- }- },- "sections": {- "models": {- "title": "🎯 프리미엄 AI 모델",- "items": [- "<strong>플래그십 LLM:</strong> Claude Opus 4.5, GPT-5.1, Gemini 3.0 - 최신 최첨단 모델",- "<strong>전문 비디오 도구:</strong> Sora-2, Veo-3.1로 고급 비디오 생성 및 편집",- "<strong>고품질 이미지 생성:</strong> Nano Banana Pro, GPT-Image로 전문가급 비주얼"- ]- },- "distribution": {- "title": "📱 옴니채널 배포",- "items": [- "<strong>소셜 미디어 매트릭스:</strong> Instagram, TikTok, YouTube, Bilibili, Douyin + 20+ 플랫폼",- "<strong>스마트 콘텐츠 적응:</strong> 각 플랫폼의 최상의 성능을 위해 형식 자동 최적화",- "<strong>대량 관리:</strong> 원클릭 게시로 다중 계정 처리"- ]- },- "processing": {- "title": "⚡ 전문 비디오 처리",- "items": [- "<strong>AI 기반 편집:</strong> 매력적인 숏폼 콘텐츠를 위해 하이라이트 자동 식별",- "<strong>다국어 보이스오버:</strong> 자연스럽고 유창한 내레이션으로 실시간 번역",- "<strong>스타일 변환:</strong> 개인화된 시각적 경험을 위한 즉각적인 비디오 스타일 변경"- ]- },- "revolution": {- "title": "🌟 콘텐츠 제작 혁명",- "description": "콘텐츠 제작을 수작업에서 지능적인 방향으로 전환하세요. 크리에이터, 마케터 또는 비즈니스 - Aitoearn Agent로 무한한 창의적 잠재력을 발휘하세요."- }- }- },- "totalEarnings": "총 수익",- "pending": "대기 중",- "pendingTooltip": "대기 중인 수입은 {{date}}에 계정으로 정산됩니다. ",- "viewIncome": "수입 확인하기",- "settled": "정산 완료",- "referralLink": {- "title": "귀하의 추천 링크",- "copy": "복사",- "copied": "복사됨!",- "copySuccess": "추천 링크가 복사되었습니다!",- "copyError": "링크 복사 실패",- "description": "이 링크를 친구들과 공유하고 첫 12회 결제에 대해 30% 커미션을 받으세요!"- },- "goToPublish": "AiToEarn 게시 페이지로 이동",- "oneClickPromotion": {- "button": "원클릭으로 AiToEarn 홍보하고 {{amount}} 벌기",- "description": "AI가 자동으로 귀하의 추천 링크가 포함된 홍보 비디오를 만들어 모든 채널에 게시합니다"- },- "stats": {- "totalReferrals": "총 추천 수",- "paidReferrals": "유료 추천 수",- "conversionRate": "전환율"- },- "commissions": {- "title": "월별 커미션 세부정보",- "settled": "정산 완료",- "pending": "대기 중",- "noData": "아직 커미션이 없습니다. 추천 링크 공유를 시작하세요!"- },- "howItWorks": {- "title": "작동 방식",- "step1": "친구 및 연락처와 고유한 추천 링크 공유",- "step2": "가입하고 결제하면 30% 커미션 획득",- "step3": "12개월 내 첫 12회 결제에 대한 커미션 획득",- "step4": "커미션은 매월 정산되며 지갑으로 인출 가능"- },- "loading": {- "failed": "데이터 로드 실패"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/ko/brandPromotion.jsonindex aeec6684..aba0bae3 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/brandPromotion.json@@ -29,6 +29,20 @@"imageCountExceeded": "이미지 수가 플랫폼 제한을 초과합니다 (최대 {{max}}장)"},"platformIncompatibleCount": "{{count}}개 비호환",- "timeLimitedModelTip": "한시적 모델은 가용성이 보장되지 않습니다. 사용할 수 없는 경우 나중에 다시 시도하거나 다른 모델로 전환하세요."+ "timeLimitedModelTip": "한시적 모델은 가용성이 보장되지 않습니다. 사용할 수 없는 경우 나중에 다시 시도하거나 다른 모델로 전환하세요.",+ "draftModeOn": "초안 생성",+ "draftModeOffVideo": "비디오 생성",+ "draftModeOffImage": "이미지 생성",+ "modelType": "모델",+ "duration": "영상 길이",+ "aspectRatio": "비율",+ "promptTitle": "사용자 정의 프롬프트",+ "referenceImages": "참조 이미지",+ "imageModel": "이미지 모델",+ "imageCount": "이미지 수",+ "imageResolution": "해상도"+ },+ "publishRecord": {+ "untitled": "제목 없음"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/common.json b/project/aitoearn-web/src/app/i18n/locales/ko/common.jsonindex 0798c4fb..474135f1 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/common.json@@ -89,7 +89,8 @@"draftBox": "콘텐츠 관리","draftBoxSeoTitle": "콘텐츠 관리 - AI 일괄 생성 및 초안 편집기","draftBoxSeoDescription": "모든 콘텐츠 초안을 한 곳에서 관리하세요. AI로 소셜 미디어 게시물을 일괄 생성하고, 게시 전 초안을 편집하고, AiToEarn으로 멀티 플랫폼 배포를 정리하세요.",- "draftBoxSeoKeywords": "콘텐츠 관리, 초안 편집기, AI 콘텐츠 생성, 일괄 생성, 소셜 미디어 초안, AiToEarn"+ "draftBoxSeoKeywords": "콘텐츠 관리, 초안 편집기, AI 콘텐츠 생성, 일괄 생성, 소셜 미디어 초안, AiToEarn",+ "agentAssets": "Agent 자산"},"tasks": "마켓플레이스","signIn": {@@ -128,20 +129,23 @@"networkError": "네트워크 오류, 나중에 다시 시도해 주세요!","contact": "도움이 필요하세요? 지원팀에 문의하세요:","uptime": {- "seoTitle": "서비스 상태 - 실시간 시스템 모니터링",- "pageKeywords": "서비스 상태, 시스템 모니터링, 가동률 추적, 서버 상태, API 상태, AiToEarn 상태",- "pageTitle": "서비스 상태",- "pageDescription": "AiToEarn 서비스의 실시간 상태와 가동 시간을 모니터링합니다. Agent, Server, AI, Database, Network 모듈의 작동 상태를 확인합니다.",+ "seoTitle": "AI 모델 상태 - 실시간 모델 가용성 모니터링",+ "pageKeywords": "AI 모델 상태, 모델 가용성, 가동률 추적, AI 서비스 상태, 모델 모니터링, AiToEarn 상태",+ "pageTitle": "AI 모델 상태",+ "pageDescription": "AI 모델의 실시간 가용성과 가동 시간을 모니터링합니다. 각 모델과 제공업체의 작동 상태를 확인합니다.","loading": "로딩 중...","noData": "데이터 없음","uptimePercentage": "가동률:","normal": "정상","timeout": "시간 초과","unavailable": "사용 불가",+ "provider": "제공업체",+ "operation": "작업",+ "latency": "지연 시간",+ "errorType": "오류","filter": {"title": "필터",- "module": "모듈",- "type": "유형",+ "model": "모델","timeRange": "기간","all": "전체","last7Days": "최근 7일",@@ -151,20 +155,7 @@"apply": "적용"},"copy": "복사",- "copied": "복사됨",- "module": {- "Agent": "에이전트",- "Server": "서버",- "Ai": "AI",- "Database": "데이터베이스",- "Network": "네트워크",- "Other": "기타"- },- "type": {- "AgentStatus": "에이전트 상태",- "AgentMcpStatus": "에이전트 MCP 상태",- "NewApiStatus": "NewApi 상태"- }+ "copied": "복사됨"},"websit": {"termsOfService": {@@ -275,5 +266,6 @@"abroadContent": "{{platform}}은(는) 국제 사이트에서만 이용 가능합니다. 국제 사이트로 이동하시겠습니까?","ok": "이동","cancel": "취소"- }+ },+ "noMore": "더 이상 데이터가 없습니다"}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/material.json b/project/aitoearn-web/src/app/i18n/locales/ko/material.jsonindex bcb5168e..c188c1e6 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/material.json@@ -51,6 +51,10 @@"upload": "업로드","deleteMediaConfirm": "이 미디어를 삭제하시겠습니까?","noMedia": "미디어 리소스 없음",+ "noVideo": "아직 동영상이 없습니다",+ "noImage": "아직 이미지가 없습니다",+ "noVideoDesc": "생성된 동영상이 여기에 표시됩니다",+ "noImageDesc": "생성된 이미지가 여기에 표시됩니다","uploadMediaHint": "아래 버튼을 클릭하여 {{type}}을(를) 업로드하세요","searchPlaceholder": "그룹 검색...","default": "기본",@@ -69,7 +73,8 @@"selectImage": "이미지 선택","selectedCount": "{{count}}개 선택됨","confirm": "확인",- "noMediaDesc": "이 그룹에 미디어가 없습니다"+ "noMediaDesc": "이 그룹에 미디어가 없습니다",+ "drafts": "초안"},"aiGenerate": {"title": "AI 도구",diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/plugin.json b/project/aitoearn-web/src/app/i18n/locales/ko/plugin.jsonindex 1d787853..75959167 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "AiToEarn 브라우저 플러그인은 샤오홍슈의 지능형 운영을 위해 특별히 설계되었습니다. 아래 버튼을 클릭하여 다운로드하고 설치하세요.","downloadButton": "지금 다운로드","chromeWebStore": "Chrome 웹 스토어",- "githubRelease": "GitHub 릴리스","chinaDownload": "중국 다운로드","activeDescription": "브라우저 플러그인이 활성화되었습니다. 게시 기능을 사용할 수 있습니다!","platformAccounts": "플랫폼 계정",@@ -96,6 +95,6 @@"title": "데스크톱 전용","description": "브라우저 확장 프로그램은 모바일 기기에서 사용할 수 없습니다. 확장 프로그램을 설치하고 사용하려면 데스크톱 브라우저를 이용해 주세요.","goToPC": "PC에서 방문해 주세요",- "introduction": "AiToEarn 플랫폼용 브라우저 확장 프로그램입니다. AiToEarn 웹과 연동하여 샤오홍슈 콘텐츠 게시를 자동화합니다 — 동영상, 이미지 캐러셀, 제목, 해시태그 등을 원클릭으로 처리합니다. 세계 최고 수준의 AI 모델인 Claude Opus 4.6 기반의 내장 AI 에이전트가 자연스러운 대화를 통해 브라우저 작업을 자동화합니다. 설치하면 원클릭 게시, 실시간 진행 상황 추적, AI 자동화 등 AiToEarn 플랫폼의 모든 기능을 이용할 수 있습니다."+ "introduction": "AiToEarn 플랫폼용 브라우저 확장 프로그램입니다. AiToEarn 웹과 연동하여 샤오홍슈, TikTok 등 플랫폼에서의 상호작용을 자동화합니다 — 팔로우, 좋아요, 북마크, 댓글 등."}}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/promo.json b/project/aitoearn-web/src/app/i18n/locales/ko/promo.jsondeleted file mode 100644index ce68c756..00000000--- a/project/aitoearn-web/src/app/i18n/locales/ko/promo.json+++ /dev/null@@ -1,7 +0,0 @@-{- "meta": {- "title": "빠른 게시 - 프로모션 코드로 콘텐츠 공유",- "description": "프로모션 코드를 사용하여 소셜 미디어 계정에 홍보 콘텐츠를 게시하세요. 플랫폼을 선택하고, 게시물을 커스터마이즈하여 AiToEarn에서 보상을 획득하세요.",- "keywords": "프로모션 코드, 소셜 미디어 게시, 콘텐츠 공유, 브랜드 프로모션, 보상 획득, AiToEarn"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/task.json b/project/aitoearn-web/src/app/i18n/locales/ko/task.jsonindex 8c73d71a..5842b927 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/task.json@@ -13,6 +13,7 @@"menu.aiContent": "AI Content","menu.aiInteraction": "AI Interact","menu.myChannel": "My Channel",+ "menu.mySettings": "설정","menu.myBrand": "My Agent","menu.contentTrading": "Content Trading","menu.aiAgent": "AI Agent",@@ -26,6 +27,20 @@"filter.allCountries": "모든 국가","filter.allStatuses": "모든 상태","filter.search": "작업 검색…",+ "filter.searchPlaceholder": "키워드 검색…",+ "filter.taskType": "작업 유형",+ "filter.allTypes": "전체",+ "filter.promotion": "프로모션",+ "filter.interaction": "인터랙션",+ "filter.country": "국가/지역",+ "filter.dateRange": "게시일",+ "filter.startDate": "시작일",+ "filter.endDate": "종료일",+ "filter.advancedFilter": "고급 필터",+ "filter.confirm": "필터 적용",+ "filter.selectDateRange": "날짜 범위 선택",+ "filter.clear": "지우기",+ "filter.reset": "초기화","card.publishTime": "게시일","banner.title": "Want to promote your brand?",@@ -33,6 +48,7 @@"banner.publishNow": "Publish Now","card.perArticle": "Earn per post",+ "card.perInteraction": "Earn per task","card.goCheck": "Details","card.inviting": "Inviting","card.soldOut": "Sold Out",@@ -79,6 +95,7 @@"status.del": "철회됨","statusHint.doing": "작업 요구 사항을 완료하고 작품을 제출하세요",+ "statusHint.doing_interaction": "인터랙션 작업을 완료하고 스크린샷을 제출하세요","statusHint.waiting": "작품이 게시 중입니다. 잠시 기다려 주세요","statusHint.pending": "작품이 제출되었습니다. 검토를 기다리고 있습니다","statusHint.approved": "검토 통과, 정산 대기 중",@@ -106,6 +123,7 @@"detail.platform": "Platform","detail.deadline": "Deadline","detail.submissionTime": "제출 시간",+ "detail.submittedWorkLink": "제출한 작품","detail.recruits": "Max Recruits","detail.currentRecruits": "Recruited","detail.interactionReq": "Interaction Requirements",@@ -203,13 +221,18 @@"create.districtPlaceholder": "구/동","create.validation.placeRequired": "위치 요구사항이 활성화되어 있습니다. 장소를 입력하세요","create.validation.countryRequired": "위치 요구사항이 활성화되어 있습니다. 국가를 선택하세요",+ "create.validation.cpmRewardMin": "CPM 가격은 0보다 커야 합니다",+ "create.validation.cpeRewardMin": "CPE 가격은 0보다 커야 합니다","create.collectNotSupported": "이 플랫폼은 즐겨찾기를 지원하지 않습니다","detail.rewardPerPost": "건당 보상",+ "detail.rewardPerInteraction": "인터랙션당 보상","detail.recruitProgress": "모집 현황","detail.taskType": "작업 유형","detail.taskType.promotion": "프로모션","detail.taskType.interaction": "인터랙션",+ "detail.taskType.promotionTip": "사용자가 작업을 수락하고 요구 사항에 따라 동영상을 게시합니다",+ "detail.taskType.interactionTip": "사용자가 작업을 수락하고 요구 사항에 따라 좋아요, 댓글, 즐겨찾기를 합니다","detail.scope.online": "온라인","detail.scope.offline": "오프라인","detail.location": "위치",@@ -265,6 +288,13 @@"stats.noTitle": "제목 없음","stats.fetchFailed": "통계 데이터 가져오기 실패","stats.publishTime": "게시일",+ "stats.trendTitle": "7일 인터랙션 트렌드",+ "stats.trendViews": "조회수",+ "stats.trendLikes": "좋아요",+ "stats.trendComments": "댓글",+ "stats.trendShares": "공유",+ "stats.trendFavorites": "즐겨찾기",+ "stats.trendNoData": "아직 트렌드 데이터가 없습니다","seo.homeTitle": "유료 프로모션 작업 - 소셜 미디어로 수익 창출","seo.myTasksTitle": "내 작업 - 게시 및 수락한 프로모션 추적",@@ -290,7 +320,7 @@"detail.interactionHint": "먼저 다음 작업을 완료해 주세요: {{actions}}, 그런 다음 스크린샷을 업로드하세요","detail.interactionAction.like": "좋아요","detail.interactionAction.collect": "즐겨찾기",- "detail.interactionAction.forward": "공유",+ "detail.interactionAction.comment": "댓글","create.insufficientBalance.title": "잔액 부족","create.insufficientBalance.description": "이 작업을 생성하려면 {{symbol}}{{required}}이(가) 필요합니다. 현재 잔액은 {{symbol}}{{current}}, 부족액은 {{symbol}}{{deficit}}입니다. {{symbol}}{{rechargeAmount}}을(를) 충전하시겠습니까?",@@ -309,7 +339,7 @@"create.interaction.actions": "인터랙션 항목","create.interaction.actionLike": "좋아요","create.interaction.actionCollect": "즐겨찾기",- "create.interaction.actionForward": "공유",+ "create.interaction.actionComment": "댓글","create.interaction.quantity": "인터랙션 인원","create.interaction.quantityHint": "이 인터랙션에 몇 명을 모집할지","create.interaction.quantityMin": "최소 1명",@@ -321,6 +351,7 @@"create.interaction.validation.actionsRequired": "최소 하나의 인터랙션 항목을 선택하세요","create.interaction.validation.rewardMin": "1인당 최소 {{symbol}}{{min}}","create.interaction.validation.quantityMin": "최소 1명이 필요합니다",+ "create.interaction.validation.unsupportedPlatform": "지원되는 플랫폼 링크를 입력하세요 (지원: Xiaohongshu, TikTok, YouTube, Twitter, Facebook, Instagram, Bilibili, Douyin)","detail.submitByLink": "링크 제출","detail.publishFromPlatform": "플랫폼에서 게시",@@ -351,5 +382,27 @@"dispute.confirm": "이의를 제출하시겠습니까? 제출 후 과제는 이의 심사 상태로 전환됩니다.","dispute.confirmTitle": "이의 제기 확인","dispute.reasonRequired": "이의 사유를 입력해 주세요",- "dispute.screenshotRequired": "증거로 최소 1장의 스크린샷을 업로드해 주세요"+ "dispute.screenshotRequired": "증거로 최소 1장의 스크린샷을 업로드해 주세요",++ "detail.cpmReward": "1K 조회당",+ "detail.cpeReward": "1K 참여당",+ "detail.engagementRule": "참여 규칙: 좋아요×1 + 즐겨찾기×3 + 댓글×5",+ "detail.cpmRewardLabel": "1K 조회당",+ "detail.cpeRewardLabel": "1K 참여당",+ "detail.cpmRewardUnit": "/ 1K 조회",+ "detail.cpeRewardUnit": "/ 1K 참여",+ "card.cpmReward": "1K 조회당",+ "card.cpeReward": "1K 참여당",++ "detail.interactionLink": "인터랙션 링크",+ "detail.interactionTip": "이 작품에 {{actions}}해야 합니다",++ "time.justNow": "방금 전",+ "time.minutesAgo": "{{minutes}}분 전",+ "time.hoursAgo": "{{hours}}시간 전",+ "time.daysAgo": "{{days}}일 전",+ "format.tenThousand": "{{value}}만",+ "create.defaultTaskTitle": "{{platform}} 프로모션",+ "workPerformance.dataUpdateTime": "작품 데이터는 매일 UTC 오전 2시에 업데이트됩니다",+ "userTasks.settle.rule": "정산 규칙: 작품이 승인된 후 시스템은 7일간 데이터를 수집하고 자동으로 정산합니다"}diff --git a/project/aitoearn-web/src/app/i18n/locales/ko/welcome.json b/project/aitoearn-web/src/app/i18n/locales/ko/welcome.jsonindex 09fabfd3..5459615c 100644--- a/project/aitoearn-web/src/app/i18n/locales/ko/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/ko/welcome.json@@ -12,7 +12,7 @@"pricing": "요금제","docs": "문서","brandPromotion": "제품",- "aiSocial": "AI 소셜",+ "aiSocial": "AI 퍼블리시","login": "로그인","getDemo": "무료로 시작"},diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/account.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/account.jsonindex 20eaab48..ceff80a2 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/account.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/account.json@@ -307,9 +307,9 @@"xhsMobileNotSupported": "对不起,小红书需要依赖浏览器插件,请去PC端AiToEarn操作小红书","myChannels": "我的频道","title": "频道管理",- "description": "管理您的频道和空间分组",+ "description": "管理您的频道和分组","platforms": "平台列表",- "allChannels": "全部频道",+ "allChannels": "我的频道","availablePlatforms": "可连接的平台","connectNewChannel": "连接新频道","backToChannels": "返回我的频道",@@ -335,15 +335,15 @@"syncFailed": "账号同步失败","tabs": {"channels": "频道",- "spaces": "空间"+ "spaces": "分组"},- "searchPlaceholder": "搜索频道或空间...",- "createSpace": "新建空间",- "createSpaceNamePlaceholder": "输入空间名称",- "createSpaceSuccess": "创建空间成功",- "createSpaceFailed": "创建空间失败",- "editSpaceSuccess": "空间编辑成功",- "editSpaceFailed": "空间编辑失败",+ "searchPlaceholder": "搜索频道或分组...",+ "createSpace": "新建分组",+ "createSpaceNamePlaceholder": "输入分组名称",+ "createSpaceSuccess": "创建分组成功",+ "createSpaceFailed": "创建分组失败",+ "editSpaceSuccess": "分组编辑成功",+ "editSpaceFailed": "分组编辑失败","deleteChannelSuccess": "删除频道成功","deleteChannelFailed": "删除频道失败","sortSuccess": "排序成功",@@ -359,10 +359,11 @@"reauth": "重新授权","addToSpace": "添加到: {{space}}","deleteDialogContent": "确定要删除 {{type}} \"{{name}}\" 吗?此操作无法撤销。",- "deleteSpaceConfirm": "确认删除空间",- "deleteSpaceSuccess": "删除空间成功",- "deleteSpaceFailed": "删除空间失败",+ "deleteSpaceConfirm": "确认删除分组",+ "deleteSpaceSuccess": "删除分组成功",+ "deleteSpaceFailed": "删除分组失败","noData": "暂无数据"},- "channel": "频道"+ "channel": "频道",+ "agentCreate": "Agent创建"}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/affiliates.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/affiliates.jsondeleted file mode 100644index ce77b208..00000000--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/affiliates.json+++ /dev/null@@ -1,98 +0,0 @@-{- "title": "加入 AiToEarn 推广计划",- "seo": {- "title": "推广计划 - 赚取30%循环佣金",- "description": "加入AiToEarn推广计划,每推荐一位付费用户即可获得12个月内30%返佣。分享专属推广链接,实时追踪收益,用AI内容工具建立被动收入。",- "keywords": "推广计划, 推荐返佣, 网赚, 被动收入, 30%佣金, 推荐计划, 内容创作者推广, AiToEarn推广"- },- "describe": "推荐付费用户注册 aitoearn.ai,即可获得其前 12 个月内前 12 次付款的 30% 返佣,总计 $716.4!",- "keywords": "AiToEarn 推广, 联盟营销, 赚钱, 分享赚钱, 推广赚钱",- "subtitle": "推荐付费用户注册 aitoearn.ai,即可获得其前 12 个月内前 12 次付款的 <strong>30% 返佣</strong>($199×12×30% = $716.4)!",- "productIntro": {- "badge": "Github 10k+ Star 开源项目",- "headline": "自动化 AI 工作流引擎",- "features": {- "oneClick": {- "title": "一键任务执行",- "description": "描述你的需求,Agent 智能编排最优 AI 工具组合"- },- "multiModal": {- "title": "多模态集成",- "description": "无缝结合文本生成、图像创作、视频处理和翻译"- },- "zeroCurve": {- "title": "零学习曲线",- "description": "从概念到成品 - 无需手动切换工具,效率提升 10 倍"- }- },- "sections": {- "models": {- "title": "🎯 顶级 AI 模型",- "items": [- "<strong>旗舰级 LLM:</strong>Claude Opus 4.5、GPT-5.1、Gemini 3.0 - 最新前沿模型",- "<strong>专业视频工具:</strong>Sora-2、Veo-3.1 提供先进的视频生成和编辑",- "<strong>高质量图像创作:</strong>Nano Banana Pro、GPT-Image 打造专业级视觉效果"- ]- },- "distribution": {- "title": "📱 全渠道分发",- "items": [- "<strong>社交媒体矩阵:</strong>Instagram、TikTok、YouTube、B站、抖音等 20+ 平台",- "<strong>智能内容适配:</strong>自动优化格式以适应各平台最佳表现",- "<strong>批量管理:</strong>多账号处理,一键发布"- ]- },- "processing": {- "title": "⚡ 专业视频处理",- "items": [- "<strong>AI 驱动剪辑:</strong>自动识别精彩片段,制作引人入胜的短视频内容",- "<strong>多语言配音:</strong>实时翻译,自然流畅的旁白",- "<strong>风格转换:</strong>即时改变视频风格,打造个性化视觉体验"- ]- },- "revolution": {- "title": "🌟 内容创作革命",- "description": "将内容创作从手工劳动转变为智能指导。无论你是创作者、营销人员还是企业 - 用 Aitoearn Agent 释放无限创意潜能。"- }- }- },- "totalEarnings": "累计收益",- "pending": "待结算",- "pendingTooltip": "您的待结算收入会在 {{date}} 结算到您的收入,",- "viewIncome": "点击查看收入",- "settled": "已结算",- "referralLink": {- "title": "你的推广链接",- "copy": "复制",- "copied": "已复制!",- "copySuccess": "推广链接已复制!",- "copyError": "复制失败",- "description": "分享此链接给你的朋友,即可获得他们前 12 次付款的 30% 返佣!"- },- "goToPublish": "前往发布推广 AiToEarn",- "oneClickPromotion": {- "button": "一键完成推广 AiToEarn 赚 {{amount}}",- "description": "AI 自动制作带有你邀请链接的推广视频,并发布到你的所有频道"- },- "stats": {- "totalReferrals": "总推荐人数",- "paidReferrals": "付费用户数",- "conversionRate": "转化率"- },- "commissions": {- "title": "月度返佣明细",- "settled": "已结算",- "pending": "待结算",- "noData": "暂无返佣记录。开始分享你的推广链接吧!"- },- "howItWorks": {- "title": "工作原理",- "step1": "分享你的专属推广链接给朋友和联系人",- "step2": "当他们注册并完成付款时,你将获得 30% 返佣",- "step3": "在 12 个月内,可获得他们前 12 次付款的返佣",- "step4": "返佣每月结算,可提现到你的钱包"- },- "loading": {- "failed": "加载数据失败"- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/brandPromotion.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/brandPromotion.jsonindex 82497430..7764c401 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/brandPromotion.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/brandPromotion.json@@ -106,7 +106,6 @@"videoEditMode": "视频编辑","ratioLockedByVideo": "比例跟随输入视频","durationLockedByVideo": "时长跟随输入视频",- "durationAutoAdjusted": "时长已自动调整为 {{duration}}s","dropToUpload": "拖拽文件到此处上传","resetConfig": "重置配置","targetPlatforms": "目标平台",@@ -131,7 +130,10 @@"imageCountExceeded": "图片数量超出该平台限制(最多 {{max}} 张)"},"platformIncompatibleCount": "{{count}} 个不兼容",- "timeLimitedModelTip": "限时模型不保证可用性,如不可使用,可稍后再试或切换其他模型"+ "timeLimitedModelTip": "限时模型不保证可用性,如不可使用,可稍后再试或切换其他模型",+ "draftModeOn": "生成草稿",+ "draftModeOffVideo": "生成视频",+ "draftModeOffImage": "生成图片"},"tabs": {"overview": "概览",@@ -155,6 +157,8 @@"downloadQRCode": "下载二维码","draftSummary": "草稿摘要","draftList": "{{count}} 个草稿",+ "videoList": "{{count}} 个视频",+ "imageList": "{{count}} 个图片","viewMore": "查看更多","publishRecordSummary": "发布记录","backToTop": "回到顶部",@@ -220,12 +224,15 @@"shareCount": "分享数","favoriteCount": "收藏数","dataUpdatedAt": "数据更新时间",- "noWorkLink": "暂无作品链接"+ "noWorkLink": "暂无作品链接",+ "untitled": "未命名"},"material": {"emptyTitle": "暂无草稿","emptyDesc": "创建草稿或使用 Agent 批量生成","useCount": "已使用 {{count}} 次",+ "draft": "草稿",+ "untitled": "未命名草稿","generating": "生成中","completed": "已生成"},@@ -293,7 +300,18 @@"titlePlaceholder": "请输入草稿标题","pleaseUploadMedia": "请上传图片或视频","titleRequired": "请输入标题",- "descRequired": "请输入描述"+ "descRequired": "请输入描述",+ "targetPlatforms": "目标平台",+ "selectAll": "全选",+ "deselectAll": "取消全选",+ "titleExceeded": "标题超过 {{platform}} 限制的 {{max}} 个字符",+ "descExceeded": "描述超过 {{platform}} 限制的 {{max}} 个字符",+ "imageExceeded": "图片数超过 {{platform}} 限制的 {{max}} 张",+ "validationWarnings": "参数兼容性提示",+ "instagramImageAspectRatio": "Instagram 图片宽高比需在 4:5 ~ 1.91:1 范围内",+ "instagramVideoAspectRatio": "Instagram 视频宽高比需在 9:16 ~ 4:5 范围内",+ "facebookImageAspectRatio": "Facebook 图片宽高比需在 4:5 ~ 1.91:1 范围内",+ "facebookVideoAspectRatio": "Facebook 视频宽高比需在 9:16 ~ 4:5 范围内"},"planTab": {"more": "更多",diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.jsonindex 00034d82..36fd5169 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/common.json@@ -91,7 +91,8 @@"draftBoxSeoTitle": "内容管理 - AI批量创作与草稿编辑","draftBoxSeoDescription": "在一个地方管理所有内容草稿。使用AI批量生成社媒帖子,发布前编辑草稿,用AiToEarn组织多平台分发内容。","draftBoxSeoKeywords": "内容管理, 草稿编辑, AI内容生成, 批量创作, 社媒草稿, 内容排期, AiToEarn",- "brandPromotion": "AI打卡"+ "brandPromotion": "AI打卡",+ "agentAssets": "Agent素材"},"tasks": "内容市场","signIn": {@@ -127,20 +128,23 @@"tip": "💡 提示:安装完成后,请在App中登录您的账号,然后重新尝试相关操作"},"uptime": {- "seoTitle": "服务状态 - 实时系统健康监控",- "pageKeywords": "服务状态, 系统监控, 在线率追踪, 服务器健康, API状态, AiToEarn状态, 实时监控",- "pageTitle": "服务状态",- "pageDescription": "实时监控 AiToEarn 服务的运行状态和可用性。查看 Agent、服务器、AI、数据库和网络模块的运行状况。",+ "seoTitle": "AI 模型状态 - 实时模型可用性监控",+ "pageKeywords": "AI模型状态, 模型可用性, 在线率追踪, AI服务健康, 模型监控, AiToEarn状态",+ "pageTitle": "AI 模型状态",+ "pageDescription": "实时监控 AI 模型的可用性和运行状态。查看各模型和服务商的运行状况。","loading": "加载中...","noData": "暂无数据","uptimePercentage": "正常运行时间:","normal": "正常","timeout": "超时","unavailable": "中断",+ "provider": "服务商",+ "operation": "操作",+ "latency": "延迟",+ "errorType": "错误","filter": {"title": "筛选条件",- "module": "模块",- "type": "类型",+ "model": "模型","timeRange": "时间范围","all": "全部","last7Days": "最近7天",@@ -150,20 +154,7 @@"apply": "应用"},"copy": "复制",- "copied": "已复制",- "module": {- "Agent": "Agent",- "Server": "服务器",- "Ai": "AI",- "Database": "数据库",- "Network": "网络",- "Other": "其他"- },- "type": {- "AgentStatus": "Agent状态",- "AgentMcpStatus": "Agent Mcp 状态",- "NewApiStatus": "NewApi 状态"- }+ "copied": "已复制"},"websit": {"termsOfService": {@@ -274,5 +265,6 @@"abroadContent": "{{platform}} 仅在国际站支持,是否跳转到国际站?","ok": "前往","cancel": "取消"- }+ },+ "noMore": "没有更多了"}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/material.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/material.jsonindex 7a0368a7..ce093c5c 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/material.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/material.json@@ -51,6 +51,10 @@"upload": "上传","deleteMediaConfirm": "确定要删除这个媒体资源吗?","noMedia": "暂无媒体资源",+ "noVideo": "暂无视频",+ "noImage": "暂无图片",+ "noVideoDesc": "生成的视频将显示在这里",+ "noImageDesc": "生成的图片将显示在这里","uploadMediaHint": "点击下方按钮上传{{type}}资源","searchPlaceholder": "搜索素材组...","default": "默认",@@ -69,7 +73,8 @@"selectImage": "选择图片","selectedCount": "已选择 {{count}} 项","confirm": "确认",- "noMediaDesc": "该分组暂无媒体资源"+ "noMediaDesc": "该分组暂无媒体资源",+ "drafts": "草稿箱"},"aiGenerate": {"title": "AI生成",diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/notification.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/notification.jsonindex 77cb3708..8553b773 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/notification.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/notification.json@@ -70,6 +70,7 @@"task_review_approved": "任务审核","ai_review_skipped": "AI 审核","task_submitted": "任务提交",+ "interaction_ai_review_failed": "AI 审核","other": "其他通知"},"taskStatus": {diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.jsonindex 66c718e9..1ae385e8 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/plugin.json@@ -71,7 +71,6 @@"downloadDescription": "AiToEarn 浏览器插件专门用于小红书的智能操作。请点击下方按钮下载安装。","downloadButton": "立即下载","chromeWebStore": "Chrome 应用商店",- "githubRelease": "GitHub 下载","chinaDownload": "中国地区下载","activeDescription": "您的浏览器插件已成功激活,可以开始使用发布功能了!","platformAccounts": "平台账号",@@ -96,6 +95,6 @@"title": "仅支持桌面端","description": "浏览器插件无法在移动设备上使用,请前往电脑端浏览器安装和使用插件。","goToPC": "请在电脑端访问",- "introduction": "AiToEarn 平台浏览器插件,配合 AiToEarn 网页端使用,可自动化小红书内容发布——视频、图文、标题、话题标签等,一键搞定。内置 AI Agent,由 Claude Opus 4.6 驱动——全球最先进的 AI 模型之一,通过自然对话帮你自动完成浏览器操作。安装即可解锁 AiToEarn 平台全部功能,包括一键发布、实时进度追踪和 AI 智能自动化。"+ "introduction": "AiToEarn平台浏览器插件,配合AiToEarn网页端使用,可自动化小红书,tiktok等平台互动,实现关注,点赞,收藏,评论等。"}}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/promo.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/promo.jsondeleted file mode 100644index 3787628e..00000000--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/promo.json+++ /dev/null@@ -1,124 +0,0 @@-{- "meta": {- "title": "快速发布 - 通过推广码分享内容到社交平台",- "description": "使用推广码将推广内容发布到您的社交媒体账号。选择平台、自定义帖子,分享品牌内容赚取AiToEarn奖励。",- "keywords": "推广码, 社交媒体发布, 内容分享, 品牌推广, 赚取奖励, 快速发布, AiToEarn推广"- },- "platformSelect": {- "title": "选择发布平台",- "description": "请选择要发布内容的平台",- "confirm": "确认选择"- },- "error": {- "title": "出错了",- "invalidCode": "无效的推广码",- "taskNotFound": "任务不存在或已过期",- "noAccountSelected": "请选择要发布的账号",- "noDraft": "无法发布,该推广不存在草稿,请联系店主",- "retry": "重试"- },- "taskType": {- "video": "视频",- "article": "文章",- "promotion": "推广",- "interaction": "互动"- },- "taskCard": {- "reward": "奖励",- "deadline": "截止日期",- "noDeadline": "无截止日期",- "recruits": "招募人数",- "area": "区域",- "platforms": "支持平台",- "noDescription": "暂无描述",- "proceedToPublish": "开始发布",- "loginToPublish": "登录后发布"- },- "material": {- "title": "推荐素材",- "description": "使用以下素材可获得更好的推广效果",- "preview": "预览",- "clickToPreview": "点击预览",- "usedCount": "已使用 {{count}} 次"- },- "account": {- "title": "选择发布账号",- "description": "选择一个账号来发布此内容",- "loading": "正在加载账号列表...",- "noAccount": "没有可用账号",- "noMatchingAccount": "没有符合任务要求的账号,请先添加相应平台的账号",- "requiredPlatforms": "需要的平台",- "back": "返回",- "publish": "确认发布"- },- "publish": {- "publishing": "发布中",- "pleaseWait": "正在发布内容,请稍候...",- "success": "发布成功",- "failed": "发布失败,请稍后重试",- "authFailed": "授权失败,请重试"- },- "result": {- "successTitle": "发布成功",- "successDescription": "您的内容已成功提交发布",- "defaultSuccessMessage": "内容已提交到发布队列,请稍后查看发布状态",- "flowId": "发布流水号",- "publishAgain": "再次发布",- "goHome": "返回首页",- "failedTitle": "发布失败",- "failedDescription": "发布过程中出现了问题",- "defaultFailedMessage": "发布失败,请检查网络连接后重试",- "retry": "重新发布",- "workLinkLabel": "作品链接",- "workLinkPlaceholder": "请粘贴您发布的作品链接",- "submitWorkLink": "提交作品链接",- "submitting": "提交中...",- "submitSuccess": "提交成功!感谢您的参与",- "submittedLink": "已提交的作品链接",- "submitFailed": "提交失败,请重试",- "linkSubmitSuccessTitle": "链接提交成功",- "linkSubmitSuccessDescription": "感谢您的参与,我们会尽快审核",- "pendingTitle": "待提交作品链接",- "pendingDescription": "请在抖音发布后,将作品链接粘贴到下方提交",- "howToGetLink": "如何获取作品链接?",- "platformSuccessDescription": "您的内容已成功发布到 {{platform}}"- },- "intro": {- "title": "一人公司的 AI 运营助手",- "subtitle": "让 AI 成为你的运营团队",- "heroTitle": "无需雇佣团队",- "heroSubtitle": "AiToEarn 帮你完成从内容创作到推广投放的全流程运营",- "features": {- "offlineMarketing": "线下推广营销",- "offlineMarketingDesc": "让顾客成为你的推广大使",- "payForResults": "按效果付费",- "payForResultsDesc": "风险归零,只为真实效果付费",- "aiAssist": "AI 全程助力",- "aiAssistDesc": "从创意到发布,AI 帮你搞定一切"- }- },- "autoPublish": {- "publishing": "正在发布中...",- "publishingDouyin": "正在打开抖音...",- "publishingTikTok": "正在发布中...",- "publishingInstagram": "正在发布中...",- "douyinPublishingDesc": "请在抖音 App 中完成发布",- "tiktokPublishingDesc": "正在处理您的内容,请稍候...",- "instagramPublishingDesc": "正在处理您的内容,请稍候...",- "platformNotSupported": "平台暂不支持",- "platformNotSupportedDesc": "当前任务的平台暂不支持自动发布,请使用其他方式发布",- "tiktokComingSoon": "TikTok 即将支持",- "tiktokComingSoonDesc": "TikTok 平台的自动发布功能即将上线,敬请期待",- "openingApp": "正在打开抖音...",- "openingAppDesc": "请在抖音 App 中完成发布",- "redirectingToTikTok": "正在前往 TikTok 授权页",- "redirectingToInstagram": "正在前往 Instagram 授权页",- "adapting": "AI 正在优化内容...",- "adaptingDesc": "正在为目标平台适配内容,请稍候",- "alreadyPublished": "您已成功发布",- "cooldownRemaining": "{{minutes}} 分钟后可再次发布"- },- "callback": {- "processing": "正在处理授权..."- }-}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/route.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/route.jsonindex 905c0664..ede703df 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/route.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/route.json@@ -18,7 +18,7 @@"addChannel": "添加频道","sidebar.more": "更多","uptime": "服务状态",- "aiSocial": "AI社媒",+ "aiSocial": "AI发布","taskSquare": "淘金广场","myTasks": "我的任务","createTask": "创建任务"diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/task.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/task.jsonindex 833ac242..689f6f6a 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/task.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/task.json@@ -10,9 +10,10 @@"menu.draftBox": "内容管理","menu.offlinePromo": "AI打卡","menu.myTasks": "我的任务",- "menu.aiContent": "AI内容制作",+ "menu.aiContent": "AI发布","menu.aiInteraction": "AI互动","menu.myChannel": "我的频道",+ "menu.mySettings": "我的设置","menu.myBrand": "我的Agent","menu.contentTrading": "内容交易","menu.aiAgent": "AI Agent",@@ -27,6 +28,20 @@"filter.allCountries": "全部国家","filter.allStatuses": "全部状态","filter.search": "搜索任务…",+ "filter.searchPlaceholder": "搜索关键词…",+ "filter.taskType": "任务类型",+ "filter.allTypes": "全部",+ "filter.promotion": "推广",+ "filter.interaction": "互动",+ "filter.country": "国家/地区",+ "filter.dateRange": "发布时间",+ "filter.startDate": "开始日期",+ "filter.endDate": "结束日期",+ "filter.advancedFilter": "高级筛选",+ "filter.confirm": "确认筛选",+ "filter.selectDateRange": "选择日期范围",+ "filter.clear": "清除",+ "filter.reset": "重置","card.publishTime": "发布时间","banner.title": "想要推广您的品牌?",@@ -37,6 +52,8 @@"banner.statsSettlement": "快速结算","card.perArticle": "每篇可赚",+ "card.perInteraction": "每次可赚",+ "card.baseReward": "基础奖励","card.goCheck": "查看详情","card.inviting": "邀请中","card.soldOut": "已抢光",@@ -83,6 +100,7 @@"status.del": "已撤销","statusHint.doing": "请完成任务要求并提交作品",+ "statusHint.doing_interaction": "请完成互动任务并提交截图","statusHint.waiting": "作品正在发布中,请耐心等待","statusHint.pending": "作品已提交,等待审核中","statusHint.approved": "审核已通过,等待结算",@@ -110,6 +128,7 @@"detail.platform": "发布平台","detail.deadline": "截止日期","detail.submissionTime": "提交时间",+ "detail.submittedWorkLink": "已提交的作品","detail.recruits": "招募人数","detail.currentRecruits": "已招募","detail.interactionReq": "互动要求",@@ -155,7 +174,10 @@"create.selectBrand": "选择品牌","create.prompt": "提示词","create.promptPlaceholder": "描述您想要的推广内容...",- "create.pricePerArticle": "单篇稿费",+ "create.pricingMode": "计费方式",+ "create.pricingModeFixed": "一口价",+ "create.pricingModeCpmCpe": "CPM/CPE 结算",+ "create.pricePerArticle": "一口价","create.priceMin": "最低 {{symbol}}{{min}}","create.quantity": "发布篇数","create.quantityMin": "最少1篇",@@ -167,16 +189,22 @@"create.costFormula": "单价 × 篇数","create.interactionHint": "设置达人需完成的互动目标,未填写表示无硬性要求","create.customPricing": "自定义结算单价(可选)",- "create.customPricingHint": "不填则使用平台默认定价,单位为每千次/千互动分",+ "create.selectPlatformFirst": "请先选择平台",+ "create.customPricingPlatformLimit": "仅 {{platforms}} 平台支持自定义结算单价设置","create.cpmReward": "CPM 单价(每千播放)","create.cpeReward": "CPE 单价(每千互动分)",- "create.pricingPlaceholder": "使用平台默认",+ "create.cpmPlaceholder": "请输入 CPM 单价",+ "create.cpePlaceholder": "请输入 CPE 单价",+ "create.cpmDesc": "每千次播放价格",+ "create.cpeDesc": "每千次互动分价格(互动分规则:点赞×1 + 收藏×3 + 评论×5)",+ "create.pricingReference": "参考价:{{symbol}}{{value}}",+ "create.pricingAutoFill": "使用参考价","create.totalPayment": "实付总额","create.priceUnit": "元/篇","create.sectionContent": "内容设置","create.sectionPricing": "价格与数量","create.validation.titleRequired": "请输入任务标题",- "create.validation.priceMin": "单篇稿费最低 {{symbol}}{{min}}",+ "create.validation.priceMin": "一口价最低 {{symbol}}{{min}}","create.validation.quantityMin": "发布篇数最少 1 篇","create.validation.platformRequired": "请选择平台","create.platformPlaceholder": "搜索并选择平台...",@@ -188,7 +216,7 @@"create.draftBoxEmpty": "暂无草稿箱","create.draftBoxPreview": "预览草稿箱","create.draftBoxMediaCount": "{{count}} 个素材",- "create.draftBoxHint": "建议在草稿箱中准备好推广素材,接单用户可参考使用,提升内容质量",+ "create.draftBoxHint": "建议在草稿箱中准备好推广素材,供接单用户使用,未设置则允许接单用户自由发挥。","create.validation.titleMax": "任务标题最多50个字","create.validation.descriptionMax": "任务描述最多1000个字","create.validation.draftRequired": "请选择草稿箱",@@ -210,6 +238,8 @@"create.districtPlaceholder": "区","create.validation.placeRequired": "已开启位置要求,请填写地点","create.validation.countryRequired": "已开启位置要求,请选择国家",+ "create.validation.cpmRewardMin": "CPM 价格必须大于 0",+ "create.validation.cpeRewardMin": "CPE 价格必须大于 0","create.publishSuccess": "发布成功","create.publishFailed": "发布失败","create.collectNotSupported": "该平台不支持收藏",@@ -221,10 +251,13 @@"detail.loginToAccept": "登录后接受任务","detail.rewardPerPost": "每篇奖励",+ "detail.rewardPerInteraction": "每次奖励","detail.recruitProgress": "招募进度","detail.taskType": "任务类型","detail.taskType.promotion": "推广任务","detail.taskType.interaction": "互动任务",+ "detail.taskType.promotionTip": "用户接受任务按要求发布视频",+ "detail.taskType.interactionTip": "用户接受任务按要求点赞、评论、收藏任务要求的作品","detail.scope.online": "线上推广","detail.scope.offline": "线下推广","detail.location": "任务地点",@@ -280,6 +313,26 @@"stats.noTitle": "未填写标题","stats.fetchFailed": "获取任务统计数据失败","stats.publishTime": "发布时间",+ "stats.trendTitle": "七日互动趋势",+ "stats.trendViews": "播放量",+ "stats.trendLikes": "点赞量",+ "stats.trendComments": "评论量",+ "stats.trendShares": "分享量",+ "stats.trendFavorites": "收藏量",+ "stats.trendNoData": "暂无趋势数据",++ "workPerformance.title": "作品表现",+ "workPerformance.estimatedEarnings": "预估收益",+ "workPerformance.estimatedCost": "预估花费",+ "workPerformance.cpmFormula": "{{views}} 播放 × {{price}}/千次",+ "workPerformance.cpeFormula": "互动分 {{score}} × {{price}}/千分",+ "workPerformance.viewDetails": "查看详情",+ "workPerformance.noData": "暂无数据",+ "workPerformance.updatedAt": "更新于 {{time}}",+ "workPerformance.engagementScore": "互动分",+ "workPerformance.settleAmount": "金额",+ "workPerformance.settlementRule": "结算规则:作品审核通过后,系统将持续采集 7 天数据,届时自动结算",+ "workPerformance.dataUpdateTime": "我们会在 UTC 时间晚上两点更新作品数据","userTasks.title": "接受用户列表","userTasks.empty": "暂无用户接受此任务",@@ -292,6 +345,8 @@"userTasks.aiVerify.passed": "通过","userTasks.aiVerify.failed": "未通过","userTasks.aiVerify.skipped": "跳过",+ "userTasks.aiVerify.reason": "AI 分析",+ "userTasks.aiVerify.matchScore": "匹配分数","userTasks.settle": "结算","userTasks.settle.cpm": "CPM结算","userTasks.settle.reward": "奖励结算",@@ -300,7 +355,9 @@"userTasks.settle.settled": "已结算","userTasks.settle.failed": "失败","userTasks.settle.expired": "已过期",+ "userTasks.settle.rule": "结算规则:作品审核通过后,系统将持续采集 7 天数据,届时自动结算","userTasks.rejectionReason": "拒绝原因",+ "userTasks.screenshots": "截图","userTasks.manualReview": "需人工审核","userTasks.autoRejectReview": "自动驳回,发布者可手动审核","userTasks.approve": "通过",@@ -340,7 +397,7 @@"detail.interactionHint": "请先完成以下互动操作:{{actions}},然后截图上传","detail.interactionAction.like": "点赞","detail.interactionAction.collect": "收藏",- "detail.interactionAction.forward": "转发",+ "detail.interactionAction.comment": "评论","create.insufficientBalance.title": "余额不足","create.insufficientBalance.description": "创建此任务需要 {{symbol}}{{required}},当前余额 {{symbol}}{{current}},差额 {{symbol}}{{deficit}},是否前往充值 {{symbol}}{{rechargeAmount}}?",@@ -359,7 +416,7 @@"create.interaction.actions": "互动条目","create.interaction.actionLike": "点赞","create.interaction.actionCollect": "收藏",- "create.interaction.actionForward": "转发",+ "create.interaction.actionComment": "评论","create.interaction.quantity": "互动人数","create.interaction.quantityHint": "需要招募多少人来完成此互动","create.interaction.quantityMin": "最少1人",@@ -371,6 +428,7 @@"create.interaction.validation.actionsRequired": "请至少选择一个互动条目","create.interaction.validation.rewardMin": "单次奖励最低 {{symbol}}{{min}}","create.interaction.validation.quantityMin": "至少需要1人",+ "create.interaction.validation.unsupportedPlatform": "请输入支持的平台作品链接(支持:小红书、TikTok、YouTube、Twitter、Facebook、Instagram、B站、抖音)","verifyCode.AI_THEME_MISMATCH": "AI 判定内容与任务主题不相关(匹配分数:{{matchScore}}/100,阈值:{{threshold}})","verifyCode.AI_CANNOT_ANALYZE": "AI 无法分析内容,需人工审核",@@ -446,5 +504,54 @@"stats.interactionRequired": "要求: ≥{{count}},当前: {{current}}","create.cpmCpeDeposit": "CPM/CPE 押金",- "create.cpmCpeDepositHint": "CPM/CPE 任务每篇需预付 $50 押金,结算金额封顶为押金额度,剩余押金将退回。"+ "create.cpmCpeDepositHint": "CPM/CPE 任务每篇需预付 $50 押金,结算金额封顶为押金额度,剩余押金将退回。",++ "create.tabPromotionDesc": "发布您的推广需求,让创作者领取任务并制作发布视频内容",+ "create.tabInteractionDesc": "发布互动需求,让用户为您的作品进行点赞、收藏、评论等互动操作",+ "create.confirmDialog.title": "确认发布任务",+ "create.confirmDialog.notSet": "未设置",+ "create.confirmDialog.taskTitle": "任务标题",+ "create.confirmDialog.platform": "发布平台",+ "create.confirmDialog.draftBox": "关联草稿箱",+ "create.confirmDialog.pricePerArticle": "一口价",+ "create.confirmDialog.quantity": "发布篇数",+ "create.confirmDialog.totalCost": "总费用",+ "create.confirmDialog.location": "位置要求",+ "create.confirmDialog.cpmReward": "CPM 单价",+ "create.confirmDialog.cpeReward": "CPE 单价",+ "create.confirmDialog.articles": "篇",+ "create.pricingTypeCpm": "CPM(按播放量结算)",+ "create.pricingTypeCpe": "CPE(按互动量结算)",+ "create.cpmCpeDataPeriod": "只统计一条内容提交之后7天的数据",+ "create.priceMinFree": "可设为免费",+ "create.confirmDialog.interactionActions": "互动条目",+ "create.confirmDialog.rewardPerPerson": "单次奖励",+ "create.confirmDialog.interactionQuantity": "互动人数",+ "create.confirmDialog.people": "人",++ "detail.cpmReward": "千次播放金额",+ "detail.cpeReward": "千次互动金额",+ "detail.engagementRule": "互动分规则:点赞×1 + 收藏×3 + 评论×5",+ "detail.cpmRewardLabel": "每千次播放",+ "detail.cpeRewardLabel": "每千次互动",+ "detail.cpmRewardUnit": "/ 千次播放",+ "detail.cpeRewardUnit": "/ 千次互动",+ "card.cpmReward": "千次播放",+ "card.cpeReward": "千次互动",++ "detail.interactionLink": "互动链接",+ "detail.interactionTip": "需要{{actions}}此作品",++ "action.delete": "删除任务",+ "action.deleteConfirm": "确认删除该任务?",+ "action.deleteConfirmContent": "任务必须已停止且无进行中的用户任务,任务删除后剩余的余额会被退回。",+ "toast.deleteSuccess": "删除成功",+ "toast.deleteFailed": "删除失败",++ "time.justNow": "刚刚",+ "time.minutesAgo": "{{minutes}}分钟前",+ "time.hoursAgo": "{{hours}}小时前",+ "time.daysAgo": "{{days}}天前",+ "format.tenThousand": "{{value}}万",+ "create.defaultTaskTitle": "{{platform}}推广"}diff --git a/project/aitoearn-web/src/app/i18n/locales/zh-CN/welcome.json b/project/aitoearn-web/src/app/i18n/locales/zh-CN/welcome.jsonindex 09d0bb4a..44fc386e 100644--- a/project/aitoearn-web/src/app/i18n/locales/zh-CN/welcome.json+++ b/project/aitoearn-web/src/app/i18n/locales/zh-CN/welcome.json@@ -12,7 +12,7 @@"pricing": "定价","docs": "文档","brandPromotion": "产品",- "aiSocial": "AI社媒",+ "aiSocial": "AI发布","login": "登录","getDemo": "免费开始"},diff --git a/project/aitoearn-web/src/app/layout/AnnouncementBanner/index.tsx b/project/aitoearn-web/src/app/layout/AnnouncementBanner/index.tsxdeleted file mode 100644index 62edc637..00000000--- a/project/aitoearn-web/src/app/layout/AnnouncementBanner/index.tsx+++ /dev/null@@ -1,48 +0,0 @@-/**- * AnnouncementBanner - 全局公告横幅组件- * 在主内容区顶部显示促销信息,点击跳转草稿箱,用户关闭后永久不再显示(持久化到 IndexedDB)- */-'use client'--import { ChevronRight, Megaphone, X } from 'lucide-react'-import Link from 'next/link'-import { useShallow } from 'zustand/react/shallow'-import { useTransClient } from '@/app/i18n/client'-import { useSystemStore } from '@/store/system'-import { appCurrencySymbol } from '@/utils/currency'--function AnnouncementBanner() {- const { t } = useTransClient('common')-- const { dismissSeedanceBanner, setDismissSeedanceBanner, _hasHydrated } = useSystemStore(- useShallow(state => ({- dismissSeedanceBanner: state.dismissSeedanceBanner,- setDismissSeedanceBanner: state.setDismissSeedanceBanner,- _hasHydrated: state._hasHydrated,- })),- )-- // 等待 hydration 完成避免闪烁,或已关闭则不渲染- if (!_hasHydrated || dismissSeedanceBanner) {- return null- }-- return (- <div className="flex items-center gap-2 px-4 py-2 bg-muted text-muted-foreground text-sm w-full max-w-full overflow-hidden">- <Link href="/draft-box" className="flex items-center gap-2 min-w-0 flex-1 hover:text-foreground transition-colors">- <Megaphone className="w-4 h-4 shrink-0" />- <span className="truncate">{t('announcementBanner.videoPromo', { price: `${appCurrencySymbol}0.003` })}</span>- <ChevronRight className="w-4 h-4 shrink-0" />- </Link>- <button- className="shrink-0 p-1 rounded-full hover:bg-foreground/10 transition-colors cursor-pointer"- onClick={() => setDismissSeedanceBanner(true)}- aria-label="Close"- >- <X className="w-4 h-4" />- </button>- </div>- )-}--export default AnnouncementBannerdiff --git a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/BottomSection/AffiliatesEntry.tsx b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/BottomSection/AffiliatesEntry.tsxdeleted file mode 100644index 7ac6e939..00000000--- a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/BottomSection/AffiliatesEntry.tsx+++ /dev/null@@ -1,42 +0,0 @@-/**- * AffiliatesEntry - 推广赚钱入口组件- */--'use client'--import type { SidebarCommonProps } from '../../types'-import { Share2 } from 'lucide-react'-import Link from 'next/link'-import { useTransClient } from '@/app/i18n/client'-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'-import { cn } from '@/lib/utils'--export function AffiliatesEntry({ collapsed }: SidebarCommonProps) {- const { t } = useTransClient('common')-- return (- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Link- href="/affiliates"- className={cn(- 'flex items-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',- collapsed ? 'h-9 w-9 justify-center' : 'justify-between px-3 py-2',- )}- >- <div className="flex items-center gap-2">- <Share2 size={18} className="text-primary" />- {!collapsed && <span className="text-sm">{t('affiliates')}</span>}- </div>- </Link>- </TooltipTrigger>- {collapsed && (- <TooltipContent side="right">- <p>{t('affiliates')}</p>- </TooltipContent>- )}- </Tooltip>- </TooltipProvider>- )-}diff --git a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/IconBar.tsx b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/IconBar.tsxindex 67f3bc8e..1506fec9 100644--- a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/IconBar.tsx+++ b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/IconBar.tsx@@ -1,5 +1,5 @@/**- * IconBar - 底部图标栏(邮箱、下载APP、通知)+ * IconBar - 底部图标栏(邮箱、通知)*/'use client'@@ -17,7 +17,6 @@ export function IconBar({isLoggedIn,unreadCount,onOpenNotification,- onOpenSettings,}: IconBarProps) {const { t } = useTransClient('common')@@ -85,7 +84,6 @@ export function IconBar({</Tooltip></TooltipProvider>)}-</div>)}diff --git a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsxindex df480b39..cae885a8 100644--- a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx+++ b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserDropdownMenu.tsx@@ -141,9 +141,11 @@ function LoggedInMenuContent({<div className="flex flex-col gap-1 p-2">{/* 用户信息区域 */}<div className="flex items-center gap-3 px-3 py-2">- <Avatar className="h-10 w-10">+ <Avatar className="h-10 w-10 shrink-0 border border-border"><AvatarImage src={getOssUrl(userInfo?.avatar) || ''} alt={userInfo?.name || t('common:unknownUser')} />- <AvatarFallback>{userInfo?.name?.charAt(0)?.toUpperCase() || 'U'}</AvatarFallback>+ <AvatarFallback className="bg-muted-foreground font-semibold text-background">+ {userInfo?.name?.charAt(0)?.toUpperCase() || 'U'}+ </AvatarFallback></Avatar><div className="flex min-w-0 flex-1 flex-col"><span className="truncate text-sm font-medium text-foreground" data-testid="sidebar-user-name">@@ -319,13 +321,13 @@ export function UserDropdownMenu({collapsed ? 'justify-center' : 'gap-2',)}>- {/* 用户头像 */}- <Avatar className="h-8 w-8">+ <Avatar className="h-8 w-8 shrink-0 border border-border"><AvatarImage src={getOssUrl(userInfo?.avatar) || ''} alt={userInfo?.name || t('unknownUser')} />- <AvatarFallback>{userInfo?.name?.charAt(0)?.toUpperCase() || 'U'}</AvatarFallback>+ <AvatarFallback className="bg-muted-foreground font-semibold text-background">+ {userInfo?.name?.charAt(0)?.toUpperCase() || 'U'}+ </AvatarFallback></Avatar>- {/* 用户名 */}{!collapsed && (<div className="flex min-w-0 flex-1 flex-col items-start"><span className="w-full truncate text-left text-sm font-medium text-foreground">diff --git a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserSection.tsx b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserSection.tsxindex d9684116..a1bfd8c1 100644--- a/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserSection.tsx+++ b/project/aitoearn-web/src/app/layout/LayoutSidebar/components/UserSection.tsx@@ -28,7 +28,6 @@ function UserAvatar({return null}- // 点击打开默认设置页const handleClick = () => {onOpenSettings()}@@ -44,13 +43,13 @@ function UserAvatar({collapsed ? 'justify-center p-1' : 'gap-2 px-2 py-1.5',)}>- {/* 用户头像 */}- <Avatar className="h-8 w-8">+ <Avatar className="h-8 w-8 shrink-0 border border-border"><AvatarImage src={getOssUrl(userInfo.avatar) || ''} alt={userInfo.name || t('unknownUser')} />- <AvatarFallback>{userInfo.name?.charAt(0)?.toUpperCase() || 'U'}</AvatarFallback>+ <AvatarFallback className="bg-muted-foreground font-semibold text-background">+ {userInfo.name?.charAt(0)?.toUpperCase() || 'U'}+ </AvatarFallback></Avatar>- {/* 用户名 */}{!collapsed && (<div className="flex min-w-0 flex-1 flex-col items-start"><span className="w-full truncate text-sm font-medium text-foreground text-left">@@ -78,7 +77,6 @@ export function UserSection({ collapsed, onLogin, onOpenSettings }: UserSectionPreturn <UserAvatar collapsed={collapsed} onOpenSettings={onOpenSettings} />}- // 未登录状态if (collapsed) {return (<TooltipProvider>diff --git a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileBottomSection.tsx b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileBottomSection.tsxindex 112e1898..c992436e 100644--- a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileBottomSection.tsx+++ b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileBottomSection.tsx@@ -1,7 +1,7 @@import type { MobileBottomSectionProps } from '../types'/*** MobileBottomSection - 移动端底部功能区- * 包含通知、邮箱联系、外部链接和用户区域+ * 包含图标栏、外部链接和用户区域*/import {Bell,diff --git a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileTopBar.tsx b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileTopBar.tsxindex 90544a94..43b66153 100644--- a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileTopBar.tsx+++ b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileTopBar.tsx@@ -33,9 +33,11 @@ export function MobileTopBar({ onOpen }: MobileTopBarProps) {data-testid="mobile-topbar-menu-btn"className="flex items-center rounded-lg p-1.5 text-muted-foreground hover:bg-muted transition-colors cursor-pointer">- <Avatar className="h-7 w-7">+ <Avatar className="h-7 w-7 shrink-0 border border-border"><AvatarImage src={getOssUrl(userInfo.avatar) || ''} alt={userInfo.name || t('unknownUser')} />- <AvatarFallback>{userInfo.name?.charAt(0)?.toUpperCase() || 'U'}</AvatarFallback>+ <AvatarFallback className="bg-muted-foreground font-semibold text-background text-xs">+ {userInfo.name?.charAt(0)?.toUpperCase() || 'U'}+ </AvatarFallback></Avatar></button>) : (diff --git a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileUserSection.tsx b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileUserSection.tsxindex 3226383a..6e580e59 100644--- a/project/aitoearn-web/src/app/layout/MobileNav/components/MobileUserSection.tsx+++ b/project/aitoearn-web/src/app/layout/MobileNav/components/MobileUserSection.tsx@@ -34,13 +34,13 @@ export function MobileUserSection({data-testid="mobile-user-btn"className="flex w-full items-center gap-3 px-4 py-3 rounded-lg text-muted-foreground hover:bg-muted transition-colors cursor-pointer">- {/* 用户头像 */}- <Avatar className="h-8 w-8">+ <Avatar className="h-8 w-8 shrink-0 border border-border"><AvatarImage src={getOssUrl(userInfo.avatar) || ''} alt={userInfo.name || t('unknownUser')} />- <AvatarFallback>{userInfo.name?.charAt(0)?.toUpperCase() || 'U'}</AvatarFallback>+ <AvatarFallback className="bg-muted-foreground font-semibold text-background">+ {userInfo.name?.charAt(0)?.toUpperCase() || 'U'}+ </AvatarFallback></Avatar>- {/* 用户名 */}<div className="flex min-w-0 flex-1 flex-col items-start"><span className="truncate text-sm font-medium text-foreground" data-testid="mobile-user-name">{userInfo.name || t('unknownUser')}diff --git a/project/aitoearn-web/src/app/layout/Providers.tsx b/project/aitoearn-web/src/app/layout/Providers.tsxindex 28c14a8d..53a0e64a 100644--- a/project/aitoearn-web/src/app/layout/Providers.tsx+++ b/project/aitoearn-web/src/app/layout/Providers.tsx@@ -12,7 +12,7 @@ import { useEffect, useLayoutEffect, useRef } from 'react'import { useShallow } from 'zustand/shallow'import LoginDialog from '@/app/layout/LoginDialog'import { useLoginDialogStore } from '@/app/layout/LoginDialog/store'-import { InviteCodeHandler } from '@/components/InviteCodeHandler'+import { LowBalanceAlertProvider } from '@/components/common/LowBalanceAlert/LowBalanceAlertProvider'import SettingsModal from '@/components/SettingsModal'import { useSettingsModalStore } from '@/components/SettingsModal/store'import NotificationCenter from '@/components/ui/NotificationCenter'@@ -20,17 +20,16 @@ import { Toaster } from '@/components/ui/sonner'import { useUserStore } from '@/store/user'import { isPublicPage } from '@/utils/route'-export function Providers({ children, lng }: { children: React.ReactNode, lng: string }) {+export function Providers({ children, lng, autoLoginToken }: { children: React.ReactNode, lng: string, autoLoginToken?: string }) {const pathname = usePathname()const router = useRouter()// 用于追踪是否已经在当前路由弹出过登录框,避免重复弹出const hasPromptedRef = useRef(false)- const { _hasHydrated, token, _appInitialized } = useUserStore(+ const { _hasHydrated, token } = useUserStore(useShallow(state => ({_hasHydrated: state._hasHydrated,token: state.token,- _appInitialized: state._appInitialized,})),)@@ -38,10 +37,14 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: sconst { settingsVisible, settingsDefaultTab, closeSettings } = useSettingsModalStore()useEffect(() => {- if (_hasHydrated) {- useUserStore.getState().appInit()+ if (!_hasHydrated)+ return+ // 自动登录:无 token 时使用环境变量注入的 token+ if (!useUserStore.getState().token && autoLoginToken) {+ useUserStore.getState().setToken(autoLoginToken)}- }, [_hasHydrated])+ useUserStore.getState().appInit()+ }, [_hasHydrated, autoLoginToken])useEffect(() => {useUserStore.getState().setLang(lng)@@ -49,8 +52,8 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s// 未登录用户访问非公开页面时,跳转到登录页useEffect(() => {- // 等待持久化数据同步完成和 appInit 完成(含自动登录)- if (!_hasHydrated || !_appInitialized) {+ // 等待持久化数据同步完成+ if (!_hasHydrated) {return}@@ -74,7 +77,7 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s// 在当前页面弹出登录框,不跳转hasPromptedRef.current = trueuseLoginDialogStore.getState().openLoginDialog({ fromGuard: true })- }, [_hasHydrated, _appInitialized, token, pathname])+ }, [_hasHydrated, token, pathname])// 拦截 @react-oauth/google 的脚本加载,添加 ?hl= 参数以设置按钮语言useLayoutEffect(() => {@@ -98,11 +101,10 @@ export function Providers({ children, lng }: { children: React.ReactNode, lng: s<><ThemeProvider attribute="class" defaultTheme="light" enableSystem disableTransitionOnChange><GoogleOAuthProvider clientId="1094109734611-flskoscgp609mecqk9ablvc6i3205vqk.apps.googleusercontent.com">- {/* 邀请码处理 - 检测 URL 中的 ref 参数并绑定邀请关系 */}- <InviteCodeHandler /><Toaster position="top-center" richColors />{/* 专用右上角通知中心(不影响现有 toast) */}<NotificationCenter />+ <LowBalanceAlertProvider />{/* 全局登录弹框 */}<LoginDialog />{/* 全局设置弹框 - 统一在此渲染,避免多处重复 */}diff --git a/project/aitoearn-web/src/app/layout/routerData.tsx b/project/aitoearn-web/src/app/layout/routerData.tsxindex 7ae31f0b..62bf0518 100644--- a/project/aitoearn-web/src/app/layout/routerData.tsx+++ b/project/aitoearn-web/src/app/layout/routerData.tsx@@ -3,8 +3,9 @@* 包含导航项的图标、路径、翻译键等信息*/import {- FileText,- FolderOpen,+ Bot,+ History,+ Home,Sparkles,Upload,} from 'lucide-react'@@ -26,25 +27,32 @@ export const routerData: IRouterDataItem[] = [{name: 'Content Management',translationKey: 'header.draftBox',- path: '/draft-box',- icon: <FileText size={20} />,+ path: '/',+ icon: <Home size={20} />,},{- name: 'AI social media',+ name: 'AI Publish',translationKey: 'aiSocial',path: '/ai-social',icon: <Sparkles size={20} />,},+ {+ name: 'Task History',+ translationKey: 'tasksHistory',+ path: '/tasks-history',+ icon: <History size={20} />,+ },{name: 'Publish',translationKey: 'accounts',path: '/accounts',icon: <Upload size={20} />,},+ // Tasks moved to notification panel{- name: 'Material Library',- translationKey: 'header.materialLibrary',- path: '/material',- icon: <FolderOpen size={20} />,+ name: 'Agent Assets',+ translationKey: 'header.agentAssets',+ path: '/agent-assets',+ icon: <Bot size={20} />,},]diff --git a/project/aitoearn-web/src/app/layout/shared/constants.ts b/project/aitoearn-web/src/app/layout/shared/constants.tsindex ae4491f7..d8f7ed0a 100644--- a/project/aitoearn-web/src/app/layout/shared/constants.ts+++ b/project/aitoearn-web/src/app/layout/shared/constants.ts@@ -9,11 +9,6 @@ export const GITHUB_REPO = 'yikart/AiToEarn'/** 文档网站地址 */export const DOCS_URL = 'https://docs.aitoearn.ai'-/** 推广注册地址 */-// export const AFFILIATES_URL = 'https://geddle.com/affiliate-program/aitoearn'-export const AFFILIATES_URL- = 'https://aitoearn.getrewardful.com/signup?_gl=1*15wk8k8*_gcl_au*MjAzNTIwODgyMi4xNzY1MjkwMjc2LjExMjI2NzUyNDguMTc2NjE1MjM5OS4xNzY2MTUzODYz*_ga*OTk1MTc5MzQzLjE3NjUyOTAyNzY.*_ga_YJYFH7ZS27*czE3NjYxNTIzOTIkbzckZzEkdDE3NjYxNTM4OTQkajQ3JGwwJGgxODk3OTAxMTc1'-/*** 导航菜单分组配置* MobileNav 中 "More" 折叠菜单包含的路由项@@ -21,5 +16,4 @@ export const AFFILIATES_URLexport const NAV_GROUP_KEYS = ['tasksHistory','header.materialLibrary',- 'uptime',] as constdiff --git a/project/aitoearn-web/src/app/layout/shared/index.ts b/project/aitoearn-web/src/app/layout/shared/index.tsindex c91e2f8c..19513479 100644--- a/project/aitoearn-web/src/app/layout/shared/index.ts+++ b/project/aitoearn-web/src/app/layout/shared/index.ts@@ -1,6 +1,6 @@/*** layout/shared - 导航共享模块- * MobileNav 和 LayoutSidebar 共用的常量、hooks、组件+ * MobileNav 和 LayoutSidebar 共用的常量、hooks、组件、工具函数*/export * from './components'diff --git a/project/aitoearn-web/src/assets/fonts/font.css b/project/aitoearn-web/src/assets/fonts/font.cssindex c86b7fec..54155adf 100644--- a/project/aitoearn-web/src/assets/fonts/font.css+++ b/project/aitoearn-web/src/assets/fonts/font.css@@ -3,4 +3,5 @@src: url('./DIN-Medium.otf') format('opentype');font-weight: normal;font-style: normal;+ font-display: swap;}diff --git a/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts b/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.tsindex 765bbb77..3449a290 100644--- a/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts+++ b/project/aitoearn-web/src/components/ChannelManager/channelManagerStore.ts@@ -582,7 +582,7 @@ export const useChannelManagerStore = create(/** 授权成功处理 */handleAuthSuccess(account: SocialAccount) {- const { authState, onAuthSuccess } = get()+ const { authState, onAuthSuccess, selectedPlatform } = get()const platform = authState.platform// 调用外部回调@@ -590,10 +590,17 @@ export const useChannelManagerStore = create(onAuthSuccess(account, platform)}- // 重置状态,跳转到主页并选中该平台+ // 移动端保持原筛选状态,PC 端切换到授权平台+ const isMobile+ = typeof window !== 'undefined'+ && window.matchMedia('(max-width: 767px)').matches++ // 重置状态,跳转到主页set({currentView: 'main',- selectedPlatform: platform || 'all',+ selectedPlatform: isMobile+ ? selectedPlatform+ : (platform || 'all'),authState: { ...initialAuthState },isNewUser: false,})diff --git a/project/aitoearn-web/src/components/ChannelManager/components/ChannelSidebar.tsx b/project/aitoearn-web/src/components/ChannelManager/components/ChannelSidebar.tsxindex 0571338a..f7a4663f 100644--- a/project/aitoearn-web/src/components/ChannelManager/components/ChannelSidebar.tsx+++ b/project/aitoearn-web/src/components/ChannelManager/components/ChannelSidebar.tsx@@ -9,7 +9,7 @@ import type { PlatType } from '@/app/config/platConfig'import { Layers, Plus, Puzzle } from 'lucide-react'import { useMemo } from 'react'import { useShallow } from 'zustand/react/shallow'-import { AccountPlatInfoMap, RegionSortedPlatInfoArr } from '@/app/config/platConfig'+import { AccountPlatInfoMap, isPlatformAvailable, RegionSortedPlatInfoArr } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import { ScrollArea } from '@/components/ui/scroll-area'@@ -137,6 +137,7 @@ export function ChannelSidebar() {const info = AccountPlatInfoMap.get(platform)const count = platformAccountCounts.get(platform) || 0const needsPlugin = isPluginPlatform(platform)+ const isRegionRestricted = !isPlatformAvailable(platform)if (!info)return null@@ -149,9 +150,11 @@ export function ChannelSidebar() {onClick={() => handlePlatformClick(platform)}className={cn('flex w-full cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors',- selectedPlatform === platform- ? 'bg-primary text-primary-foreground font-medium'- : 'hover:bg-muted/60',+ isRegionRestricted+ ? 'opacity-50 grayscale'+ : selectedPlatform === platform+ ? 'bg-primary text-primary-foreground font-medium'+ : 'hover:bg-muted/60',)}><div className="relative shrink-0">@@ -189,6 +192,7 @@ export function ChannelSidebar() {{platformsWithoutAccounts.map((platform) => {const info = AccountPlatInfoMap.get(platform)const needsPlugin = isPluginPlatform(platform)+ const isRegionRestricted = !isPlatformAvailable(platform)if (!info)return null@@ -200,7 +204,9 @@ export function ChannelSidebar() {onClick={() => handlePlatformClick(platform)}className={cn('flex w-full cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm text-muted-foreground transition-colors',- 'opacity-60 hover:bg-muted/60 hover:opacity-100',+ isRegionRestricted+ ? 'opacity-30 grayscale'+ : 'opacity-60 hover:bg-muted/60 hover:opacity-100',)}><div className="relative shrink-0">diff --git a/project/aitoearn-web/src/components/ChannelManager/components/ConnectChannelList.tsx b/project/aitoearn-web/src/components/ChannelManager/components/ConnectChannelList.tsxindex 3ef5cdad..63da7649 100644--- a/project/aitoearn-web/src/components/ChannelManager/components/ConnectChannelList.tsx+++ b/project/aitoearn-web/src/components/ChannelManager/components/ConnectChannelList.tsx@@ -8,7 +8,7 @@import { ArrowLeft, Sparkles } from 'lucide-react'import { toast } from 'sonner'import { useShallow } from 'zustand/react/shallow'-import { PlatType, RegionSortedPlatInfoArr } from '@/app/config/platConfig'+import { isPlatformAvailable, PlatType, RegionSortedPlatInfoArr } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import { ScrollArea } from '@/components/ui/scroll-area'@@ -114,6 +114,7 @@ export function ConnectChannelList() {><TooltipProvider>{RegionSortedPlatInfoArr.map(([key, value]) => {+ const isRegionRestricted = !isPlatformAvailable(key)return (<Tooltip key={key}><TooltipTrigger asChild>@@ -131,6 +132,7 @@ export function ConnectChannelList() {active:translate-y-0 active:scale-[0.98]sm:h-[100px] sm:rounded-xl sm:p-3md:h-[110px]+ ${isRegionRestricted ? 'opacity-50 grayscale' : ''}`}onClick={() => handlePlatformClick(key as PlatType)}>diff --git a/project/aitoearn-web/src/components/ChannelManager/components/MainPage.tsx b/project/aitoearn-web/src/components/ChannelManager/components/MainPage.tsxindex 791708a3..3b84ca48 100644--- a/project/aitoearn-web/src/components/ChannelManager/components/MainPage.tsx+++ b/project/aitoearn-web/src/components/ChannelManager/components/MainPage.tsx@@ -121,8 +121,9 @@ export function MainPage() {setDeleteDialog({ open: false, type: 'space', id: '', name: '' })}catch (error) {- const errorType = deleteDialog.type === 'space' ? '空间' : '频道'- toast.error(`删除${errorType}失败`)+ toast.error(deleteDialog.type === 'space'+ ? t('channelManager.deleteSpaceFailed')+ : t('channelManager.deleteChannelFailed'))}finally {setDeleteLoading(null)diff --git a/project/aitoearn-web/src/components/ChannelManager/components/SpaceItem.tsx b/project/aitoearn-web/src/components/ChannelManager/components/SpaceItem.tsxindex 07c44e92..f19004ac 100644--- a/project/aitoearn-web/src/components/ChannelManager/components/SpaceItem.tsx+++ b/project/aitoearn-web/src/components/ChannelManager/components/SpaceItem.tsx@@ -182,14 +182,14 @@ export function SpaceItem({data-testid="cm-space-add-channel-btn"variant="outline"size="sm"- className="h-7 cursor-pointer shrink-0 px-2 sm:px-3"+ className="h-7 cursor-pointer shrink-0 px-2"onClick={(e) => {e.stopPropagation()onAddChannel()}}>- <Plus className="h-3 w-3 sm:mr-1" />- <span className="hidden sm:inline">{t('channelManager.addChannel')}</span>+ <Plus className="h-3 w-3 mr-1" />+ <span>{t('channelManager.addChannel')}</span></Button>)}diff --git a/project/aitoearn-web/src/components/ChannelManager/components/UnifiedChannelSpaceList.tsx b/project/aitoearn-web/src/components/ChannelManager/components/UnifiedChannelSpaceList.tsxindex b005d96e..5d010171 100644--- a/project/aitoearn-web/src/components/ChannelManager/components/UnifiedChannelSpaceList.tsx+++ b/project/aitoearn-web/src/components/ChannelManager/components/UnifiedChannelSpaceList.tsx@@ -112,8 +112,9 @@ export function UnifiedChannelSpaceList() {setDeleteDialog({ open: false, type: 'space', id: '', name: '' })}catch (error) {- const errorType = deleteDialog.type === 'space' ? '空间' : '频道'- toast.error(`删除${errorType}失败`)+ toast.error(deleteDialog.type === 'space'+ ? t('channelManager.deleteSpaceFailed')+ : t('channelManager.deleteChannelFailed'))// 删除失败不关闭对话框,让用户可以重试}finally {diff --git a/project/aitoearn-web/src/components/Chat/ActionCard/index.tsx b/project/aitoearn-web/src/components/Chat/ActionCard/index.tsxindex 230e0fe8..7d82604b 100644--- a/project/aitoearn-web/src/components/Chat/ActionCard/index.tsx+++ b/project/aitoearn-web/src/components/Chat/ActionCard/index.tsx@@ -16,6 +16,7 @@ import { useChannelManagerStore } from '@/components/ChannelManager'import { Button } from '@/components/ui/button'import { toast } from '@/lib/toast'import { cn } from '@/lib/utils'+import { useAccountStore } from '@/store'import { useAgentStore } from '@/store/agent'import { ActionRegistry } from '@/store/agent/handlers/action.handlers'import { PluginStatus, usePluginStore } from '@/store/plugin'@@ -225,7 +226,7 @@ export function ActionCard({ action, className }: IActionCardProps) {switch (action.type) {case 'insufficientCredits':- toast.warning('Insufficient credits')+ useAccountStore.getState().setLowBalanceAlertOpen(true)returncase 'createChannel':// 未登录时跳转登录页diff --git a/project/aitoearn-web/src/components/Chat/ChatMessage/ChatMessage.module.scss b/project/aitoearn-web/src/components/Chat/ChatMessage/ChatMessage.module.scssindex 4982e36e..dbd7cf57 100644--- a/project/aitoearn-web/src/components/Chat/ChatMessage/ChatMessage.module.scss+++ b/project/aitoearn-web/src/components/Chat/ChatMessage/ChatMessage.module.scss@@ -24,7 +24,10 @@animation: slideIn 0.15s ease-out;button {- transition: all 0.15s ease;+ transition:+ transform 0.15s ease,+ background-color 0.15s ease,+ box-shadow 0.15s ease;&:active {transform: scale(0.98);diff --git a/project/aitoearn-web/src/components/ChooseAccountModule/chooseAccountModule.module.scss b/project/aitoearn-web/src/components/ChooseAccountModule/chooseAccountModule.module.scssindex ac66d377..afd7154f 100644--- a/project/aitoearn-web/src/components/ChooseAccountModule/chooseAccountModule.module.scss+++ b/project/aitoearn-web/src/components/ChooseAccountModule/chooseAccountModule.module.scss@@ -198,7 +198,10 @@padding: 12px;border-radius: 8px;border: 1px solid #e9ecef;- transition: all 0.2s ease;+ transition:+ border-color 0.2s ease,+ box-shadow 0.2s ease,+ background-color 0.2s ease;position: relative;display: flex;align-items: center;@@ -264,7 +267,9 @@justify-content: center;font-size: 12px;opacity: 0;- transition: all 0.2s ease;+ transition:+ opacity 0.2s ease,+ background-color 0.2s ease;}&--active {@@ -322,7 +327,7 @@align-items: center;justify-content: center;opacity: 0.8;- transition: all 0.2s ease;+ transition: opacity 0.2s ease;z-index: 10;&-text {diff --git a/project/aitoearn-web/src/components/InviteCodeHandler.tsx b/project/aitoearn-web/src/components/InviteCodeHandler.tsxdeleted file mode 100644index 98905511..00000000--- a/project/aitoearn-web/src/components/InviteCodeHandler.tsx+++ /dev/null@@ -1,10 +0,0 @@-/**- * InviteCodeHandler - 邀请码处理组件(已停用)- * 联盟营销功能已移除,此组件保留为空壳以防止引用报错- */--'use client'--export function InviteCodeHandler() {- return null-}diff --git a/project/aitoearn-web/src/components/Plugin/PluginNotInstalled.tsx b/project/aitoearn-web/src/components/Plugin/PluginNotInstalled.tsxindex b66d8a81..f9299fc6 100644--- a/project/aitoearn-web/src/components/Plugin/PluginNotInstalled.tsx+++ b/project/aitoearn-web/src/components/Plugin/PluginNotInstalled.tsx@@ -5,7 +5,7 @@'use client'-import { BookOpen, Chrome, CloudDownload, Github, Monitor, Puzzle } from 'lucide-react'+import { BookOpen, Chrome, CloudDownload, Monitor, Puzzle } from 'lucide-react'import Link from 'next/link'import { useTranslation } from 'react-i18next'import { Button } from '@/components/ui/button'@@ -40,12 +40,12 @@ function MobilePluginTip() {</div>{/* 插件介绍卡片 */}- <div className="w-full rounded-lg border border-border bg-muted/30 p-4">+ <div className="w-full rounded-lg border border-border bg-muted/30 p-5"><div className="mb-2 flex items-center gap-2">- <Puzzle className="h-4 w-4 text-muted-foreground" />- <span className="text-xs font-medium text-muted-foreground">{t('header.downloadPlugin')}</span>+ <Puzzle className="h-5 w-5 text-muted-foreground" />+ <span className="text-sm font-medium text-muted-foreground">{t('header.downloadPlugin')}</span></div>- <p className="text-xs leading-relaxed text-muted-foreground">+ <p className="text-sm leading-relaxed text-muted-foreground">{t('mobile.introduction')}</p></div>@@ -80,7 +80,7 @@ export function PluginNotInstalled() {</p>{/* 下载按钮 */}- <div className="flex w-full max-w-xs flex-col gap-3">+ <div className="flex w-full max-w-xs flex-col space-y-3"><Button className="w-full gap-2" asChild><a href={PLUGIN_DOWNLOAD_LINKS.chrome} target="_blank" rel="noopener noreferrer"><Chrome className="h-4 w-4" />@@ -88,13 +88,6 @@ export function PluginNotInstalled() {</a></Button>- <Button variant="outline" className="w-full gap-2" asChild>- <a href={PLUGIN_DOWNLOAD_LINKS.github} target="_blank" rel="noopener noreferrer">- <Github className="h-4 w-4" />- {t('header.githubRelease')}- </a>- </Button>-<Button variant="outline" className="w-full gap-2" asChild><a href={PLUGIN_DOWNLOAD_LINKS.china} target="_blank" rel="noopener noreferrer"><CloudDownload className="h-4 w-4" />diff --git a/project/aitoearn-web/src/components/Plugin/PublishDetailModal.tsx b/project/aitoearn-web/src/components/Plugin/PublishDetailModal.tsxindex 5aff1b23..5381e372 100644--- a/project/aitoearn-web/src/components/Plugin/PublishDetailModal.tsx+++ b/project/aitoearn-web/src/components/Plugin/PublishDetailModal.tsx@@ -38,6 +38,8 @@ export interface PublishDetailModalProps {taskId?: string/** 任务对象(二选一) */task?: PublishTask+ /** 发布完成后是否自动关闭弹框(默认 false) */+ autoCloseOnComplete?: boolean}/**@@ -227,7 +229,7 @@ function PlatformTaskCard({ platformTask }: { platformTask: PlatformPublishTask/*** 发布详情弹框组件*/-export function PublishDetailModal({ visible, onClose, taskId, task }: PublishDetailModalProps) {+export function PublishDetailModal({ visible, onClose, taskId, task, autoCloseOnComplete = false }: PublishDetailModalProps) {const { t } = useTranslation('plugin')const isCreatingRecord = usePluginStore(state => state.isCreatingRecord)@@ -239,12 +241,12 @@ export function PublishDetailModal({ visible, onClose, taskId, task }: PublishDereturn task})- // 自动关闭:发布完成且发布记录创建完毕+ // 自动关闭:仅当 autoCloseOnComplete 为 true 时,发布完成且发布记录创建完毕后自动关闭useEffect(() => {- if (currentTask?.overallStatus === PlatformTaskStatus.COMPLETED && !isCreatingRecord) {+ if (autoCloseOnComplete && currentTask?.overallStatus === PlatformTaskStatus.COMPLETED && !isCreatingRecord) {onClose()}- }, [currentTask?.overallStatus, isCreatingRecord, onClose])+ }, [autoCloseOnComplete, currentTask?.overallStatus, isCreatingRecord, onClose])if (!currentTask) {return nulldiff --git a/project/aitoearn-web/src/components/PublishDialog/PublishDialog.util.ts b/project/aitoearn-web/src/components/PublishDialog/PublishDialog.util.tsindex 943fdd75..64c1491d 100644--- a/project/aitoearn-web/src/components/PublishDialog/PublishDialog.util.ts+++ b/project/aitoearn-web/src/components/PublishDialog/PublishDialog.util.ts@@ -28,8 +28,10 @@ export function VideoGrabFrame(}> {return new Promise((resolve, reject) => {const video = document.createElement('video')- video.src = getOssUrl(videoUrl)- video.crossOrigin = 'anonymous' // 尝试跨域访问+ video.crossOrigin = 'anonymous'+ // 添加查询参数避免浏览器复用非 CORS 缓存(同一 URL 无 crossOrigin 的请求会污染缓存)+ const url = getOssUrl(videoUrl)+ video.src = url.startsWith('blob:') ? url : `${url}${url.includes('?') ? '&' : '?'}x-cors=1`// 设置超时const timeout = setTimeout(() => {diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/AccountSelector/index.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/AccountSelector/index.tsxindex 090d5574..52f78850 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/AccountSelector/index.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/AccountSelector/index.tsx@@ -8,7 +8,7 @@ import type { PubItem } from '@/components/PublishDialog/publishDialog.type'import { memo } from 'react'import { useShallow } from 'zustand/react/shallow'-import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { AccountPlatInfoMap, isPlatformAvailable, PlatType } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import AvatarPlat from '@/components/AvatarPlat'import { useAccountClickHandler } from '@/components/PublishDialog/hooks/useAccountClickHandler'@@ -74,6 +74,7 @@ export const AccountSelector = memo(const isChoosed = pubListChoosed.find(v => v.account.id === pubItem.account.id)const isOffline = pubItem.account.status === 0const isPcNotSupported = platConfig && platConfig.pcNoThis === true+ const isRegionRestricted = !isPlatformAvailable(pubItem.account.type)return (<TooltipProvider key={pubItem.account.id}>@@ -100,19 +101,19 @@ export const AccountSelector = memo(handleAccountClick(pubItem)}}>- {/* 账号头像:离线、PC不支持显示遮罩并禁用 */}+ {/* 账号头像:离线、PC不支持或区域限制显示遮罩并禁用 */}<div className="relative"><AvatarPlatclassName={`cursor-pointer transition-all duration-300 p-[1px] ${- isChoosed && !isOffline && !isPcNotSupported+ isChoosed && !isOffline && !isPcNotSupported && !isRegionRestricted? '[&>img]:grayscale-0': '[&>img]:grayscale hover:[&>img]:grayscale-0'}`}account={pubItem.account}size="large"- disabled={isOffline || !isChoosed || isPcNotSupported}+ disabled={isOffline || !isChoosed || isPcNotSupported || isRegionRestricted}/>- {isOffline && (+ {isOffline && !isRegionRestricted && (<divonClick={(e) => {e.stopPropagation()@@ -129,7 +130,12 @@ export const AccountSelector = memo({t('badges.offline')}</div>)}- {isPcNotSupported && !isOffline && (+ {isRegionRestricted && (+ <div className="absolute inset-0 bg-black/60 rounded-full flex items-center justify-center text-white text-[10px] font-semibold pointer-events-auto cursor-pointer text-center leading-tight">+ 🌐+ </div>+ )}+ {isPcNotSupported && !isOffline && !isRegionRestricted && (<div className="absolute inset-0 bg-black/60 rounded-full flex items-center justify-center text-white text-[10px] font-semibold pointer-events-none text-center leading-tight">APP</div>@@ -137,9 +143,9 @@ export const AccountSelector = memo(</div></div></TooltipTrigger>- {(isPcNotSupported || isOffline) && (+ {(isPcNotSupported || isOffline || isRegionRestricted) && (<TooltipContent>- {isPcNotSupported ? t('tips.pcNotSupported') : t('tips.accountOffline')}+ {isRegionRestricted ? t('tips.regionRestricted') : isPcNotSupported ? t('tips.pcNotSupported') : t('tips.accountOffline')}</TooltipContent>)}</Tooltip>diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/components/GroupCard.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/components/GroupCard.tsxindex f1b7d6e3..6cd60477 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/components/GroupCard.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/components/GroupCard.tsx@@ -8,7 +8,7 @@import type { GroupCardProps } from '../types'import { motion } from 'framer-motion'-import { Image as ImageIcon, Video } from 'lucide-react'+import { FolderOpen } from 'lucide-react'import Image from 'next/image'import { useTransClient } from '@/app/i18n/client'import { Badge } from '@/components/ui/badge'@@ -17,7 +17,6 @@ import { getOssUrl } from '@/utils/oss'export function GroupCard({ group, onClick }: GroupCardProps) {const { t } = useTransClient('material')- const isVideo = group.type === 'video'const isDefault = group.isDefault// 获取封面 URL@@ -52,25 +51,8 @@ export function GroupCard({ group, onClick }: GroupCardProps) {/>) : (// 无封面占位符- <div- className={cn(- 'absolute inset-0 flex flex-col items-center justify-center',- isVideo- ? 'bg-gradient-to-br from-blue-500/10 to-purple-500/10'- : 'bg-gradient-to-br from-green-500/10 to-teal-500/10',- )}- >- {isVideo ? (- <>- <Video className="w-10 h-10 text-blue-500/50 mb-1.5" />- <span className="text-xs text-muted-foreground">{t('mediaManagement.video')}</span>- </>- ) : (- <>- <ImageIcon className="w-10 h-10 text-green-500/50 mb-1.5" />- <span className="text-xs text-muted-foreground">{t('mediaManagement.image')}</span>- </>- )}+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-gradient-to-br from-slate-500/10 to-gray-500/10">+ <FolderOpen className="w-10 h-10 text-muted-foreground/50 mb-1.5" /></div>)}@@ -81,29 +63,6 @@ export function GroupCard({ group, onClick }: GroupCardProps) {</Badge>)}- {/* 类型图标 */}- <Badge- className={cn(- 'absolute bottom-2 left-2 backdrop-blur-sm text-xs',- isVideo- ? 'bg-blue-500/80 hover:bg-blue-500/80 text-white'- : 'bg-green-500/80 hover:bg-green-500/80 text-white',- )}- >- {isVideo ? <Video className="w-3 h-3 mr-1" /> : <ImageIcon className="w-3 h-3 mr-1" />}- {isVideo ? t('mediaManagement.video') : t('mediaManagement.image')}- </Badge>-- {/* 资源数量 */}- <Badge- variant="secondary"- className="absolute bottom-2 right-2 backdrop-blur-sm bg-black/50 hover:bg-black/50 text-white border-0 text-xs"- >- {group.count || 0}- {' '}- {t('mediaManagement.resources')}- </Badge>-{/* Hover 遮罩 */}<div className="absolute inset-0 bg-black/0 group-hover:bg-black/5 transition-colors pointer-events-none" /></div>diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsxindex bec68b29..d33effcc 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx@@ -15,7 +15,8 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import InfiniteScroll from 'react-infinite-scroll-component'import Masonry from 'react-masonry-css'import { getAgentAssets } from '@/api/ai'-import { getMediaGroupList, getMediaList } from '@/api/media'+import { apiGetMaterialGroupList } from '@/api/material'+import { getMediaList } from '@/api/media'import { useTransClient } from '@/app/i18n/client'import { Button } from '@/components/ui/button'import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'@@ -56,31 +57,23 @@ const MEDIA_BREAKPOINTS = {const PAGE_SIZE = 20/**- * 处理分组数据,提取封面和资源数量+ * 将草稿箱 PromotionPlan 转换为 MediaGroup 兼容结构*/-function processGroups(list: MediaGroup[]): MediaGroup[] {- return list.map((group) => {- const mediaList = group.mediaList-- // 查找第一个媒体作为预览- let previewMedia = null- if (mediaList && mediaList.list && mediaList.list.length > 0) {- previewMedia = mediaList.list[0]- }-- return {- ...group,- cover: previewMedia?.thumbUrl || previewMedia?.url,- count: mediaList?.total || 0,- previewMedia: previewMedia- ? {- type: previewMedia.type,- url: previewMedia.url,- thumbUrl: previewMedia.thumbUrl,- }- : null,- }- })+function adaptPlansToGroups(plans: { id: string, name: string, title?: string, desc?: string, isDefault?: boolean, createdAt?: string, updatedAt?: string }[]): MediaGroup[] {+ return plans.map(plan => ({+ _id: plan.id,+ title: plan.name || plan.title || '',+ type: 'img',+ desc: plan.desc,+ count: 0,+ isDefault: plan.isDefault,+ cover: undefined,+ previewMedia: null,+ userId: '',+ userType: '',+ createdAt: plan.createdAt || '',+ updatedAt: plan.updatedAt || '',+ }))}/**@@ -123,35 +116,16 @@ const MaterialSelectionModalContent = memo(// 多选状态(仅图片模式)const [selectedMedia, setSelectedMedia] = useState<Set<string>>(new Set())- // 是否为多选模式(Agent 分组支持多种类型时,根据 mediaTypes 判断)- const isMultiSelect = isAgentGroup- ? typesArray.includes('img') // Agent 分组:包含图片即启用多选模式- : selectedGroup?.type === 'img' // 普通分组:图片组多选+ // 是否为多选模式:包含图片类型即启用多选+ const isMultiSelect = typesArray.includes('img')- // 获取分组列表+ // 获取草稿箱分组列表const fetchGroups = useCallback(async () => {setGroupsLoading(true)try {- // 如果支持多种类型,分别获取然后合并- if (isMultipleTypes) {- const promises = typesArray.map(type => getMediaGroupList(1, 50, type))- const responses = await Promise.all(promises)- const allGroups: MediaGroup[] = []- responses.forEach((response) => {- if (response?.data?.list) {- allGroups.push(...response.data.list)- }- })- const processedGroups = processGroups(allGroups)- setGroups(processedGroups)- }- else {- // 单一类型- const response = await getMediaGroupList(1, 50, typesArray[0])- if (response?.data?.list) {- const processedGroups = processGroups(response.data.list)- setGroups(processedGroups)- }+ const response = await apiGetMaterialGroupList(1, 100)+ if (response?.data?.list) {+ setGroups(adaptPlansToGroups(response.data.list))}}catch (error) {@@ -160,19 +134,19 @@ const MaterialSelectionModalContent = memo(finally {setGroupsLoading(false)}- }, [typesArray, isMultipleTypes])+ }, [])// 使用 ref 稳定化 fetchGroups 引用,避免 useEffect 因函数引用变化而重复执行const fetchGroupsRef = useRef(fetchGroups)fetchGroupsRef.current = fetchGroups// 获取媒体列表(首次加载)- const fetchMediaList = useCallback(async (groupId: string) => {+ const fetchMediaList = useCallback(async (materialGroupId: string) => {setMediaLoading(true)setMediaPage(1)setHasMoreMedia(true)try {- const response = await getMediaList(groupId, 1, PAGE_SIZE)+ const response = await getMediaList({ materialGroupId }, 1, PAGE_SIZE)if (response?.data?.list) {const list = response.data.listconst total = response.data.total || 0@@ -283,7 +257,7 @@ const MaterialSelectionModalContent = memo(setIsLoadingMore(true)try {- const response = await getMediaList(selectedGroup._id, nextPage, PAGE_SIZE)+ const response = await getMediaList({ materialGroupId: selectedGroup._id }, nextPage, PAGE_SIZE)if (response?.data?.list) {const newList = response.data.listconst total = response.data.total || 0@@ -347,11 +321,8 @@ const MaterialSelectionModalContent = memo(// 点击媒体const handleMediaClick = useCallback((media: MediaItem) => {- // 根据当前分组类型判断选择模式- // Agent 分组:按素材类型判断;普通分组:图片组多选- const currentIsMultiSelect = isAgentGroup- ? media.type === 'img'- : selectedGroup?.type === 'img'+ // 图片多选,视频单选+ const currentIsMultiSelect = media.type === 'img'if (currentIsMultiSelect) {// 图片多选:切换选中状态@@ -372,7 +343,7 @@ const MaterialSelectionModalContent = memo(onOpenChange(false)}},- [selectedGroup, isAgentGroup, onSelect, onOpenChange],+ [onSelect, onOpenChange],)// 确认选择(多选模式)@@ -527,7 +498,7 @@ const MaterialSelectionModalContent = memo(<SelectableMediaCardmedia={media}selected={selectedMedia.has(media._id)}- multiSelect={isAgentGroup ? media.type === 'img' : isMultiSelect}+ multiSelect={media.type === 'img'}onClick={handleMediaClick}/></div>diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/types.ts b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/types.tsindex 944510d3..34c57665 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/types.ts+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/MaterialSelectionModal/types.ts@@ -3,7 +3,7 @@* 素材选择器弹窗的类型定义*/-import type { MediaGroup, MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaGroup, MediaItem } from '@/api/types/media'/*** 媒体类型diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsxindex 3701ec4e..07462fe3 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx@@ -18,7 +18,6 @@ import {formatVideo,VideoGrabFrame,} from '@/components/PublishDialog/PublishDialog.util'-import { OSS_URL } from '@/constant'import { toast } from '@/lib/toast'import { cn } from '@/lib/utils'import { getOssUrl } from '@/utils/oss'@@ -351,7 +350,7 @@ const PubParmasTextareaUpload = memo(// 处理图片素材导入const processImageMedia = useCallback(async (media: MediaItem): Promise<IImgFile> => {const ossUrl = getOssUrl(media.url)- const req = await fetch(ossUrl.replace(OSS_URL, '/ossProxy/'))+ const req = await fetch(ossUrl)const blob = await req.blob()const imagefile = await formatImg({blob,@@ -367,7 +366,7 @@ const PubParmasTextareaUpload = memo(const coverOss = getOssUrl(media.thumbUrl)// 下载封面- const req = await fetch(coverOss.replace(OSS_URL, '/ossProxy/'))+ const req = await fetch(coverOss)const blob = await req.blob()const imagefile = await formatImg({blob,diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsxindex 91fc268b..f271093f 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx@@ -63,6 +63,10 @@ export interface IPubParmasTextareaProps {hideWritingAssistant?: boolean// toolbar 额外内容(写作助手按钮后面)toolbarExtra?: React.ReactNode+ // 覆盖图片最大数量(优先于平台配置)+ imagesMaxOverride?: number+ // 覆盖描述最大长度(优先于平台配置)+ desMaxOverride?: number}const PubParmasTextarea = memo(@@ -84,6 +88,8 @@ const PubParmasTextarea = memo(isMobile,hideWritingAssistant,toolbarExtra,+ imagesMaxOverride,+ desMaxOverride,}: IPubParmasTextareaProps,ref: ForwardedRef<IPubParmasTextareaRef>,) => {@@ -160,8 +166,8 @@ const PubParmasTextarea = memo(return AccountPlatInfoMap.get(platType)! || {}}, [platType])const imageMax = useMemo(() => {- return platConfig.commonPubParamsConfig?.imagesMax || 10- }, [platConfig])+ return imagesMaxOverride ?? platConfig.commonPubParamsConfig?.imagesMax ?? 10+ }, [platConfig, imagesMaxOverride])// 动态accept类型const uploadAccept = useMemo(() => {@@ -280,8 +286,8 @@ const PubParmasTextarea = memo()const desMax = useMemo(() => {- return platConfig.commonPubParamsConfig?.desMax || 2200- }, [platConfig])+ return desMaxOverride ?? platConfig.commonPubParamsConfig?.desMax ?? 2200+ }, [platConfig, desMaxOverride])return (<>diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/PublishDialogAi.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/PublishDialogAi.tsxindex cf4042bc..0749e51d 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/PublishDialogAi.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/PublishDialogAi.tsx@@ -347,10 +347,10 @@ const PublishDialogAi = memo(// Video generation stateconst [videoModels, setVideoModels] = useState<any[]>([])const videoModelsLoadingRef = useRef(true) // Use ref to track loading state- // Initialize from localStorage or use default 'sora-2'+ // Initialize from localStorage, will be set from API if emptyconst [selectedVideoModel, setSelectedVideoModel] = useState(() => {const savedModel = localStorage.getItem('ai_video_model')- return savedModel || 'sora-2'+ return savedModel || ''})const [videoTaskId, setVideoTaskId] = useState<string | null>(null)const [videoStatus, setVideoStatus] = useState<string>('')@@ -434,22 +434,10 @@ const PublishDialogAi = memo(// Use saved model if it exists in listsetSelectedVideoModel(savedModel)}- else {- // Try to find sora-related model- const soraModel = res.data.find(- (m: any) => m.name?.toLowerCase().includes('sora') || m.name === 'sora-2',- )-- if (soraModel) {- // Prefer sora model- setSelectedVideoModel(soraModel.name)- localStorage.setItem('ai_video_model', soraModel.name)- }- else if (res.data.length > 0) {- // Use first model if no sora found- setSelectedVideoModel(res.data[0].name)- localStorage.setItem('ai_video_model', res.data[0].name)- }+ else if (res.data.length > 0) {+ // Use first available model+ setSelectedVideoModel(res.data[0].name)+ localStorage.setItem('ai_video_model', res.data[0].name)}}}@@ -611,35 +599,16 @@ const PublishDialogAi = memo(let duration = 5let size = '720p'- if (selectedModel?.channel === 'kling' && selectedModel?.pricing) {- const durations = [- ...new Set(selectedModel.pricing.map((p: any) => p.duration)),- ] as number[]- const modes = [...new Set(selectedModel.pricing.map((p: any) => p.mode))] as string[]- if (durations.length > 0)- duration = durations[0]- if (modes.length > 0)- size = modes[0]- }- else {- if (selectedModel?.durations?.length > 0)- duration = selectedModel.durations[0]- if (selectedModel?.resolutions?.length > 0)- size = selectedModel.resolutions[0]- }+ if (selectedModel?.durations?.length > 0)+ duration = selectedModel.durations[0]+ if (selectedModel?.resolutions?.length > 0)+ size = selectedModel.resolutions[0]const data: any = {model: selectedVideoModel,prompt,duration,- }-- // Use mode parameter for kling model- if (selectedModel?.channel === 'kling') {- data.mode = size- }- else {- data.size = size+ size,}const res: any = await generateVideo(data)@@ -706,7 +675,7 @@ const PublishDialogAi = memo(let matchconst replacements: Array<{ original: string, blobUrl: string }> = []- while ((match = base64Regex.exec(result.data.content)) !== null) {+ while ((match = base64Regex.exec(result.data.content)) !== null) { // eslint-disable-line no-cond-assignconst [fullMatch, alt, base64Url] = matchtry {// Extract base64 data@@ -1027,7 +996,7 @@ const PublishDialogAi = memo(const downloadVideoAsVideoFile = async (url: string): Promise<IVideoFile | null> => {try {// Convert relative path to full S3 URL for publishing- // API returns: ai/video/sora-2/...+ // API returns: ai/video/{model}/...const ossUrl = `${getOssUrl(url)}`const filename = `ai-generated-video.mp4`@@ -1268,7 +1237,7 @@ const PublishDialogAi = memo(const href = props.href || ''// Check if it's an audio file- if (/\.(aac|mp3|opus|wav)$/.test(href)) {+ if (/\.(?:aac|mp3|opus|wav)$/.test(href)) {return (<figure className="my-2"><audio controls src={href}></audio>@@ -1277,7 +1246,7 @@ const PublishDialogAi = memo(}// Check if it's a video file- if (/\.(3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href) || href.includes('video')) {+ if (/\.(?:3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href) || href.includes('video')) {return (<div className="my-2"><video controls className="max-w-full max-h-[400px] rounded-lg block">@@ -1607,22 +1576,10 @@ const PublishDialogAi = memo(let duration = 5let size = '720p'- if (model?.channel === 'kling' && model?.pricing) {- const durations = [- ...new Set(model.pricing.map((p: any) => p.duration)),- ] as number[]- const modes = [...new Set(model.pricing.map((p: any) => p.mode))] as string[]- if (durations.length > 0)- duration = durations[0]- if (modes.length > 0)- size = modes[0]- }- else {- if (model?.durations?.length > 0)- duration = model.durations[0]- if (model?.resolutions?.length > 0)- size = model.resolutions[0]- }+ if (model?.durations?.length > 0)+ duration = model.durations[0]+ if (model?.resolutions?.length > 0)+ size = model.resolutions[0]return (<div className="mt-2 p-2 bg-muted rounded text-xs text-muted-foreground">diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/PublishModals/index.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/PublishModals/index.tsxindex d71f9b77..d42cde8f 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/PublishModals/index.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/PublishModals/index.tsx@@ -1,6 +1,6 @@/*** 发布弹框相关的模态框组件集合- * 包含下载App弹窗、Facebook页面选择、抖音扫码、发布详情等弹窗+ * 包含 Facebook 页面选择、抖音扫码、发布详情等弹窗*/import { memo } from 'react'@@ -9,10 +9,6 @@ import { DouyinQRCodeModal } from '@/components/PublishDialog/compoents/DouyinQRimport FacebookPagesModal from './FacebookPagesModal'interface PublishModalsProps {- // 下载App弹窗(已移除,保留 props 兼容)- downloadModalVisible: boolean- setDownloadModalVisible: (visible: boolean) => void- currentPlatform: string// Facebook页面选择弹窗showFacebookPagesModal: booleansetShowFacebookPagesModal: (show: boolean) => void@@ -25,6 +21,8 @@ interface PublishModalsProps {publishDetailVisible: booleanonPublishDetailClose: () => voidcurrentPublishTaskId: string | undefined+ // 发布完成后是否自动关闭弹框+ autoCloseOnComplete?: boolean}/**@@ -41,6 +39,7 @@ export const PublishModals = memo(publishDetailVisible,onPublishDetailClose,currentPublishTaskId,+ autoCloseOnComplete,}: PublishModalsProps) => {return (<>@@ -63,6 +62,7 @@ export const PublishModals = memo(visible={publishDetailVisible}onClose={onPublishDetailClose}taskId={currentPublishTaskId}+ autoCloseOnComplete={autoCloseOnComplete}/></>)diff --git a/project/aitoearn-web/src/components/PublishDialog/compoents/mobile/MobilePublishContent.tsx b/project/aitoearn-web/src/components/PublishDialog/compoents/mobile/MobilePublishContent.tsxindex 5b1c7055..9b224361 100644--- a/project/aitoearn-web/src/components/PublishDialog/compoents/mobile/MobilePublishContent.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/compoents/mobile/MobilePublishContent.tsx@@ -9,7 +9,7 @@ import { ArrowRight, ChevronDown, FolderOpen, Layers, X } from 'lucide-react'import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useShallow } from 'zustand/react/shallow'-import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { AccountPlatInfoMap, isPlatformAvailable, PlatType } from '@/app/config/platConfig'import { useTransClient } from '@/app/i18n/client'import AvatarPlat from '@/components/AvatarPlat'import { DouyinLaunchModal } from '@/components/PublishDialog/compoents/DouyinLaunchModal'@@ -187,7 +187,7 @@ const MobilePublishContent = memo(// 处理 PC 不支持平台点击const handlePcNotSupportedClick = useCallback((_platformName: string) => {- // No-op: download app modal removed+ // DownloadAppModal has been removed; no-op for now}, [])// 处理图生图(移动端暂不支持)@@ -354,6 +354,7 @@ const MobilePublishContent = memo(const isChoosed = pubListChoosed.find(v => v.account.id === pubItem.account.id)const isOffline = pubItem.account.status === 0const isPcNotSupported = platConfig && platConfig.pcNoThis === true+ const isRegionRestricted = !isPlatformAvailable(pubItem.account.type)return (<TooltipProvider key={pubItem.account.id}>@@ -374,17 +375,17 @@ const MobilePublishContent = memo(<div className="relative"><AvatarPlatclassName={`cursor-pointer transition-all duration-300 p-[1px] ${- isChoosed && !isOffline && !isPcNotSupported+ isChoosed && !isOffline && !isPcNotSupported && !isRegionRestricted? '[&>img]:grayscale-0': '[&>img]:grayscale hover:[&>img]:grayscale-0'}`}account={pubItem.account}size="large"disabled={- isOffline || !isChoosed || isPcNotSupported+ isOffline || !isChoosed || isPcNotSupported || isRegionRestricted}/>- {isOffline && (+ {isOffline && !isRegionRestricted && (<divonClick={(e) => {e.stopPropagation()@@ -399,7 +400,12 @@ const MobilePublishContent = memo({t('badges.offline')}</div>)}- {isPcNotSupported && !isOffline && (+ {isRegionRestricted && (+ <div className="absolute inset-0 bg-black/60 rounded-full flex items-center justify-center text-white text-[10px] font-semibold pointer-events-auto cursor-pointer text-center leading-tight">+ 🌐+ </div>+ )}+ {isPcNotSupported && !isOffline && !isRegionRestricted && (<div className="absolute inset-0 bg-black/60 rounded-full flex items-center justify-center text-white text-[10px] font-semibold pointer-events-none text-center leading-tight">APP</div>@@ -407,11 +413,13 @@ const MobilePublishContent = memo(</div></div></TooltipTrigger>- {(isPcNotSupported || isOffline) && (+ {(isPcNotSupported || isOffline || isRegionRestricted) && (<TooltipContent>- {isPcNotSupported- ? t('tips.pcNotSupported')- : t('tips.accountOffline')}+ {isRegionRestricted+ ? t('tips.regionRestricted')+ : isPcNotSupported+ ? t('tips.pcNotSupported')+ : t('tips.accountOffline')}</TooltipContent>)}</Tooltip>diff --git a/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishActions.ts b/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishActions.tsindex 9e590398..2da8e09a 100644--- a/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishActions.ts+++ b/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishActions.ts@@ -192,7 +192,7 @@ export function usePublishActions({) {if (!isMobile) {// PC端:显示二维码弹窗,优先使用 shortLink(标准 HTTPS URL,扫码兼容性更好)- setDouyinPermalink(`shortLink?apiLink=${encodeURIComponent(resData.shortLink)}`)+ setDouyinPermalink(`/shortLink?apiLink=${encodeURIComponent(resData.shortLink)}`)}else {// 移动端:显示引导弹窗,用户点击按钮后唤起抖音 Appdiff --git a/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishState.ts b/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishState.tsindex c561ec1f..853ebb63 100644--- a/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishState.ts+++ b/project/aitoearn-web/src/components/PublishDialog/hooks/usePublishState.ts@@ -9,11 +9,6 @@ export interface PublishModalState {// 创建发布loadingcreateLoading: booleansetCreateLoading: (loading: boolean) => void- // 下载App弹窗- downloadModalVisible: boolean- setDownloadModalVisible: (visible: boolean) => void- currentPlatform: string- setCurrentPlatform: (platform: string) => void// 抖音扫码发布弹窗douyinQRCodeVisible: booleansetDouyinQRCodeVisible: (visible: boolean) => void@@ -35,9 +30,6 @@ export interface PublishModalState {export function usePublishModalState(): PublishModalState {// 创建发布loadingconst [createLoading, setCreateLoading] = useState(false)- // 下载App弹窗状态- const [downloadModalVisible, setDownloadModalVisible] = useState(false)- const [currentPlatform, setCurrentPlatform] = useState<string>('')// 抖音扫码发布弹窗状态const [douyinQRCodeVisible, setDouyinQRCodeVisible] = useState(false)const [douyinPermalink, setDouyinPermalink] = useState('')@@ -50,10 +42,6 @@ export function usePublishModalState(): PublishModalState {return {createLoading,setCreateLoading,- downloadModalVisible,- setDownloadModalVisible,- currentPlatform,- setCurrentPlatform,douyinQRCodeVisible,setDouyinQRCodeVisible,douyinPermalink,diff --git a/project/aitoearn-web/src/components/PublishDialog/index.tsx b/project/aitoearn-web/src/components/PublishDialog/index.tsxindex c57ea897..820ad281 100644--- a/project/aitoearn-web/src/components/PublishDialog/index.tsx+++ b/project/aitoearn-web/src/components/PublishDialog/index.tsx@@ -65,6 +65,8 @@ export interface IPublishDialogProps {onPublishConfirmed?: (taskId?: string, publishRecordId?: string, workLink?: string) => void// 发布开始回调(pubClick 开头触发,用于提前设置外部 loading)onPublishStart?: () => void+ // 发布完成后是否自动关闭详情弹框(默认 false)+ autoCloseOnComplete?: boolean}// ============ 主组件 ============@@ -82,6 +84,7 @@ const PublishDialog = memo(taskIdForPublish,onPublishConfirmed,onPublishStart,+ autoCloseOnComplete,}: IPublishDialogProps,ref: ForwardedRef<IPublishDialogRef>,) => {@@ -353,11 +356,10 @@ const PublishDialog = memo(// PC 不支持平台点击const handlePcNotSupportedClick = useCallback(- (platformName: string) => {- modalState.setCurrentPlatform(platformName)- modalState.setDownloadModalVisible(true)+ (_platformName: string) => {+ // DownloadAppModal has been removed; no-op for now},- [modalState],+ [],)// Facebook 授权成功@@ -412,9 +414,6 @@ const PublishDialog = memo(</Modal><PublishModals- downloadModalVisible={modalState.downloadModalVisible}- setDownloadModalVisible={modalState.setDownloadModalVisible}- currentPlatform={modalState.currentPlatform}showFacebookPagesModal={modalState.showFacebookPagesModal}setShowFacebookPagesModal={modalState.setShowFacebookPagesModal}onFacebookPagesSuccess={handleFacebookPagesSuccess}@@ -424,6 +423,7 @@ const PublishDialog = memo(publishDetailVisible={modalState.publishDetailVisible}onPublishDetailClose={closePublishDetailModal}currentPublishTaskId={modalState.currentPublishTaskId}+ autoCloseOnComplete={autoCloseOnComplete}/></>)@@ -470,9 +470,6 @@ const PublishDialog = memo(</Modal><PublishModals- downloadModalVisible={modalState.downloadModalVisible}- setDownloadModalVisible={modalState.setDownloadModalVisible}- currentPlatform={modalState.currentPlatform}showFacebookPagesModal={modalState.showFacebookPagesModal}setShowFacebookPagesModal={modalState.setShowFacebookPagesModal}onFacebookPagesSuccess={handleFacebookPagesSuccess}diff --git a/project/aitoearn-web/src/components/PublishDialog/publishDialogTransition.css b/project/aitoearn-web/src/components/PublishDialog/publishDialogTransition.cssindex 4f960b83..0877a035 100644--- a/project/aitoearn-web/src/components/PublishDialog/publishDialogTransition.css+++ b/project/aitoearn-web/src/components/PublishDialog/publishDialogTransition.css@@ -11,7 +11,7 @@/* 右侧面板进入动画 - 激活状态 */.right-enter-active {width: 380px;- transition: all 300ms;+ transition: width 300ms;}/* 右侧面板退出动画 - 初始状态 */@@ -22,7 +22,7 @@/* 右侧面板退出动画 - 激活状态 */.right-exit-active {width: 0;- transition: all 300ms;+ transition: width 300ms;}/* 左侧面板进入动画 - 初始状态 */@@ -33,7 +33,7 @@/* 左侧面板进入动画 - 激活状态 */.left-enter-active {width: 380px;- transition: all 300ms;+ transition: width 300ms;}/* 左侧面板退出动画 - 初始状态 */@@ -44,5 +44,5 @@/* 左侧面板退出动画 - 激活状态 */.left-exit-active {width: 0;- transition: all 300ms;+ transition: width 300ms;}diff --git a/project/aitoearn-web/src/components/PublishDialog/usePublishDialog.ts b/project/aitoearn-web/src/components/PublishDialog/usePublishDialog.tsindex 8fe91ee6..79f2ef4b 100644--- a/project/aitoearn-web/src/components/PublishDialog/usePublishDialog.ts+++ b/project/aitoearn-web/src/components/PublishDialog/usePublishDialog.ts@@ -4,7 +4,7 @@ import type { IPubParams, PubItem } from '@/components/PublishDialog/publishDialimport lodash from 'lodash'import { create } from 'zustand'import { combine } from 'zustand/middleware'-import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { AccountPlatInfoMap, isPlatformAvailable } from '@/app/config/platConfig'import { PubType } from '@/app/config/publishConfig'import { usePublishDialogStorageStore } from '@/components/PublishDialog/usePublishDialogStorageStore'@@ -140,10 +140,10 @@ export const usePublishDialog = create(})if (defaultAccountIds && defaultAccountIds.length > 0) {- // 过滤掉离线账号(status === 0)+ // 过滤掉离线账号(status === 0)和区域不可用的平台const validIds = defaultAccountIds.filter((id) => {const acc = account.find(a => a.id === id)- return acc && acc.status !== 0+ return acc && acc.status !== 0 && isPlatformAvailable(acc.type)})const chosen = pubList.filter(p => validIds.includes(p.account.id))diff --git a/project/aitoearn-web/src/components/README.md b/project/aitoearn-web/src/components/README.mdindex e5b66808..d457a889 100644--- a/project/aitoearn-web/src/components/README.md+++ b/project/aitoearn-web/src/components/README.md@@ -30,6 +30,7 @@| `form.tsx` | 表单组件(基于 react-hook-form,提供 FormField/FormItem/FormLabel/FormControl/FormMessage) || `star-rating.tsx` | 星星评分组件(悬停预览、点击选择) || `sonner.tsx` | Toast 通知(配合 `@/lib/toast` 使用) |+| `number-input.tsx` | 数字输入框(基于 react-number-format,替代 type="number") |> **Modal** 使用:`<Modal open onClose title="标题" footer={...}>`,命令式确认用 `@/lib/confirm`。新代码禁止使用 antd Modal。@@ -97,18 +98,19 @@## 独立组件-| 组件 | 说明 |-| ----------------------- | ------------------------------------------------------------------ |-| `AvatarPlat` | 带平台标识的头像 |-| `AvatarCropModal` | 头像裁剪弹窗(基于 cropperjs,输出 400x400 PNG) |-| `WalletAccountSelect` | 钱包账户选择器(分页加载) |-| `SignInCalendar` | 签到日历 |-| `ScrollButtonContainer` | 左右滚动按钮容器 |-| `ChooseAccountModule` | 社交账号选择模块 |-| `GetCode` | 获取验证码组件 |-| `UserLogsModal` | 用户 AI 使用日志弹窗(分页) |-| `VideoHistoryModal` | 视频生成历史弹窗(分页、播放、下载) |-| `InviteCodeHandler` | 邀请码处理(纯逻辑组件,已集成到 Providers,自动处理推广链接绑定) |+| 组件 | 说明 |+| ----------------------- | -------------------------------------------------------------------------------------------------- |+| `AvatarPlat` | 带平台标识的头像 |+| `AvatarCropModal` | 头像裁剪弹窗(基于 cropperjs,输出 400x400 PNG) |+| `WalletAccountSelect` | 钱包账户选择器(分页加载) |+| `SignInCalendar` | 签到日历 |+| `ScrollButtonContainer` | 左右滚动按钮容器 |+| `ChooseAccountModule` | 社交账号选择模块 |+| `GetCode` | 获取验证码组件 |+| `UserLogsModal` | 用户 AI 使用日志弹窗(分页) |+| `VideoHistoryModal` | 视频生成历史弹窗(分页、播放、下载) |+| `InviteCodeHandler` | 邀请码处理(纯逻辑组件,已集成到 Providers,自动处理推广链接绑定) |+| `RewardDisplay` | 任务奖励金额展示,根据定价类型(基础/CPM/CPE)智能切换主显金额,支持 sidebar/card/compact 三种尺寸 |### 关键组件说明diff --git a/project/aitoearn-web/src/components/SettingsModal/index.tsx b/project/aitoearn-web/src/components/SettingsModal/index.tsxindex f9a02dd5..ad838b3e 100644--- a/project/aitoearn-web/src/components/SettingsModal/index.tsx+++ b/project/aitoearn-web/src/components/SettingsModal/index.tsx@@ -1,6 +1,6 @@/*** SettingsModal - 设置弹框组件- * 包含个人资料、通用设置等功能+ * 包含个人资料、Agent、通用设置等功能* 采用可扩展的 Tab 配置结构* 支持移动端响应式布局*/@@ -16,6 +16,7 @@ import logo from '@/assets/images/logo.png'import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'import { cn } from '@/lib/utils'import { useUserStore } from '@/store/user'+import { useSettingsModalStore } from './store'import {GeneralTab,ProfileTab,@@ -50,7 +51,8 @@ export interface SettingsModalProps {*/export function SettingsModal({ open, onClose, defaultTab }: SettingsModalProps) {// 预加载所有子组件需要的 namespace,避免切换 tab 时闪烁- const { t } = useTransClient(['settings', 'profile'])+ const { t } = useTransClient(['settings', 'profile', 'wallet'])+ const settingsSubTab = useSettingsModalStore(state => state.settingsSubTab)const token = useUserStore(state => state.token)const isLoggedIn = !!tokenconst [activeTab, setActiveTab] = useState<SettingsTab>(isLoggedIn ? 'profile' : 'general')@@ -119,7 +121,7 @@ export function SettingsModal({ open, onClose, defaultTab }: SettingsModalProps){ key: 'general', icon: <Globe className="h-4 w-4" />, label: t('tabs.general') },]- // 根据登录状态过滤 Tab+ // 根据登录状态和 placeId 过滤 Tabconst visibleTabs = tabConfigs.filter((tab) => {if (tab.requireAuth && !isLoggedIn)return falsediff --git a/project/aitoearn-web/src/components/SettingsModal/store.ts b/project/aitoearn-web/src/components/SettingsModal/store.tsindex 081628b4..b0734323 100644--- a/project/aitoearn-web/src/components/SettingsModal/store.ts+++ b/project/aitoearn-web/src/components/SettingsModal/store.ts@@ -1,13 +1,16 @@-import type { SettingsTab } from './index'import { create } from 'zustand'+type SettingsTab = 'profile' | 'general'+interface SettingsModalState {/** 设置弹框是否可见 */settingsVisible: boolean/** 设置弹框默认 Tab */settingsDefaultTab?: SettingsTab- /** 打开设置弹框,并可指定默认 Tab */- openSettings: (defaultTab?: SettingsTab) => void+ /** 设置弹框子 Tab(如 IncomeTab 内部的 balance / withdraw) */+ settingsSubTab?: string+ /** 打开设置弹框,并可指定默认 Tab 和选项 */+ openSettings: (defaultTab?: SettingsTab, options?: { subTab?: string }) => void/** 关闭设置弹框并重置默认 Tab */closeSettings: () => void}@@ -15,14 +18,17 @@ interface SettingsModalState {export const useSettingsModalStore = create<SettingsModalState>(set => ({settingsVisible: false,settingsDefaultTab: undefined,- openSettings: (defaultTab?: SettingsTab) =>+ settingsSubTab: undefined,+ openSettings: (defaultTab?: SettingsTab, options?: { subTab?: string }) =>set({settingsVisible: true,settingsDefaultTab: defaultTab,+ settingsSubTab: options?.subTab,}),closeSettings: () =>set({settingsVisible: false,settingsDefaultTab: undefined,+ settingsSubTab: undefined,}),}))diff --git a/project/aitoearn-web/src/components/Share/generateShareImages.ts b/project/aitoearn-web/src/components/Share/generateShareImages.tsindex 372add2f..e4d709c0 100644--- a/project/aitoearn-web/src/components/Share/generateShareImages.ts+++ b/project/aitoearn-web/src/components/Share/generateShareImages.ts@@ -270,8 +270,6 @@ async function generateImageFromAllMessages(// 等待组件渲染完成setTimeout(async () => {- // 替换媒体URL- replaceMediaUrlsWithProxy(container)// 等待视频首帧await ensureVideoThumbnails(container)// 强制设置所有元素的样式(修复透明度问题)@@ -522,31 +520,6 @@ function waitForImagesToLoad(container: HTMLElement, timeoutMs = 15000): Promise})}-/**- * 替换媒体 URL 为代理地址- */-function replaceMediaUrlsWithProxy(container: HTMLElement): void {- const awsUrl = process.env.NEXT_PUBLIC_S3_URL- const proxyUrl = process.env.NEXT_PUBLIC_S3_PROXY- if (!awsUrl || !proxyUrl)- return-- container.querySelectorAll('img').forEach((img) => {- if (img.src?.startsWith(awsUrl)) {- img.src = proxyUrl + img.src.substring(awsUrl.length)- }- })-- container.querySelectorAll('video').forEach((video) => {- if (video.src?.startsWith(awsUrl)) {- video.src = proxyUrl + video.src.substring(awsUrl.length)- }- if (video.poster?.startsWith(awsUrl)) {- video.poster = proxyUrl + video.poster.substring(awsUrl.length)- }- })-}-/*** 确保视频显示首帧*/diff --git a/project/aitoearn-web/src/components/common/LowBalanceAlert/LowBalanceAlertProvider.tsx b/project/aitoearn-web/src/components/common/LowBalanceAlert/LowBalanceAlertProvider.tsxnew file mode 100644index 00000000..adb33efd--- /dev/null+++ b/project/aitoearn-web/src/components/common/LowBalanceAlert/LowBalanceAlertProvider.tsx@@ -0,0 +1,173 @@+/**+ * LowBalanceAlertProvider - 余额不足提示逻辑处理组件+ *+ * 功能描述: 数据就绪后立即检查,在满足条件时弹出余额不足提示+ *+ * 触发条件:+ * 1. 用户已登录+ * 2. 余额低于阈值(0.5美元 = 50美分)+ * 3. 本次会话未点击"取消"+ * 4. 未永久禁用提示+ * 5. 不在公开页面(/pricing、/auth 等)+ */++'use client'++import { usePathname } from 'next/navigation'+import { useEffect, useRef } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useAccountStore } from '@/store'+import { useSystemStore } from '@/store/system'+import { useUserStore } from '@/store/user'+import { isPublicPage } from '@/utils/route'+import { LowBalanceAlert } from './index'++// 余额阈值:0.5美元 = 50美分+const BALANCE_THRESHOLD = -1++// sessionStorage key+const SESSION_STORAGE_KEY = 'lowBalanceAlertDismissed'++export function LowBalanceAlertProvider() {+ const pathname = usePathname()++ // 本次组件生命周期内是否已弹出过,避免重复弹出+ const hasShownRef = useRef(false)++ // 从 userStore 获取状态+ const { token, creditsBalance, userHasHydrated, lang, creditsInitialized } = useUserStore(+ useShallow(state => ({+ token: state.token,+ creditsBalance: state.creditsBalance,+ userHasHydrated: state._hasHydrated,+ lang: state.lang,+ creditsInitialized: state.creditsInitialized,+ })),+ )+ const { setLowBalanceAlertOpen, lowBalanceAlertOpen } = useAccountStore(+ useShallow(state => ({+ setLowBalanceAlertOpen: state.setLowBalanceAlertOpen,+ lowBalanceAlertOpen: state.lowBalanceAlertOpen,+ })),+ )++ // 从 systemStore 获取状态+ const { disableLowBalanceAlert, systemHasHydrated, setDisableLowBalanceAlert } = useSystemStore(+ useShallow(state => ({+ disableLowBalanceAlert: state.disableLowBalanceAlert,+ systemHasHydrated: state._hasHydrated,+ setDisableLowBalanceAlert: state.setDisableLowBalanceAlert,+ })),+ )++ /**+ * 检查 sessionStorage 是否已禁用本次会话提示+ */+ const isSessionDismissed = (): boolean => {+ if (typeof window === 'undefined')+ return false+ return sessionStorage.getItem(SESSION_STORAGE_KEY) === 'true'+ }++ /**+ * 设置 sessionStorage 禁用本次会话提示+ */+ const setSessionDismissed = () => {+ if (typeof window !== 'undefined') {+ sessionStorage.setItem(SESSION_STORAGE_KEY, 'true')+ }+ }++ /**+ * 检查是否应该显示余额不足提示+ */+ const checkShouldShowAlert = (): boolean => {+ // 未登录不提示+ if (!token) {+ return false+ }++ // 余额充足不提示+ if (creditsBalance >= BALANCE_THRESHOLD) {+ return false+ }++ // 公开页面不提示+ if (isPublicPage(pathname)) {+ return false+ }++ // 聊天页面不自动弹出(聊天页通过 ActionCard 处理余额不足)+ if (pathname.includes('/chat/')) {+ return false+ }++ // 本次会话已点击取消,不再提示+ if (isSessionDismissed()) {+ return false+ }++ // 永久禁用,不提示+ if (disableLowBalanceAlert) {+ return false+ }++ return true+ }++ // 数据就绪后立即检查余额+ useEffect(() => {+ // 等待两个 store 的持久化数据都加载完成+ if (!userHasHydrated || !systemHasHydrated) {+ return+ }++ // 等待余额数据加载完成+ if (!creditsInitialized) {+ return+ }++ // 已弹出过,不再重复弹出+ if (hasShownRef.current) {+ return+ }++ // 检查是否应该显示提示+ const shouldShowAlert = checkShouldShowAlert()++ if (shouldShowAlert) {+ hasShownRef.current = true+ // 延迟一小段时间再弹出,确保页面渲染完成+ setTimeout(() => {+ setLowBalanceAlertOpen(true)+ }, 500)+ }+ }, [pathname, userHasHydrated, systemHasHydrated, token, creditsBalance, disableLowBalanceAlert, creditsInitialized])++ /**+ * 处理关闭弹窗(点击取消或关闭按钮)+ */+ const handleClose = () => {+ setLowBalanceAlertOpen(false)+ // 设置本次会话不再提示+ setSessionDismissed()+ }++ /**+ * 处理"不再提示"+ */+ const handleNeverRemind = () => {+ setDisableLowBalanceAlert(true)+ }++ return (+ <LowBalanceAlert+ open={lowBalanceAlertOpen}+ onClose={handleClose}+ onNeverRemind={handleNeverRemind}+ lng={lang || 'en'}+ />+ )+}++export default LowBalanceAlertProviderdiff --git a/project/aitoearn-web/src/components/common/LowBalanceAlert/index.tsx b/project/aitoearn-web/src/components/common/LowBalanceAlert/index.tsxnew file mode 100644index 00000000..f27241b2--- /dev/null+++ b/project/aitoearn-web/src/components/common/LowBalanceAlert/index.tsx@@ -0,0 +1,67 @@+/**+ * LowBalanceAlert - 余额不足提示弹窗+ *+ * 功能描述: 当用户余额低于阈值时显示,提供不再提示和取消选项+ */++'use client'++import { AlertTriangle } from 'lucide-react'+import { useTransClient } from '@/app/i18n/client'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'++export interface LowBalanceAlertProps {+ /** 弹窗是否打开 */+ open: boolean+ /** 关闭弹窗回调(点击取消或关闭按钮) */+ onClose: () => void+ /** 点击"不再提示"回调 */+ onNeverRemind: () => void+ /** 当前语言 */+ lng: string+}++export function LowBalanceAlert({ open, onClose, onNeverRemind }: LowBalanceAlertProps) {+ const { t } = useTransClient('common')++ // 处理"不再提示"+ const handleNeverRemind = () => {+ onNeverRemind()+ onClose()+ }++ return (+ <Dialog open={open} onOpenChange={isOpen => !isOpen && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <AlertTriangle className="h-5 w-5 text-warning" />+ {t('lowBalanceAlert.title')}+ </DialogTitle>+ <DialogDescription>{t('lowBalanceAlert.content')}</DialogDescription>+ </DialogHeader>++ <DialogFooter className="flex-col sm:flex-row gap-2">+ {/* 不再提示按钮 - 放在最左边 */}+ <Button variant="ghost" onClick={handleNeverRemind} className="sm:mr-auto cursor-pointer">+ {t('lowBalanceAlert.neverRemind')}+ </Button>+ {/* 取消按钮 */}+ <Button variant="outline" onClick={onClose} className="cursor-pointer">+ {t('actions.cancel')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++export default LowBalanceAlertdiff --git a/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationItem.tsx b/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationItem.tsxindex 727e4fd5..25063c76 100644--- a/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationItem.tsx+++ b/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationItem.tsx@@ -59,6 +59,7 @@ const NOTIFICATION_TYPE_CONFIG: Record<string, {task_review_approved: { icon: CheckCircle, iconClass: 'text-success' },ai_review_skipped: { icon: AlertTriangle, iconClass: 'text-warning' },task_submitted: { icon: CheckCircle, iconClass: 'text-info' },+ interaction_ai_review_failed: { icon: XCircle, iconClass: 'text-destructive' },other: { icon: Info, iconClass: 'text-muted-foreground' },}diff --git a/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationList.tsx b/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationList.tsxindex 98fdbc10..17309e92 100644--- a/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationList.tsx+++ b/project/aitoearn-web/src/components/notification/NotificationPanel/NotificationList.tsx@@ -138,6 +138,13 @@ export default function NotificationList({ onClose }: NotificationListProps) {return}+ // 互动任务AI审核失败 → 已发布任务详情+ if (item.type === 'interaction_ai_review_failed' && item.relatedId) {+ onClose()+ router.push(`/my-tasks/published/${item.relatedId}`)+ return+ }+// Agent结果 → 聊天页if (item.type === 'agent_result' && item.relatedId) {onClose()@@ -145,7 +152,7 @@ export default function NotificationList({ onClose }: NotificationListProps) {return}- // 提现通知 → 设置-个人Tab+ // 提现通知 → 设置-个人资料Tabif (item.type === 'user_withdraw') {onClose()useSettingsModalStore.getState().openSettings('profile')diff --git a/project/aitoearn-web/src/components/ui/number-input.tsx b/project/aitoearn-web/src/components/ui/number-input.tsxnew file mode 100644index 00000000..3667f10c--- /dev/null+++ b/project/aitoearn-web/src/components/ui/number-input.tsx@@ -0,0 +1,45 @@+/**+ * NumberInput - 数字输入框+ * 基于 react-number-format,解决原生 type="number" 的浏览器行为不一致问题+ */+'use client'++import type { NumericFormatProps } from 'react-number-format'+import * as React from 'react'+import { NumericFormat } from 'react-number-format'+import { cn } from '@/lib/utils'++// 基础样式,与 src/components/ui/input.tsx 保持一致+const inputBaseClass+ = 'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm'++interface NumberInputProps+ extends Omit<NumericFormatProps, 'value' | 'onValueChange' | 'customInput' | 'isAllowed'> {+ value?: number | null+ onValueChange?: (value: number | undefined) => void+ /** 最小值,设置后输入框不允许清空或低于此值 */+ min?: number+ className?: string+}++const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(+ ({ className, value, onValueChange, min, ...props }, ref) => {+ return (+ <NumericFormat+ getInputRef={ref}+ className={cn(inputBaseClass, className)}+ value={value ?? ''}+ onValueChange={(values) => {+ onValueChange?.(values.floatValue)+ }}+ isAllowed={min !== undefined+ ? ({ floatValue }) => floatValue !== undefined && floatValue >= min+ : undefined}+ {...props}+ />+ )+ },+)+NumberInput.displayName = 'NumberInput'++export { NumberInput, type NumberInputProps }diff --git a/project/aitoearn-web/src/constant.ts b/project/aitoearn-web/src/constant.tsindex cc5b0266..e31ae309 100644--- a/project/aitoearn-web/src/constant.ts+++ b/project/aitoearn-web/src/constant.ts@@ -1,13 +1,7 @@// 代理地址export const ProxyUrls = ['/api/',- process.env.NEXT_PUBLIC_BILI_OSS_PROXY,- process.env.NEXT_PUBLIC_OSS_URL_PROXY,- process.env.NEXT_PUBLIC_S3_PROXY,]-// OSS URL-export const OSS_URL = process.env.NEXT_PUBLIC_OSS_URL!-// 联系方式export const CONTACT = '[email protected]'diff --git a/project/aitoearn-web/src/lib/README.md b/project/aitoearn-web/src/lib/README.mdindex 8f649079..4a119858 100644--- a/project/aitoearn-web/src/lib/README.md+++ b/project/aitoearn-web/src/lib/README.md@@ -11,8 +11,6 @@| `utils.ts` | 通用工具函数 || `vip.ts` | VIP 状态判断工具函数 || `i18n/languageConfig.ts` | 语言配置中心,统一管理语言相关配置 |-| `server-fetch.ts` | 服务端 fetch 封装(SSR/Metadata/Sitemap 用)|-| `server-api.ts` | 服务端 API 方法(任务列表/详情/Sitemap) |---@@ -432,53 +430,3 @@ export const LANGUAGE_METADATA: Record<string, LanguageMetadata> = {- ⚠️ **禁止硬编码语言判断**,统一使用此工具的函数- 添加新语言时,还需在 `src/app/i18n/settings.ts` 的 `languages` 数组中添加语言代码-------## server-fetch.ts - 服务端 fetch 封装--用于 Server Component / generateMetadata / sitemap 等 SSR 场景的轻量 fetch 封装。无客户端依赖(不使用 useUserStore、directTrans)。--### 导入方式--```typescript-import { serverFetch } from '@/lib/server-fetch'-```--### 特点--- 自动拼接完整 API URL(生产环境 `NEXT_PUBLIC_API_URL=/api` 是相对路径,SSR 中需要绝对路径)-- 支持 Next.js `fetch` + `next.revalidate` 实现 ISR 缓存-- 支持 `tags` 用于按需 revalidation-- 无 token、无客户端依赖--### 注意事项--- ⚠️ **仅用于无需鉴权的公开 API**-- 如需鉴权请求,请使用客户端 `src/utils/request.ts`-------## server-api.ts - 服务端 API 方法--基于 `server-fetch.ts` 封装的业务 API,对应客户端 `src/api/advertiser/task.ts`。--### 导入方式--```typescript-import { getTaskListSSR, getTaskInfoSSR, getAllTaskIdsForSitemap } from '@/lib/server-api'-```--### API--| 函数 | 说明 | 缓存时间 |-| --- | --- | --- |-| `getTaskListSSR(pageNo, pageSize, revalidate?)` | 获取任务列表 | 5 分钟 |-| `getTaskInfoSSR(id, revalidate?)` | 获取任务详情 | 10 分钟 |-| `getAllTaskIdsForSitemap()` | 获取所有任务 ID(用于 Sitemap) | 1 小时 |--### 使用场景--- `generateMetadata` 中获取任务数据生成动态 SEO 标签-- Server Component 中预取数据传给客户端组件-- Sitemap 路由中获取所有任务 IDdiff --git a/project/aitoearn-web/src/lib/server-fetch.ts b/project/aitoearn-web/src/lib/server-fetch.tsdeleted file mode 100644index 367ba8e1..00000000--- a/project/aitoearn-web/src/lib/server-fetch.ts+++ /dev/null@@ -1,78 +0,0 @@-/**- * server-fetch - 服务端 fetch 封装- * 用于 Server Component / generateMetadata / sitemap 等 SSR 场景- * 无客户端依赖(不使用 useUserStore、directTrans)- */--import { headers } from 'next/headers'--interface ServerFetchOptions {- revalidate?: number | false- tags?: string[]-}--interface ApiResponse<T> {- code: number | string- data: T- message: string-}--async function getApiBaseUrl() {- const apiUrl = process.env.NEXT_PUBLIC_API_URL || '/api'- if (apiUrl.startsWith('http')) {- return apiUrl- }- // 相对路径时,从请求 headers 中获取 host 拼接完整 URL- const h = await headers()- const host = h.get('host') || 'localhost:3000'- const proto = h.get('x-forwarded-proto') || 'http'- return `${proto}://${host}${apiUrl}`-}--/**- * 服务端 GET 请求- * 利用 Next.js fetch + next.revalidate 实现 ISR 缓存- */-export async function serverFetch<T>(- path: string,- params?: Record<string, string | number | undefined>,- options: ServerFetchOptions = {},-): Promise<ApiResponse<T> | null> {- try {- const baseUrl = await getApiBaseUrl()- const url = new URL(`${baseUrl}/${path}`)-- if (params) {- Object.entries(params).forEach(([key, value]) => {- if (value !== undefined) {- url.searchParams.set(key, String(value))- }- })- }-- const fetchOptions: RequestInit & { next?: { revalidate?: number | false, tags?: string[] } } = {- method: 'GET',- headers: {- 'Content-Type': 'application/json',- },- next: {},- }-- if (options.revalidate !== undefined) {- fetchOptions.next!.revalidate = options.revalidate- }- if (options.tags) {- fetchOptions.next!.tags = options.tags- }-- const res = await fetch(url.toString(), fetchOptions)- if (!res.ok)- return null-- const data: ApiResponse<T> = await res.json()- return data- }- catch {- return null- }-}diff --git a/project/aitoearn-web/src/middleware.ts b/project/aitoearn-web/src/middleware.tsindex 76cb101a..ef64122d 100644--- a/project/aitoearn-web/src/middleware.ts+++ b/project/aitoearn-web/src/middleware.ts@@ -8,7 +8,7 @@ acceptLanguage.languages(languages)export const config = {// matcher: '/:lng*'- matcher: ['/((?!api|auto-login|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'],+ matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'],}export function middleware(req: NextRequest) {diff --git a/project/aitoearn-web/src/store/README.md b/project/aitoearn-web/src/store/README.mdindex 4043f52a..1a9e9074 100644--- a/project/aitoearn-web/src/store/README.md+++ b/project/aitoearn-web/src/store/README.md@@ -39,7 +39,7 @@ src/store/| `account.ts` | `useAccountStore` | 社交账户管理、账户分组、余额不足弹框 | 否 || `user.ts` | `useUserStore` | 用户登录态、Credits 余额、语言、侧边栏 | 是 || `system.ts` | `useSystemStore` | 系统配置(余额提示、日历视图) | 是(IndexedDB) |-| `brandInfo.ts` | `useBrandInfoStore` | 品牌信息(品牌库、品牌图片) | 否 |+| `brandInfo.ts` | `useBrandInfoStore` | 品牌信息(按草稿箱独立,多实例缓存) | 否 || `publishDetailCache.ts` | `usePublishDetailCache` | 发布详情缓存(5 分钟过期) | 是(IndexedDB) || `taskSquare.ts` | `useTaskSquareStore` | 任务广场列表、分页、平台筛选、国家筛选 | 否 || `notification.ts` | `useNotificationStore` | 通知列表、未读数、无限滚动、乐观更新 | 否 |@@ -118,16 +118,21 @@ src/store/**主要状态:**-- `brandInfo` — 品牌库数据(`BrandLibraryVo`)-- `loading` / `updating` / `switching` — 各操作加载状态-- `initialized` — 是否已初始化+- `brandInfoMap` — `groupId → BrandLibraryVo | null` 品牌信息映射+- `loadingMap` / `updatingMap` / `switchingMap` — 各操作按 groupId 隔离的加载状态+- `initializedMap` — 按 groupId 隔离的初始化状态**主要方法:**-- `fetchBrandInfo()` — 获取品牌信息-- `updateBrandInfo()` — 更新品牌基本信息-- `addImage()` / `deleteImage()` — 品牌图片增删-- `switchBrandLib()` — 切换关联餐厅+- `fetchBrandInfo(groupId)` — 获取草稿箱关联的品牌信息+- `updateBrandInfo(groupId, data)` — 更新品牌基本信息+- `addImage(groupId, url)` / `deleteImage(groupId, imageId)` — 品牌图片增删+- `linkBrandLib(groupId, placeId)` — 关联品牌到草稿箱+- `switchBrandLib(groupId, placeId)` — 切换关联品牌++**便捷 Hook:**++- `useBrandInfoByGroup(groupId)` — 获取指定草稿箱的品牌信息及状态---diff --git a/project/aitoearn-web/src/store/account.ts b/project/aitoearn-web/src/store/account.tsindex e5fbc137..0367b6c9 100644--- a/project/aitoearn-web/src/store/account.ts+++ b/project/aitoearn-web/src/store/account.ts@@ -22,6 +22,8 @@ export interface IAccountStore {accountActive?: SocialAccount// 当前选择的空间IDactiveSpaceId?: string+ // 余额不足弹框状态+ lowBalanceAlertOpen: boolean}const store: IAccountStore = {@@ -35,6 +37,7 @@ const store: IAccountStore = {accountLoading: false,accountActive: undefined,activeSpaceId: undefined,+ lowBalanceAlertOpen: false,}function getStore() {@@ -49,6 +52,12 @@ export const useAccountStore = create(},(set, get, storeApi) => {const methods = {+ setLowBalanceAlertOpen(lowBalanceAlertOpen: boolean) {+ set({+ lowBalanceAlertOpen,+ })+ },+clear() {set({...getStore(),diff --git a/project/aitoearn-web/src/store/agent/agent.methods.ts b/project/aitoearn-web/src/store/agent/agent.methods.tsindex 87838ec7..3d68ebbd 100644--- a/project/aitoearn-web/src/store/agent/agent.methods.ts+++ b/project/aitoearn-web/src/store/agent/agent.methods.ts@@ -273,6 +273,7 @@ export function createStoreMethods(ctx: IMethodsContext) {},onComplete: () => {console.log('[AgentStore] TaskInstance SSE Complete')+ useUserStore.getState().fetchCreditsBalance()},}@@ -301,6 +302,7 @@ export function createStoreMethods(ctx: IMethodsContext) {instance.setIsGenerating(false)instance.clearWorkflowSteps()refs.sseAbort.value = null+ useUserStore.getState().fetchCreditsBalance()},)@@ -446,6 +448,7 @@ export function createStoreMethods(ctx: IMethodsContext) {},onComplete: () => {console.log('[AgentStore] TaskInstance SSE Complete')+ useUserStore.getState().fetchCreditsBalance()},}@@ -470,6 +473,7 @@ export function createStoreMethods(ctx: IMethodsContext) {instance!.setIsGenerating(false)instance!.clearWorkflowSteps()refs.sseAbort.value = null+ useUserStore.getState().fetchCreditsBalance()},)diff --git a/project/aitoearn-web/src/store/agent/handlers/action.handlers.ts b/project/aitoearn-web/src/store/agent/handlers/action.handlers.tsindex d0055cfd..d6222111 100644--- a/project/aitoearn-web/src/store/agent/handlers/action.handlers.ts+++ b/project/aitoearn-web/src/store/agent/handlers/action.handlers.ts@@ -372,7 +372,7 @@ const saveDraftHandler: IActionHandler = {const hasVideo = medias.some((m: IMediaItem) => m.type === 'VIDEO')const targetGroupType = hasVideo ? PubType.VIDEO : PubType.ImageTextconst defaultGroup = groups.find((g: any) => g.type === targetGroupType) || groups[0]- const finalGroupId = defaultGroup._id || defaultGroup.id+ const finalGroupId = defaultGroup.idif (!finalGroupId) {toast.warning(t('aiGeneration.noDraftGroup' as any))diff --git a/project/aitoearn-web/src/store/plugin/constants.ts b/project/aitoearn-web/src/store/plugin/constants.tsindex 370d59e6..df51d79f 100644--- a/project/aitoearn-web/src/store/plugin/constants.ts+++ b/project/aitoearn-web/src/store/plugin/constants.ts@@ -13,7 +13,6 @@ export const DEFAULT_POLLING_INTERVAL = 2000export const PLUGIN_DOWNLOAD_LINKS = {chrome:'https://chromewebstore.google.com/detail/aitoearn-extension/hnmocdhmnfgcjnedmdgfefcobideaeja',- github: 'https://github.com/yikart/AiToEarn/releases/download/v1.4.0/aitoearn-extension.crx',china: 'https://ai-to-earn.oss-cn-beijing.aliyuncs.com/comment/aitoearn-extension.crx',} as constdiff --git a/project/aitoearn-web/src/store/system.ts b/project/aitoearn-web/src/store/system.tsindex 146d2baa..bf5c6677 100644--- a/project/aitoearn-web/src/store/system.ts+++ b/project/aitoearn-web/src/store/system.ts@@ -5,10 +5,16 @@ import { createPersistStore } from '@/utils/createPersistStore'export type CalendarViewType = 'month' | 'week'export interface ISystemStore {+ /** 是否永久禁用余额不足提示 */+ disableLowBalanceAlert: boolean/** 日历视图类型(PC端) */calendarViewType: CalendarViewType/** 是否已关闭 Seedance 公告横幅 */dismissSeedanceBanner: boolean+ /** 我的任务当前选中的 Tab */+ myTasksTab: 'accepted' | 'published'+ /** 创建任务 - 描述区域是否展开 */+ createTaskDescExpanded: boolean/** GitHub Stars 缓存值 */githubStars: string/** GitHub Stars 缓存时间戳 */@@ -16,8 +22,11 @@ export interface ISystemStore {}const state: ISystemStore = {+ disableLowBalanceAlert: false,calendarViewType: 'week',dismissSeedanceBanner: false,+ myTasksTab: 'accepted',+ createTaskDescExpanded: false,githubStars: '11.5k',githubStarsUpdatedAt: 0,}@@ -32,6 +41,12 @@ export const useSystemStore = createPersistStore(},(set, _get) => {const methods = {+ /**+ * 设置是否永久禁用余额不足提示+ */+ setDisableLowBalanceAlert(disabled: boolean) {+ set({ disableLowBalanceAlert: disabled })+ },/*** 设置日历视图类型*/@@ -44,6 +59,18 @@ export const useSystemStore = createPersistStore(setDismissSeedanceBanner(dismissed: boolean) {set({ dismissSeedanceBanner: dismissed })},+ /**+ * 设置我的任务当前选中的 Tab+ */+ setMyTasksTab(tab: 'accepted' | 'published') {+ set({ myTasksTab: tab })+ },+ /**+ * 设置创建任务 - 描述区域是否展开+ */+ setCreateTaskDescExpanded(expanded: boolean) {+ set({ createTaskDescExpanded: expanded })+ },setGitHubStars(stars: string) {set({ githubStars: stars, githubStarsUpdatedAt: Date.now() })},@@ -53,7 +80,7 @@ export const useSystemStore = createPersistStore(},{name: 'System',- version: 5,+ version: 4,migrate(persistedState: any, version: number) {// v0→v1: 无需处理(已废弃的 batchAspectRatio 迁移)// v1→v2: 无需处理(已废弃的 batchImageSize 迁移)@@ -72,12 +99,6 @@ export const useSystemStore = createPersistStore(if (version < 4) {persistedState.dismissSeedanceBanner = false}- // v4→v5: 移除任务系统和支付系统相关字段- if (version < 5) {- delete persistedState.disableLowBalanceAlert- delete persistedState.myTasksTab- delete persistedState.createTaskDescExpanded- }return persistedState},},diff --git a/project/aitoearn-web/src/store/user.ts b/project/aitoearn-web/src/store/user.tsindex 378bdaa9..9d4cd9df 100644--- a/project/aitoearn-web/src/store/user.ts+++ b/project/aitoearn-web/src/store/user.ts@@ -1,6 +1,7 @@import i18next from 'i18next'import lodash from 'lodash'import { getUserInfoApi } from '@/api/apiReq'+import { getCreditsBalanceApi } from '@/api/credits'import { createPersistStore } from '@/utils/createPersistStore'import { useAccountStore } from '.'@@ -37,12 +38,20 @@ export interface IUserStore {isAddAccountPorxy: boolean// 语言lang: string+ // Credits 余额(美分)+ creditsBalance: number+ // Credits 余额加载状态+ creditsLoading: boolean+ // Credits 余额是否已初始化(用于判断是否可以依赖余额数据)+ creditsInitialized: boolean// 侧边栏收起状态sidebarCollapsed: boolean+ // 默认品牌推广计划 ID(缓存)+ defaultPlanId?: string// 是否曾经登录过(用于判断是否显示登录页或重定向到注册页)hasEverLoggedIn: boolean- // appInit 是否已完成(用于路由守卫等待自动登录)- _appInitialized: boolean+ // ISO alpha-2 国家代码(如 "SG"、"US")+ countryCode?: string}const state: IUserStore = {@@ -50,9 +59,13 @@ const state: IUserStore = {userInfo: {},isAddAccountPorxy: false,lang: i18next.language || 'en',+ creditsBalance: 0,+ creditsLoading: false,+ creditsInitialized: false,sidebarCollapsed: false,+ defaultPlanId: undefined,hasEverLoggedIn: false,- _appInitialized: false,+ countryCode: undefined,}function getState(): IUserStore {@@ -75,23 +88,19 @@ export const useUserStore = createPersistStore(set({ isAddAccountPorxy })},setToken: (token: string) => {- set({ token, hasEverLoggedIn: true })+ // 登录时重置余额初始化状态,确保重新获取+ set({ token, hasEverLoggedIn: true, creditsInitialized: false })+ // 立即获取余额+ methods.fetchCreditsBalance()},setUserInfo: (userInfo: UserInfo) => {set({ userInfo })},- async appInit() {- // 自动登录:从 init 服务生成的 token 文件中获取- if (!_get().token) {- try {- const res = await fetch('/auto-login')- const data = await res.json()- if (data.token) methods.setToken(data.token)- } catch {}- }- set({ _appInitialized: true })+ appInit() {+ set({ creditsInitialized: false }) // 防御性重置,确保等 API 返回后再判定余额methods.getUserInfo()+ methods.fetchCreditsBalance()useAccountStore.getState().accountInit()},@@ -105,11 +114,41 @@ export const useUserStore = createPersistStore(}},+ // 获取 Credits 余额+ async fetchCreditsBalance() {+ const token = _get().token+ // 未登录时不调用 API,也不设置 creditsInitialized+ if (!token) {+ return+ }++ set({ creditsLoading: true })+ try {+ const res = await getCreditsBalanceApi()+ if (res?.data) {+ set({ creditsBalance: res.data.balance, creditsInitialized: true })+ }+ }+ finally {+ set({ creditsLoading: false })+ }+ },++ // 设置 Credits 余额+ setCreditsBalance(balance: number) {+ set({ creditsBalance: balance })+ },+// 设置侧边栏收起状态setSidebarCollapsed(collapsed: boolean) {set({ sidebarCollapsed: collapsed })},+ // 设置默认品牌推广计划 ID+ setDefaultPlanId(planId: string | undefined) {+ set({ defaultPlanId: planId })+ },+// 清除登录状态(保留 hasEverLoggedIn 标记)clearLoginStatus: () => {const hasEverLoggedIn = _get().hasEverLoggedIn@@ -128,6 +167,12 @@ export const useUserStore = createPersistStore(},{name: 'User',+ partialize: (state) => {+ // creditsInitialized 和 creditsLoading 为运行时状态,不持久化+ // 避免页面刷新后水合恢复旧值导致 LowBalanceAlert 误弹+ const { creditsInitialized, creditsLoading, ...rest } = state+ return rest as typeof state+ },},'localStorage',)diff --git a/project/aitoearn-web/src/utils/FetchService/FetchService.ts b/project/aitoearn-web/src/utils/FetchService/FetchService.tsindex e78e8a86..afe8d63d 100644--- a/project/aitoearn-web/src/utils/FetchService/FetchService.ts+++ b/project/aitoearn-web/src/utils/FetchService/FetchService.ts@@ -33,10 +33,15 @@ class FetchService<T = Response> {requestParams = newRequestParams}+ let baseURL = this.baseURL+ if (requestParams.url === 'assets/uploadSign' && process.env.NEXT_PUBLIC_OSS_TEMP_URL) {+ baseURL = process.env.NEXT_PUBLIC_OSS_TEMP_URL+ }+// body 参数处理const fetchURL = requestParams.url.startsWith('http')? requestParams.url- : this.baseURL + requestParams.url+ : baseURL + requestParams.urlif (!requestParams.body && requestParams.data) {// 检查是否为FormDataif (requestParams.data instanceof FormData) {diff --git a/project/aitoearn-web/src/utils/README.md b/project/aitoearn-web/src/utils/README.mdindex e2cd4f7b..c0af16d1 100644--- a/project/aitoearn-web/src/utils/README.md+++ b/project/aitoearn-web/src/utils/README.md@@ -20,11 +20,11 @@| `storageIndexedDb.ts` | IndexedDB 封装(SSR 安全,自动降级) || `createPersistStore.ts` | Zustand 持久化 Store 工厂函数 || `appLaunch.ts` | App 唤起工具(多策略:iframe + href + 超时降级) |-| `regionRedirect.ts` | 平台区域限制跳转确认工具 |-| `ipLocation.ts` | IP 地理位置获取(JSONP + ping0.cc) || `geoData.ts` | 地理数据工具(国家/省/市三级联动数据源) || `download.ts` | 带进度回调的文件下载工具(fetchWithProgress) || `FetchService/` | 底层 Fetch 请求封装类 |+| `detectPlatform.ts` | URL 自动识别社交平台(`detectPlatformFromUrl`) |+| `settlement.ts` | CPM/CPE 预估计算(互动分、预估金额) |---@@ -194,33 +194,22 @@ export async function generateMetadata({### 导入方式```typescript-import { getOssUrl, getOssProxyPath } from '@/utils/oss'+import { getOssUrl } from '@/utils/oss'```### API-| 函数 | 说明 | 参数 | 返回值 |-| -------------------------- | ---------------------------------------------------- | ----------------- | -------- |-| `getOssUrl(path?)` | 将 OSS 路径拼接为完整 URL(已为完整 URL 则直接返回) | `path?: string` | `string` |-| `getOssProxyPath(ossUrl?)` | 将 OSS URL 转为同域代理 URL(解决 Canvas 跨域问题) | `ossUrl?: string` | `string` |+| 函数 | 说明 | 参数 | 返回值 |+| ------------------ | ---------------------------------------------------- | --------------- | -------- |+| `getOssUrl(path?)` | 将 OSS 路径拼接为完整 URL(已为完整 URL 则直接返回) | `path?: string` | `string` |### 使用示例```typescript-// 拼接完整 URL-getOssUrl('images/avatar.png')-// => 'https://proxy.example.com/images/avatar.png'--// 转为代理路径(解决跨域)-getOssProxyPath('https://oss.example.com/image.png')-// => 'https://proxy.example.com/image.png'+getOssUrl('https://example.com/images/avatar.png')+// => 'https://example.com/images/avatar.png'```-### 注意事项--- ⚠️ 所有 OSS 资源引用必须使用 `getOssUrl`,不要硬编码 OSS 域名-- Canvas 操作中使用 `getOssProxyPath` 避免跨域污染----## auth.ts - 登录跳转@@ -652,66 +641,6 @@ getCountryDisplayName('US', 'en') // => 'United States'----## ipLocation.ts - IP 地理位置获取--### 导入方式--```typescript-import {- getIpLocation,- extractCountry,- formatLocationInfo,- getCountryCode,- getCountryCodeFromChineseName,-} from '@/utils/ipLocation'-import type { IpLocationInfo } from '@/utils/ipLocation'-```--### API--| 函数 | 说明 | 参数 | 返回值 |-| ------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------- | ------------------------------ |-| `getIpLocation()` | JSONP 方式获取 IP 地理位置(10 秒超时) | - | `Promise<IpLocationInfo>` |-| `extractCountry(location)` | 从位置字符串提取国家 | `location: string` | `string` |-| `formatLocationInfo(info)` | 格式化位置信息为 `国家 \| IP` | `info: IpLocationInfo` | `string` |-| `getCountryCode(ipLocationInfo?)` | 从免费 IP API 获取 ISO 国家代码(顺序尝试多个 API,每个 5 秒超时),全部失败时用中文名映射兜底 | `ipLocationInfo?: IpLocationInfo` | `Promise<string \| undefined>` |-| `getCountryCodeFromChineseName(name)` | 通过中文国家名反查 ISO alpha-2 国家代码 | `name: string` | `string \| undefined` |--### IpLocationInfo 接口--| 字段 | 类型 | 说明 |-| ---------- | -------- | ---------------------------------- |-| `ip` | `string` | IP 地址 |-| `location` | `string` | 位置信息(格式:"国家 省份 城市") |-| `asn` | `string` | ASN 编号 |-| `org` | `string` | 运营商/组织 |--### 使用示例--```typescript-const info = await getIpLocation()-// => { ip: '1.2.3.4', location: '中国 广东 深圳', asn: 'AS12345', org: 'China Telecom' }--extractCountry('中国 广东 深圳') // => '中国'-formatLocationInfo(info) // => '中国 | 1.2.3.4'--// 获取国家代码(顺序尝试: country.is → ipwho.is → freeipapi.com → 中文名映射)-const code = await getCountryCode() // => 'SG' | 'US' | undefined--// 从中文名反查国家代码-getCountryCodeFromChineseName('新加坡') // => 'SG'-getCountryCodeFromChineseName('美国') // => 'US'-```--### 注意事项--- 仅在浏览器端可用(依赖 `document` 和 `window`)-- 通常由 `useUserStore.fetchIpLocation()` 调用,自带 24 小时缓存,无需手动管理-- 调用 `https://ping0.cc/geo/jsonp/` 第三方服务-- 国家代码获取优先级:`country.is` → `ipwho.is` → `freeipapi.com` → `countries_alpha2.json` 中文名映射兜底------## appLaunch.ts - App 唤起工具### 导入方式@@ -742,67 +671,71 @@ openApp('https://api.example.com/redirect', () => {----## regionRedirect.ts - 平台区域限制跳转+## download.ts - 下载工具### 导入方式```typescript-import { confirmPlatformRegionRedirect } from '@/utils/regionRedirect'+import { fetchWithProgress } from '@/utils/download'```### API-| 函数 | 说明 | 参数 | 返回值 |-| --------------------------------------------- | -------------------------------------- | ---------------------- | --------------- |-| `confirmPlatformRegionRedirect(platformName)` | 弹出区域限制提示,确认后跳转到对应域名 | `platformName: string` | `Promise<void>` |+| 函数 | 说明 | 参数 | 返回值 |+| ------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------- | --------------- |+| `fetchWithProgress(url, onProgress?)` | 带进度回调的 fetch 下载,通过 ReadableStream 实时计算百分比 | `url: string`, `onProgress?: (progress: number) => void` | `Promise<Blob>` |### 使用示例```typescript-// 用户点击了当前区域不支持的平台-if (!isPlatformAvailable(platform)) {- confirmPlatformRegionRedirect(platInfo.name)- return-}+// 带进度回调下载+const blob = await fetchWithProgress('https://example.com/file.zip', (progress) => {+ console.log(`${progress}%`) // 0-100+})++// 不需要进度时+const blob = await fetchWithProgress('https://example.com/file.zip')```### 注意事项-- 国内站点击后跳转到 `NEXT_PUBLIC_ABROAD_DOMAIN`,国外站跳转到 `NEXT_PUBLIC_CHINA_DOMAIN`-- 使用 `confirm()` 弹窗,用户确认后才跳转+- 无 `Content-Length` 响应头时降级为无进度下载(直接返回 blob,回调 100%)+- 进度值为 0-100 的整数----## download.ts - 下载工具+## settlement.ts - CPM/CPE 预估计算### 导入方式```typescript-import { fetchWithProgress } from '@/utils/download'+import {+ ENGAGEMENT_WEIGHTS,+ calculateEngagementScore,+ calculateEstimatedAmount,+} from '@/utils/settlement'```### API-| 函数 | 说明 | 参数 | 返回值 |-| ------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------- | --------------- |-| `fetchWithProgress(url, onProgress?)` | 带进度回调的 fetch 下载,通过 ReadableStream 实时计算百分比 | `url: string`, `onProgress?: (progress: number) => void` | `Promise<Blob>` |+| 函数/常量 | 说明 | 参数 | 返回值 |+| ------------------------------------------------------ | ---------------------------------------------- | ---------------------------------------------------------------------------- | -------- |+| `ENGAGEMENT_WEIGHTS` | CPE 互动分权重(LIKE=1, COLLECT=3, COMMENT=5) | - | `object` |+| `calculateEngagementScore(likes, favorites, comments)` | 计算互动分 | `likes, favorites, comments: number` | `number` |+| `calculateEstimatedAmount(count, pricePerThousand)` | 计算预估金额(分) | `count: number` (播放量/互动分), `pricePerThousand: number` (每千次单价,分) | `number` |### 使用示例```typescript-// 带进度回调下载-const blob = await fetchWithProgress('https://example.com/file.zip', (progress) => {- console.log(`${progress}%`) // 0-100-})+// 互动分 = 234×1 + 89×3 + 56×5 = 781+const score = calculateEngagementScore(234, 89, 56)-// 不需要进度时-const blob = await fetchWithProgress('https://example.com/file.zip')-```--### 注意事项+// CPM 预估 = (12345 / 1000) × 100 = 1235 分+const cpmAmount = calculateEstimatedAmount(12345, 100)-- 无 `Content-Length` 响应头时降级为无进度下载(直接返回 blob,回调 100%)-- 进度值为 0-100 的整数+// CPE 预估 = (781 / 1000) × 500 = 391 分+const cpeAmount = calculateEstimatedAmount(score, 500)+```---diff --git a/project/aitoearn-web/src/utils/agent-asset.ts b/project/aitoearn-web/src/utils/agent-asset.tsindex ce0269b7..d2775853 100644--- a/project/aitoearn-web/src/utils/agent-asset.ts+++ b/project/aitoearn-web/src/utils/agent-asset.ts@@ -3,7 +3,7 @@* 提供 Agent 素材的类型判断和数据转换功能*/-import type { MediaItem } from '@/app/[lng]/material/materialStore/materialStore.types'+import type { MediaItem } from '@/api/types/media'import type { AssetType, AssetVo } from '@/types/agent-asset'import { IMAGE_ASSET_TYPES, VIDEO_ASSET_TYPES } from '@/types/agent-asset'diff --git a/project/aitoearn-web/src/utils/detectPlatform.ts b/project/aitoearn-web/src/utils/detectPlatform.tsnew file mode 100644index 00000000..58260ada--- /dev/null+++ b/project/aitoearn-web/src/utils/detectPlatform.ts@@ -0,0 +1,54 @@+/**+ * detectPlatform - URL 自动识别平台工具+ * 从作品链接中检测社交平台类型+ */++import { PlatType } from '@/app/config/platConfig'++/** hostname 后缀 → PlatType 映射 */+const PLATFORM_HOST_MAP: [string, PlatType][] = [+ ['xiaohongshu.com', PlatType.Xhs],+ ['xhslink.com', PlatType.Xhs],+ ['tiktok.com', PlatType.Tiktok],+ ['youtube.com', PlatType.YouTube],+ ['youtu.be', PlatType.YouTube],+ ['x.com', PlatType.Twitter],+ ['twitter.com', PlatType.Twitter],+ ['facebook.com', PlatType.Facebook],+ ['fb.com', PlatType.Facebook],+ ['fb.watch', PlatType.Facebook],+ ['instagram.com', PlatType.Instagram],+ ['instagr.am', PlatType.Instagram],+ ['bilibili.com', PlatType.BILIBILI],+ ['b23.tv', PlatType.BILIBILI],+ ['douyin.com', PlatType.Douyin],+ ['iesdouyin.com', PlatType.Douyin],+ ['kuaishou.com', PlatType.KWAI],+]++/**+ * 从 URL 中检测社交平台类型+ * @param url 作品链接+ * @returns 匹配到的 PlatType,未匹配返回 null+ */+export function detectPlatformFromUrl(url: string): PlatType | null {+ const trimmed = url.trim()+ if (!trimmed)+ return null++ try {+ const fullUrl = trimmed.includes('://') ? trimmed : `https://${trimmed}`+ const { hostname } = new URL(fullUrl)++ for (const [domain, platType] of PLATFORM_HOST_MAP) {+ if (hostname === domain || hostname.endsWith(`.${domain}`)) {+ return platType+ }+ }+ }+ catch {+ return null+ }++ return null+}diff --git a/project/aitoearn-web/src/utils/general.ts b/project/aitoearn-web/src/utils/general.tsindex 24e3ae6b..2fc7135f 100644--- a/project/aitoearn-web/src/utils/general.ts+++ b/project/aitoearn-web/src/utils/general.ts@@ -1,7 +1,92 @@+import type { Metadata } from 'next'+import { getHreflang, languages } from '@/lib/i18n/languageConfig'+export async function getPageTitle(name: string, lng: string) {return `${name} —— AiToEarn`}-export function sleep(ms: number) {- return new Promise(resolve => setTimeout(resolve, ms))+/**+ * 生成页面 Metadata(符合 SEO 最佳实践)+ * @param props - 基础 Metadata 配置+ * @param lng - 当前语言+ * @param path - 页面路径(不含语言前缀),如 '/accounts'+ */+export async function getMetadata(props: Metadata, lng: string, path?: string): Promise<Metadata> {+ path = path || '/'++ const { headers } = await import('next/headers')+ const headersList = await headers()+ const host = headersList.get('host') || 'localhost:3000'+ const proto = headersList.get('x-forwarded-proto') || 'https'+ const baseUrl = `${proto}://${host}`++ const title = await getPageTitle(typeof props.title === 'string' ? props.title : '', lng)++ const description = typeof props.description === 'string' ? props.description : ''++ // 生成所有语言的 alternate links(用于 hreflang)+ const languageAlternates = languages.reduce(+ (acc, lang) => {+ // 使用 x-default 作为默认语言的 hreflang+ const hreflang = lang === 'en' ? 'x-default' : getHreflang(lang)+ acc[hreflang] = `${baseUrl}/${lang}${path}`+ return acc+ },+ {} as Record<string, string>,+ )++ // 默认的 OG 图片+ const defaultOgImage = `${baseUrl}/og-image.png`++ return {+ ...props,+ title,+ description,+ keywords: props.keywords,+ referrer: 'no-referrer',+ // Canonical URL 和 alternate links+ alternates: {+ canonical: `${baseUrl}/${lng}${path}`,+ languages: languageAlternates,+ ...props.alternates,+ },+ // OpenGraph 元数据(社交媒体分享)+ openGraph: {+ title,+ description,+ url: `${baseUrl}/${lng}${path}`,+ siteName: 'AiToEarn',+ locale: lng,+ type: 'website',+ images: [+ {+ url: defaultOgImage,+ width: 1200,+ height: 630,+ alt: title,+ },+ ],+ ...props.openGraph,+ },+ // Twitter Card 元数据+ twitter: {+ card: 'summary_large_image',+ title,+ description,+ images: [defaultOgImage],+ ...props.twitter,+ },+ // 搜索引擎爬虫指令+ robots: props.robots || {+ index: true,+ follow: true,+ googleBot: {+ 'index': true,+ 'follow': true,+ 'max-video-preview': -1,+ 'max-image-preview': 'large',+ 'max-snippet': -1,+ },+ },+ }}diff --git a/project/aitoearn-web/src/utils/oss.ts b/project/aitoearn-web/src/utils/oss.tsindex 503a83fb..61d25d4c 100644--- a/project/aitoearn-web/src/utils/oss.ts+++ b/project/aitoearn-web/src/utils/oss.ts@@ -2,18 +2,7 @@export function getOssUrl(path?: string) {if (!path)return ''- if (path.startsWith('http') || path.startsWith('https') || path.startsWith('ossProxy') || path.startsWith('blob:http'))+ if (path.startsWith('http') || path.startsWith('https') || path.startsWith('blob:http'))return path- return `${process.env.NEXT_PUBLIC_OSS_URL}${path}`-}--// 将完整的oss url转为代理的 oss url-export function getOssProxyPath(ossUrl?: string) {- if (!ossUrl)- return ''-- return ossUrl?.replace(- process.env.NEXT_PUBLIC_OSS_URL ?? '',- process.env.NEXT_PUBLIC_OSS_URL_PROXY ?? '',- )+ return path}diff --git a/project/aitoearn-web/src/utils/route.ts b/project/aitoearn-web/src/utils/route.tsindex 71e3732a..85babd22 100644--- a/project/aitoearn-web/src/utils/route.ts+++ b/project/aitoearn-web/src/utils/route.ts@@ -10,7 +10,6 @@ const PUBLIC_PATHS = ['/websit', // 网站公共页面(条款、隐私政策等)'/blog', // 博客页面'/chat', // 分享页面- '/promo', // 推广页面'/welcome', // 欢迎页面]diff --git a/project/aitoearn-web/src/utils/server-general.ts b/project/aitoearn-web/src/utils/server-general.tsdeleted file mode 100644index 8bac88cd..00000000--- a/project/aitoearn-web/src/utils/server-general.ts+++ /dev/null@@ -1,98 +0,0 @@-/**- * server-general - 服务端专用工具函数- * 仅在 Server Component / generateMetadata 中使用,不可被客户端组件引用- */--import type { Metadata } from 'next'-import { headers } from 'next/headers'-import { getHreflang, languages } from '@/lib/i18n/languageConfig'-import { getPageTitle } from '@/utils/general'--export async function getBaseUrl() {- const h = await headers()- const host = h.get('host') || 'localhost:3000'- const proto = h.get('x-forwarded-proto') || 'http'- return `${proto}://${host}`-}--/**- * 生成页面 Metadata(符合 SEO 最佳实践)- * @param props - 基础 Metadata 配置- * @param lng - 当前语言- * @param path - 页面路径(不含语言前缀),如 '/accounts'- */-export async function getMetadata(props: Metadata, lng: string, path?: string): Promise<Metadata> {- path = path || '/'-- const baseUrl = await getBaseUrl()-- const title = await getPageTitle(typeof props.title === 'string' ? props.title : '', lng)-- const description = typeof props.description === 'string' ? props.description : ''-- // 生成所有语言的 alternate links(用于 hreflang)- const languageAlternates = languages.reduce(- (acc, lang) => {- // 使用 x-default 作为默认语言的 hreflang- const hreflang = lang === 'en' ? 'x-default' : getHreflang(lang)- acc[hreflang] = `${baseUrl}/${lang}${path}`- return acc- },- {} as Record<string, string>,- )-- // 默认的 OG 图片- const defaultOgImage = `${baseUrl}/og-image.png`-- return {- ...props,- title,- description,- keywords: props.keywords,- referrer: 'no-referrer',- // Canonical URL 和 alternate links- alternates: {- canonical: `${baseUrl}/${lng}${path}`,- languages: languageAlternates,- ...props.alternates,- },- // OpenGraph 元数据(社交媒体分享)- openGraph: {- title,- description,- url: `${baseUrl}/${lng}${path}`,- siteName: 'AiToEarn',- locale: lng,- type: 'website',- images: [- {- url: defaultOgImage,- width: 1200,- height: 630,- alt: title,- },- ],- ...props.openGraph,- },- // Twitter Card 元数据- twitter: {- card: 'summary_large_image',- title,- description,- images: [defaultOgImage],- ...props.twitter,- },- // 搜索引擎爬虫指令- robots: props.robots || {- index: true,- follow: true,- googleBot: {- 'index': true,- 'follow': true,- 'max-video-preview': -1,- 'max-image-preview': 'large',- 'max-snippet': -1,- },- },- }-}diff --git a/project/aitoearn-web/src/utils/settlement.ts b/project/aitoearn-web/src/utils/settlement.tsnew file mode 100644index 00000000..8a36a626--- /dev/null+++ b/project/aitoearn-web/src/utils/settlement.ts@@ -0,0 +1,21 @@+/**+ * settlement.ts - CPM/CPE 预估计算工具+ * 计算互动分与预估金额(与后端 common.ts 权重一致)+ */++/** CPE 互动分权重 */+export const ENGAGEMENT_WEIGHTS = { LIKE: 1, COLLECT: 3, COMMENT: 5 } as const++/** 计算互动分 */+export function calculateEngagementScore(likes: number, favorites: number, comments: number): number {+ return likes * ENGAGEMENT_WEIGHTS.LIKE + favorites * ENGAGEMENT_WEIGHTS.COLLECT + comments * ENGAGEMENT_WEIGHTS.COMMENT+}++/** 预估金额上限(分),50 元 */+export const ESTIMATED_AMOUNT_CAP = 5000++/** 计算预估金额(分),count 为播放量或互动分,pricePerThousand 为每千次单价(分) */+export function calculateEstimatedAmount(count: number, pricePerThousand: number): number {+ const amount = Math.round((count / 1000) * pricePerThousand)+ return Math.min(amount, ESTIMATED_AMOUNT_CAP)+}