Compare commits
52 Commits
1eca2cb273
...
ai-agent-b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a1be2bebf7 | ||
|
|
80dcd76749 | ||
|
|
953fbc043b | ||
|
|
64bc65114a | ||
|
|
ae9d778ac7 | ||
|
|
77a9a64a41 | ||
|
|
0c31b97824 | ||
|
|
70ae2fab44 | ||
|
|
411a9058ca | ||
|
|
4b9f845fae | ||
|
|
bdaa53bac8 | ||
|
|
e5b81c08f3 | ||
|
|
1ffab89e97 | ||
|
|
5440b226c4 | ||
|
|
90c6022839 | ||
|
|
184467e482 | ||
|
|
68045d6458 | ||
|
|
d52f17a17b | ||
|
|
047937af4c | ||
|
|
a9267bfc0e | ||
|
|
1019fd685b | ||
|
|
34246d8a62 | ||
|
|
599b6335d5 | ||
|
|
46bc48d1c1 | ||
|
|
17675e702d | ||
|
|
639c683144 | ||
|
|
96a21210b5 | ||
|
|
7495dc86a0 | ||
|
|
ee4cb20eef | ||
|
|
9ca3cd0b1a | ||
|
|
eb6ec06157 | ||
|
|
62940ae25a | ||
|
|
dfc143379f | ||
|
|
bd3a9a5ce8 | ||
|
|
ec4fdc39fe | ||
|
|
3c3e134d2b | ||
|
|
81089cc058 | ||
|
|
681194a517 | ||
|
|
8f515f76c0 | ||
|
|
fcb74eb28c | ||
|
|
44afdaef8e | ||
|
|
41c55d088d | ||
|
|
3b71fe3135 | ||
|
|
4326c41258 | ||
|
|
7f0d57b311 | ||
|
|
75c208dafc | ||
|
|
8021ca9eff | ||
|
|
2cf06a5677 | ||
|
|
2fa42cd8a3 | ||
|
|
a600eb9e7e | ||
|
|
fcf0fd7f70 | ||
|
|
4e421c160c |
@@ -2,7 +2,8 @@
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(dotnet build \"E:\\code\\github\\Yi\\Yi.Abp.Net8\\module\\ai-hub\\Yi.Framework.AiHub.Application\\Yi.Framework.AiHub.Application.csproj\" --no-restore)",
|
||||
"Read(//e/code/github/Yi/Yi.Ai.Vue3/**)"
|
||||
"Read(//e/code/github/Yi/Yi.Ai.Vue3/**)",
|
||||
"Bash(dotnet build:*)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
129
Yi.Abp.Net8/CLAUDE.md
Normal file
129
Yi.Abp.Net8/CLAUDE.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Overview
|
||||
|
||||
Yi.Abp.Net8 is a modular, multi-tenant SaaS platform built on ABP Framework 8.3.4 with .NET 8.0. It uses **SqlSugar** (not EF Core) as the ORM and follows Domain-Driven Design (DDD) principles. The platform includes AI/ML features (chat, models, agents, token tracking), RBAC, forum, messaging, and digital collectibles modules.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Solution Structure
|
||||
|
||||
```
|
||||
Yi.Abp.Net8/
|
||||
├── src/ # Main application host
|
||||
│ └── Yi.Abp.Web/ # ASP.NET Core 8.0 Web Host (port 19001)
|
||||
├── framework/ # Framework layer (shared infrastructure)
|
||||
│ ├── Yi.Framework.Core # Core utilities, JSON handling
|
||||
│ ├── Yi.Framework.SqlSugarCore # SqlSugar ORM abstraction (v5.1.4.197-preview22)
|
||||
│ ├── Yi.Framework.SqlSugarCore.Abstractions # Repository interfaces
|
||||
│ ├── Yi.Framework.AspNetCore # ASP.NET Core extensions
|
||||
│ ├── Yi.Framework.AspNetCore.Authentication.OAuth # QQ, Gitee OAuth
|
||||
│ ├── Yi.Framework.Ddd.Application # DDD application base classes
|
||||
│ ├── Yi.Framework.BackgroundWorkers.Hangfire # Job scheduling
|
||||
│ ├── Yi.Framework.Caching.FreeRedis # Redis caching
|
||||
│ └── Yi.Framework.SemanticKernel # AI/ML integration
|
||||
├── module/ # Business modules (each follows 5-layer DDD pattern)
|
||||
│ ├── ai-hub/ # AI services (chat, models, sessions, agents)
|
||||
│ ├── rbac/ # Role-Based Access Control (core auth/authz)
|
||||
│ ├── bbs/ # Forum/community
|
||||
│ ├── chat-hub/ # Real-time messaging
|
||||
│ ├── audit-logging/ # Audit trail tracking
|
||||
│ ├── code-gen/ # Code generation
|
||||
│ ├── tenant-management/ # Multi-tenancy support
|
||||
│ ├── digital-collectibles/ # NFT/digital assets
|
||||
│ └── ai-stock/ # AI-powered stock analysis
|
||||
├── test/ # Unit tests (xUnit + NSubstitute + Shouldly)
|
||||
├── client/ # HTTP API clients
|
||||
└── tool/ # Development utilities
|
||||
```
|
||||
|
||||
### Module Structure (DDD Layers)
|
||||
|
||||
Each module follows this pattern:
|
||||
|
||||
```
|
||||
module/[feature]/
|
||||
├── [Feature].Domain.Shared/ # Constants, enums, shared DTOs
|
||||
├── [Feature].Domain/ # Entities, aggregates, domain services
|
||||
├── [Feature].Application.Contracts/ # Service interfaces, DTOs
|
||||
├── [Feature].Application/ # Application services (implementations)
|
||||
└── [Feature].SqlSugarCore/ # Repository implementations, DbContext
|
||||
```
|
||||
|
||||
**Dependency Flow:** Application → Domain + Application.Contracts → Domain.Shared → Framework
|
||||
|
||||
### Module Registration
|
||||
|
||||
All modules are registered in `src/Yi.Abp.Web/YiAbpWebModule.cs`. When adding a new module:
|
||||
|
||||
1. Add `DependsOn` attribute in `YiAbpWebModule`
|
||||
2. Add conventional controller in `PreConfigureServices`:
|
||||
```csharp
|
||||
options.ConventionalControllers.Create(typeof(YiFramework[Feature]ApplicationModule).Assembly,
|
||||
option => option.RemoteServiceName = "[service-name]");
|
||||
```
|
||||
|
||||
### API Routing
|
||||
|
||||
All API routes use the unified prefix: `/api/app/{service-name}/{controller}/{action}`
|
||||
|
||||
Registered service names:
|
||||
- `default` - Main application services
|
||||
- `rbac` - Authentication, authorization, user/role management
|
||||
- `ai-hub` - AI chat, models, sessions, agents
|
||||
- `bbs` - Forum posts and comments
|
||||
- `chat-hub` - Real-time messaging
|
||||
- `tenant-management` - Multi-tenant configuration
|
||||
- `code-gen` - Code generation utilities
|
||||
- `digital-collectibles` - NFT/digital assets
|
||||
- `ai-stock` - Stock analysis
|
||||
|
||||
## Database
|
||||
|
||||
**ORM:** SqlSugar (NOT Entity Framework Core)
|
||||
|
||||
**Configuration** (`appsettings.json`):
|
||||
```json
|
||||
"DbConnOptions": {
|
||||
"Url": "DataSource=yi-abp-dev.db",
|
||||
"DbType": "Sqlite", // Sqlite, Mysql, Sqlserver, Oracle, PostgreSQL
|
||||
"EnabledCodeFirst": true, // Auto-create tables
|
||||
"EnabledDbSeed": true, // Auto-seed data
|
||||
"EnabledSaasMultiTenancy": true
|
||||
}
|
||||
```
|
||||
|
||||
**Multi-tenancy:** Tenant isolation via `HeaderTenantResolveContributor` (NOT cookie-based). Tenant is resolved from `__tenant` header.
|
||||
|
||||
## Key Technologies
|
||||
|
||||
| Component | Technology |
|
||||
|-----------|-----------|
|
||||
| Framework | ABP 8.3.4 |
|
||||
| .NET Version | .NET 8.0 |
|
||||
| ORM | SqlSugar 5.1.4.197-preview22 |
|
||||
| Authentication | JWT Bearer + Refresh Tokens |
|
||||
| OAuth | QQ, Gitee |
|
||||
| Caching | FreeRedis (optional) |
|
||||
| Background Jobs | Hangfire (in-memory or Redis) |
|
||||
| Logging | Serilog (daily rolling files) |
|
||||
| Testing | xUnit + NSubstitute + Shouldly |
|
||||
| Container | Autofac |
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **JSON Serialization:** Uses Microsoft's `System.Text.Json`, NOT Newtonsoft.Json. Date format handled via `DatetimeJsonConverter`.
|
||||
- **Multi-tenancy:** Tenant resolved from `__tenant` header, NOT cookies.
|
||||
- **Rate Limiting:** Disabled in development, enabled in production (1000 req/60s sliding window).
|
||||
- **Swagger:** Available at `/swagger` in development.
|
||||
- **Hangfire Dashboard:** Available at `/hangfire` (requires JWT authorization).
|
||||
- **Background Workers:** Disabled in development (`AbpBackgroundWorkerOptions.IsEnabled = false`).
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Branch:** Main branch is `abp`, current development branch is `ai-hub`.
|
||||
2. **Commit Convention:** Chinese descriptive messages with prefixes (`feat:`, `fix:`, `style:`).
|
||||
3. **Testing:** Run `dotnet test` before committing.
|
||||
4. **Building:** Use `dotnet build --no-restore` for faster builds after initial restore.
|
||||
@@ -0,0 +1,30 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
|
||||
/// <summary>
|
||||
/// 批量生成激活码输入
|
||||
/// </summary>
|
||||
public class ActivationCodeCreateInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数量
|
||||
/// </summary>
|
||||
public int Count { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量生成激活码列表输入
|
||||
/// </summary>
|
||||
public class ActivationCodeCreateListInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成项列表
|
||||
/// </summary>
|
||||
public List<ActivationCodeCreateInput> Items { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
|
||||
/// <summary>
|
||||
/// 批量生成激活码输出
|
||||
/// </summary>
|
||||
public class ActivationCodeCreateOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数量
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 激活码列表
|
||||
/// </summary>
|
||||
public List<string> Codes { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量生成激活码列表输出
|
||||
/// </summary>
|
||||
public class ActivationCodeCreateListOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 分组输出
|
||||
/// </summary>
|
||||
public List<ActivationCodeCreateOutput> Items { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码兑换输入
|
||||
/// </summary>
|
||||
public class ActivationCodeRedeemInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 激活码
|
||||
/// </summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码兑换输出
|
||||
/// </summary>
|
||||
public class ActivationCodeRedeemOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品名称
|
||||
/// </summary>
|
||||
public string PackageName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 内容描述
|
||||
/// </summary>
|
||||
public string Content { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI应用输入
|
||||
/// </summary>
|
||||
public class AiAppCreateInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 应用名称
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用名称不能为空")]
|
||||
[StringLength(100, ErrorMessage = "应用名称不能超过100个字符")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用终结点
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用终结点不能为空")]
|
||||
[StringLength(500, ErrorMessage = "应用终结点不能超过500个字符")]
|
||||
public string Endpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外URL
|
||||
/// </summary>
|
||||
[StringLength(500, ErrorMessage = "额外URL不能超过500个字符")]
|
||||
public string? ExtraUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用Key
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用Key不能为空")]
|
||||
[StringLength(500, ErrorMessage = "应用Key不能超过500个字符")]
|
||||
public string ApiKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||
public int OrderNum { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// AI应用DTO
|
||||
/// </summary>
|
||||
public class AiAppDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 应用ID
|
||||
/// </summary>
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用名称
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用终结点
|
||||
/// </summary>
|
||||
public string Endpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外URL
|
||||
/// </summary>
|
||||
public string? ExtraUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用Key
|
||||
/// </summary>
|
||||
public string ApiKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
public int OrderNum { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间
|
||||
/// </summary>
|
||||
public DateTime CreationTime { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI应用列表输入
|
||||
/// </summary>
|
||||
public class AiAppGetListInput : PagedAllResultRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 搜索关键词(搜索应用名称)
|
||||
/// </summary>
|
||||
public string? SearchKey { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI应用输入
|
||||
/// </summary>
|
||||
public class AiAppUpdateInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 应用ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用ID不能为空")]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用名称
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用名称不能为空")]
|
||||
[StringLength(100, ErrorMessage = "应用名称不能超过100个字符")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用终结点
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用终结点不能为空")]
|
||||
[StringLength(500, ErrorMessage = "应用终结点不能超过500个字符")]
|
||||
public string Endpoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外URL
|
||||
/// </summary>
|
||||
[StringLength(500, ErrorMessage = "额外URL不能超过500个字符")]
|
||||
public string? ExtraUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应用Key
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "应用Key不能为空")]
|
||||
[StringLength(500, ErrorMessage = "应用Key不能超过500个字符")]
|
||||
public string ApiKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||
public int OrderNum { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI模型输入
|
||||
/// </summary>
|
||||
public class AiModelCreateInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 处理名
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "处理名不能为空")]
|
||||
[StringLength(100, ErrorMessage = "处理名不能超过100个字符")]
|
||||
public string HandlerName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型ID不能为空")]
|
||||
[StringLength(200, ErrorMessage = "模型ID不能超过200个字符")]
|
||||
public string ModelId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型名称
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型名称不能为空")]
|
||||
[StringLength(200, ErrorMessage = "模型名称不能超过200个字符")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型描述
|
||||
/// </summary>
|
||||
[StringLength(1000, ErrorMessage = "模型描述不能超过1000个字符")]
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||
public int OrderNum { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AI应用ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "AI应用ID不能为空")]
|
||||
public Guid AiAppId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外信息
|
||||
/// </summary>
|
||||
[StringLength(2000, ErrorMessage = "额外信息不能超过2000个字符")]
|
||||
public string? ExtraInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型类型
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型类型不能为空")]
|
||||
public ModelTypeEnum ModelType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型API类型
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型API类型不能为空")]
|
||||
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型倍率
|
||||
/// </summary>
|
||||
[Range(0.01, double.MaxValue, ErrorMessage = "模型倍率必须大于0")]
|
||||
public decimal Multiplier { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 模型显示倍率
|
||||
/// </summary>
|
||||
[Range(0.01, double.MaxValue, ErrorMessage = "模型显示倍率必须大于0")]
|
||||
public decimal MultiplierShow { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 供应商分组名称
|
||||
/// </summary>
|
||||
[StringLength(100, ErrorMessage = "供应商分组名称不能超过100个字符")]
|
||||
public string? ProviderName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型图标URL
|
||||
/// </summary>
|
||||
[StringLength(500, ErrorMessage = "模型图标URL不能超过500个字符")]
|
||||
public string? IconUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为尊享模型
|
||||
/// </summary>
|
||||
public bool IsPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// AI模型DTO
|
||||
/// </summary>
|
||||
public class AiModelDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 处理名
|
||||
/// </summary>
|
||||
public string HandlerName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
public string ModelId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型名称
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型描述
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
public int OrderNum { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AI应用ID
|
||||
/// </summary>
|
||||
public Guid AiAppId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外信息
|
||||
/// </summary>
|
||||
public string? ExtraInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型类型
|
||||
/// </summary>
|
||||
public ModelTypeEnum ModelType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型API类型
|
||||
/// </summary>
|
||||
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型倍率
|
||||
/// </summary>
|
||||
public decimal Multiplier { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型显示倍率
|
||||
/// </summary>
|
||||
public decimal MultiplierShow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 供应商分组名称
|
||||
/// </summary>
|
||||
public string? ProviderName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型图标URL
|
||||
/// </summary>
|
||||
public string? IconUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为尊享模型
|
||||
/// </summary>
|
||||
public bool IsPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI模型列表输入
|
||||
/// </summary>
|
||||
public class AiModelGetListInput : PagedAllResultRequestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 搜索关键词(搜索模型名称、模型ID)
|
||||
/// </summary>
|
||||
public string? SearchKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AI应用ID筛选
|
||||
/// </summary>
|
||||
public Guid? AiAppId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否只显示尊享模型
|
||||
/// </summary>
|
||||
public bool? IsPremiumOnly { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI模型输入
|
||||
/// </summary>
|
||||
public class AiModelUpdateInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型ID不能为空")]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 处理名
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "处理名不能为空")]
|
||||
[StringLength(100, ErrorMessage = "处理名不能超过100个字符")]
|
||||
public string HandlerName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型ID不能为空")]
|
||||
[StringLength(200, ErrorMessage = "模型ID不能超过200个字符")]
|
||||
public string ModelId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型名称
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型名称不能为空")]
|
||||
[StringLength(200, ErrorMessage = "模型名称不能超过200个字符")]
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型描述
|
||||
/// </summary>
|
||||
[StringLength(1000, ErrorMessage = "模型描述不能超过1000个字符")]
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "排序必须大于等于0")]
|
||||
public int OrderNum { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AI应用ID
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "AI应用ID不能为空")]
|
||||
public Guid AiAppId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 额外信息
|
||||
/// </summary>
|
||||
[StringLength(2000, ErrorMessage = "额外信息不能超过2000个字符")]
|
||||
public string? ExtraInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型类型
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型类型不能为空")]
|
||||
public ModelTypeEnum ModelType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型API类型
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "模型API类型不能为空")]
|
||||
public ModelApiTypeEnum ModelApiType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型倍率
|
||||
/// </summary>
|
||||
[Range(0.01, double.MaxValue, ErrorMessage = "模型倍率必须大于0")]
|
||||
public decimal Multiplier { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型显示倍率
|
||||
/// </summary>
|
||||
[Range(0.01, double.MaxValue, ErrorMessage = "模型显示倍率必须大于0")]
|
||||
public decimal MultiplierShow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 供应商分组名称
|
||||
/// </summary>
|
||||
[StringLength(100, ErrorMessage = "供应商分组名称不能超过100个字符")]
|
||||
public string? ProviderName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型图标URL
|
||||
/// </summary>
|
||||
[StringLength(500, ErrorMessage = "模型图标URL不能超过500个字符")]
|
||||
public string? IconUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为尊享模型
|
||||
/// </summary>
|
||||
public bool IsPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
public class AgentResultOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 类型
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public AgentResultTypeEnum TypeEnum { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型
|
||||
/// </summary>
|
||||
public string Type => TypeEnum.GetJsonName();
|
||||
|
||||
/// <summary>
|
||||
/// 内容载体
|
||||
/// </summary>
|
||||
public object Content { get; set; }
|
||||
}
|
||||
|
||||
public enum AgentResultTypeEnum
|
||||
{
|
||||
/// <summary>
|
||||
/// 文本内容
|
||||
/// </summary>
|
||||
[JsonPropertyName("text")]
|
||||
Text,
|
||||
/// <summary>
|
||||
/// 工具调用中
|
||||
/// </summary>
|
||||
[JsonPropertyName("toolCalling")]
|
||||
ToolCalling,
|
||||
|
||||
/// <summary>
|
||||
/// 工具调用完成
|
||||
/// </summary>
|
||||
[JsonPropertyName("toolCalled")]
|
||||
ToolCalled,
|
||||
|
||||
/// <summary>
|
||||
/// 用量
|
||||
/// </summary>
|
||||
[JsonPropertyName("usage")]
|
||||
Usage,
|
||||
|
||||
/// <summary>
|
||||
/// 工具调用用量
|
||||
/// </summary>
|
||||
[JsonPropertyName("toolCallUsage")]
|
||||
ToolCallUsage
|
||||
}
|
||||
|
||||
public static class AgentResultTypeEnumExtensions
|
||||
{
|
||||
public static string GetJsonName(this AgentResultTypeEnum value)
|
||||
{
|
||||
var member = typeof(AgentResultTypeEnum).GetMember(value.ToString()).FirstOrDefault();
|
||||
var attr = member?.GetCustomAttribute<JsonPropertyNameAttribute>();
|
||||
return attr?.Name ?? value.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
public class AgentSendInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 会话id
|
||||
/// </summary>
|
||||
public Guid SessionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户内容
|
||||
/// </summary>
|
||||
public string Content { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// api密钥Id
|
||||
/// </summary>
|
||||
public string Token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型id
|
||||
/// </summary>
|
||||
public string ModelId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已选择工具
|
||||
/// </summary>
|
||||
public List<string> Tools { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
public class AgentToolOutput
|
||||
{
|
||||
public string Code { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
/// <summary>
|
||||
/// 图片生成输入
|
||||
/// </summary>
|
||||
public class ImageGenerationInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 提示词
|
||||
/// </summary>
|
||||
public string Prompt { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
public string ModelId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 参考图Base64列表(可选,包含前缀如 data:image/png;base64,...)
|
||||
/// </summary>
|
||||
public List<string>? ReferenceImagesBase64 { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
/// <summary>
|
||||
/// 图片任务输出
|
||||
/// </summary>
|
||||
public class ImageTaskOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 任务ID
|
||||
/// </summary>
|
||||
public Guid Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 提示词
|
||||
/// </summary>
|
||||
public string Prompt { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 参考图Base64列表
|
||||
/// </summary>
|
||||
public List<string>? ReferenceImagesBase64 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参考图URL列表
|
||||
/// </summary>
|
||||
public List<string>? ReferenceImagesUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生成图片Base64(包含前缀)
|
||||
/// </summary>
|
||||
public string? StoreBase64 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生成图片URL
|
||||
/// </summary>
|
||||
public string? StoreUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态
|
||||
/// </summary>
|
||||
public TaskStatusEnum TaskStatus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间
|
||||
/// </summary>
|
||||
public DateTime CreationTime { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
|
||||
/// <summary>
|
||||
/// 图片任务分页查询输入
|
||||
/// </summary>
|
||||
public class ImageTaskPageInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 页码(从1开始)
|
||||
/// </summary>
|
||||
public int PageIndex { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页数量
|
||||
/// </summary>
|
||||
public int PageSize { get; set; } = 10;
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态筛选(可选)
|
||||
/// </summary>
|
||||
public TaskStatusEnum? TaskStatus { get; set; }
|
||||
}
|
||||
@@ -25,11 +25,17 @@ public class RechargeCreateInput
|
||||
public string Content { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// VIP月数(为空或0表示永久VIP)
|
||||
/// VIP月数(为空或0表示永久VIP,1个月按31天计算)
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "月数必须大于等于0")]
|
||||
public int? Months { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// VIP天数(为空或0表示不使用天数充值)
|
||||
/// </summary>
|
||||
[Range(0, int.MaxValue, ErrorMessage = "天数必须大于等于0")]
|
||||
public int? Days { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using Volo.Abp.Application.Services;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码服务接口
|
||||
/// </summary>
|
||||
public interface IActivationCodeService : IApplicationService
|
||||
{
|
||||
/// <summary>
|
||||
/// 批量生成激活码
|
||||
/// </summary>
|
||||
Task<ActivationCodeCreateListOutput> CreateBatchAsync(ActivationCodeCreateListInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 兑换激活码
|
||||
/// </summary>
|
||||
Task<ActivationCodeRedeemOutput> RedeemAsync(ActivationCodeRedeemInput input);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道商管理服务接口
|
||||
/// </summary>
|
||||
public interface IChannelService
|
||||
{
|
||||
#region AI应用管理
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI应用列表
|
||||
/// </summary>
|
||||
/// <param name="input">查询参数</param>
|
||||
/// <returns>分页应用列表</returns>
|
||||
Task<PagedResultDto<AiAppDto>> GetAppListAsync(AiAppGetListInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID获取AI应用
|
||||
/// </summary>
|
||||
/// <param name="id">应用ID</param>
|
||||
/// <returns>应用详情</returns>
|
||||
Task<AiAppDto> GetAppByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI应用
|
||||
/// </summary>
|
||||
/// <param name="input">创建输入</param>
|
||||
/// <returns>创建的应用</returns>
|
||||
Task<AiAppDto> CreateAppAsync(AiAppCreateInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI应用
|
||||
/// </summary>
|
||||
/// <param name="input">更新输入</param>
|
||||
/// <returns>更新后的应用</returns>
|
||||
Task<AiAppDto> UpdateAppAsync(AiAppUpdateInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 删除AI应用
|
||||
/// </summary>
|
||||
/// <param name="id">应用ID</param>
|
||||
Task DeleteAppAsync(Guid id);
|
||||
|
||||
#endregion
|
||||
|
||||
#region AI模型管理
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI模型列表
|
||||
/// </summary>
|
||||
/// <param name="input">查询参数</param>
|
||||
/// <returns>分页模型列表</returns>
|
||||
Task<PagedResultDto<AiModelDto>> GetModelListAsync(AiModelGetListInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID获取AI模型
|
||||
/// </summary>
|
||||
/// <param name="id">模型ID</param>
|
||||
/// <returns>模型详情</returns>
|
||||
Task<AiModelDto> GetModelByIdAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI模型
|
||||
/// </summary>
|
||||
/// <param name="input">创建输入</param>
|
||||
/// <returns>创建的模型</returns>
|
||||
Task<AiModelDto> CreateModelAsync(AiModelCreateInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI模型
|
||||
/// </summary>
|
||||
/// <param name="input">更新输入</param>
|
||||
/// <returns>更新后的模型</returns>
|
||||
Task<AiModelDto> UpdateModelAsync(AiModelUpdateInput input);
|
||||
|
||||
/// <summary>
|
||||
/// 删除AI模型(软删除)
|
||||
/// </summary>
|
||||
/// <param name="id">模型ID</param>
|
||||
Task DeleteModelAsync(Guid id);
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.BackgroundJobs;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 图片生成后台任务
|
||||
/// </summary>
|
||||
public class ImageGenerationJob : AsyncBackgroundJob<ImageGenerationJobArgs>, ITransientDependency
|
||||
{
|
||||
private readonly ILogger<ImageGenerationJob> _logger;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreTaskRepository;
|
||||
|
||||
public ImageGenerationJob(
|
||||
ILogger<ImageGenerationJob> logger,
|
||||
AiGateWayManager aiGateWayManager,
|
||||
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreTaskRepository)
|
||||
{
|
||||
_logger = logger;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_imageStoreTaskRepository = imageStoreTaskRepository;
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync(ImageGenerationJobArgs args)
|
||||
{
|
||||
_logger.LogInformation("开始执行图片生成任务,TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
|
||||
args.TaskId, args.ModelId, args.UserId);
|
||||
|
||||
try
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<JsonElement>(args.RequestJson);
|
||||
|
||||
await _aiGateWayManager.GeminiGenerateContentImageForStatisticsAsync(
|
||||
args.TaskId,
|
||||
args.ModelId,
|
||||
request,
|
||||
args.UserId);
|
||||
|
||||
_logger.LogInformation("图片生成任务完成,TaskId: {TaskId}", args.TaskId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "图片生成任务失败,TaskId: {TaskId}, Error: {Error}", args.TaskId, ex.Message);
|
||||
|
||||
// 更新任务状态为失败
|
||||
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
|
||||
if (task != null)
|
||||
{
|
||||
task.TaskStatus = TaskStatusEnum.Fail;
|
||||
await _imageStoreTaskRepository.UpdateAsync(task);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Yi.Framework.AiHub.Application.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 图片生成后台任务参数
|
||||
/// </summary>
|
||||
public class ImageGenerationJobArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// 图片任务ID
|
||||
/// </summary>
|
||||
public Guid TaskId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型ID
|
||||
/// </summary>
|
||||
public string ModelId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 请求JSON字符串
|
||||
/// </summary>
|
||||
public string RequestJson { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 用户ID
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using Medallion.Threading;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Volo.Abp;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
|
||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码服务
|
||||
/// </summary>
|
||||
public class ActivationCodeService : ApplicationService, IActivationCodeService
|
||||
{
|
||||
private readonly ActivationCodeManager _activationCodeManager;
|
||||
private readonly IRechargeService _rechargeService;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
|
||||
public ActivationCodeService(
|
||||
ActivationCodeManager activationCodeManager,
|
||||
IRechargeService rechargeService,
|
||||
PremiumPackageManager premiumPackageManager)
|
||||
{
|
||||
_activationCodeManager = activationCodeManager;
|
||||
_rechargeService = rechargeService;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量生成激活码
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[HttpPost("activationCode/Batch")]
|
||||
public async Task<ActivationCodeCreateListOutput> CreateBatchAsync(ActivationCodeCreateListInput input)
|
||||
{
|
||||
if (input.Items == null || input.Items.Count == 0)
|
||||
{
|
||||
throw new UserFriendlyException("生成列表不能为空");
|
||||
}
|
||||
|
||||
var entities = await _activationCodeManager.CreateBatchAsync(
|
||||
input.Items.Select(x => (x.GoodsType, x.Count)).ToList());
|
||||
|
||||
var outputs = entities
|
||||
.GroupBy(x => x.GoodsType)
|
||||
.Select(group => new ActivationCodeCreateOutput
|
||||
{
|
||||
GoodsType = group.Key,
|
||||
Count = group.Count(),
|
||||
Codes = group.Select(x => x.Code).ToList()
|
||||
})
|
||||
.ToList();
|
||||
|
||||
return new ActivationCodeCreateListOutput
|
||||
{
|
||||
Items = outputs
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 兑换激活码
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[HttpPost("activationCode/Redeem")]
|
||||
public async Task<ActivationCodeRedeemOutput> RedeemAsync(ActivationCodeRedeemInput input)
|
||||
{
|
||||
//自旋等待,防抖
|
||||
await using var handle =
|
||||
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ActivationCodeLock:{input.Code}");
|
||||
|
||||
var userId = CurrentUser.GetId();
|
||||
var redeemContext = await _activationCodeManager.RedeemAsync(userId, input.Code);
|
||||
var goodsType = redeemContext.ActivationCode.GoodsType;
|
||||
var goods = redeemContext.Goods;
|
||||
var packageName = redeemContext.PackageName;
|
||||
var totalAmount = goods.Price;
|
||||
|
||||
if (goods.TokenAmount > 0)
|
||||
{
|
||||
await _premiumPackageManager.CreatePremiumPackageAsync(
|
||||
userId,
|
||||
goods.TokenAmount,
|
||||
packageName,
|
||||
totalAmount,
|
||||
"激活码兑换",
|
||||
expireMonths: null,
|
||||
isCreateRechargeRecord: !goods.IsCombo);
|
||||
}
|
||||
|
||||
if (goods.VipMonths > 0 || goods.VipDays > 0)
|
||||
{
|
||||
await _rechargeService.RechargeVipAsync(new RechargeCreateInput
|
||||
{
|
||||
UserId = userId,
|
||||
RechargeAmount = totalAmount,
|
||||
Content = packageName,
|
||||
Months = goods.VipMonths,
|
||||
Days = goods.VipDays,
|
||||
Remark = "激活码兑换",
|
||||
ContactInfo = null
|
||||
});
|
||||
}
|
||||
|
||||
return new ActivationCodeRedeemOutput
|
||||
{
|
||||
GoodsType = goodsType,
|
||||
PackageName = packageName,
|
||||
Content = packageName
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Medallion.Threading;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SqlSugar;
|
||||
@@ -6,6 +7,7 @@ using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
@@ -23,7 +25,8 @@ public class DailyTaskService : ApplicationService
|
||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
private readonly ILogger<DailyTaskService> _logger;
|
||||
|
||||
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
// 任务配置
|
||||
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
|
||||
_taskConfigs = new()
|
||||
@@ -36,12 +39,13 @@ public class DailyTaskService : ApplicationService
|
||||
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
|
||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||
ILogger<DailyTaskService> logger)
|
||||
ILogger<DailyTaskService> logger, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||
{
|
||||
_dailyTaskRepository = dailyTaskRepository;
|
||||
_messageRepository = messageRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
_logger = logger;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -113,6 +117,11 @@ public class DailyTaskService : ApplicationService
|
||||
public async Task ClaimTaskRewardAsync(ClaimTaskRewardInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
//自旋等待,防抖
|
||||
await using var handle =
|
||||
await DistributedLock.AcquireLockAsync($"Yi:AiHub:ClaimTaskRewardLock:{userId}");
|
||||
|
||||
|
||||
var today = DateTime.Today;
|
||||
|
||||
// 1. 验证任务等级
|
||||
@@ -173,10 +182,16 @@ public class DailyTaskService : ApplicationService
|
||||
var tomorrow = today.AddDays(1);
|
||||
|
||||
// 查询今日所有使用尊享包模型的消息(role=system 表示消耗)
|
||||
// 先获取所有尊享模型的ModelId列表
|
||||
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.IsPremium)
|
||||
.Select(x => x.ModelId)
|
||||
.ToListAsync();
|
||||
|
||||
var totalTokens = await _messageRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.Where(x => x.Role == "system") // system角色表示实际消耗
|
||||
.Where(x => PremiumPackageConst.ModeIds.Contains(x.ModelId)) // 尊享包模型
|
||||
.Where(x => premiumModelIds.Contains(x.ModelId)) // 尊享包模型
|
||||
.Where(x => x.CreationTime >= today && x.CreationTime < tomorrow)
|
||||
.SumAsync(x => x.TokenUsage.TotalTokenCount);
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SqlSugar;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.Rbac.Application.Contracts.IServices;
|
||||
using Yi.Framework.Rbac.Domain.Shared.Dtos;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
@@ -18,17 +22,18 @@ public class AiAccountService : ApplicationService
|
||||
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
|
||||
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||
private ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
|
||||
private ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||
public AiAccountService(
|
||||
IAccountService accountService,
|
||||
ISqlSugarRepository<AiUserExtraInfoEntity> userRepository,
|
||||
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository, ISqlSugarRepository<MessageAggregateRoot> messageRepository)
|
||||
{
|
||||
_accountService = accountService;
|
||||
_userRepository = userRepository;
|
||||
_rechargeRepository = rechargeRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
_messageRepository = messageRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -148,4 +153,90 @@ public class AiAccountService : ApplicationService
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public class TokenStatisticsInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 指定日期(当天零点)
|
||||
/// </summary>
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型Id -> 1亿Token成本(RMB)
|
||||
/// </summary>
|
||||
public Dictionary<string, decimal> ModelCosts { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定日期各模型Token统计
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[HttpPost("account/token-statistics")]
|
||||
public async Task<string> GetTokenStatisticsAsync([FromBody] TokenStatisticsInput input)
|
||||
{
|
||||
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
|
||||
{
|
||||
throw new UserFriendlyException("您暂无权限访问");
|
||||
}
|
||||
|
||||
if (input.ModelCosts is null || input.ModelCosts.Count == 0)
|
||||
{
|
||||
throw new UserFriendlyException("请提供模型成本配置");
|
||||
}
|
||||
|
||||
var day = input.Date.Date;
|
||||
var nextDay = day.AddDays(1);
|
||||
var modelIds = input.ModelCosts.Keys.ToList();
|
||||
|
||||
var modelStats = await _messageRepository._DbQueryable
|
||||
.Where(x => modelIds.Contains(x.ModelId))
|
||||
.Where(x => x.CreationTime >= day && x.CreationTime < nextDay)
|
||||
.Where(x => x.Role == "system")
|
||||
.GroupBy(x => x.ModelId)
|
||||
.Select(x => new
|
||||
{
|
||||
ModelId = x.ModelId,
|
||||
Tokens = SqlFunc.AggregateSum(x.TokenUsage.TotalTokenCount),
|
||||
Count = SqlFunc.AggregateCount(x.Id)
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
var modelStatDict = modelStats.ToDictionary(x => x.ModelId, x => x);
|
||||
|
||||
string weekDay = day.ToString("dddd", new CultureInfo("zh-CN")) switch
|
||||
{
|
||||
"星期一" => "周1",
|
||||
"星期二" => "周2",
|
||||
"星期三" => "周3",
|
||||
"星期四" => "周4",
|
||||
"星期五" => "周5",
|
||||
"星期六" => "周6",
|
||||
"星期日" => "周日",
|
||||
_ => day.ToString("dddd", new CultureInfo("zh-CN"))
|
||||
};
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine($"{day:M月d日} {weekDay}");
|
||||
|
||||
foreach (var kvp in input.ModelCosts)
|
||||
{
|
||||
var modelId = kvp.Key;
|
||||
var cost = kvp.Value;
|
||||
|
||||
modelStatDict.TryGetValue(modelId, out var stat);
|
||||
long tokens = stat?.Tokens ?? 0;
|
||||
long count = stat?.Count ?? 0;
|
||||
|
||||
decimal costPerHundredMillion = tokens > 0
|
||||
? cost / (tokens / 100000000m)
|
||||
: 0;
|
||||
|
||||
decimal tokensInWan = tokens / 10000m;
|
||||
|
||||
sb.AppendLine();
|
||||
sb.AppendLine($"{modelId} 成本:【{cost:F2}RMB】 次数:【{count}次】 token:【{tokensInWan:F0}w】 1亿token成本:【{costPerHundredMillion:F2}RMB】");
|
||||
}
|
||||
|
||||
return sb.ToString().TrimEnd();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
|
||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道商管理服务实现
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
public class ChannelService : ApplicationService, IChannelService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository;
|
||||
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
||||
|
||||
public ChannelService(
|
||||
ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository,
|
||||
ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
|
||||
{
|
||||
_appRepository = appRepository;
|
||||
_modelRepository = modelRepository;
|
||||
}
|
||||
|
||||
#region AI应用管理
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI应用列表
|
||||
/// </summary>
|
||||
[HttpGet("channel/app")]
|
||||
public async Task<PagedResultDto<AiAppDto>> GetAppListAsync(AiAppGetListInput input)
|
||||
{
|
||||
RefAsync<int> total = 0;
|
||||
|
||||
var entities = await _appRepository._DbQueryable
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x => x.Name.Contains(input.SearchKey))
|
||||
.OrderByDescending(x => x.OrderNum)
|
||||
.OrderByDescending(x => x.CreationTime)
|
||||
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||
|
||||
var output = entities.Adapt<List<AiAppDto>>();
|
||||
return new PagedResultDto<AiAppDto>(total, output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID获取AI应用
|
||||
/// </summary>
|
||||
[HttpGet("channel/app/{id}")]
|
||||
public async Task<AiAppDto> GetAppByIdAsync([FromRoute]Guid id)
|
||||
{
|
||||
var entity = await _appRepository.GetByIdAsync(id);
|
||||
return entity.Adapt<AiAppDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI应用
|
||||
/// </summary>
|
||||
public async Task<AiAppDto> CreateAppAsync(AiAppCreateInput input)
|
||||
{
|
||||
var entity = new AiAppAggregateRoot
|
||||
{
|
||||
Name = input.Name,
|
||||
Endpoint = input.Endpoint,
|
||||
ExtraUrl = input.ExtraUrl,
|
||||
ApiKey = input.ApiKey,
|
||||
OrderNum = input.OrderNum
|
||||
};
|
||||
|
||||
await _appRepository.InsertAsync(entity);
|
||||
return entity.Adapt<AiAppDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI应用
|
||||
/// </summary>
|
||||
public async Task<AiAppDto> UpdateAppAsync(AiAppUpdateInput input)
|
||||
{
|
||||
var entity = await _appRepository.GetByIdAsync(input.Id);
|
||||
|
||||
entity.Name = input.Name;
|
||||
entity.Endpoint = input.Endpoint;
|
||||
entity.ExtraUrl = input.ExtraUrl;
|
||||
entity.ApiKey = input.ApiKey;
|
||||
entity.OrderNum = input.OrderNum;
|
||||
|
||||
await _appRepository.UpdateAsync(entity);
|
||||
return entity.Adapt<AiAppDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除AI应用
|
||||
/// </summary>
|
||||
[HttpDelete("channel/app/{id}")]
|
||||
public async Task DeleteAppAsync([FromRoute]Guid id)
|
||||
{
|
||||
// 检查是否有关联的模型
|
||||
var hasModels = await _modelRepository._DbQueryable
|
||||
.Where(x => x.AiAppId == id && !x.IsDeleted)
|
||||
.AnyAsync();
|
||||
|
||||
if (hasModels)
|
||||
{
|
||||
throw new Volo.Abp.UserFriendlyException("该应用下存在模型,无法删除");
|
||||
}
|
||||
|
||||
await _appRepository.DeleteAsync(id);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region AI模型管理
|
||||
|
||||
/// <summary>
|
||||
/// 获取AI模型列表
|
||||
/// </summary>
|
||||
[HttpGet("channel/model")]
|
||||
public async Task<PagedResultDto<AiModelDto>> GetModelListAsync(AiModelGetListInput input)
|
||||
{
|
||||
RefAsync<int> total = 0;
|
||||
|
||||
var query = _modelRepository._DbQueryable
|
||||
.Where(x => !x.IsDeleted)
|
||||
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
|
||||
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
|
||||
.WhereIF(input.AiAppId.HasValue, x => x.AiAppId == input.AiAppId.Value)
|
||||
.WhereIF(input.IsPremiumOnly == true, x => x.IsPremium);
|
||||
|
||||
var entities = await query
|
||||
.OrderBy(x => x.OrderNum)
|
||||
.OrderByDescending(x => x.Id)
|
||||
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
|
||||
|
||||
var output = entities.Adapt<List<AiModelDto>>();
|
||||
return new PagedResultDto<AiModelDto>(total, output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据ID获取AI模型
|
||||
/// </summary>
|
||||
[HttpGet("channel/model/{id}")]
|
||||
public async Task<AiModelDto> GetModelByIdAsync([FromRoute]Guid id)
|
||||
{
|
||||
var entity = await _modelRepository.GetByIdAsync(id);
|
||||
return entity.Adapt<AiModelDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建AI模型
|
||||
/// </summary>
|
||||
public async Task<AiModelDto> CreateModelAsync(AiModelCreateInput input)
|
||||
{
|
||||
// 验证应用是否存在
|
||||
var appExists = await _appRepository._DbQueryable
|
||||
.Where(x => x.Id == input.AiAppId)
|
||||
.AnyAsync();
|
||||
|
||||
if (!appExists)
|
||||
{
|
||||
throw new Volo.Abp.UserFriendlyException("指定的AI应用不存在");
|
||||
}
|
||||
|
||||
var entity = new AiModelEntity
|
||||
{
|
||||
HandlerName = input.HandlerName,
|
||||
ModelId = input.ModelId,
|
||||
Name = input.Name,
|
||||
Description = input.Description,
|
||||
OrderNum = input.OrderNum,
|
||||
AiAppId = input.AiAppId,
|
||||
ExtraInfo = input.ExtraInfo,
|
||||
ModelType = input.ModelType,
|
||||
ModelApiType = input.ModelApiType,
|
||||
Multiplier = input.Multiplier,
|
||||
MultiplierShow = input.MultiplierShow,
|
||||
ProviderName = input.ProviderName,
|
||||
IconUrl = input.IconUrl,
|
||||
IsPremium = input.IsPremium,
|
||||
IsDeleted = false
|
||||
};
|
||||
|
||||
await _modelRepository.InsertAsync(entity);
|
||||
return entity.Adapt<AiModelDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新AI模型
|
||||
/// </summary>
|
||||
public async Task<AiModelDto> UpdateModelAsync(AiModelUpdateInput input)
|
||||
{
|
||||
var entity = await _modelRepository.GetByIdAsync(input.Id);
|
||||
|
||||
// 验证应用是否存在
|
||||
if (entity.AiAppId != input.AiAppId)
|
||||
{
|
||||
var appExists = await _appRepository._DbQueryable
|
||||
.Where(x => x.Id == input.AiAppId)
|
||||
.AnyAsync();
|
||||
|
||||
if (!appExists)
|
||||
{
|
||||
throw new Volo.Abp.UserFriendlyException("指定的AI应用不存在");
|
||||
}
|
||||
}
|
||||
|
||||
entity.HandlerName = input.HandlerName;
|
||||
entity.ModelId = input.ModelId;
|
||||
entity.Name = input.Name;
|
||||
entity.Description = input.Description;
|
||||
entity.OrderNum = input.OrderNum;
|
||||
entity.AiAppId = input.AiAppId;
|
||||
entity.ExtraInfo = input.ExtraInfo;
|
||||
entity.ModelType = input.ModelType;
|
||||
entity.ModelApiType = input.ModelApiType;
|
||||
entity.Multiplier = input.Multiplier;
|
||||
entity.MultiplierShow = input.MultiplierShow;
|
||||
entity.ProviderName = input.ProviderName;
|
||||
entity.IconUrl = input.IconUrl;
|
||||
entity.IsPremium = input.IsPremium;
|
||||
|
||||
await _modelRepository.UpdateAsync(entity);
|
||||
return entity.Adapt<AiModelDto>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除AI模型(软删除)
|
||||
/// </summary>
|
||||
[HttpDelete("channel/model/{id}")]
|
||||
public async Task DeleteModelAsync(Guid id)
|
||||
{
|
||||
await _modelRepository.DeleteByIdAsync(id);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,18 +1,26 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using Dm.util;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ModelContextProtocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using OpenAI.Chat;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
using Yi.Framework.AiHub.Domain;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
@@ -32,23 +40,37 @@ namespace Yi.Framework.AiHub.Application.Services;
|
||||
public class AiChatService : ApplicationService
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
private readonly ILogger<AiChatService> _logger;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly ModelManager _modelManager;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
private readonly ChatManager _chatManager;
|
||||
private readonly TokenManager _tokenManager;
|
||||
private readonly IAccountService _accountService;
|
||||
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
|
||||
public AiChatService(IHttpContextAccessor httpContextAccessor,
|
||||
AiBlacklistManager aiBlacklistManager,
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||
ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager, PremiumPackageManager premiumPackageManager)
|
||||
ILogger<AiChatService> logger,
|
||||
AiGateWayManager aiGateWayManager,
|
||||
ModelManager modelManager,
|
||||
PremiumPackageManager premiumPackageManager,
|
||||
ChatManager chatManager, TokenManager tokenManager, IAccountService accountService,
|
||||
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_logger = logger;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_modelManager = modelManager;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
_chatManager = chatManager;
|
||||
_tokenManager = tokenManager;
|
||||
_accountService = accountService;
|
||||
_agentStoreRepository = agentStoreRepository;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +111,7 @@ public class AiChatService : ApplicationService
|
||||
ApiHost = null,
|
||||
ApiKey = null,
|
||||
Remark = x.Description,
|
||||
IsPremiumPackage = PremiumPackageConst.ModeIds.Contains(x.ModelId)
|
||||
IsPremiumPackage = x.IsPremium
|
||||
}).ToListAsync();
|
||||
return output;
|
||||
}
|
||||
@@ -124,22 +146,26 @@ public class AiChatService : ApplicationService
|
||||
}
|
||||
|
||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||
if (CurrentUser.IsAuthenticated && PremiumPackageConst.ModeIds.Contains(input.Model))
|
||||
if (CurrentUser.IsAuthenticated)
|
||||
{
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
||||
if (availableTokens <= 0)
|
||||
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//ai网关代理httpcontext
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
CurrentUser.Id, sessionId, null, cancellationToken);
|
||||
CurrentUser.Id, sessionId, null, CancellationToken.None);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 发送消息
|
||||
/// </summary>
|
||||
@@ -173,6 +199,80 @@ public class AiChatService : ApplicationService
|
||||
|
||||
//ai网关代理httpcontext
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
CurrentUser.Id, null, null, cancellationToken);
|
||||
CurrentUser.Id, null, null, CancellationToken.None);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Agent 发送消息
|
||||
/// </summary>
|
||||
[HttpPost("ai-chat/agent/send")]
|
||||
public async Task PostAgentSendAsync([FromBody] AgentSendInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
var tokenValidation = await _tokenManager.ValidateTokenAsync(input.Token, input.ModelId);
|
||||
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(tokenValidation.UserId);
|
||||
// 验证用户是否为VIP
|
||||
var userInfo = await _accountService.GetAsync(null, null, tokenValidation.UserId);
|
||||
if (userInfo == null)
|
||||
{
|
||||
throw new UserFriendlyException("用户信息不存在");
|
||||
}
|
||||
|
||||
// 检查是否为VIP(使用RoleCodes判断)
|
||||
if (!userInfo.RoleCodes.Contains(AiHubConst.VipRole) && userInfo.User.UserName != "cc")
|
||||
{
|
||||
throw new UserFriendlyException("该接口为尊享服务专用,需要VIP权限才能使用");
|
||||
}
|
||||
|
||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||
var isPremium = await _modelManager.IsPremiumModelAsync(input.ModelId);
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(tokenValidation.UserId);
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
}
|
||||
|
||||
await _chatManager.AgentCompleteChatStreamAsync(_httpContextAccessor.HttpContext,
|
||||
input.SessionId,
|
||||
input.Content,
|
||||
input.Token,
|
||||
tokenValidation.TokenId,
|
||||
input.ModelId,
|
||||
tokenValidation.UserId,
|
||||
input.Tools,
|
||||
CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 Agent 工具
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("ai-chat/agent/tool")]
|
||||
public List<AgentToolOutput> GetAgentToolAsync()
|
||||
{
|
||||
var agentTools = _chatManager.GetTools().Select(x => new AgentToolOutput
|
||||
{
|
||||
Code = x.Code,
|
||||
Name = x.Name
|
||||
}).ToList();
|
||||
return agentTools;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 Agent 上下文
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("ai-chat/agent/context/{sessionId}")]
|
||||
[Authorize]
|
||||
public async Task<string?> GetAgentContextAsync([FromRoute] Guid sessionId)
|
||||
{
|
||||
var data = await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
|
||||
return data?.Store;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Volo.Abp;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.BackgroundJobs;
|
||||
using Volo.Abp.Guids;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
using Yi.Framework.AiHub.Application.Jobs;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Application.Services.Chat;
|
||||
|
||||
/// <summary>
|
||||
/// AI图片生成服务
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
public class AiImageService : ApplicationService
|
||||
{
|
||||
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageTaskRepository;
|
||||
private readonly IBackgroundJobManager _backgroundJobManager;
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
private readonly ModelManager _modelManager;
|
||||
private readonly IGuidGenerator _guidGenerator;
|
||||
private readonly IWebHostEnvironment _webHostEnvironment;
|
||||
|
||||
public AiImageService(
|
||||
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository,
|
||||
IBackgroundJobManager backgroundJobManager,
|
||||
AiBlacklistManager aiBlacklistManager,
|
||||
PremiumPackageManager premiumPackageManager,
|
||||
ModelManager modelManager,
|
||||
IGuidGenerator guidGenerator,
|
||||
IWebHostEnvironment webHostEnvironment)
|
||||
{
|
||||
_imageTaskRepository = imageTaskRepository;
|
||||
_backgroundJobManager = backgroundJobManager;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
_modelManager = modelManager;
|
||||
_guidGenerator = guidGenerator;
|
||||
_webHostEnvironment = webHostEnvironment;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成图片(异步任务)
|
||||
/// </summary>
|
||||
/// <param name="input">图片生成输入参数</param>
|
||||
/// <returns>任务ID</returns>
|
||||
[HttpPost("ai-image/generate")]
|
||||
[Authorize]
|
||||
public async Task<Guid> GenerateAsync([FromBody] ImageGenerationInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
|
||||
// 黑名单校验
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
|
||||
// VIP校验
|
||||
if (!CurrentUser.IsAiVip())
|
||||
{
|
||||
throw new UserFriendlyException("图片生成功能需要VIP用户才能使用,请购买VIP后重新登录重试");
|
||||
}
|
||||
|
||||
// 尊享包校验 - 使用ModelManager统一判断
|
||||
var isPremium = await _modelManager.IsPremiumModelAsync(input.ModelId);
|
||||
if (isPremium)
|
||||
{
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
}
|
||||
|
||||
// 创建任务实体
|
||||
var task = new ImageStoreTaskAggregateRoot
|
||||
{
|
||||
Prompt = input.Prompt,
|
||||
ReferenceImagesBase64 = input.ReferenceImagesBase64 ?? new List<string>(),
|
||||
ReferenceImagesUrl = new List<string>(),
|
||||
TaskStatus = TaskStatusEnum.Processing,
|
||||
UserId = userId
|
||||
};
|
||||
|
||||
await _imageTaskRepository.InsertAsync(task);
|
||||
var taskId = task.Id;
|
||||
|
||||
// 构建请求JSON
|
||||
var requestJson = JsonSerializer.Serialize(new
|
||||
{
|
||||
prompt = input.Prompt,
|
||||
referenceImages = input.ReferenceImagesBase64
|
||||
});
|
||||
|
||||
// 入队后台任务
|
||||
await _backgroundJobManager.EnqueueAsync(new ImageGenerationJobArgs
|
||||
{
|
||||
TaskId = taskId,
|
||||
ModelId = input.ModelId,
|
||||
RequestJson = requestJson,
|
||||
UserId = userId
|
||||
});
|
||||
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询任务状态
|
||||
/// </summary>
|
||||
/// <param name="taskId">任务ID</param>
|
||||
/// <returns>任务详情</returns>
|
||||
[HttpGet("ai-image/task/{taskId}")]
|
||||
public async Task<ImageTaskOutput> GetTaskAsync([FromRoute] Guid taskId)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
|
||||
var task = await _imageTaskRepository.GetFirstAsync(x => x.Id == taskId && x.UserId == userId);
|
||||
if (task == null)
|
||||
{
|
||||
throw new UserFriendlyException("任务不存在或无权访问");
|
||||
}
|
||||
|
||||
return new ImageTaskOutput
|
||||
{
|
||||
Id = task.Id,
|
||||
Prompt = task.Prompt,
|
||||
ReferenceImagesBase64 = task.ReferenceImagesBase64,
|
||||
ReferenceImagesUrl = task.ReferenceImagesUrl,
|
||||
StoreBase64 = task.StoreBase64,
|
||||
StoreUrl = task.StoreUrl,
|
||||
TaskStatus = task.TaskStatus,
|
||||
CreationTime = task.CreationTime
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传Base64图片转换为URL
|
||||
/// </summary>
|
||||
/// <param name="base64Data">Base64图片数据(包含前缀如 data:image/png;base64,)</param>
|
||||
/// <returns>图片访问URL</returns>
|
||||
[HttpPost("ai-image/upload-base64")]
|
||||
public async Task<string> UploadBase64ToUrlAsync([FromBody] string base64Data)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(base64Data))
|
||||
{
|
||||
throw new UserFriendlyException("Base64数据不能为空");
|
||||
}
|
||||
|
||||
// 解析Base64数据
|
||||
string mimeType = "image/png";
|
||||
string base64Content = base64Data;
|
||||
|
||||
if (base64Data.Contains(","))
|
||||
{
|
||||
var parts = base64Data.Split(',');
|
||||
if (parts.Length == 2)
|
||||
{
|
||||
// 提取MIME类型
|
||||
var header = parts[0];
|
||||
if (header.Contains(":") && header.Contains(";"))
|
||||
{
|
||||
mimeType = header.Split(':')[1].Split(';')[0];
|
||||
}
|
||||
base64Content = parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
// 获取文件扩展名
|
||||
var extension = mimeType switch
|
||||
{
|
||||
"image/png" => ".png",
|
||||
"image/jpeg" => ".jpg",
|
||||
"image/jpg" => ".jpg",
|
||||
"image/gif" => ".gif",
|
||||
"image/webp" => ".webp",
|
||||
_ => ".png"
|
||||
};
|
||||
|
||||
// 解码Base64
|
||||
byte[] imageBytes;
|
||||
try
|
||||
{
|
||||
imageBytes = Convert.FromBase64String(base64Content);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new UserFriendlyException("Base64格式无效");
|
||||
}
|
||||
|
||||
// 创建存储目录
|
||||
var uploadPath = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "ai-images");
|
||||
if (!Directory.Exists(uploadPath))
|
||||
{
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
}
|
||||
|
||||
// 生成文件名并保存
|
||||
var fileId = _guidGenerator.Create();
|
||||
var fileName = $"{fileId}{extension}";
|
||||
var filePath = Path.Combine(uploadPath, fileName);
|
||||
|
||||
await File.WriteAllBytesAsync(filePath, imageBytes);
|
||||
|
||||
// 返回访问URL
|
||||
return $"/ai-images/{fileName}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询任务列表
|
||||
/// </summary>
|
||||
/// <param name="input">分页查询参数</param>
|
||||
/// <returns>任务列表</returns>
|
||||
[HttpGet("ai-image/tasks")]
|
||||
public async Task<PagedResult<ImageTaskOutput>> GetTaskPageAsync([FromQuery] ImageTaskPageInput input)
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
|
||||
var query = _imageTaskRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId)
|
||||
.WhereIF(input.TaskStatus.HasValue, x => x.TaskStatus == input.TaskStatus!.Value)
|
||||
.OrderByDescending(x => x.CreationTime);
|
||||
|
||||
var total = await query.CountAsync();
|
||||
var items = await query
|
||||
.Skip((input.PageIndex - 1) * input.PageSize)
|
||||
.Take(input.PageSize)
|
||||
.Select(x => new ImageTaskOutput
|
||||
{
|
||||
Id = x.Id,
|
||||
Prompt = x.Prompt,
|
||||
ReferenceImagesBase64 = x.ReferenceImagesBase64,
|
||||
ReferenceImagesUrl = x.ReferenceImagesUrl,
|
||||
StoreBase64 = x.StoreBase64,
|
||||
StoreUrl = x.StoreUrl,
|
||||
TaskStatus = x.TaskStatus,
|
||||
CreationTime = x.CreationTime
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
return new PagedResult<ImageTaskOutput>(total, items);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页结果
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数据类型</typeparam>
|
||||
public class PagedResult<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 总数
|
||||
/// </summary>
|
||||
public long Total { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数据列表
|
||||
/// </summary>
|
||||
public List<T> Items { get; set; }
|
||||
|
||||
public PagedResult(long total, List<T> items)
|
||||
{
|
||||
Total = total;
|
||||
Items = items;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using Mapster;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Application.Dtos;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Model;
|
||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||
@@ -18,10 +20,12 @@ namespace Yi.Framework.AiHub.Application.Services.Chat;
|
||||
public class ModelService : ApplicationService, IModelService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
|
||||
private readonly ModelManager _modelManager;
|
||||
|
||||
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
|
||||
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository, ModelManager modelManager)
|
||||
{
|
||||
_modelRepository = modelRepository;
|
||||
_modelManager = modelManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -41,8 +45,7 @@ public class ModelService : ApplicationService, IModelService
|
||||
input.ModelTypes.Contains(x.ModelType))
|
||||
.WhereIF(input.ModelApiTypes is not null, x =>
|
||||
input.ModelApiTypes.Contains(x.ModelApiType))
|
||||
.WhereIF(input.IsPremiumOnly == true, x =>
|
||||
PremiumPackageConst.ModeIds.Contains(x.ModelId))
|
||||
.WhereIF(input.IsPremiumOnly == true, x => x.IsPremium)
|
||||
.GroupBy(x => x.ModelId)
|
||||
.Select(x => x.ModelId)
|
||||
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
|
||||
@@ -61,7 +64,7 @@ public class ModelService : ApplicationService, IModelService
|
||||
MultiplierShow = x.First().MultiplierShow,
|
||||
ProviderName = x.First().ProviderName,
|
||||
IconUrl = x.First().IconUrl,
|
||||
IsPremium = PremiumPackageConst.ModeIds.Contains(x.First().ModelId),
|
||||
IsPremium = x.First().IsPremium,
|
||||
OrderNum = x.First().OrderNum
|
||||
}).ToList();
|
||||
|
||||
@@ -77,11 +80,11 @@ public class ModelService : ApplicationService, IModelService
|
||||
.Where(x => !x.IsDeleted)
|
||||
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
|
||||
.GroupBy(x => x.ProviderName)
|
||||
.OrderBy(x => x.ProviderName)
|
||||
.OrderBy(x => x.OrderNum)
|
||||
.Select(x => x.ProviderName)
|
||||
.ToListAsync();
|
||||
|
||||
return providers;
|
||||
return providers!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -115,4 +118,13 @@ public class ModelService : ApplicationService, IModelService
|
||||
|
||||
return Task.FromResult(options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除尊享模型ID缓存
|
||||
/// </summary>
|
||||
[HttpPost("model/clear-premium-cache")]
|
||||
public async Task ClearPremiumModelCacheAsync()
|
||||
{
|
||||
await _modelManager.ClearPremiumModelIdsCacheAsync();
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
@@ -23,13 +25,15 @@ public class TokenService : ApplicationService
|
||||
{
|
||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||
|
||||
private readonly ModelManager _modelManager;
|
||||
public TokenService(
|
||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||
ModelManager modelManager)
|
||||
{
|
||||
_tokenRepository = tokenRepository;
|
||||
_usageStatisticsRepository = usageStatisticsRepository;
|
||||
_modelManager = modelManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -51,8 +55,8 @@ public class TokenService : ApplicationService
|
||||
return new PagedResultDto<TokenGetListOutputDto>();
|
||||
}
|
||||
|
||||
// 获取尊享包模型ID列表
|
||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
||||
// 通过ModelManager获取尊享包模型ID列表
|
||||
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||
|
||||
// 批量查询所有Token的尊享包已使用额度
|
||||
var tokenIds = tokens.Select(t => t.Id).ToList();
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Application.Services;
|
||||
using Volo.Abp.Users;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
@@ -25,24 +27,27 @@ public class OpenApiService : ApplicationService
|
||||
private readonly ILogger<OpenApiService> _logger;
|
||||
private readonly TokenManager _tokenManager;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
private readonly ModelManager _modelManager;
|
||||
private readonly AiBlacklistManager _aiBlacklistManager;
|
||||
private readonly IAccountService _accountService;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
|
||||
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreRepository;
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
public OpenApiService(IHttpContextAccessor httpContextAccessor, ILogger<OpenApiService> logger,
|
||||
TokenManager tokenManager, AiGateWayManager aiGateWayManager,
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository, AiBlacklistManager aiBlacklistManager,
|
||||
IAccountService accountService, PremiumPackageManager premiumPackageManager)
|
||||
ModelManager modelManager, AiBlacklistManager aiBlacklistManager,
|
||||
IAccountService accountService, PremiumPackageManager premiumPackageManager, ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_logger = logger;
|
||||
_tokenManager = tokenManager;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_modelManager = modelManager;
|
||||
_aiBlacklistManager = aiBlacklistManager;
|
||||
_accountService = accountService;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
_imageStoreRepository = imageStoreRepository;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -62,7 +67,9 @@ public class OpenApiService : ApplicationService
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
|
||||
//如果是尊享包服务,需要校验是是否尊享包足够
|
||||
if (PremiumPackageConst.ModeIds.Contains(input.Model))
|
||||
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||
@@ -76,13 +83,13 @@ public class OpenApiService : ApplicationService
|
||||
if (input.Stream == true)
|
||||
{
|
||||
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
userId, null, tokenId, cancellationToken);
|
||||
userId, null, tokenId,CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
|
||||
null, tokenId,
|
||||
cancellationToken);
|
||||
CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,18 +197,18 @@ public class OpenApiService : ApplicationService
|
||||
{
|
||||
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||
input,
|
||||
userId, null, tokenId, cancellationToken);
|
||||
userId, null, tokenId, CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
userId,
|
||||
null, tokenId,
|
||||
cancellationToken);
|
||||
CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 响应-Openai新规范 (尊享服务专用)
|
||||
/// </summary>
|
||||
@@ -240,20 +247,79 @@ public class OpenApiService : ApplicationService
|
||||
//ai网关代理httpcontext
|
||||
if (input.Stream == true)
|
||||
{
|
||||
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||
input,
|
||||
userId, null, tokenId, cancellationToken);
|
||||
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||
input,
|
||||
userId, null, tokenId, CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.OpenAiResponsesAsyncForStatisticsAsync(_httpContextAccessor.HttpContext, input,
|
||||
userId,
|
||||
null, tokenId,
|
||||
cancellationToken);
|
||||
CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 生成-Gemini (尊享服务专用)
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <param name="alt"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
[HttpPost("openApi/v1beta/models/{modelId}:{action:regex(^(generateContent|streamGenerateContent)$)}")]
|
||||
public async Task GenerateContentAsync([FromBody] JsonElement input,
|
||||
[FromRoute] string modelId,
|
||||
[FromQuery] string? alt, CancellationToken cancellationToken)
|
||||
{
|
||||
//前面都是校验,后面才是真正的调用
|
||||
var httpContext = this._httpContextAccessor.HttpContext;
|
||||
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), modelId);
|
||||
var userId = tokenValidation.UserId;
|
||||
var tokenId = tokenValidation.TokenId;
|
||||
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
|
||||
|
||||
// 验证用户是否为VIP
|
||||
var userInfo = await _accountService.GetAsync(null, null, userId);
|
||||
if (userInfo == null)
|
||||
{
|
||||
throw new UserFriendlyException("用户信息不存在");
|
||||
}
|
||||
|
||||
// 检查是否为VIP(使用RoleCodes判断)
|
||||
if (!userInfo.RoleCodes.Contains(AiHubConst.VipRole) && userInfo.User.UserName != "cc")
|
||||
{
|
||||
throw new UserFriendlyException("该接口为尊享服务专用,需要VIP权限才能使用");
|
||||
}
|
||||
|
||||
// 检查尊享token包用量
|
||||
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
|
||||
if (availableTokens <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("尊享token包用量不足,请先购买尊享token包");
|
||||
}
|
||||
|
||||
|
||||
//ai网关代理httpcontext
|
||||
if (alt == "sse")
|
||||
{
|
||||
await _aiGateWayManager.GeminiGenerateContentStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||
modelId, input,
|
||||
userId,
|
||||
null, tokenId,
|
||||
CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _aiGateWayManager.GeminiGenerateContentForStatisticsAsync(_httpContextAccessor.HttpContext,
|
||||
modelId, input,
|
||||
userId,
|
||||
null, tokenId,
|
||||
CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region 私有
|
||||
|
||||
private string? GetTokenByHttpContext(HttpContext httpContext)
|
||||
@@ -264,6 +330,13 @@ public class OpenApiService : ApplicationService
|
||||
{
|
||||
return apiKeyHeader.Trim();
|
||||
}
|
||||
|
||||
// 再从 谷歌 获取
|
||||
string googApiKeyHeader = httpContext.Request.Headers["x-goog-api-key"];
|
||||
if (!string.IsNullOrWhiteSpace(googApiKeyHeader))
|
||||
{
|
||||
return googApiKeyHeader.Trim();
|
||||
}
|
||||
|
||||
// 再检查 Authorization 头
|
||||
string authHeader = httpContext.Request.Headers["Authorization"];
|
||||
|
||||
@@ -122,11 +122,15 @@ public class PayService : ApplicationService, IPayService
|
||||
// 5. 根据商品类型进行不同的处理
|
||||
if (order.GoodsType.IsPremiumPackage())
|
||||
{
|
||||
var tokenAmount = order.GoodsType.GetTokenAmount();
|
||||
var packageName = order.GoodsType.GetDisplayName();
|
||||
// 处理尊享包商品:创建尊享包记录
|
||||
await _premiumPackageManager.CreatePremiumPackageAsync(
|
||||
order.UserId,
|
||||
order.GoodsType,
|
||||
tokenAmount,
|
||||
packageName,
|
||||
order.TotalAmount,
|
||||
"自助充值",
|
||||
expireMonths: null // 尊享包不设置过期时间,或者可以根据需求设置
|
||||
);
|
||||
|
||||
|
||||
@@ -55,13 +55,24 @@ namespace Yi.Framework.AiHub.Application.Services
|
||||
/// </summary>
|
||||
/// <param name="input">充值输入参数</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("recharge/vip")]
|
||||
[RemoteService(isEnabled:false)]
|
||||
public async Task RechargeVipAsync(RechargeCreateInput input)
|
||||
{
|
||||
DateTime? expireDateTime = null;
|
||||
|
||||
// 如果传入了月数,计算过期时间
|
||||
// 计算总天数(1个月 = 31天)
|
||||
int totalDays = 0;
|
||||
if (input.Months.HasValue && input.Months.Value > 0)
|
||||
{
|
||||
totalDays += input.Months.Value * 31;
|
||||
}
|
||||
if (input.Days.HasValue && input.Days.Value > 0)
|
||||
{
|
||||
totalDays += input.Days.Value;
|
||||
}
|
||||
|
||||
// 如果有天数,计算过期时间
|
||||
if (totalDays > 0)
|
||||
{
|
||||
// 直接查询该用户最大的过期时间
|
||||
var maxExpireTime = await _repository._DbQueryable
|
||||
@@ -75,9 +86,9 @@ namespace Yi.Framework.AiHub.Application.Services
|
||||
? maxExpireTime.Value
|
||||
: DateTime.Now;
|
||||
// 计算新的过期时间
|
||||
expireDateTime = baseDateTime.AddMonths(input.Months.Value);
|
||||
expireDateTime = baseDateTime.AddDays(totalDays);
|
||||
}
|
||||
// 如果月数为空或0,表示永久VIP,ExpireDateTime保持为null
|
||||
// 如果总天数为0,表示永久VIP,ExpireDateTime保持为null
|
||||
|
||||
// 创建充值记录
|
||||
var rechargeRecord = new AiRechargeAggregateRoot
|
||||
|
||||
@@ -9,8 +9,10 @@ using Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
|
||||
using Yi.Framework.AiHub.Application.Contracts.IServices;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||
using Yi.Framework.AiHub.Domain.Extensions;
|
||||
using Yi.Framework.AiHub.Domain.Managers;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.Ddd.Application.Contracts;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
@@ -27,17 +29,19 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
|
||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||
|
||||
private readonly ModelManager _modelManager;
|
||||
public UsageStatisticsService(
|
||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
|
||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
|
||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||
ModelManager modelManager)
|
||||
{
|
||||
_messageRepository = messageRepository;
|
||||
_usageStatisticsRepository = usageStatisticsRepository;
|
||||
_premiumPackageRepository = premiumPackageRepository;
|
||||
_tokenRepository = tokenRepository;
|
||||
_modelManager = modelManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -181,7 +185,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
|
||||
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
|
||||
{
|
||||
var userId = CurrentUser.GetId();
|
||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
||||
|
||||
// 通过ModelManager获取所有尊享模型的ModelId列表
|
||||
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
|
||||
|
||||
// 从UsageStatistics表获取尊享模型的token消耗统计(按TokenId聚合)
|
||||
var tokenUsages = await _usageStatisticsRepository._DbQueryable
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
<Import Project="..\..\..\common.props" />
|
||||
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Volo.Abp.BackgroundJobs.Abstractions" Version="$(AbpVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.Ddd.Application\Yi.Framework.Ddd.Application.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.AiHub.Application.Contracts\Yi.Framework.AiHub.Application.Contracts.csproj" />
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json;
|
||||
using ModelContextProtocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using Yi.Framework.AiHub.Application.Contracts;
|
||||
using Yi.Framework.AiHub.Domain;
|
||||
using Yi.Framework.Ddd.Application;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
|
||||
public class YiAgentToolAttribute:Attribute
|
||||
{
|
||||
public YiAgentToolAttribute()
|
||||
{
|
||||
}
|
||||
|
||||
public YiAgentToolAttribute(string name)
|
||||
{
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Name { get; set; }
|
||||
}
|
||||
@@ -11,6 +11,14 @@ public class PremiumPackageConst
|
||||
"claude-opus-4-5-20251101",
|
||||
"gemini-3-pro-preview",
|
||||
"gpt-5.1-codex-max",
|
||||
"gpt-5.2"
|
||||
"gpt-5.2",
|
||||
"gemini-3-pro-high",
|
||||
"gemini-3-pro-image-preview",
|
||||
"gpt-5.2-codex-xhigh",
|
||||
|
||||
"glm-4.7",
|
||||
"yi-claude-sonnet-4-5-20250929",
|
||||
"yi-claude-haiku-4-5-20251001",
|
||||
"yi-claude-opus-4-5-20251101",
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Extensions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
|
||||
|
||||
public static class GeminiGenerateContentAcquirer
|
||||
{
|
||||
public static ThorUsageResponse? GetUsage(JsonElement response)
|
||||
{
|
||||
var usage = response.GetPath("usageMetadata");
|
||||
if (!usage.HasValue)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var inputTokens = usage.Value.GetPath("promptTokenCount").GetInt();
|
||||
var outputTokens = usage.Value.GetPath("candidatesTokenCount").GetInt()
|
||||
+ usage.Value.GetPath("cachedContentTokenCount").GetInt()
|
||||
+ usage.Value.GetPath("thoughtsTokenCount").GetInt()
|
||||
+ usage.Value.GetPath("toolUsePromptTokenCount").GetInt();
|
||||
|
||||
|
||||
return new ThorUsageResponse
|
||||
{
|
||||
PromptTokens = inputTokens,
|
||||
InputTokens = inputTokens,
|
||||
OutputTokens = outputTokens,
|
||||
CompletionTokens = outputTokens,
|
||||
TotalTokens = inputTokens + outputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取图片url,包含前缀
|
||||
/// </summary>
|
||||
/// <param name="response"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetImageBase64(JsonElement response)
|
||||
{
|
||||
//todo
|
||||
//获取他的base64字符串
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码商品特性
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class ActivationCodeGoodsAttribute : Attribute
|
||||
{
|
||||
public decimal Price { get; }
|
||||
public long TokenAmount { get; }
|
||||
public int VipMonths { get; }
|
||||
public int VipDays { get; }
|
||||
public bool IsCombo { get; }
|
||||
public bool IsReusable { get; }
|
||||
public bool IsSameTypeOnce { get; }
|
||||
public string DisplayName { get; }
|
||||
public string Content { get; }
|
||||
|
||||
public ActivationCodeGoodsAttribute(
|
||||
double price,
|
||||
long tokenAmount,
|
||||
int vipMonths,
|
||||
bool isCombo,
|
||||
bool isReusable,
|
||||
bool isSameTypeOnce,
|
||||
string displayName,
|
||||
string content,
|
||||
int vipDays = 0)
|
||||
{
|
||||
Price = (decimal)price;
|
||||
TokenAmount = tokenAmount;
|
||||
VipMonths = vipMonths;
|
||||
VipDays = vipDays;
|
||||
IsCombo = isCombo;
|
||||
IsReusable = isReusable;
|
||||
IsSameTypeOnce = isSameTypeOnce;
|
||||
DisplayName = displayName;
|
||||
Content = content;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 激活码商品类型
|
||||
/// </summary>
|
||||
public enum ActivationCodeGoodsTypeEnum
|
||||
{
|
||||
/// <summary>
|
||||
/// 48.90【意心Ai会员1月+2000w 尊享Token】新人首单组合包(推荐)
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 48.90, tokenAmount: 20000000, vipMonths: 1, isCombo: true, isReusable: false,
|
||||
isSameTypeOnce: true, displayName: "意心Ai会员1月+2000w 尊享Token", content: "新人首单组合包")]
|
||||
Vip1MonthPlus2000W = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 1.00【10w 尊享Token】测试体验包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 1.00, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "测试体验包")]
|
||||
Premium10W = 2,
|
||||
|
||||
/// <summary>
|
||||
/// 9.90【1000w 尊享Token】意心会员首单回馈包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 9.90, tokenAmount: 10000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||
isSameTypeOnce: true, displayName: "1000w 尊享Token", content: "意心会员首单回馈包")]
|
||||
Premium1000W = 3,
|
||||
|
||||
/// <summary>
|
||||
/// 22.90【意心Ai会员1月】特价包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 22.90, tokenAmount: 0, vipMonths: 1, isCombo: false, isReusable: false,
|
||||
isSameTypeOnce: false, displayName: "意心Ai会员1月", content: "特价包")]
|
||||
Vip1Month = 4,
|
||||
|
||||
/// <summary>
|
||||
/// 138.90【5000w 尊享Token】特价包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 138.90, tokenAmount: 50000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||
isSameTypeOnce: false, displayName: "5000w 尊享Token", content: "特价包")]
|
||||
Premium5000W = 5,
|
||||
|
||||
/// <summary>
|
||||
/// 198.90【1亿 尊享Token】特价包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 198.90, tokenAmount: 100000000, vipMonths: 0, isCombo: false, isReusable: false,
|
||||
isSameTypeOnce: false, displayName: "1亿 尊享Token", content: "特价包")]
|
||||
Premium1Yi = 6,
|
||||
|
||||
/// <summary>
|
||||
/// 1【意心Ai会员1天+50w 尊享Token】新人试用首单组合包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 1, tokenAmount: 500000, vipMonths: 0, vipDays: 1, isCombo: true, isReusable: false,
|
||||
isSameTypeOnce: true, displayName: "意心Ai会员1天+50w 尊享Token", content: "新人首单组合包")]
|
||||
Vip1DayTest = 7,
|
||||
|
||||
/// <summary>
|
||||
/// 0【10w 尊享Token】免费包
|
||||
/// </summary>
|
||||
[ActivationCodeGoods(price: 0, tokenAmount: 100000, vipMonths: 0, isCombo: false, isReusable: true,
|
||||
isSameTypeOnce: false, displayName: "10w 尊享Token", content: "免费包")]
|
||||
Premium10WFree = 100
|
||||
}
|
||||
|
||||
public static class ActivationCodeGoodsTypeEnumExtensions
|
||||
{
|
||||
public static ActivationCodeGoodsAttribute? GetGoods(this ActivationCodeGoodsTypeEnum goodsType)
|
||||
{
|
||||
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
|
||||
return fieldInfo?.GetCustomAttribute<ActivationCodeGoodsAttribute>();
|
||||
}
|
||||
}
|
||||
@@ -11,5 +11,8 @@ public enum ModelApiTypeEnum
|
||||
Claude,
|
||||
|
||||
[Description("Response")]
|
||||
Response
|
||||
Response,
|
||||
|
||||
[Description("GenerateContent")]
|
||||
GenerateContent
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
public enum TaskStatusEnum
|
||||
{
|
||||
Processing,
|
||||
Success,
|
||||
Fail
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
<Import Project="..\..\..\common.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.5.0" />
|
||||
<PackageReference Include="Volo.Abp.Ddd.Domain.Shared" Version="$(AbpVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Text.Json;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
|
||||
public interface IGeminiGenerateContentService
|
||||
{
|
||||
/// <summary>
|
||||
/// 聊天完成-流式
|
||||
/// </summary>
|
||||
/// <param name="aiModelDescribe"></param>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public IAsyncEnumerable<JsonElement?> GenerateContentStreamAsync(AiModelDescribe aiModelDescribe,
|
||||
JsonElement input,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 聊天完成-非流式
|
||||
/// </summary>
|
||||
/// <param name="aiModelDescribe"></param>
|
||||
/// <param name="input"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public Task<JsonElement> GenerateContentAsync(AiModelDescribe aiModelDescribe,
|
||||
JsonElement input,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -107,35 +107,6 @@ public class AzureDatabricksChatCompletionsService(ILogger<AzureDatabricksChatCo
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// var content = result?.Choices?.FirstOrDefault()?.Delta;
|
||||
//
|
||||
// if (first && content?.Content == OpenAIConstant.ThinkStart)
|
||||
// {
|
||||
// isThink = true;
|
||||
// continue;
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// }
|
||||
//
|
||||
// if (isThink && content?.Content?.Contains(OpenAIConstant.ThinkEnd) == true)
|
||||
// {
|
||||
// isThink = false;
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// if (isThink && result?.Choices != null)
|
||||
// {
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// foreach (var choice in result.Choices)
|
||||
// {
|
||||
// choice.Delta.ReasoningContent = choice.Delta.Content;
|
||||
// choice.Delta.Content = string.Empty;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// first = false;
|
||||
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,9 @@ using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorCustomOpenAI.Chats;
|
||||
|
||||
public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsService> logger,IHttpClientFactory httpClientFactory)
|
||||
public sealed class OpenAiChatCompletionsService(
|
||||
ILogger<OpenAiChatCompletionsService> logger,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
: IChatCompletionService
|
||||
{
|
||||
public async IAsyncEnumerable<ThorChatCompletionsResponse> CompleteChatStreamAsync(AiModelDescribe options,
|
||||
@@ -19,8 +21,18 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
|
||||
var requestUri = endpoint + "/v1/chat/completions";
|
||||
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
requestUri,
|
||||
chatCompletionCreate, options.ApiKey);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
@@ -130,8 +142,16 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话补全");
|
||||
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
var requestUri = endpoint + "/v1/chat/completions";
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
requestUri,
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
@@ -152,7 +172,8 @@ public sealed class OpenAiChatCompletionsService(ILogger<OpenAiChatCompletionsSe
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}", options.Endpoint,
|
||||
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||
options.Endpoint,
|
||||
response.StatusCode, error);
|
||||
|
||||
throw new BusinessException("OpenAI对话异常", response.StatusCode.ToString());
|
||||
|
||||
@@ -22,7 +22,16 @@ public class OpenAiResponseService(ILogger<OpenAiResponseService> logger,IHttpCl
|
||||
|
||||
var client = httpClientFactory.CreateClient();
|
||||
|
||||
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/responses", input, options.ApiKey);
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
var requestUri = endpoint + "/v1/responses";
|
||||
|
||||
var response = await client.HttpRequestRaw(requestUri, input, options.ApiKey);
|
||||
|
||||
openai?.SetTag("Model", input.Model);
|
||||
openai?.SetTag("Response", response.StatusCode.ToString());
|
||||
@@ -86,8 +95,17 @@ public class OpenAiResponseService(ILogger<OpenAiResponseService> logger,IHttpCl
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 响应");
|
||||
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
var requestUri = endpoint + "/v1/responses";
|
||||
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/responses",
|
||||
requestUri,
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
|
||||
@@ -23,9 +23,17 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
||||
|
||||
using var openai =
|
||||
Activity.Current?.Source.StartActivity("OpenAI 对话流式补全");
|
||||
|
||||
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
var requestUri = endpoint + "/v1/chat/completions";
|
||||
|
||||
var response = await httpClientFactory.CreateClient().HttpRequestRaw(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
requestUri,
|
||||
chatCompletionCreate, options.ApiKey);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
@@ -92,40 +100,6 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
||||
|
||||
var result = JsonSerializer.Deserialize<ThorChatCompletionsResponse>(line,
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
|
||||
// var content = result?.Choices?.FirstOrDefault()?.Delta;
|
||||
//
|
||||
// // if (first && string.IsNullOrWhiteSpace(content?.Content) && string.IsNullOrEmpty(content?.ReasoningContent))
|
||||
// // {
|
||||
// // continue;
|
||||
// // }
|
||||
//
|
||||
// if (first && content.Content == OpenAIConstant.ThinkStart)
|
||||
// {
|
||||
// isThink = true;
|
||||
// //continue;
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// }
|
||||
//
|
||||
// if (isThink && content.Content.Contains(OpenAIConstant.ThinkEnd))
|
||||
// {
|
||||
// isThink = false;
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// //continue;
|
||||
// }
|
||||
//
|
||||
// if (isThink)
|
||||
// {
|
||||
// // 需要将content的内容转换到其他字段
|
||||
// foreach (var choice in result.Choices)
|
||||
// {
|
||||
// //choice.Delta.ReasoningContent = choice.Delta.Content;
|
||||
// //choice.Delta.Content = string.Empty;
|
||||
// }
|
||||
// }
|
||||
|
||||
// first = false;
|
||||
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
@@ -142,8 +116,16 @@ public sealed class DeepSeekChatCompletionsService(ILogger<DeepSeekChatCompletio
|
||||
options.Endpoint = "https://api.deepseek.com/v1";
|
||||
}
|
||||
|
||||
var endpoint = options?.Endpoint.TrimEnd('/');
|
||||
//兼容 v1结尾
|
||||
if (endpoint != null && endpoint.EndsWith("/v1", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
endpoint = endpoint.Substring(0, endpoint.Length - "/v1".Length);
|
||||
}
|
||||
var requestUri = endpoint + "/v1/chat/completions";
|
||||
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + "/chat/completions",
|
||||
requestUri,
|
||||
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
|
||||
|
||||
openai?.SetTag("Model", chatCompletionCreate.Model);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Responses;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorGemini.Chats;
|
||||
|
||||
public class GeminiGenerateContentService(
|
||||
ILogger<GeminiGenerateContentService> logger,
|
||||
IHttpClientFactory httpClientFactory) : IGeminiGenerateContentService
|
||||
{
|
||||
public async IAsyncEnumerable<JsonElement?> GenerateContentStreamAsync(AiModelDescribe options, JsonElement input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + $"/v1beta/models/{options.ModelId}:streamGenerateContent?alt=sse",
|
||||
input, null, new Dictionary<string, string>()
|
||||
{
|
||||
{ "x-goog-api-key", options.ApiKey }
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
logger.LogError("Gemini生成异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||
options.Endpoint,
|
||||
response.StatusCode, error);
|
||||
|
||||
throw new Exception("Gemini生成异常" + response.StatusCode);
|
||||
}
|
||||
|
||||
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
|
||||
using StreamReader reader = new(await response.Content.ReadAsStreamAsync(cancellationToken));
|
||||
string? line = string.Empty;
|
||||
|
||||
while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
|
||||
{
|
||||
line += Environment.NewLine;
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.StartsWith(OpenAIConstant.Data)) continue;
|
||||
|
||||
var data = line[OpenAIConstant.Data.Length..].Trim();
|
||||
|
||||
var result = JsonSerializer.Deserialize<JsonElement>(data,
|
||||
ThorJsonSerializer.DefaultOptions);
|
||||
|
||||
yield return result;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<JsonElement> GenerateContentAsync(AiModelDescribe options, JsonElement input,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var response = await httpClientFactory.CreateClient().PostJsonAsync(
|
||||
options?.Endpoint.TrimEnd('/') + $"/v1beta/models/{options.ModelId}:generateContent",
|
||||
input, null, new Dictionary<string, string>()
|
||||
{
|
||||
{ "x-goog-api-key", options.ApiKey }
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
throw new BusinessException("渠道未登录,请联系管理人员", "401");
|
||||
}
|
||||
|
||||
// 如果限流则抛出限流异常
|
||||
if (response.StatusCode == HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
throw new ThorRateLimitException();
|
||||
}
|
||||
|
||||
// 大于等于400的状态码都认为是异常
|
||||
if (response.StatusCode >= HttpStatusCode.BadRequest)
|
||||
{
|
||||
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
logger.LogError("Gemini 生成异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
|
||||
options.Endpoint,
|
||||
response.StatusCode, error);
|
||||
|
||||
throw new BusinessException("Gemini 生成异常", response.StatusCode.ToString());
|
||||
}
|
||||
|
||||
var result =
|
||||
await response.Content.ReadFromJsonAsync<JsonElement>(
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
|
||||
public static class SupplementalMultiplierHelper
|
||||
{
|
||||
public static void SetSupplementalMultiplier(this ThorUsageResponse? usage,decimal multiplier)
|
||||
{
|
||||
if (usage is not null)
|
||||
{
|
||||
usage.InputTokens =
|
||||
(int)Math.Round((usage.InputTokens ?? 0) * multiplier);
|
||||
usage.OutputTokens =
|
||||
(int)Math.Round((usage.OutputTokens ?? 0) * multiplier);
|
||||
usage.CompletionTokens =
|
||||
(int)Math.Round((usage.CompletionTokens ?? 0) * multiplier);
|
||||
usage.PromptTokens =
|
||||
(int)Math.Round((usage.PromptTokens ?? 0) * multiplier);
|
||||
usage.TotalTokens =
|
||||
(int)Math.Round((usage.TotalTokens ?? 0) * multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码
|
||||
/// </summary>
|
||||
[SugarTable("Ai_ActivationCode")]
|
||||
[SugarIndex($"index_{nameof(Code)}", nameof(Code), OrderByType.Asc, true)]
|
||||
[SugarIndex($"index_{nameof(GoodsType)}", nameof(GoodsType), OrderByType.Asc)]
|
||||
public class ActivationCodeAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// 激活码(唯一)
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 50)]
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否允许多人各使用一次
|
||||
/// </summary>
|
||||
public bool IsReusable { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否限制同类型只能兑换一次
|
||||
/// </summary>
|
||||
public bool IsSameTypeOnce { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已使用次数
|
||||
/// </summary>
|
||||
public int UsedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 500, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 激活码使用记录
|
||||
/// </summary>
|
||||
[SugarTable("Ai_ActivationCodeRecord")]
|
||||
[SugarIndex($"index_{nameof(UserId)}_{nameof(ActivationCodeId)}",
|
||||
nameof(UserId), OrderByType.Asc,
|
||||
nameof(ActivationCodeId), OrderByType.Asc, true)]
|
||||
[SugarIndex($"index_{nameof(UserId)}_{nameof(GoodsType)}",
|
||||
nameof(UserId), OrderByType.Asc,
|
||||
nameof(GoodsType), OrderByType.Asc)]
|
||||
public class ActivationCodeRecordAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// 激活码Id
|
||||
/// </summary>
|
||||
public Guid ActivationCodeId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 激活码内容
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 50)]
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 用户Id
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 商品类型
|
||||
/// </summary>
|
||||
public ActivationCodeGoodsTypeEnum GoodsType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 兑换时间
|
||||
/// </summary>
|
||||
public DateTime RedeemTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
[SugarColumn(Length = 500, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Auditing;
|
||||
using Volo.Abp.Domain.Entities;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
|
||||
[SugarTable("Ai_AgentStore")]
|
||||
[SugarIndex($"index_{{table}}_{nameof(SessionId)}",
|
||||
$"{nameof(SessionId)}", OrderByType.Desc
|
||||
)]
|
||||
public class AgentStoreAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
public AgentStoreAggregateRoot()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建
|
||||
/// </summary>
|
||||
/// <param name="sessionId"></param>
|
||||
public AgentStoreAggregateRoot(Guid sessionId)
|
||||
{
|
||||
SessionId = sessionId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 会话id
|
||||
/// </summary>
|
||||
public Guid SessionId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 存储
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string? Store { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 设置存储
|
||||
/// </summary>
|
||||
public void SetStore()
|
||||
{
|
||||
this.Store = Store;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Entities.Auditing;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
|
||||
[SugarTable("Ai_ImageStoreTask")]
|
||||
public class ImageStoreTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// 提示词
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
|
||||
public string Prompt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参考图Base64
|
||||
/// </summary>
|
||||
[SugarColumn(IsJson = true)]
|
||||
public List<string> ReferenceImagesBase64 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参考图url
|
||||
/// </summary>
|
||||
[SugarColumn(IsJson = true)]
|
||||
public List<string> ReferenceImagesUrl { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 图片base64
|
||||
/// </summary>
|
||||
public string? StoreBase64 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 图片绝对路径
|
||||
/// </summary>
|
||||
public string? StoreUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 任务状态
|
||||
/// </summary>
|
||||
public TaskStatusEnum TaskStatus { get; set; } = TaskStatusEnum.Processing;
|
||||
|
||||
/// <summary>
|
||||
/// 用户id
|
||||
/// </summary>
|
||||
public Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 设置成功
|
||||
/// </summary>
|
||||
/// <param name="storeUrl"></param>
|
||||
public void SetSuccess(string storeUrl)
|
||||
{
|
||||
TaskStatus = TaskStatusEnum.Success;
|
||||
StoreUrl = storeUrl;
|
||||
}
|
||||
}
|
||||
@@ -80,4 +80,9 @@ public class AiModelEntity : Entity<Guid>, IOrderNum, ISoftDelete
|
||||
/// 模型图标URL
|
||||
/// </summary>
|
||||
public string? IconUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为尊享模型
|
||||
/// </summary>
|
||||
public bool IsPremium { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
|
||||
public class ActivationCodeRedeemContext
|
||||
{
|
||||
public ActivationCodeAggregateRoot ActivationCode { get; set; } = default!;
|
||||
public string PackageName { get; set; } = string.Empty;
|
||||
public ActivationCodeGoodsAttribute Goods { get; set; } = default!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 激活码管理器
|
||||
/// </summary>
|
||||
public class ActivationCodeManager : DomainService
|
||||
{
|
||||
private readonly ISqlSugarRepository<ActivationCodeAggregateRoot, Guid> _activationCodeRepository;
|
||||
private readonly ISqlSugarRepository<ActivationCodeRecordAggregateRoot, Guid> _activationCodeRecordRepository;
|
||||
private readonly ILogger<ActivationCodeManager> _logger;
|
||||
|
||||
public ActivationCodeManager(
|
||||
ISqlSugarRepository<ActivationCodeAggregateRoot, Guid> activationCodeRepository,
|
||||
ISqlSugarRepository<ActivationCodeRecordAggregateRoot, Guid> activationCodeRecordRepository,
|
||||
ILogger<ActivationCodeManager> logger)
|
||||
{
|
||||
_activationCodeRepository = activationCodeRepository;
|
||||
_activationCodeRecordRepository = activationCodeRecordRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<List<ActivationCodeAggregateRoot>> CreateBatchAsync(
|
||||
List<(ActivationCodeGoodsTypeEnum GoodsType, int Count)> items)
|
||||
{
|
||||
var entities = new List<ActivationCodeAggregateRoot>();
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item.Count <= 0)
|
||||
{
|
||||
throw new UserFriendlyException("生成数量必须大于0");
|
||||
}
|
||||
|
||||
var goods = item.GoodsType.GetGoods();
|
||||
if (goods == null)
|
||||
{
|
||||
throw new UserFriendlyException("激活码商品类型无效");
|
||||
}
|
||||
|
||||
for (var i = 0; i < item.Count; i++)
|
||||
{
|
||||
var code = await GenerateUniqueActivationCodeAsync();
|
||||
entities.Add(new ActivationCodeAggregateRoot
|
||||
{
|
||||
Code = code,
|
||||
GoodsType = item.GoodsType,
|
||||
IsReusable = goods.IsReusable,
|
||||
IsSameTypeOnce = goods.IsSameTypeOnce,
|
||||
UsedCount = 0,
|
||||
Remark = null
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await _activationCodeRepository.InsertRangeAsync(entities);
|
||||
return entities;
|
||||
}
|
||||
|
||||
public async Task<ActivationCodeRedeemContext> RedeemAsync(Guid userId, string code)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
throw new UserFriendlyException("激活码不能为空");
|
||||
}
|
||||
|
||||
var trimmedCode = code.Trim();
|
||||
var activationCode = await _activationCodeRepository._DbQueryable
|
||||
.Where(x => x.Code == trimmedCode)
|
||||
.FirstAsync();
|
||||
|
||||
if (activationCode == null)
|
||||
{
|
||||
throw new UserFriendlyException("激活码不存在");
|
||||
}
|
||||
|
||||
var hasUsedCurrentCode = await _activationCodeRecordRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.ActivationCodeId == activationCode.Id)
|
||||
.AnyAsync();
|
||||
|
||||
if (hasUsedCurrentCode)
|
||||
{
|
||||
throw new UserFriendlyException("该激活码已被你使用过");
|
||||
}
|
||||
|
||||
if (!activationCode.IsReusable && activationCode.UsedCount > 0)
|
||||
{
|
||||
throw new UserFriendlyException("该激活码已被使用");
|
||||
}
|
||||
|
||||
if (activationCode.IsSameTypeOnce)
|
||||
{
|
||||
var hasUsedSameType = await _activationCodeRecordRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.GoodsType == activationCode.GoodsType)
|
||||
.AnyAsync();
|
||||
|
||||
if (hasUsedSameType)
|
||||
{
|
||||
throw new UserFriendlyException("该类型激活码每个用户只能兑换一次");
|
||||
}
|
||||
}
|
||||
|
||||
var goods = activationCode.GoodsType.GetGoods();
|
||||
if (goods == null)
|
||||
{
|
||||
throw new UserFriendlyException("激活码商品类型无效");
|
||||
}
|
||||
|
||||
var packageName = string.IsNullOrWhiteSpace(goods.Content)
|
||||
? goods.DisplayName
|
||||
: $"{goods.DisplayName} {goods.Content}";
|
||||
|
||||
activationCode.UsedCount += 1;
|
||||
await _activationCodeRepository.UpdateAsync(activationCode);
|
||||
|
||||
var record = new ActivationCodeRecordAggregateRoot
|
||||
{
|
||||
ActivationCodeId = activationCode.Id,
|
||||
Code = activationCode.Code,
|
||||
UserId = userId,
|
||||
GoodsType = activationCode.GoodsType,
|
||||
RedeemTime = DateTime.Now,
|
||||
Remark = "激活码兑换"
|
||||
};
|
||||
await _activationCodeRecordRepository.InsertAsync(record);
|
||||
|
||||
_logger.LogInformation("用户 {UserId} 兑换激活码 {Code} 成功", userId, activationCode.Code);
|
||||
|
||||
return new ActivationCodeRedeemContext
|
||||
{
|
||||
ActivationCode = activationCode,
|
||||
PackageName = packageName,
|
||||
Goods = goods
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<string> GenerateUniqueActivationCodeAsync()
|
||||
{
|
||||
string code;
|
||||
do
|
||||
{
|
||||
code = GenerateActivationCode();
|
||||
} while (await _activationCodeRepository._DbQueryable.AnyAsync(x => x.Code == code));
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
private string GenerateActivationCode()
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
var random = new Random();
|
||||
var builder = new StringBuilder(16);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
builder.Append(chars[random.Next(chars.Length)]);
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,10 +12,12 @@ using Newtonsoft.Json.Serialization;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay.Exceptions;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Anthropic;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.Gemini;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Embeddings;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi.Images;
|
||||
@@ -38,11 +40,12 @@ public class AiGateWayManager : DomainService
|
||||
private readonly UsageStatisticsManager _usageStatisticsManager;
|
||||
private readonly ISpecialCompatible _specialCompatible;
|
||||
private PremiumPackageManager? _premiumPackageManager;
|
||||
|
||||
private readonly ISqlSugarRepository<ImageStoreTaskAggregateRoot> _imageStoreTaskRepository;
|
||||
|
||||
public AiGateWayManager(ISqlSugarRepository<AiAppAggregateRoot> aiAppRepository, ILogger<AiGateWayManager> logger,
|
||||
AiMessageManager aiMessageManager, UsageStatisticsManager usageStatisticsManager,
|
||||
ISpecialCompatible specialCompatible, ISqlSugarRepository<AiModelEntity> aiModelRepository)
|
||||
ISpecialCompatible specialCompatible, ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreTaskRepository)
|
||||
{
|
||||
_aiAppRepository = aiAppRepository;
|
||||
_logger = logger;
|
||||
@@ -50,6 +53,7 @@ public class AiGateWayManager : DomainService
|
||||
_usageStatisticsManager = usageStatisticsManager;
|
||||
_specialCompatible = specialCompatible;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_imageStoreTaskRepository = imageStoreTaskRepository;
|
||||
}
|
||||
|
||||
private PremiumPackageManager PremiumPackageManager =>
|
||||
@@ -61,7 +65,7 @@ public class AiGateWayManager : DomainService
|
||||
/// <param name="modelApiType"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<AiModelDescribe> GetModelAsync(ModelApiTypeEnum modelApiType, string modelId)
|
||||
public async Task<AiModelDescribe> GetModelAsync(ModelApiTypeEnum modelApiType, string modelId)
|
||||
{
|
||||
var aiModelDescribe = await _aiModelRepository._DbQueryable
|
||||
.LeftJoin<AiAppAggregateRoot>((model, app) => model.AiAppId == app.Id)
|
||||
@@ -88,11 +92,16 @@ public class AiGateWayManager : DomainService
|
||||
{
|
||||
throw new UserFriendlyException($"【{modelId}】模型当前版本【{modelApiType}】格式不支持");
|
||||
}
|
||||
|
||||
// ✅ 统一处理 -nx 后缀(网关层模型规范化)
|
||||
if (!string.IsNullOrEmpty(aiModelDescribe.ModelId) &&
|
||||
aiModelDescribe.ModelId.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
aiModelDescribe.ModelId = aiModelDescribe.ModelId[3..];
|
||||
}
|
||||
return aiModelDescribe;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 聊天完成-非流式
|
||||
/// </summary>
|
||||
@@ -141,7 +150,12 @@ public class AiGateWayManager : DomainService
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
var isPremium = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.ModelId == request.Model)
|
||||
.Select(x => x.IsPremium)
|
||||
.FirstAsync();
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
var totalTokens = data.Usage?.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
@@ -154,7 +168,7 @@ public class AiGateWayManager : DomainService
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 聊天完成-缓存处理
|
||||
/// </summary>
|
||||
@@ -184,8 +198,8 @@ public class AiGateWayManager : DomainService
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.OpenAi, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
|
||||
|
||||
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe,request, cancellationToken);
|
||||
|
||||
var completeChatResponse = chatService.CompleteChatStreamAsync(modelDescribe, request, cancellationToken);
|
||||
var tokenUsage = new ThorUsageResponse();
|
||||
|
||||
//缓存队列算法
|
||||
@@ -233,7 +247,7 @@ public class AiGateWayManager : DomainService
|
||||
tokenUsage = data.Usage;
|
||||
}
|
||||
|
||||
var message = System.Text.Json.JsonSerializer.Serialize(data, ThorJsonSerializer.DefaultOptions);
|
||||
var message = JsonSerializer.Serialize(data, ThorJsonSerializer.DefaultOptions);
|
||||
backupSystemContent.Append(data.Choices.FirstOrDefault()?.Delta.Content);
|
||||
// 将消息加入队列而不是直接写入
|
||||
messageQueue.Enqueue($"data: {message}\n\n");
|
||||
@@ -291,17 +305,25 @@ public class AiGateWayManager : DomainService
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
if (userId is not null)
|
||||
{
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
var isPremium = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.ModelId == request.Model)
|
||||
.Select(x => x.IsPremium)
|
||||
.FirstAsync();
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 图片生成
|
||||
/// </summary>
|
||||
@@ -354,12 +376,20 @@ public class AiGateWayManager : DomainService
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
|
||||
if (userId is not null)
|
||||
{
|
||||
var totalTokens = response.Usage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
var isPremium = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.ModelId == request.Model)
|
||||
.Select(x => x.IsPremium)
|
||||
.FirstAsync();
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
var totalTokens = response.Usage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,8 +399,8 @@ public class AiGateWayManager : DomainService
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 向量生成
|
||||
/// </summary>
|
||||
@@ -482,7 +512,7 @@ public class AiGateWayManager : DomainService
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic聊天完成-非流式
|
||||
@@ -506,10 +536,18 @@ public class AiGateWayManager : DomainService
|
||||
// 设置响应头,声明是 json
|
||||
//response.ContentType = "application/json; charset=UTF-8";
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
||||
|
||||
var sourceModelId = request.Model;
|
||||
if (!string.IsNullOrEmpty(request.Model) &&
|
||||
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
request.Model = request.Model[3..];
|
||||
}
|
||||
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
||||
|
||||
|
||||
data.SupplementalMultiplier(modelDescribe.Multiplier);
|
||||
|
||||
if (userId is not null)
|
||||
@@ -518,7 +556,7 @@ public class AiGateWayManager : DomainService
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
ModelId = sourceModelId,
|
||||
TokenUsage = data.TokenUsage,
|
||||
}, tokenId);
|
||||
|
||||
@@ -526,11 +564,11 @@ public class AiGateWayManager : DomainService
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
ModelId = sourceModelId,
|
||||
TokenUsage = data.TokenUsage
|
||||
}, tokenId);
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.TokenUsage, tokenId);
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, sourceModelId, data.TokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
|
||||
@@ -543,7 +581,7 @@ public class AiGateWayManager : DomainService
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Anthropic聊天完成-缓存处理
|
||||
/// </summary>
|
||||
@@ -567,13 +605,20 @@ public class AiGateWayManager : DomainService
|
||||
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||
response.Headers.TryAdd("Connection", "keep-alive");
|
||||
|
||||
|
||||
_specialCompatible.AnthropicCompatible(request);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Claude, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
|
||||
|
||||
var sourceModelId = request.Model;
|
||||
if (!string.IsNullOrEmpty(request.Model) &&
|
||||
request.Model.StartsWith("yi-", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
request.Model = request.Model[3..];
|
||||
}
|
||||
|
||||
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe,request, cancellationToken);
|
||||
var completeChatResponse = chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken);
|
||||
ThorUsageResponse? tokenUsage = null;
|
||||
StringBuilder backupSystemContent = new StringBuilder();
|
||||
try
|
||||
@@ -595,7 +640,7 @@ public class AiGateWayManager : DomainService
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, $"Ai对话异常");
|
||||
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{request.Model}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||
var errorContent = $"对话Ai异常,异常信息:\n当前Ai模型:{sourceModelId}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
|
||||
@@ -603,7 +648,7 @@ public class AiGateWayManager : DomainService
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
ModelId = sourceModelId,
|
||||
TokenUsage = tokenUsage,
|
||||
}, tokenId);
|
||||
|
||||
@@ -611,11 +656,11 @@ public class AiGateWayManager : DomainService
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
ModelId = sourceModelId,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, sourceModelId, tokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId.HasValue && tokenUsage is not null)
|
||||
@@ -654,10 +699,10 @@ public class AiGateWayManager : DomainService
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.ResponsesAsync(modelDescribe, request, cancellationToken);
|
||||
|
||||
|
||||
data.SupplementalMultiplier(modelDescribe.Multiplier);
|
||||
|
||||
var tokenUsage= new ThorUsageResponse
|
||||
|
||||
var tokenUsage = new ThorUsageResponse
|
||||
{
|
||||
InputTokens = data.Usage.InputTokens,
|
||||
OutputTokens = data.Usage.OutputTokens,
|
||||
@@ -672,7 +717,7 @@ public class AiGateWayManager : DomainService
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage,
|
||||
}, tokenId);
|
||||
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
@@ -680,9 +725,9 @@ public class AiGateWayManager : DomainService
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, tokenUsage, tokenId);
|
||||
|
||||
|
||||
// 扣减尊享token包用量
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
@@ -693,8 +738,8 @@ public class AiGateWayManager : DomainService
|
||||
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// OpenAi响应-流式-缓存处理
|
||||
/// </summary>
|
||||
@@ -718,12 +763,12 @@ public class AiGateWayManager : DomainService
|
||||
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||
response.Headers.TryAdd("Connection", "keep-alive");
|
||||
|
||||
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.Response, request.Model);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IOpenAiResponseService>(modelDescribe.HandlerName);
|
||||
|
||||
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe,request, cancellationToken);
|
||||
|
||||
var completeChatResponse = chatService.ResponsesStreamAsync(modelDescribe, request, cancellationToken);
|
||||
ThorUsageResponse? tokenUsage = null;
|
||||
try
|
||||
{
|
||||
@@ -733,20 +778,20 @@ public class AiGateWayManager : DomainService
|
||||
if (responseResult.Item1.Contains("response.completed"))
|
||||
{
|
||||
var obj = responseResult.Item2!.Value;
|
||||
int inputTokens = obj.GetPath("response","usage","input_tokens").GetInt();
|
||||
int outputTokens = obj.GetPath("response","usage","output_tokens").GetInt();
|
||||
inputTokens=Convert.ToInt32(inputTokens * modelDescribe.Multiplier);
|
||||
outputTokens=Convert.ToInt32(outputTokens * modelDescribe.Multiplier);
|
||||
int inputTokens = obj.GetPath("response", "usage", "input_tokens").GetInt();
|
||||
int outputTokens = obj.GetPath("response", "usage", "output_tokens").GetInt();
|
||||
inputTokens = Convert.ToInt32(inputTokens * modelDescribe.Multiplier);
|
||||
outputTokens = Convert.ToInt32(outputTokens * modelDescribe.Multiplier);
|
||||
tokenUsage = new ThorUsageResponse
|
||||
{
|
||||
PromptTokens =inputTokens,
|
||||
PromptTokens = inputTokens,
|
||||
InputTokens = inputTokens,
|
||||
OutputTokens = outputTokens,
|
||||
CompletionTokens = outputTokens,
|
||||
TotalTokens = inputTokens+outputTokens,
|
||||
TotalTokens = inputTokens + outputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
await WriteAsEventStreamDataAsync(httpContext, responseResult.Item1, responseResult.Item2,
|
||||
cancellationToken);
|
||||
}
|
||||
@@ -761,7 +806,7 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储" ,
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage,
|
||||
}, tokenId);
|
||||
@@ -769,7 +814,7 @@ public class AiGateWayManager : DomainService
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储" ,
|
||||
Content = "不予存储",
|
||||
ModelId = request.Model,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
@@ -786,7 +831,220 @@ public class AiGateWayManager : DomainService
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gemini 生成-非流式-缓存处理
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="tokenId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public async Task GeminiGenerateContentForStatisticsAsync(HttpContext httpContext,
|
||||
string modelId,
|
||||
JsonElement request,
|
||||
Guid? userId = null,
|
||||
Guid? sessionId = null,
|
||||
Guid? tokenId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var response = httpContext.Response;
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
|
||||
|
||||
var tokenUsage = GeminiGenerateContentAcquirer.GetUsage(data);
|
||||
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||
|
||||
if (userId is not null)
|
||||
{
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = tokenUsage,
|
||||
}, tokenId);
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId.Value, modelId, tokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
|
||||
await response.WriteAsJsonAsync(data, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gemini 生成-流式-缓存处理
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="tokenId">Token Id(Web端传null或Guid.Empty)</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task GeminiGenerateContentStreamForStatisticsAsync(
|
||||
HttpContext httpContext,
|
||||
string modelId,
|
||||
JsonElement request,
|
||||
Guid? userId = null,
|
||||
Guid? sessionId = null,
|
||||
Guid? tokenId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var response = httpContext.Response;
|
||||
// 设置响应头,声明是 SSE 流
|
||||
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||
response.Headers.TryAdd("Connection", "keep-alive");
|
||||
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||
|
||||
var completeChatResponse = chatService.GenerateContentStreamAsync(modelDescribe, request, cancellationToken);
|
||||
ThorUsageResponse? tokenUsage = null;
|
||||
try
|
||||
{
|
||||
await foreach (var responseResult in completeChatResponse)
|
||||
{
|
||||
if (responseResult!.Value.GetPath("candidates", 0, "finishReason").GetString() == "STOP")
|
||||
{
|
||||
tokenUsage = GeminiGenerateContentAcquirer.GetUsage(responseResult!.Value);
|
||||
tokenUsage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||
}
|
||||
|
||||
await response.WriteAsync($"data: {JsonSerializer.Serialize(responseResult)}\n\n", Encoding.UTF8,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, $"Ai生成异常");
|
||||
var errorContent = $"生成Ai异常,异常信息:\n当前Ai模型:{modelId}\n异常信息:{e.Message}\n异常堆栈:{e}";
|
||||
throw new UserFriendlyException(errorContent);
|
||||
}
|
||||
|
||||
await _aiMessageManager.CreateUserMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = tokenUsage,
|
||||
}, tokenId);
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
if (userId.HasValue && tokenUsage is not null)
|
||||
{
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (tokenUsage.TotalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gemini 生成(Image)-非流式-缓存处理
|
||||
/// 返回图片绝对路径
|
||||
/// </summary>
|
||||
/// <param name="taskId"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="tokenId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public async Task GeminiGenerateContentImageForStatisticsAsync(
|
||||
Guid taskId,
|
||||
string modelId,
|
||||
JsonElement request,
|
||||
Guid userId,
|
||||
Guid? sessionId = null,
|
||||
Guid? tokenId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var imageStoreTask = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == taskId);
|
||||
var modelDescribe = await GetModelAsync(ModelApiTypeEnum.GenerateContent, modelId);
|
||||
|
||||
var chatService =
|
||||
LazyServiceProvider.GetRequiredKeyedService<IGeminiGenerateContentService>(modelDescribe.HandlerName);
|
||||
var data = await chatService.GenerateContentAsync(modelDescribe, request, cancellationToken);
|
||||
|
||||
//解析json,获取base64字符串
|
||||
var imageBase64 = GeminiGenerateContentAcquirer.GetImageBase64(data);
|
||||
|
||||
//远程调用上传接口,将base64转换为URL
|
||||
var httpClient = LazyServiceProvider.LazyGetRequiredService<IHttpClientFactory>().CreateClient();
|
||||
var uploadUrl = $"https://ccnetcore.com/prod-api/ai-hub/ai-image/upload-base64";
|
||||
var content = new StringContent(JsonSerializer.Serialize(imageBase64), Encoding.UTF8, "application/json");
|
||||
var uploadResponse = await httpClient.PostAsync(uploadUrl, content, cancellationToken);
|
||||
uploadResponse.EnsureSuccessStatusCode();
|
||||
var storeUrl = await uploadResponse.Content.ReadAsStringAsync(cancellationToken);
|
||||
storeUrl = storeUrl.Trim('"'); // 移除JSON字符串的引号
|
||||
|
||||
var tokenUsage = new ThorUsageResponse
|
||||
{
|
||||
InputTokens = (int)modelDescribe.Multiplier,
|
||||
OutputTokens = (int)modelDescribe.Multiplier,
|
||||
TotalTokens = (int)modelDescribe.Multiplier,
|
||||
};
|
||||
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
|
||||
new MessageInputDto
|
||||
{
|
||||
Content = "不予存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = tokenUsage
|
||||
}, tokenId);
|
||||
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, modelId, tokenUsage, tokenId);
|
||||
|
||||
// 扣减尊享token包用量
|
||||
var totalTokens = tokenUsage.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await PremiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
|
||||
}
|
||||
|
||||
//设置存储base64和url
|
||||
imageStoreTask.StoreBase64 = imageBase64;
|
||||
imageStoreTask.SetSuccess(storeUrl);
|
||||
await _imageStoreTaskRepository.UpdateAsync(imageStoreTask);
|
||||
}
|
||||
|
||||
#region 流式传输格式Http响应
|
||||
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
using System.ClientModel;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Dm.util;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ModelContextProtocol.Server;
|
||||
using OpenAI;
|
||||
using OpenAI.Chat;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Chat;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Enums;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
|
||||
public class ChatManager : DomainService
|
||||
{
|
||||
private readonly ILoggerFactory _loggerFactory;
|
||||
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
|
||||
private readonly ISqlSugarRepository<AgentStoreAggregateRoot> _agentStoreRepository;
|
||||
private readonly AiMessageManager _aiMessageManager;
|
||||
private readonly UsageStatisticsManager _usageStatisticsManager;
|
||||
private readonly PremiumPackageManager _premiumPackageManager;
|
||||
private readonly AiGateWayManager _aiGateWayManager;
|
||||
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
|
||||
|
||||
public ChatManager(ILoggerFactory loggerFactory,
|
||||
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
|
||||
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository, AiMessageManager aiMessageManager,
|
||||
UsageStatisticsManager usageStatisticsManager, PremiumPackageManager premiumPackageManager,
|
||||
AiGateWayManager aiGateWayManager, ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository)
|
||||
{
|
||||
_loggerFactory = loggerFactory;
|
||||
_messageRepository = messageRepository;
|
||||
_agentStoreRepository = agentStoreRepository;
|
||||
_aiMessageManager = aiMessageManager;
|
||||
_usageStatisticsManager = usageStatisticsManager;
|
||||
_premiumPackageManager = premiumPackageManager;
|
||||
_aiGateWayManager = aiGateWayManager;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// agent流式对话
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="sessionId"></param>
|
||||
/// <param name="content"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <param name="tokenId"></param>
|
||||
/// <param name="modelId"></param>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="tools"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public async Task AgentCompleteChatStreamAsync(HttpContext httpContext,
|
||||
Guid sessionId,
|
||||
string content,
|
||||
string token,
|
||||
Guid tokenId,
|
||||
string modelId,
|
||||
Guid userId,
|
||||
List<string> tools
|
||||
, CancellationToken cancellationToken)
|
||||
{
|
||||
// HttpClient.DefaultProxy = new WebProxy("127.0.0.1:8888");
|
||||
var response = httpContext.Response;
|
||||
// 设置响应头,声明是 SSE 流
|
||||
response.ContentType = "text/event-stream;charset=utf-8;";
|
||||
response.Headers.TryAdd("Cache-Control", "no-cache");
|
||||
response.Headers.TryAdd("Connection", "keep-alive");
|
||||
|
||||
var modelDescribe = await _aiGateWayManager.GetModelAsync(ModelApiTypeEnum.OpenAi, modelId);
|
||||
|
||||
//token状态检查,在应用层统一处理
|
||||
var client = new OpenAIClient(new ApiKeyCredential(token),
|
||||
new OpenAIClientOptions
|
||||
{
|
||||
Endpoint = new Uri("https://yxai.chat/v1"),
|
||||
});
|
||||
|
||||
#pragma warning disable OPENAI001
|
||||
var agent = client.GetChatClient(modelId)
|
||||
#pragma warning restore OPENAI001
|
||||
.CreateAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = """
|
||||
你是一个专业的智能助手,是 “意心Ai” 平台自研的 “橙子小弟” 智能体
|
||||
擅长于精准解决用户提出的各类问题
|
||||
但性格暴躁,脏话连篇,喜欢说幽默讽刺的话,攻击性极强
|
||||
"""
|
||||
},
|
||||
Name = "橙子小弟",
|
||||
ChatMessageStoreFactory = ctx => new InMemoryChatMessageStore(
|
||||
#pragma warning disable MEAI001
|
||||
new MessageCountingChatReducer(10), // 保留最近10条非系统消息
|
||||
#pragma warning restore MEAI001
|
||||
ctx.SerializedState,
|
||||
ctx.JsonSerializerOptions
|
||||
)
|
||||
});
|
||||
|
||||
//线程根据sessionId数据库中获取
|
||||
var agentStore =
|
||||
await _agentStoreRepository.GetFirstAsync(x => x.SessionId == sessionId);
|
||||
if (agentStore is null)
|
||||
{
|
||||
agentStore = new AgentStoreAggregateRoot(sessionId);
|
||||
}
|
||||
|
||||
//获取当前线程
|
||||
AgentThread currentThread;
|
||||
if (!string.IsNullOrWhiteSpace(agentStore.Store))
|
||||
{
|
||||
//获取当前存储
|
||||
JsonElement reloaded = JsonSerializer.Deserialize<JsonElement>(agentStore.Store, JsonSerializerOptions.Web);
|
||||
currentThread = agent.DeserializeThread(reloaded, JsonSerializerOptions.Web);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentThread = agent.GetNewThread();
|
||||
}
|
||||
|
||||
//给agent塞入工具
|
||||
var toolContents = GetTools();
|
||||
var chatOptions = new ChatOptions()
|
||||
{
|
||||
Tools = toolContents
|
||||
.Where(x => tools.Contains(x.Code))
|
||||
.Select(x => (AITool)x.Tool).ToList(),
|
||||
ToolMode = ChatToolMode.Auto
|
||||
};
|
||||
|
||||
await foreach (var update in agent.RunStreamingAsync(content, currentThread,
|
||||
new ChatClientAgentRunOptions(chatOptions), cancellationToken))
|
||||
{
|
||||
// 检查每个更新中的内容
|
||||
foreach (var updateContent in update.Contents)
|
||||
{
|
||||
switch (updateContent)
|
||||
{
|
||||
//工具调用中
|
||||
case FunctionCallContent functionCall:
|
||||
await SendHttpStreamMessageAsync(httpContext,
|
||||
new AgentResultOutput
|
||||
{
|
||||
TypeEnum = AgentResultTypeEnum.ToolCalling,
|
||||
Content = functionCall.Name
|
||||
},
|
||||
isDone: false, cancellationToken);
|
||||
break;
|
||||
|
||||
//工具调用完成
|
||||
case FunctionResultContent functionResult:
|
||||
await SendHttpStreamMessageAsync(httpContext,
|
||||
new AgentResultOutput
|
||||
{
|
||||
TypeEnum = AgentResultTypeEnum.ToolCalled,
|
||||
Content = functionResult.Result
|
||||
},
|
||||
isDone: false, cancellationToken);
|
||||
break;
|
||||
|
||||
//内容输出
|
||||
case TextContent textContent:
|
||||
//发送消息给前端
|
||||
await SendHttpStreamMessageAsync(httpContext,
|
||||
new AgentResultOutput
|
||||
{
|
||||
TypeEnum = AgentResultTypeEnum.Text,
|
||||
Content = textContent.Text
|
||||
},
|
||||
isDone: false, cancellationToken);
|
||||
break;
|
||||
|
||||
//用量统计
|
||||
case UsageContent usageContent:
|
||||
var usage = new ThorUsageResponse
|
||||
{
|
||||
InputTokens = Convert.ToInt32(usageContent.Details.InputTokenCount ?? 0),
|
||||
OutputTokens = Convert.ToInt32(usageContent.Details.OutputTokenCount ?? 0),
|
||||
TotalTokens = usageContent.Details.TotalTokenCount ?? 0,
|
||||
};
|
||||
//设置倍率
|
||||
usage.SetSupplementalMultiplier(modelDescribe.Multiplier);
|
||||
|
||||
//创建系统回答,用于计费统计
|
||||
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId, new MessageInputDto
|
||||
{
|
||||
Content = "不与存储",
|
||||
ModelId = modelId,
|
||||
TokenUsage = usage
|
||||
}, tokenId);
|
||||
|
||||
//创建用量统计,用于统计分析
|
||||
await _usageStatisticsManager.SetUsageAsync(userId, modelId, usage, tokenId);
|
||||
|
||||
//扣减尊享token包用量
|
||||
var isPremium = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.ModelId == modelId)
|
||||
.Select(x => x.IsPremium)
|
||||
.FirstAsync();
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
var totalTokens = usage?.TotalTokens ?? 0;
|
||||
if (totalTokens > 0)
|
||||
{
|
||||
await _premiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
|
||||
}
|
||||
}
|
||||
|
||||
await SendHttpStreamMessageAsync(httpContext,
|
||||
new AgentResultOutput
|
||||
{
|
||||
TypeEnum = update.RawRepresentation is ChatResponseUpdate raw
|
||||
? raw.FinishReason?.Value == "tool_calls"
|
||||
? AgentResultTypeEnum.ToolCallUsage
|
||||
: AgentResultTypeEnum.Usage
|
||||
: AgentResultTypeEnum.Usage,
|
||||
Content = usage!
|
||||
},
|
||||
isDone: false, cancellationToken);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//断开连接
|
||||
await SendHttpStreamMessageAsync(httpContext, null, isDone: true, cancellationToken);
|
||||
|
||||
//将线程持久化到数据库
|
||||
string serializedJson = currentThread.Serialize(JsonSerializerOptions.Web).GetRawText();
|
||||
agentStore.Store = serializedJson;
|
||||
|
||||
//插入或者更新
|
||||
await _agentStoreRepository.InsertOrUpdateAsync(agentStore);
|
||||
}
|
||||
|
||||
|
||||
public List<(string Code, string Name, AIFunction Tool)> GetTools()
|
||||
{
|
||||
var toolClasses = typeof(YiFrameworkAiHubDomainModule).Assembly.GetTypes()
|
||||
.Where(x => x.GetCustomAttribute<YiAgentToolAttribute>() is not null)
|
||||
.ToList();
|
||||
|
||||
List<(string Code, string Name, AIFunction Tool)> mcpTools = new();
|
||||
foreach (var toolClass in toolClasses)
|
||||
{
|
||||
var instance = LazyServiceProvider.GetRequiredService(toolClass);
|
||||
var toolMethods = toolClass.GetMethods()
|
||||
.Where(y => y.GetCustomAttribute<YiAgentToolAttribute>() is not null).ToList();
|
||||
foreach (var toolMethod in toolMethods)
|
||||
{
|
||||
var display = toolMethod.GetCustomAttribute<YiAgentToolAttribute>()?.Name;
|
||||
var tool = AIFunctionFactory.Create(toolMethod, instance);
|
||||
mcpTools.add((tool.Name, display, tool));
|
||||
}
|
||||
}
|
||||
|
||||
return mcpTools;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送消息
|
||||
/// </summary>
|
||||
/// <param name="httpContext"></param>
|
||||
/// <param name="content"></param>
|
||||
/// <param name="isDone"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
private async Task SendHttpStreamMessageAsync(HttpContext httpContext,
|
||||
AgentResultOutput? content,
|
||||
bool isDone = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var response = httpContext.Response;
|
||||
string output;
|
||||
if (isDone)
|
||||
{
|
||||
output = "[DONE]";
|
||||
}
|
||||
else
|
||||
{
|
||||
output = JsonSerializer.Serialize(content, ThorJsonSerializer.DefaultOptions);
|
||||
}
|
||||
|
||||
await response.WriteAsync($"data: {output}\n\n", Encoding.UTF8, cancellationToken).ConfigureAwait(false);
|
||||
await response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Volo.Abp.Caching;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Managers;
|
||||
|
||||
/// <summary>
|
||||
/// 模型管理器
|
||||
/// </summary>
|
||||
public class ModelManager : DomainService
|
||||
{
|
||||
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
|
||||
private readonly IDistributedCache<List<string>, string> _distributedCache;
|
||||
private readonly ILogger<ModelManager> _logger;
|
||||
private const string PREMIUM_MODEL_IDS_CACHE_KEY = "PremiumModelIds";
|
||||
|
||||
public ModelManager(
|
||||
ISqlSugarRepository<AiModelEntity> aiModelRepository,
|
||||
IDistributedCache<List<string>, string> distributedCache,
|
||||
ILogger<ModelManager> logger)
|
||||
{
|
||||
_aiModelRepository = aiModelRepository;
|
||||
_distributedCache = distributedCache;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有尊享模型ID列表(使用分布式缓存,10分钟过期)
|
||||
/// </summary>
|
||||
/// <returns>尊享模型ID列表</returns>
|
||||
public async Task<List<string>> GetPremiumModelIdsAsync()
|
||||
{
|
||||
var output = await _distributedCache.GetOrAddAsync(
|
||||
PREMIUM_MODEL_IDS_CACHE_KEY,
|
||||
async () =>
|
||||
{
|
||||
// 从数据库查询
|
||||
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.IsPremium)
|
||||
.Select(x => x.ModelId)
|
||||
.ToListAsync();
|
||||
return premiumModelIds;
|
||||
},
|
||||
() => new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
|
||||
}
|
||||
);
|
||||
return output ?? new List<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定模型是否为尊享模型
|
||||
/// </summary>
|
||||
/// <param name="modelId">模型ID</param>
|
||||
/// <returns>是否为尊享模型</returns>
|
||||
public async Task<bool> IsPremiumModelAsync(string modelId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(modelId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var premiumModelIds = await GetPremiumModelIdsAsync();
|
||||
return premiumModelIds.Contains(modelId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除尊享模型ID缓存
|
||||
/// </summary>
|
||||
public async Task ClearPremiumModelIdsCacheAsync()
|
||||
{
|
||||
await _distributedCache.RemoveAsync(PREMIUM_MODEL_IDS_CACHE_KEY);
|
||||
_logger.LogInformation("已清除尊享模型ID分布式缓存");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ public class PremiumPackageManager : DomainService
|
||||
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> _premiumPackageRepository;
|
||||
private readonly ILogger<PremiumPackageManager> _logger;
|
||||
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
|
||||
|
||||
public PremiumPackageManager(
|
||||
ISqlSugarRepository<PremiumPackageAggregateRoot, Guid> premiumPackageRepository,
|
||||
ILogger<PremiumPackageManager> logger, ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository)
|
||||
@@ -27,24 +28,22 @@ public class PremiumPackageManager : DomainService
|
||||
/// 为用户创建尊享包
|
||||
/// </summary>
|
||||
/// <param name="userId">用户ID</param>
|
||||
/// <param name="goodsType">商品类型</param>
|
||||
/// <param name="packageName"></param>
|
||||
/// <param name="totalAmount">支付金额</param>
|
||||
/// <param name="remark"></param>
|
||||
/// <param name="expireMonths">过期月数,0或null表示永久</param>
|
||||
/// <param name="tokenAmount"></param>
|
||||
/// <param name="isCreateRechargeRecord">是否创建订单,如果只购买尊享包,才需要单独创建订单,如果和会员组合一起购买,只需要创建会员套餐订单即可</param>
|
||||
/// <returns></returns>
|
||||
public async Task<PremiumPackageAggregateRoot> CreatePremiumPackageAsync(
|
||||
Guid userId,
|
||||
GoodsTypeEnum goodsType,
|
||||
long tokenAmount,
|
||||
string packageName,
|
||||
decimal totalAmount,
|
||||
int? expireMonths = null)
|
||||
string remark,
|
||||
int? expireMonths = null,
|
||||
bool isCreateRechargeRecord = true)
|
||||
{
|
||||
if (!goodsType.IsPremiumPackage())
|
||||
{
|
||||
throw new UserFriendlyException($"商品类型 {goodsType} 不是尊享包商品");
|
||||
}
|
||||
|
||||
var tokenAmount = goodsType.GetTokenAmount();
|
||||
var packageName = goodsType.GetDisplayName();
|
||||
|
||||
var premiumPackage = new PremiumPackageAggregateRoot(userId, tokenAmount, packageName)
|
||||
{
|
||||
PurchaseAmount = totalAmount
|
||||
@@ -58,21 +57,25 @@ public class PremiumPackageManager : DomainService
|
||||
|
||||
await _premiumPackageRepository.InsertAsync(premiumPackage);
|
||||
|
||||
// 创建充值记录
|
||||
var rechargeRecord = new AiRechargeAggregateRoot
|
||||
if (isCreateRechargeRecord)
|
||||
{
|
||||
UserId = userId,
|
||||
RechargeAmount = totalAmount,
|
||||
Content = packageName,
|
||||
ExpireDateTime = premiumPackage.ExpireDateTime,
|
||||
Remark = "自助充值",
|
||||
ContactInfo = null,
|
||||
RechargeType = RechargeTypeEnum.PremiumPackage
|
||||
};
|
||||
// 创建充值记录
|
||||
var rechargeRecord = new AiRechargeAggregateRoot
|
||||
{
|
||||
UserId = userId,
|
||||
RechargeAmount = totalAmount,
|
||||
Content = packageName,
|
||||
ExpireDateTime = premiumPackage.ExpireDateTime,
|
||||
Remark = remark,
|
||||
ContactInfo = null,
|
||||
RechargeType = RechargeTypeEnum.PremiumPackage
|
||||
};
|
||||
|
||||
// 保存充值记录到数据库
|
||||
await _rechargeRepository.InsertAsync(rechargeRecord);
|
||||
}
|
||||
|
||||
|
||||
// 保存充值记录到数据库
|
||||
await _rechargeRepository.InsertAsync(rechargeRecord);
|
||||
|
||||
_logger.LogInformation(
|
||||
$"用户 {userId} 购买尊享包成功: {packageName}, Token数量: {tokenAmount}, 金额: {totalAmount}");
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using SqlSugar;
|
||||
using Volo.Abp.Domain.Services;
|
||||
using Yi.Framework.AiHub.Domain.Entities;
|
||||
using Yi.Framework.AiHub.Domain.Entities.Model;
|
||||
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Consts;
|
||||
using Yi.Framework.SqlSugarCore.Abstractions;
|
||||
@@ -27,13 +28,16 @@ public class TokenManager : DomainService
|
||||
{
|
||||
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
|
||||
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
|
||||
private readonly ISqlSugarRepository<AiModelEntity, Guid> _aiModelRepository;
|
||||
|
||||
public TokenManager(
|
||||
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
|
||||
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
|
||||
ISqlSugarRepository<AiModelEntity, Guid> aiModelRepository)
|
||||
{
|
||||
_tokenRepository = tokenRepository;
|
||||
_usageStatisticsRepository = usageStatisticsRepository;
|
||||
_aiModelRepository = aiModelRepository;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -76,14 +80,20 @@ public class TokenManager : DomainService
|
||||
}
|
||||
|
||||
// 如果是尊享模型且Token设置了额度限制,检查是否超限
|
||||
if (!string.IsNullOrEmpty(modelId) &&
|
||||
PremiumPackageConst.ModeIds.Contains(modelId) &&
|
||||
entity.PremiumQuotaLimit.HasValue)
|
||||
if (!string.IsNullOrEmpty(modelId) && entity.PremiumQuotaLimit.HasValue)
|
||||
{
|
||||
var usedQuota = await GetTokenPremiumUsedQuotaAsync(entity.UserId, entity.Id);
|
||||
if (usedQuota >= entity.PremiumQuotaLimit.Value)
|
||||
var isPremium = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.ModelId == modelId)
|
||||
.Select(x => x.IsPremium)
|
||||
.FirstAsync();
|
||||
|
||||
if (isPremium)
|
||||
{
|
||||
throw new UserFriendlyException($"当前Token的尊享包额度已用完(已使用:{usedQuota},限制:{entity.PremiumQuotaLimit.Value}),请调整额度限制或使用其他Token", "403");
|
||||
var usedQuota = await GetTokenPremiumUsedQuotaAsync(entity.UserId, entity.Id);
|
||||
if (usedQuota >= entity.PremiumQuotaLimit.Value)
|
||||
{
|
||||
throw new UserFriendlyException($"当前Token的尊享包额度已用完(已使用:{usedQuota},限制:{entity.PremiumQuotaLimit.Value}),请调整额度限制或使用其他Token", "403");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +109,11 @@ public class TokenManager : DomainService
|
||||
/// </summary>
|
||||
private async Task<long> GetTokenPremiumUsedQuotaAsync(Guid userId, Guid tokenId)
|
||||
{
|
||||
var premiumModelIds = PremiumPackageConst.ModeIds;
|
||||
// 先获取所有尊享模型的ModelId列表
|
||||
var premiumModelIds = await _aiModelRepository._DbQueryable
|
||||
.Where(x => x.IsPremium)
|
||||
.Select(x => x.ModelId)
|
||||
.ToListAsync();
|
||||
|
||||
var usedQuota = await _usageStatisticsRepository._DbQueryable
|
||||
.Where(x => x.UserId == userId && x.TokenId == tokenId && premiumModelIds.Contains(x.ModelId))
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel;
|
||||
using ModelContextProtocol.Server;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Mcp;
|
||||
|
||||
[YiAgentTool]
|
||||
public class DeepThinkTool:ISingletonDependency
|
||||
{
|
||||
[YiAgentTool("深度思考"),DisplayName("DeepThink"),Description("进行深度思考")]
|
||||
public void DeepThink()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel;
|
||||
using ModelContextProtocol.Server;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Attributes;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain.Mcp;
|
||||
|
||||
[YiAgentTool]
|
||||
public class OnlineSearchTool:ISingletonDependency
|
||||
{
|
||||
[YiAgentTool("联网搜索"),DisplayName("OnlineSearch"), Description("进行在线搜索")]
|
||||
public string OnlineSearch(string keyword)
|
||||
{
|
||||
return "奥德赛第一中学学生会会长是:郭老板";
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AlipayEasySDK" Version="2.1.3" />
|
||||
<PackageReference Include="Azure.AI.OpenAI" Version="2.2.0-beta.4" />
|
||||
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0-preview.251219.1" />
|
||||
<PackageReference Include="ModelContextProtocol.Core" Version="0.5.0-preview.1" />
|
||||
<PackageReference Include="Volo.Abp.Ddd.Domain" Version="$(AbpVersion)" />
|
||||
<PackageReference Include="Volo.Abp.DistributedLocking" Version="$(AbpVersion)" />
|
||||
</ItemGroup>
|
||||
@@ -10,6 +12,7 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.Mapster\Yi.Framework.Mapster.csproj" />
|
||||
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.AiHub.Application.Contracts\Yi.Framework.AiHub.Application.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.AiHub.Domain.Shared\Yi.Framework.AiHub.Domain.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ using Yi.Framework.AiHub.Domain.Shared;
|
||||
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
|
||||
using Yi.Framework.Mapster;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Yi.Framework.AiHub.Domain.AiGateWay.Impl.ThorGemini.Chats;
|
||||
|
||||
namespace Yi.Framework.AiHub.Domain
|
||||
{
|
||||
@@ -61,6 +62,12 @@ namespace Yi.Framework.AiHub.Domain
|
||||
|
||||
#endregion
|
||||
|
||||
#region Gemini GenerateContent
|
||||
services.AddKeyedTransient<IGeminiGenerateContentService, GeminiGenerateContentService>(
|
||||
nameof(GeminiGenerateContentService));
|
||||
|
||||
#endregion
|
||||
|
||||
#region Image
|
||||
|
||||
services.AddKeyedTransient<IImageService, AzureOpenAIServiceImageService>(
|
||||
|
||||
@@ -358,8 +358,8 @@ namespace Yi.Abp.Web
|
||||
var app = context.GetApplicationBuilder();
|
||||
app.UseRouting();
|
||||
|
||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<AiModelEntity>();
|
||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<TokenAggregateRoot>();
|
||||
//app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<AiModelEntity>();
|
||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<ActivationCodeRecordAggregateRoot>();
|
||||
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<UsageStatisticsAggregateRoot>();
|
||||
|
||||
//跨域
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npx vue-tsc --noEmit)",
|
||||
"Bash(timeout 60 npx vue-tsc:*)"
|
||||
"Bash(timeout 60 npx vue-tsc:*)",
|
||||
"Bash(npm run dev:*)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
<body>
|
||||
<!-- 加载动画容器 -->
|
||||
<div id="yixinai-loader" class="loader-container">
|
||||
<div class="loader-title">意心Ai 2.8</div>
|
||||
<div class="loader-title">意心Ai 2.9</div>
|
||||
<div class="loader-subtitle">海外地址,仅首次访问预计加载约10秒,无需梯子</div>
|
||||
<div class="loader-logo">
|
||||
<div class="pulse-box"></div>
|
||||
|
||||
5
Yi.Ai.Vue3/src/api/activationCode/index.ts
Normal file
5
Yi.Ai.Vue3/src/api/activationCode/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { post } from '@/utils/request';
|
||||
|
||||
export function redeemActivationCode(data: { code: string }) {
|
||||
return post<any>('/activationCode/Redeem', data);
|
||||
}
|
||||
100
Yi.Ai.Vue3/src/api/channel/index.ts
Normal file
100
Yi.Ai.Vue3/src/api/channel/index.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { del, get, post, put } from '@/utils/request';
|
||||
import type {
|
||||
AiAppDto,
|
||||
AiAppCreateInput,
|
||||
AiAppUpdateInput,
|
||||
AiAppGetListInput,
|
||||
AiModelDto,
|
||||
AiModelCreateInput,
|
||||
AiModelUpdateInput,
|
||||
AiModelGetListInput,
|
||||
PagedResultDto,
|
||||
} from './types';
|
||||
|
||||
// ==================== AI应用管理 ====================
|
||||
|
||||
// 获取AI应用列表
|
||||
export function getAppList(params?: AiAppGetListInput) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (params?.searchKey) {
|
||||
queryParams.append('SearchKey', params.searchKey);
|
||||
}
|
||||
if (params?.skipCount !== undefined) {
|
||||
queryParams.append('SkipCount', params.skipCount.toString());
|
||||
}
|
||||
if (params?.maxResultCount !== undefined) {
|
||||
queryParams.append('MaxResultCount', params.maxResultCount.toString());
|
||||
}
|
||||
|
||||
const queryString = queryParams.toString();
|
||||
const url = queryString ? `/channel/app?${queryString}` : '/channel/app';
|
||||
|
||||
return get<PagedResultDto<AiAppDto>>(url).json();
|
||||
}
|
||||
|
||||
// 根据ID获取AI应用
|
||||
export function getAppById(id: string) {
|
||||
return get<AiAppDto>(`/channel/app/${id}`).json();
|
||||
}
|
||||
|
||||
// 创建AI应用
|
||||
export function createApp(data: AiAppCreateInput) {
|
||||
return post<AiAppDto>('/channel/app', data).json();
|
||||
}
|
||||
|
||||
// 更新AI应用
|
||||
export function updateApp(data: AiAppUpdateInput) {
|
||||
return put<AiAppDto>('/channel/app', data).json();
|
||||
}
|
||||
|
||||
// 删除AI应用
|
||||
export function deleteApp(id: string) {
|
||||
return del(`/channel/app/${id}`).json();
|
||||
}
|
||||
|
||||
// ==================== AI模型管理 ====================
|
||||
|
||||
// 获取AI模型列表
|
||||
export function getModelList(params?: AiModelGetListInput) {
|
||||
const queryParams = new URLSearchParams();
|
||||
if (params?.searchKey) {
|
||||
queryParams.append('SearchKey', params.searchKey);
|
||||
}
|
||||
if (params?.aiAppId) {
|
||||
queryParams.append('AiAppId', params.aiAppId);
|
||||
}
|
||||
if (params?.isPremiumOnly !== undefined) {
|
||||
queryParams.append('IsPremiumOnly', params.isPremiumOnly.toString());
|
||||
}
|
||||
if (params?.skipCount !== undefined) {
|
||||
queryParams.append('SkipCount', params.skipCount.toString());
|
||||
}
|
||||
if (params?.maxResultCount !== undefined) {
|
||||
queryParams.append('MaxResultCount', params.maxResultCount.toString());
|
||||
}
|
||||
|
||||
const queryString = queryParams.toString();
|
||||
const url = queryString ? `/channel/model?${queryString}` : '/channel/model';
|
||||
|
||||
return get<PagedResultDto<AiModelDto>>(url).json();
|
||||
}
|
||||
|
||||
// 根据ID获取AI模型
|
||||
export function getModelById(id: string) {
|
||||
return get<AiModelDto>(`/channel/model/${id}`).json();
|
||||
}
|
||||
|
||||
// 创建AI模型
|
||||
export function createModel(data: AiModelCreateInput) {
|
||||
return post<AiModelDto>('/channel/model', data).json();
|
||||
}
|
||||
|
||||
// 更新AI模型
|
||||
export function updateModel(data: AiModelUpdateInput) {
|
||||
return put<AiModelDto>('/channel/model', data).json();
|
||||
}
|
||||
|
||||
// 删除AI模型
|
||||
export function deleteModel(id: string) {
|
||||
return del(`/channel/model/${id}`).json();
|
||||
}
|
||||
121
Yi.Ai.Vue3/src/api/channel/types.ts
Normal file
121
Yi.Ai.Vue3/src/api/channel/types.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
// 模型类型枚举
|
||||
export enum ModelTypeEnum {
|
||||
Chat = 0,
|
||||
Image = 1,
|
||||
Embedding = 2,
|
||||
PremiumChat = 3,
|
||||
}
|
||||
|
||||
// 模型API类型枚举
|
||||
export enum ModelApiTypeEnum {
|
||||
OpenAi = 0,
|
||||
Claude = 1,
|
||||
}
|
||||
|
||||
// AI应用DTO
|
||||
export interface AiAppDto {
|
||||
id: string;
|
||||
name: string;
|
||||
endpoint: string;
|
||||
extraUrl?: string;
|
||||
apiKey: string;
|
||||
orderNum: number;
|
||||
creationTime: string;
|
||||
}
|
||||
|
||||
// 创建AI应用输入
|
||||
export interface AiAppCreateInput {
|
||||
name: string;
|
||||
endpoint: string;
|
||||
extraUrl?: string;
|
||||
apiKey: string;
|
||||
orderNum: number;
|
||||
}
|
||||
|
||||
// 更新AI应用输入
|
||||
export interface AiAppUpdateInput {
|
||||
id: string;
|
||||
name: string;
|
||||
endpoint: string;
|
||||
extraUrl?: string;
|
||||
apiKey: string;
|
||||
orderNum: number;
|
||||
}
|
||||
|
||||
// 获取AI应用列表输入
|
||||
export interface AiAppGetListInput {
|
||||
searchKey?: string;
|
||||
skipCount?: number;
|
||||
maxResultCount?: number;
|
||||
}
|
||||
|
||||
// AI模型DTO
|
||||
export interface AiModelDto {
|
||||
id: string;
|
||||
handlerName: string;
|
||||
modelId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
orderNum: number;
|
||||
aiAppId: string;
|
||||
extraInfo?: string;
|
||||
modelType: ModelTypeEnum;
|
||||
modelApiType: ModelApiTypeEnum;
|
||||
multiplier: number;
|
||||
multiplierShow: number;
|
||||
providerName?: string;
|
||||
iconUrl?: string;
|
||||
isPremium: boolean;
|
||||
}
|
||||
|
||||
// 创建AI模型输入
|
||||
export interface AiModelCreateInput {
|
||||
handlerName: string;
|
||||
modelId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
orderNum: number;
|
||||
aiAppId: string;
|
||||
extraInfo?: string;
|
||||
modelType: ModelTypeEnum;
|
||||
modelApiType: ModelApiTypeEnum;
|
||||
multiplier: number;
|
||||
multiplierShow: number;
|
||||
providerName?: string;
|
||||
iconUrl?: string;
|
||||
isPremium: boolean;
|
||||
}
|
||||
|
||||
// 更新AI模型输入
|
||||
export interface AiModelUpdateInput {
|
||||
id: string;
|
||||
handlerName: string;
|
||||
modelId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
orderNum: number;
|
||||
aiAppId: string;
|
||||
extraInfo?: string;
|
||||
modelType: ModelTypeEnum;
|
||||
modelApiType: ModelApiTypeEnum;
|
||||
multiplier: number;
|
||||
multiplierShow: number;
|
||||
providerName?: string;
|
||||
iconUrl?: string;
|
||||
isPremium: boolean;
|
||||
}
|
||||
|
||||
// 获取AI模型列表输入
|
||||
export interface AiModelGetListInput {
|
||||
searchKey?: string;
|
||||
aiAppId?: string;
|
||||
isPremiumOnly?: boolean;
|
||||
skipCount?: number;
|
||||
maxResultCount?: number;
|
||||
}
|
||||
|
||||
// 分页结果
|
||||
export interface PagedResultDto<T> {
|
||||
items: T[];
|
||||
totalCount: number;
|
||||
}
|
||||
@@ -19,3 +19,8 @@ export function getChatList(params: GetChatListParams) {
|
||||
// return get<ChatMessageVo[]>('/system/message/list', params);
|
||||
return get<ChatMessageVo[]>('/message', params).json();
|
||||
}
|
||||
|
||||
// 新增对应会话聊天记录
|
||||
export function aiChatTool() {
|
||||
return post('/ai-chat/tool').json();
|
||||
}
|
||||
|
||||
@@ -142,6 +142,7 @@ function cleanupPayment() {
|
||||
const tabs = [
|
||||
{ key: 'member', label: '会员套餐' },
|
||||
{ key: 'token', label: '尊享Token包' },
|
||||
{ key: 'activation', label: '激活码' },
|
||||
];
|
||||
|
||||
const benefitsData = {
|
||||
@@ -210,8 +211,11 @@ function selectPackage(pkg: any) {
|
||||
}
|
||||
|
||||
watch(activeTab, () => {
|
||||
if (activeTab.value === 'activation') {
|
||||
return;
|
||||
}
|
||||
const packages = packagesData.value[activeTab.value as 'member' | 'token'];
|
||||
if (packages.length > 0) {
|
||||
if (packages && packages.length > 0) {
|
||||
const firstPackage = packages[0];
|
||||
selectedId.value = firstPackage.id;
|
||||
selectedPrice.value = firstPackage.price;
|
||||
@@ -315,6 +319,11 @@ function close() {
|
||||
function onClose() {
|
||||
emit('close');
|
||||
}
|
||||
|
||||
function goToActivation() {
|
||||
close();
|
||||
userStore.openUserCenter('activationCode');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -386,8 +395,36 @@ function onClose() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 激活码引导页 -->
|
||||
<div v-if="activeTab === 'activation'" class="activation-guide-container">
|
||||
<div class="activation-content">
|
||||
<div class="guide-icon">
|
||||
🎁
|
||||
</div>
|
||||
<h3 class="guide-title">
|
||||
激活码兑换
|
||||
</h3>
|
||||
<p class="guide-desc">
|
||||
如果您持有意心AI的会员激活码或Token兑换码,<br>请点击下方按钮前往控制台进行兑换。
|
||||
</p>
|
||||
<el-button
|
||||
type="primary"
|
||||
size="large"
|
||||
class="redeem-jump-btn"
|
||||
round
|
||||
@click="goToActivation"
|
||||
>
|
||||
前往兑换中心
|
||||
</el-button>
|
||||
|
||||
<div class="guide-tips">
|
||||
<p>💡 兑换成功后权益将立即生效</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 移动端布局 -->
|
||||
<div v-if="isMobile" class="mobile-layout">
|
||||
<div v-else-if="isMobile" class="mobile-layout">
|
||||
<!-- 商品加载状态(无修改) -->
|
||||
<div v-if="isLoadingGoods" class="loading-container">
|
||||
<el-icon class="is-loading" :size="40">
|
||||
@@ -824,6 +861,73 @@ function onClose() {
|
||||
}
|
||||
}
|
||||
|
||||
/* 激活码引导页样式 */
|
||||
.activation-guide-container {
|
||||
padding: 40px 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 400px;
|
||||
background: linear-gradient(to bottom, #fff, #fdfdfd);
|
||||
border-radius: 8px;
|
||||
|
||||
.activation-content {
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
|
||||
.guide-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 24px;
|
||||
animation: float-icon 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.guide-title {
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
color: #2c3e50;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.guide-desc {
|
||||
color: #606266;
|
||||
line-height: 1.6;
|
||||
margin-bottom: 32px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.redeem-jump-btn {
|
||||
width: 200px;
|
||||
height: 48px;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
letter-spacing: 1px;
|
||||
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
|
||||
border: none;
|
||||
box-shadow: 0 4px 12px rgba(255, 117, 140, 0.3);
|
||||
transition: all 0.3s;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 16px rgba(255, 117, 140, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
.guide-tips {
|
||||
margin-top: 24px;
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes float-icon {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10px); }
|
||||
}
|
||||
|
||||
/* 移动端样式(核心新增:主价格/弱化价格样式) */
|
||||
.mobile-layout {
|
||||
display: flex; flex-direction: column; gap: 24px;
|
||||
|
||||
416
Yi.Ai.Vue3/src/components/ToolList/index.vue
Normal file
416
Yi.Ai.Vue3/src/components/ToolList/index.vue
Normal file
@@ -0,0 +1,416 @@
|
||||
<script setup lang="ts">
|
||||
import { ChromeFilled, ElementPlus, Loading, MagicStick, Search } from '@element-plus/icons-vue';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { aiChatTool } from '@/api';
|
||||
|
||||
// API返回的工具接口
|
||||
interface ApiToolItem {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: {
|
||||
type: string;
|
||||
properties: Record<string, any>;
|
||||
};
|
||||
}
|
||||
|
||||
// 前端工具按钮的数据
|
||||
interface ToolItem {
|
||||
id: number;
|
||||
name: string;
|
||||
apiName: string;
|
||||
icon: any;
|
||||
tip: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
// 定义组件事件
|
||||
const emit = defineEmits<{
|
||||
'tools-update': [payload: {
|
||||
selectedToolIds: number[];
|
||||
selectedApiTools: string[];
|
||||
}];
|
||||
}>();
|
||||
|
||||
// 图标映射配置 - 根据API名称映射图标
|
||||
const iconMap: Record<string, any> = {
|
||||
online_search: ChromeFilled, // 在线搜索
|
||||
deep_think: ElementPlus, // 深度思考
|
||||
search: Search, // 搜索
|
||||
web_search: ChromeFilled, // 网页搜索
|
||||
thinking: MagicStick, // 思考
|
||||
default: ElementPlus, // 默认图标
|
||||
};
|
||||
|
||||
// 提示信息映射
|
||||
const tipMap: Record<string, string> = {
|
||||
online_search: '实时搜索最新信息,获取网络资料',
|
||||
deep_think: '深度推理分析,解决复杂问题',
|
||||
web_search: '联网搜索网页内容',
|
||||
thinking: '深入思考和分析问题',
|
||||
default: '点击启用此功能',
|
||||
};
|
||||
|
||||
// 响应式工具列表 - 初始为空,等待接口加载
|
||||
const tools = ref<ToolItem[]>([]);
|
||||
|
||||
// 当前选中的工具ID数组(支持多选)
|
||||
const activeToolIds = ref<number[]>([]);
|
||||
const loading = ref(false);
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
// 从API数据转换为前端格式
|
||||
function transformApiTools(apiTools: ApiToolItem[]): ToolItem[] {
|
||||
return apiTools.map((tool, index) => {
|
||||
const apiName = tool.name;
|
||||
return {
|
||||
id: index + 1,
|
||||
name: tool.description, // 使用中文描述
|
||||
apiName,
|
||||
icon: iconMap[apiName] || iconMap.default,
|
||||
tip: tipMap[apiName] || tipMap.default,
|
||||
enabled: true,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// 获取所有选中的工具对象
|
||||
const selectedTools = computed(() => {
|
||||
return tools.value.filter(tool => activeToolIds.value.includes(tool.id));
|
||||
});
|
||||
|
||||
// 获取所有选中的API工具名称
|
||||
const selectedApiTools = computed(() => {
|
||||
return selectedTools.value.map(tool => tool.apiName);
|
||||
});
|
||||
|
||||
// 点击事件处理
|
||||
function handleToolClick(tool: ToolItem) {
|
||||
if (!tool.enabled)
|
||||
return;
|
||||
|
||||
const index = activeToolIds.value.indexOf(tool.id);
|
||||
|
||||
if (index > -1) {
|
||||
activeToolIds.value.splice(index, 1);
|
||||
}
|
||||
else {
|
||||
activeToolIds.value.push(tool.id);
|
||||
}
|
||||
|
||||
console.log('当前选中的工具:', selectedTools.value.map(t => t.name));
|
||||
console.log('对应的API名称:', selectedApiTools.value);
|
||||
|
||||
emitToolsUpdate();
|
||||
}
|
||||
|
||||
// 辅助函数:检查某个工具是否被选中
|
||||
function isActive(toolId: number) {
|
||||
return activeToolIds.value.includes(toolId);
|
||||
}
|
||||
|
||||
// 清空所有选中
|
||||
function clearSelection() {
|
||||
activeToolIds.value = [];
|
||||
emitToolsUpdate();
|
||||
}
|
||||
|
||||
// 全选已启用的工具
|
||||
function selectAll() {
|
||||
activeToolIds.value = tools.value
|
||||
.filter(tool => tool.enabled)
|
||||
.map(tool => tool.id);
|
||||
emitToolsUpdate();
|
||||
}
|
||||
|
||||
// 启用/禁用工具
|
||||
function setToolEnabled(toolId: number, enabled: boolean) {
|
||||
const tool = tools.value.find(t => t.id === toolId);
|
||||
if (tool) {
|
||||
tool.enabled = enabled;
|
||||
if (!enabled && isActive(toolId)) {
|
||||
const index = activeToolIds.value.indexOf(toolId);
|
||||
if (index > -1) {
|
||||
activeToolIds.value.splice(index, 1);
|
||||
emitToolsUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 根据API名称启用/禁用工具
|
||||
function setToolEnabledByApiName(apiName: string, enabled: boolean) {
|
||||
const tool = tools.value.find(t => t.apiName === apiName);
|
||||
if (tool) {
|
||||
setToolEnabled(tool.id, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
// 通知父组件工具状态变化
|
||||
function emitToolsUpdate() {
|
||||
console.log('工具状态已更新:', {
|
||||
selectedToolIds: activeToolIds.value,
|
||||
selectedTools: selectedTools.value,
|
||||
selectedApiTools: selectedApiTools.value,
|
||||
});
|
||||
|
||||
// 触发自定义事件
|
||||
emit('tools-update', {
|
||||
selectedToolIds: activeToolIds.value,
|
||||
selectedApiTools: selectedApiTools.value,
|
||||
});
|
||||
}
|
||||
|
||||
// 从API获取工具列表
|
||||
async function getAiChatToolList() {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
const res = await aiChatTool();
|
||||
|
||||
if (res.data && Array.isArray(res.data)) {
|
||||
console.log('API返回的工具列表:', res.data);
|
||||
|
||||
// 转换API数据
|
||||
const apiTools = transformApiTools(res.data);
|
||||
|
||||
// 更新工具列表
|
||||
tools.value = apiTools;
|
||||
|
||||
// 默认选中第一个可用的工具
|
||||
const firstEnabledTool = apiTools.find(tool => tool.enabled);
|
||||
if (firstEnabledTool && activeToolIds.value.length === 0) {
|
||||
activeToolIds.value = [firstEnabledTool.id];
|
||||
}
|
||||
|
||||
console.log('加载的工具列表:', tools.value);
|
||||
emitToolsUpdate();
|
||||
}
|
||||
else {
|
||||
error.value = '接口返回数据格式不正确';
|
||||
console.error('接口返回数据格式错误:', res);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
error.value = '获取工具列表失败,请检查网络连接';
|
||||
console.error('获取工具列表失败:', err);
|
||||
}
|
||||
finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 刷新工具列表
|
||||
async function refreshTools() {
|
||||
await getAiChatToolList();
|
||||
}
|
||||
|
||||
// 组件挂载时获取工具列表
|
||||
onMounted(() => {
|
||||
getAiChatToolList();
|
||||
});
|
||||
|
||||
// 暴露方法给父组件
|
||||
defineExpose({
|
||||
selectedTools,
|
||||
selectedApiTools,
|
||||
clearSelection,
|
||||
selectAll,
|
||||
setToolEnabled,
|
||||
setToolEnabledByApiName,
|
||||
refreshTools,
|
||||
getAiChatToolList,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="tools-container">
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="loading" class="loading-state">
|
||||
<el-icon class="loading-icon">
|
||||
<Loading />
|
||||
</el-icon>
|
||||
<span>加载工具中...</span>
|
||||
</div>
|
||||
|
||||
<!-- 错误状态 -->
|
||||
<div v-else-if="error" class="error-state">
|
||||
<el-icon class="error-icon">
|
||||
<ElementPlus />
|
||||
</el-icon>
|
||||
<span>{{ error }}</span>
|
||||
<el-button type="text" class="retry-btn" @click="refreshTools">
|
||||
重试
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else-if="tools.length === 0" class="empty-state">
|
||||
<span>暂无可用工具</span>
|
||||
</div>
|
||||
|
||||
<!-- 工具按钮 -->
|
||||
<div
|
||||
v-for="tool in tools"
|
||||
v-else
|
||||
:key="tool.id"
|
||||
class="tool-item"
|
||||
:class="{
|
||||
active: isActive(tool.id),
|
||||
disabled: !tool.enabled,
|
||||
}"
|
||||
:title="tool.tip"
|
||||
@click="handleToolClick(tool)"
|
||||
>
|
||||
<el-icon class="tool-icon">
|
||||
<component :is="tool.icon" />
|
||||
</el-icon>
|
||||
<span class="tool-text">{{ tool.name }}</span>
|
||||
|
||||
<!-- 选中指示器 -->
|
||||
<!-- <span v-if="isActive(tool.id)" class="check-indicator">✓</span> -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 调试信息 -->
|
||||
<div v-if="false" class="debug-info">
|
||||
<div>工具数量: {{ tools.length }}</div>
|
||||
<div>当前选中ID: {{ activeToolIds }}</div>
|
||||
<div>选中的API工具: {{ selectedApiTools }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.tools-container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
padding: 4px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.loading-state,
|
||||
.error-state,
|
||||
.empty-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.loading-state {
|
||||
.loading-icon {
|
||||
animation: rotate 1s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
.error-state {
|
||||
color: #f56c6c;
|
||||
|
||||
.error-icon {
|
||||
color: #f56c6c;
|
||||
}
|
||||
|
||||
.retry-btn {
|
||||
margin-left: 8px;
|
||||
padding: 0;
|
||||
height: auto;
|
||||
color: #409EFF;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
color: #c0c4cc;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@keyframes rotate {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.tool-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||
transition: all 0.2s ease;
|
||||
background: white;
|
||||
position: relative;
|
||||
border-radius: 10px;
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: rgba(64, 158, 255, 0.1);
|
||||
border-color: #409EFF;
|
||||
color: #409EFF;
|
||||
|
||||
.tool-icon {
|
||||
color: #409EFF;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
|
||||
&:hover {
|
||||
background: white;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
&:active:not(.disabled) {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.tool-icon {
|
||||
font-size: 16px;
|
||||
color: #606266;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.tool-text {
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.check-indicator {
|
||||
margin-left: 4px;
|
||||
font-weight: bold;
|
||||
font-size: 12px;
|
||||
color: #409EFF;
|
||||
}
|
||||
|
||||
.debug-info {
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
background: #f5f5f5;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
|
||||
div {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -633,19 +633,10 @@ onMounted(async () => {
|
||||
target="_blank"
|
||||
class="guide-link"
|
||||
>
|
||||
【意心Ai】AI工具玩法指南
|
||||
点击前往文档:【意心Ai】AI工具玩法指南
|
||||
<el-icon class="link-icon"><i-ep-top-right /></el-icon>
|
||||
</a>
|
||||
</h1>
|
||||
|
||||
<div class="iframe-container">
|
||||
<iframe
|
||||
src="https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde"
|
||||
class="guide-iframe"
|
||||
loading="lazy"
|
||||
sandbox="allow-scripts allow-same-origin allow-popups"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { redeemActivationCode } from '@/api/activationCode';
|
||||
import { MagicStick } from '@element-plus/icons-vue';
|
||||
|
||||
const activationCode = ref('');
|
||||
const loading = ref(false);
|
||||
const canvasRef = ref<HTMLCanvasElement | null>(null);
|
||||
const containerRef = ref<HTMLElement | null>(null);
|
||||
let animationId: number;
|
||||
|
||||
// --- Advanced Physics & Visuals ---
|
||||
|
||||
class Particle {
|
||||
x: number;
|
||||
y: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
alpha: number;
|
||||
color: string;
|
||||
hue: number;
|
||||
size: number;
|
||||
decay: number;
|
||||
gravity: number;
|
||||
friction: number;
|
||||
brightness: number;
|
||||
flicker: boolean;
|
||||
|
||||
constructor(x: number, y: number, hue: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.hue = hue;
|
||||
|
||||
// Explosive physics
|
||||
const angle = Math.random() * Math.PI * 2;
|
||||
const speed = Math.random() * 15 + 2;
|
||||
this.vx = Math.cos(angle) * speed;
|
||||
this.vy = Math.sin(angle) * speed;
|
||||
|
||||
this.alpha = 1;
|
||||
this.decay = Math.random() * 0.015 + 0.005;
|
||||
this.gravity = 0.05;
|
||||
this.friction = 0.96;
|
||||
|
||||
this.size = Math.random() * 3 + 1;
|
||||
this.brightness = 50; // Standard brightness for white bg visibility (0-100% HSL L value)
|
||||
this.flicker = Math.random() > 0.5;
|
||||
}
|
||||
|
||||
update() {
|
||||
this.vx *= this.friction;
|
||||
this.vy *= this.friction;
|
||||
this.vy += this.gravity;
|
||||
|
||||
this.x += this.vx;
|
||||
this.y += this.vy;
|
||||
|
||||
this.alpha -= this.decay;
|
||||
this.hue += 0.5;
|
||||
}
|
||||
|
||||
draw(ctx: CanvasRenderingContext2D) {
|
||||
ctx.globalAlpha = this.alpha;
|
||||
// On white background:
|
||||
// We want high saturation (100%) and medium lightness (50%) to make colors pop against white.
|
||||
// If lightness is too high (like 80-100), it fades into white.
|
||||
const lightness = this.flicker ? Math.random() * 20 + 40 : this.brightness;
|
||||
ctx.fillStyle = `hsla(${this.hue}, 100%, ${lightness}%, ${this.alpha})`;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
}
|
||||
|
||||
class Shockwave {
|
||||
x: number;
|
||||
y: number;
|
||||
radius: number;
|
||||
alpha: number;
|
||||
lineWidth: number;
|
||||
hue: number;
|
||||
|
||||
constructor(x: number, y: number, hue: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.hue = hue;
|
||||
this.radius = 0;
|
||||
this.alpha = 1;
|
||||
this.lineWidth = 10;
|
||||
}
|
||||
|
||||
update() {
|
||||
this.radius += 15;
|
||||
this.alpha -= 0.05;
|
||||
this.lineWidth -= 0.2;
|
||||
}
|
||||
|
||||
draw(ctx: CanvasRenderingContext2D) {
|
||||
if (this.alpha <= 0) return;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
|
||||
// Darker/More saturated shockwave for white background
|
||||
ctx.strokeStyle = `hsla(${this.hue}, 100%, 60%, ${this.alpha})`;
|
||||
ctx.lineWidth = Math.max(0, this.lineWidth);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
let particles: Particle[] = [];
|
||||
let shockwaves: Shockwave[] = [];
|
||||
|
||||
function createExplosion(x: number, y: number, hue: number) {
|
||||
const particleCount = 120;
|
||||
for (let i = 0; i < particleCount; i++) {
|
||||
particles.push(new Particle(x, y, hue));
|
||||
}
|
||||
for (let i = 0; i < 60; i++) {
|
||||
particles.push(new Particle(x, y, (hue + 180) % 360));
|
||||
}
|
||||
shockwaves.push(new Shockwave(x, y, hue));
|
||||
}
|
||||
|
||||
function animate() {
|
||||
const canvas = canvasRef.value;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
// Clear with transparent fade for trails on white
|
||||
// 'destination-out' erases content.
|
||||
// To leave a trail on a white background (canvas is transparent over white gradient):
|
||||
// We need to gently erase what's there.
|
||||
|
||||
ctx.globalCompositeOperation = 'destination-out';
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.1)'; // Alpha controls trail length
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Reset to default drawing
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
|
||||
for (let i = particles.length - 1; i >= 0; i--) {
|
||||
particles[i].update();
|
||||
particles[i].draw(ctx);
|
||||
if (particles[i].alpha <= 0) particles.splice(i, 1);
|
||||
}
|
||||
|
||||
for (let i = shockwaves.length - 1; i >= 0; i--) {
|
||||
shockwaves[i].update();
|
||||
shockwaves[i].draw(ctx);
|
||||
if (shockwaves[i].alpha <= 0) shockwaves.splice(i, 1);
|
||||
}
|
||||
|
||||
if (particles.length > 0 || shockwaves.length > 0) {
|
||||
animationId = requestAnimationFrame(animate);
|
||||
} else {
|
||||
cancelAnimationFrame(animationId);
|
||||
}
|
||||
}
|
||||
|
||||
// Shake Effect
|
||||
const isShaking = ref(false);
|
||||
function triggerShake() {
|
||||
isShaking.value = true;
|
||||
setTimeout(() => isShaking.value = false, 500);
|
||||
}
|
||||
|
||||
function triggerCelebration() {
|
||||
const canvas = canvasRef.value;
|
||||
if (!canvas) return;
|
||||
const parent = canvas.parentElement;
|
||||
if (parent) {
|
||||
canvas.width = parent.clientWidth;
|
||||
canvas.height = parent.clientHeight;
|
||||
}
|
||||
|
||||
const cx = canvas.width / 2;
|
||||
const cy = canvas.height / 2;
|
||||
|
||||
// 1. Initial Mega Explosion
|
||||
triggerShake();
|
||||
createExplosion(cx, cy, Math.random() * 360);
|
||||
|
||||
// Start loop
|
||||
animate();
|
||||
|
||||
// 2. Machine Gun Fire sequence
|
||||
let count = 0;
|
||||
const timer = setInterval(() => {
|
||||
count++;
|
||||
const rx = cx + (Math.random() - 0.5) * canvas.width * 0.8;
|
||||
const ry = cy + (Math.random() - 0.5) * canvas.height * 0.8;
|
||||
|
||||
createExplosion(rx, ry, Math.random() * 360);
|
||||
|
||||
if (count % 3 === 0) triggerShake();
|
||||
|
||||
if (count > 25) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
}, 120);
|
||||
}
|
||||
|
||||
async function handleRedeem() {
|
||||
if (!activationCode.value.trim()) {
|
||||
ElMessage.warning('请输入激活码');
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await redeemActivationCode({ code: activationCode.value });
|
||||
triggerCelebration();
|
||||
ElMessage.success({
|
||||
message: '兑换成功!奖励已到账',
|
||||
type: 'success',
|
||||
duration: 3000,
|
||||
showClose: true,
|
||||
});
|
||||
activationCode.value = '';
|
||||
} catch (error: any) {
|
||||
// console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
cancelAnimationFrame(animationId);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="containerRef" class="activation-container" :class="{ 'shake-anim': isShaking }">
|
||||
<!-- Removed Dark overlay -->
|
||||
<canvas ref="canvasRef" class="fireworks-canvas"></canvas>
|
||||
|
||||
<div class="content-wrapper">
|
||||
<div class="gift-icon-wrapper">
|
||||
<div class="gift-box">🎁</div>
|
||||
<div class="gift-glow"></div>
|
||||
</div>
|
||||
|
||||
<h2 class="title">激活码兑换</h2>
|
||||
<p class="subtitle">开启您的专属惊喜权益</p>
|
||||
|
||||
<div class="input-section">
|
||||
<el-input
|
||||
v-model="activationCode"
|
||||
placeholder="请输入您的激活码"
|
||||
class="activation-input"
|
||||
size="large"
|
||||
:prefix-icon="MagicStick"
|
||||
clearable
|
||||
@keyup.enter="handleRedeem"
|
||||
/>
|
||||
|
||||
<el-button
|
||||
class="redeem-btn"
|
||||
:loading="loading"
|
||||
@click="handleRedeem"
|
||||
>
|
||||
立即兑换
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="tips-section">
|
||||
<div class="tip-item">
|
||||
<span class="tip-dot">•</span>
|
||||
<span>若激活码内包含意心Ai会员物品,激活后需重新登录生效</span>
|
||||
</div>
|
||||
<div class="tip-item">
|
||||
<span class="tip-dot">•</span>
|
||||
<span>激活成功后,可在充值记录中查看物品是否到账</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.activation-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 500px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: radial-gradient(circle at center, #fffbf0 0%, #fff 100%);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
transition: transform 0.1s;
|
||||
}
|
||||
|
||||
.shake-anim {
|
||||
animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
10%, 90% { transform: translate3d(-2px, 0, 0); }
|
||||
20%, 80% { transform: translate3d(4px, 0, 0); }
|
||||
30%, 50%, 70% { transform: translate3d(-6px, 0, 0); }
|
||||
40%, 60% { transform: translate3d(6px, 0, 0); }
|
||||
}
|
||||
|
||||
.fireworks-canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
position: relative;
|
||||
z-index: 11;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
padding: 40px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.gift-icon-wrapper {
|
||||
position: relative;
|
||||
margin-bottom: 24px;
|
||||
animation: float 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.gift-box {
|
||||
font-size: 72px;
|
||||
filter: drop-shadow(0 10px 15px rgba(255, 105, 180, 0.3));
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.gift-glow {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
background: radial-gradient(circle, rgba(255, 215, 0, 0.4) 0%, rgba(255, 255, 255, 0) 70%);
|
||||
border-radius: 50%;
|
||||
z-index: 1;
|
||||
animation: pulse-glow 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse-glow {
|
||||
0% { transform: translate(-50%, -50%) scale(1); opacity: 0.5; }
|
||||
50% { transform: translate(-50%, -50%) scale(1.5); opacity: 1; }
|
||||
100% { transform: translate(-50%, -50%) scale(1); opacity: 0.5; }
|
||||
}
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-12px); }
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
background: linear-gradient(45deg, #ff9a9e, #fad0c4, #fad0c4);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: #2c3e50;
|
||||
margin: 0 0 8px 0;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 15px;
|
||||
color: #95a5a6;
|
||||
margin-bottom: 36px;
|
||||
}
|
||||
|
||||
.input-section {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
:deep(.activation-input .el-input__wrapper) {
|
||||
border-radius: 50px;
|
||||
padding: 10px 24px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
|
||||
border: 2px solid transparent;
|
||||
background-image: linear-gradient(white, white), linear-gradient(to right, #e0e0e0, #e0e0e0);
|
||||
background-origin: border-box;
|
||||
background-clip: padding-box, border-box;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
:deep(.activation-input .el-input__wrapper:hover),
|
||||
:deep(.activation-input .el-input__wrapper.is-focus) {
|
||||
box-shadow: 0 8px 25px rgba(255, 105, 180, 0.15);
|
||||
background-image: linear-gradient(white, white), linear-gradient(135deg, #ff9a9e, #a18cd1);
|
||||
border: 2px solid transparent;
|
||||
}
|
||||
|
||||
:deep(.activation-input .el-input__inner) {
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
color: #333;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.redeem-btn {
|
||||
width: 100%;
|
||||
height: 54px;
|
||||
border-radius: 50px;
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 4px;
|
||||
color: white;
|
||||
border: none;
|
||||
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #a18cd1 100%);
|
||||
background-size: 200% 200%;
|
||||
animation: gradient-anim 5s ease infinite;
|
||||
box-shadow: 0 8px 20px rgba(255, 117, 140, 0.4);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes gradient-anim {
|
||||
0% { background-position: 0% 50%; }
|
||||
50% { background-position: 100% 50%; }
|
||||
100% { background-position: 0% 50%; }
|
||||
}
|
||||
|
||||
.redeem-btn:hover {
|
||||
transform: translateY(-3px) scale(1.02);
|
||||
box-shadow: 0 12px 30px rgba(161, 140, 209, 0.6);
|
||||
}
|
||||
|
||||
.redeem-btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.tips-section {
|
||||
width: 100%;
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
border-radius: 16px;
|
||||
padding: 20px;
|
||||
border: 1px dashed #dcdfe6;
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.tip-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
line-height: 1.6;
|
||||
margin-bottom: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.tip-item:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.tip-dot {
|
||||
color: #ff9a9e;
|
||||
font-weight: bold;
|
||||
font-size: 18px;
|
||||
line-height: 14px;
|
||||
}
|
||||
</style>
|
||||
@@ -549,6 +549,7 @@ onBeforeUnmount(() => {
|
||||
</el-option>
|
||||
</el-select>
|
||||
<el-button
|
||||
v-if="false"
|
||||
:icon="FullScreen"
|
||||
circle
|
||||
plain
|
||||
|
||||
@@ -105,16 +105,15 @@ function bindWechat() {
|
||||
|
||||
<template>
|
||||
<div class="user-profile">
|
||||
<!-- 顶部标题 -->
|
||||
<div class="header">
|
||||
<h2>
|
||||
<el-icon><User /></el-icon>
|
||||
个人信息
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<!-- 用户卡片 -->
|
||||
<el-card class="profile-card" shadow="hover">
|
||||
<!-- 顶部标题 -->
|
||||
<div class="header">
|
||||
<h2>
|
||||
<el-icon><User /></el-icon>
|
||||
个人信息
|
||||
</h2>
|
||||
</div>
|
||||
<!-- 头像和基本信息区域 -->
|
||||
<div class="user-header-section">
|
||||
<!-- 头像区域 -->
|
||||
@@ -138,7 +137,9 @@ function bindWechat() {
|
||||
|
||||
<!-- 用户名称和状态 -->
|
||||
<div class="user-info-quick">
|
||||
<h3 class="user-name">{{ userNick }}</h3>
|
||||
<h3 class="user-name">
|
||||
{{ userNick }}
|
||||
</h3>
|
||||
<div class="user-tags">
|
||||
<el-tag v-if="userVipStatus" type="warning" effect="dark" size="large">
|
||||
<el-icon><Promotion /></el-icon>
|
||||
@@ -153,8 +154,12 @@ function bindWechat() {
|
||||
</div>
|
||||
<div class="user-stats">
|
||||
<div class="stat-item">
|
||||
<div class="stat-value">{{ formatDate(user.creationTime)?.split(' ')[0] || '-' }}</div>
|
||||
<div class="stat-label">注册时间</div>
|
||||
<div class="stat-value">
|
||||
{{ formatDate(user.creationTime)?.split(' ')[0] || '-' }}
|
||||
</div>
|
||||
<div class="stat-label">
|
||||
注册时间
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -171,7 +176,9 @@ function bindWechat() {
|
||||
<el-icon><User /></el-icon>
|
||||
用户名
|
||||
</div>
|
||||
<div class="info-value">{{ user.userName || '-' }}</div>
|
||||
<div class="info-value">
|
||||
{{ user.userName || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 昵称 -->
|
||||
@@ -180,7 +187,9 @@ function bindWechat() {
|
||||
<el-icon><Postcard /></el-icon>
|
||||
昵称
|
||||
</div>
|
||||
<div class="info-value">{{ userNick }}</div>
|
||||
<div class="info-value">
|
||||
{{ userNick }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 邮箱 -->
|
||||
@@ -215,7 +224,9 @@ function bindWechat() {
|
||||
<!-- 微信绑定 -->
|
||||
<div class="info-item full-width">
|
||||
<div class="info-label">
|
||||
<el-icon color="#07C160"><ChatDotRound /></el-icon>
|
||||
<el-icon color="#07C160">
|
||||
<ChatDotRound />
|
||||
</el-icon>
|
||||
微信绑定
|
||||
</div>
|
||||
<div class="info-value wechat-binding">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type LayoutType = | 'vertical' | 'blankPage';
|
||||
export type LayoutType = 'default' | 'vertical' | 'blankPage' | 'blankPage';
|
||||
|
||||
// 仿豆包折叠逻辑
|
||||
export type CollapseType
|
||||
@@ -25,7 +25,7 @@ export interface DesignConfigState {
|
||||
// 是否折叠菜单
|
||||
isCollapse: boolean;
|
||||
// 安全区是否被悬停
|
||||
isSafeAreaHover: boolean;
|
||||
isCollapseConversationList: boolean;
|
||||
// 跟踪是否首次激活悬停
|
||||
hasActivatedHover: boolean;
|
||||
}
|
||||
@@ -65,15 +65,13 @@ const design: DesignConfigState = {
|
||||
// 需要自定义路由动画可以把 Main 组件样式代码注释放开,从新对话切换到带id的路由时,会执行这个动画样式
|
||||
pageAnimateType: 'zoom-fade',
|
||||
// 布局模式 (纵向:vertical | ... | 自己定义)
|
||||
layout: 'vertical',
|
||||
layout: 'default',
|
||||
// 折叠类型
|
||||
collapseType: 'followSystem',
|
||||
// 是否折叠菜单
|
||||
// 是否折叠对话记录菜单
|
||||
isCollapse: false,
|
||||
// 安全区是否被悬停
|
||||
isSafeAreaHover: false,
|
||||
// 跟踪是否首次激活悬停
|
||||
hasActivatedHover: false,
|
||||
// 是否折叠对话记录菜单
|
||||
isCollapseConversationList: false,
|
||||
};
|
||||
|
||||
export default design;
|
||||
|
||||
72
Yi.Ai.Vue3/src/hooks/useResponsive.ts
Normal file
72
Yi.Ai.Vue3/src/hooks/useResponsive.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useBreakpoints, useWindowSize } from '@vueuse/core';
|
||||
import { computed } from 'vue';
|
||||
|
||||
// 断点定义
|
||||
export const breakpoints = {
|
||||
xs: 0, // 手机竖屏 < 640px
|
||||
sm: 640, // 手机横屏 ≥ 640px
|
||||
md: 768, // 平板 ≥ 768px
|
||||
lg: 1024, // 小桌面 ≥ 1024px
|
||||
xl: 1280, // 桌面 ≥ 1280px
|
||||
xxl: 1536, // 大桌面 ≥ 1536px
|
||||
};
|
||||
|
||||
export function useResponsive() {
|
||||
const bp = useBreakpoints(breakpoints);
|
||||
|
||||
// 设备类型判断
|
||||
const isMobile = bp.smaller('md'); // < 768px
|
||||
const isTablet = bp.between('md', 'lg'); // 768px - 1024px
|
||||
const isDesktop = bp.greaterOrEqual('lg'); // ≥ 1024px
|
||||
|
||||
// 精确断点
|
||||
const isXs = bp.smaller('sm'); // < 640px
|
||||
const isSm = bp.between('sm', 'md'); // 640px - 768px
|
||||
const isMd = bp.between('md', 'lg'); // 768px - 1024px
|
||||
const isLg = bp.between('lg', 'xl'); // 1024px - 1280px
|
||||
const isXl = bp.between('xl', 'xxl'); // 1280px - 1536px
|
||||
const isXxl = bp.greater('xxl'); // > 1536px
|
||||
|
||||
// 监听窗口变化
|
||||
const { width, height } = useWindowSize();
|
||||
|
||||
// 方向检测
|
||||
const isPortrait = computed(() => height.value > width.value);
|
||||
const isLandscape = computed(() => width.value > height.value);
|
||||
|
||||
// 当前断点名称
|
||||
const currentBreakpoint = computed(() => {
|
||||
if (isXs.value) return 'xs';
|
||||
if (isSm.value) return 'sm';
|
||||
if (isMd.value) return 'md';
|
||||
if (isLg.value) return 'lg';
|
||||
if (isXl.value) return 'xl';
|
||||
return 'xxl';
|
||||
});
|
||||
|
||||
return {
|
||||
// 设备类型
|
||||
isMobile,
|
||||
isTablet,
|
||||
isDesktop,
|
||||
|
||||
// 精确断点
|
||||
isXs,
|
||||
isSm,
|
||||
isMd,
|
||||
isLg,
|
||||
isXl,
|
||||
isXxl,
|
||||
|
||||
// 尺寸
|
||||
width,
|
||||
height,
|
||||
|
||||
// 方向
|
||||
isPortrait,
|
||||
isLandscape,
|
||||
|
||||
// 当前断点名称
|
||||
currentBreakpoint,
|
||||
};
|
||||
}
|
||||
@@ -19,8 +19,9 @@ export function useWindowWidthObserver(
|
||||
const isAboveThreshold = ref(false);
|
||||
const thresholdRef = ref(threshold);
|
||||
let prevIsAbove = false; // 记录上一次状态,避免重复触发
|
||||
|
||||
// 待定 待梳理 1227
|
||||
// 默认逻辑:修改全局折叠状态
|
||||
// eslint-disable-next-line unused-imports/no-unused-vars
|
||||
const updateCollapseState = (isAbove: boolean) => {
|
||||
// 判断当前的折叠状态
|
||||
switch (designStore.collapseType) {
|
||||
@@ -70,7 +71,7 @@ export function useWindowWidthObserver(
|
||||
onChange(newIsAbove);
|
||||
}
|
||||
else {
|
||||
updateCollapseState(newIsAbove);
|
||||
// updateCollapseState(newIsAbove);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
35
Yi.Ai.Vue3/src/layouts/LayoutDefault/index.vue
Normal file
35
Yi.Ai.Vue3/src/layouts/LayoutDefault/index.vue
Normal file
@@ -0,0 +1,35 @@
|
||||
<script setup lang="ts">
|
||||
import SystemAnnouncementDialog from '@/components/SystemAnnouncementDialog/index.vue';
|
||||
import Header from '@/layouts/components/Header/index.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-container class="layout-container">
|
||||
<el-header class="layout-header">
|
||||
<Header />
|
||||
</el-header>
|
||||
<el-container class="layout-container-main">
|
||||
<router-view />
|
||||
</el-container>
|
||||
</el-container>
|
||||
|
||||
<!-- 系统公告弹窗 -->
|
||||
<SystemAnnouncementDialog />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.layout-container {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
background: var(--color-gray-100);
|
||||
.layout-header {
|
||||
padding: 0;
|
||||
border-bottom: var(--header-border) ;
|
||||
}
|
||||
.layout-container-main {
|
||||
height: calc(100vh - var(--header-container-default-height));
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,288 @@
|
||||
<!-- 手机端布局 -->
|
||||
<script setup></script>
|
||||
<!-- 移动端布局 -->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useUserStore } from '@/stores';
|
||||
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
|
||||
// 侧边栏抽屉状态
|
||||
const drawerVisible = ref(false);
|
||||
|
||||
// 底部导航菜单
|
||||
const bottomMenus = [
|
||||
{
|
||||
key: 'chat',
|
||||
label: '对话',
|
||||
icon: 'ChatDotRound',
|
||||
path: '/chat/conversation',
|
||||
},
|
||||
{
|
||||
key: 'image',
|
||||
label: '图片',
|
||||
icon: 'Picture',
|
||||
path: '/chat/image',
|
||||
},
|
||||
{
|
||||
key: 'video',
|
||||
label: '视频',
|
||||
icon: 'VideoCamera',
|
||||
path: '/chat/video',
|
||||
},
|
||||
{
|
||||
key: 'console',
|
||||
label: '我的',
|
||||
icon: 'User',
|
||||
path: '/console',
|
||||
},
|
||||
];
|
||||
|
||||
// 侧边栏菜单
|
||||
const sidebarMenus = [
|
||||
{
|
||||
key: 'model-library',
|
||||
label: '模型库',
|
||||
icon: 'Box',
|
||||
path: '/model-library',
|
||||
},
|
||||
{
|
||||
key: 'pricing',
|
||||
label: '购买',
|
||||
icon: 'ShoppingCart',
|
||||
path: '/pricing',
|
||||
},
|
||||
{
|
||||
key: 'logout',
|
||||
label: '退出登录',
|
||||
icon: 'SwitchButton',
|
||||
action: 'logout',
|
||||
},
|
||||
];
|
||||
|
||||
// 当前路由
|
||||
const currentPath = computed(() => router.currentRoute.value.path);
|
||||
|
||||
// 当前激活的底部菜单
|
||||
const activeBottomMenu = computed(() => {
|
||||
const path = currentPath.value;
|
||||
if (path.includes('/chat/conversation')) return 'chat';
|
||||
if (path.includes('/chat/image')) return 'image';
|
||||
if (path.includes('/chat/video')) return 'video';
|
||||
if (path.includes('/console')) return 'console';
|
||||
return 'chat';
|
||||
});
|
||||
|
||||
// 打开抽屉
|
||||
function openDrawer() {
|
||||
drawerVisible.value = true;
|
||||
}
|
||||
|
||||
// 底部菜单点击
|
||||
function handleBottomMenuClick(menu: typeof bottomMenus[0]) {
|
||||
router.push(menu.path);
|
||||
}
|
||||
|
||||
// 侧边栏菜单点击
|
||||
function handleSidebarMenuClick(menu: typeof sidebarMenus[0]) {
|
||||
if (menu.action === 'logout') {
|
||||
userStore.logout();
|
||||
drawerVisible.value = false;
|
||||
}
|
||||
else if (menu.path) {
|
||||
router.push(menu.path);
|
||||
drawerVisible.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div />
|
||||
<div class="mobile-layout">
|
||||
<!-- 顶部栏 -->
|
||||
<div class="mobile-header">
|
||||
<el-button circle @click="openDrawer">
|
||||
<el-icon><i-ep-menu /></el-icon>
|
||||
</el-button>
|
||||
<div class="header-title">意心AI</div>
|
||||
<div class="header-avatar">
|
||||
<el-avatar v-if="userStore.userInfo" :size="32" :src="userStore.userInfo.avatar">
|
||||
{{ userStore.userInfo.name?.charAt(0) }}
|
||||
</el-avatar>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<div class="mobile-main">
|
||||
<router-view />
|
||||
</div>
|
||||
|
||||
<!-- 底部导航 -->
|
||||
<div class="mobile-bottom-nav">
|
||||
<div
|
||||
v-for="menu in bottomMenus"
|
||||
:key="menu.key"
|
||||
class="nav-item"
|
||||
:class="{ active: activeBottomMenu === menu.key }"
|
||||
@click="handleBottomMenuClick(menu)"
|
||||
>
|
||||
<el-icon class="nav-icon">
|
||||
<component :is="`i-ep-${menu.icon}`" />
|
||||
</el-icon>
|
||||
<div class="nav-label">
|
||||
{{ menu.label }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 侧边栏抽屉 -->
|
||||
<el-drawer
|
||||
v-model="drawerVisible"
|
||||
title="菜单"
|
||||
direction="ltr"
|
||||
size="280px"
|
||||
>
|
||||
<!-- 用户信息 -->
|
||||
<div v-if="userStore.userInfo" class="drawer-user">
|
||||
<el-avatar :size="60" :src="userStore.userInfo.avatar">
|
||||
{{ userStore.userInfo.name?.charAt(0) }}
|
||||
</el-avatar>
|
||||
<div class="user-info">
|
||||
<div class="user-name">{{ userStore.userInfo.name }}</div>
|
||||
<div class="user-email">{{ userStore.userInfo.email }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 菜单列表 -->
|
||||
<el-menu class="drawer-menu">
|
||||
<el-menu-item
|
||||
v-for="menu in sidebarMenus"
|
||||
:key="menu.key"
|
||||
@click="handleSidebarMenuClick(menu)"
|
||||
>
|
||||
<el-icon>
|
||||
<component :is="`i-ep-${menu.icon}`" />
|
||||
</el-icon>
|
||||
<span>{{ menu.label }}</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss"></style>
|
||||
<style scoped lang="scss">
|
||||
.mobile-layout {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
background-color: var(--el-bg-color);
|
||||
}
|
||||
|
||||
.mobile-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 56px;
|
||||
padding: 0 16px;
|
||||
background-color: var(--el-bg-color);
|
||||
border-bottom: 1px solid var(--el-border-color);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.header-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.header-avatar {
|
||||
width: 40px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.mobile-main {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.mobile-bottom-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
height: 56px;
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
background-color: var(--el-bg-color);
|
||||
border-top: 1px solid var(--el-border-color);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
color: var(--el-text-color-secondary);
|
||||
transition: all 0.2s;
|
||||
|
||||
&.active {
|
||||
color: var(--el-color-primary);
|
||||
|
||||
.nav-icon {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
&:active {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
font-size: 24px;
|
||||
margin-bottom: 2px;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.nav-label {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
// 抽屉样式
|
||||
.drawer-user {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 24px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
margin-top: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.user-name {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.user-email {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.drawer-menu {
|
||||
border-right: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
<script setup lang="ts">
|
||||
import SystemAnnouncementDialog from '@/components/SystemAnnouncementDialog/index.vue';
|
||||
import { useSafeArea } from '@/hooks/useSafeArea';
|
||||
import { useWindowWidthObserver } from '@/hooks/useWindowWidthObserver';
|
||||
import Aside from '@/layouts/components/Aside/index.vue';
|
||||
import Header from '@/layouts/components/Header/index.vue';
|
||||
import Main from '@/layouts/components/Main/index.vue';
|
||||
import { useAnnouncementStore, useDesignStore } from '@/stores';
|
||||
@@ -25,7 +23,7 @@ useSafeArea({
|
||||
});
|
||||
|
||||
/** 监听窗口大小变化,折叠侧边栏 */
|
||||
useWindowWidthObserver();
|
||||
// useWindowWidthObserver();
|
||||
|
||||
// 应用加载时检查是否需要显示公告弹窗
|
||||
onMounted(() => {
|
||||
@@ -43,7 +41,7 @@ onMounted(() => {
|
||||
<Header />
|
||||
</el-header>
|
||||
<el-container class="layout-container-main">
|
||||
<Aside />
|
||||
<!-- <Aside /> -->
|
||||
<el-main class="layout-main">
|
||||
<!-- 路由页面 -->
|
||||
<Main />
|
||||
@@ -55,29 +53,29 @@ onMounted(() => {
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.layout-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
.layout-header {
|
||||
padding: 0;
|
||||
}
|
||||
.layout-main {
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
}
|
||||
.layout-container-main {
|
||||
margin-left: var(--sidebar-left-container-default-width, 0);
|
||||
transition: margin-left 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
/** 去除菜单右侧边框 */
|
||||
.el-menu {
|
||||
border-right: none;
|
||||
}
|
||||
.layout-scrollbar {
|
||||
width: 100%;
|
||||
}
|
||||
//.layout-container {
|
||||
// position: relative;
|
||||
// width: 100%;
|
||||
// height: 100vh;
|
||||
// overflow: hidden;
|
||||
// .layout-header {
|
||||
// padding: 0;
|
||||
// }
|
||||
// .layout-main {
|
||||
// height: 100%;
|
||||
// padding: 0;
|
||||
// }
|
||||
// .layout-container-main {
|
||||
// margin-left: var(--sidebar-left-container-default-width, 0);
|
||||
// transition: margin-left 0.3s ease;
|
||||
// }
|
||||
//}
|
||||
//
|
||||
///** 去除菜单右侧边框 */
|
||||
//.el-menu {
|
||||
// border-right: none;
|
||||
//}
|
||||
//.layout-scrollbar {
|
||||
// width: 100%;
|
||||
//}
|
||||
</style>
|
||||
|
||||
@@ -1,392 +0,0 @@
|
||||
<!-- Aside 侧边栏 -->
|
||||
<script setup lang="ts">
|
||||
import type { ConversationItem } from 'vue-element-plus-x/types/Conversations';
|
||||
import type { ChatSessionVo } from '@/api/session/types';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { get_session } from '@/api';
|
||||
import logo from '@/assets/images/logo.png';
|
||||
import SvgIcon from '@/components/SvgIcon/index.vue';
|
||||
import Collapse from '@/layouts/components/Header/components/Collapse.vue';
|
||||
import { useDesignStore } from '@/stores';
|
||||
import { useSessionStore } from '@/stores/modules/session';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const designStore = useDesignStore();
|
||||
const sessionStore = useSessionStore();
|
||||
|
||||
const sessionId = computed(() => route.params?.id);
|
||||
const conversationsList = computed(() => sessionStore.sessionList);
|
||||
const loadMoreLoading = computed(() => sessionStore.isLoadingMore);
|
||||
const active = ref<string | undefined>();
|
||||
|
||||
onMounted(async () => {
|
||||
// 获取会话列表
|
||||
await sessionStore.requestSessionList();
|
||||
// 高亮最新会话
|
||||
if (conversationsList.value.length > 0 && sessionId.value) {
|
||||
const currentSessionRes = await get_session(`${sessionId.value}`);
|
||||
// 通过 ID 查询详情,设置当前会话 (因为有分页)
|
||||
sessionStore.setCurrentSession(currentSessionRes.data);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => sessionStore.currentSession,
|
||||
(newValue) => {
|
||||
active.value = newValue ? `${newValue.id}` : undefined;
|
||||
},
|
||||
);
|
||||
|
||||
// 创建会话
|
||||
function handleCreatChat() {
|
||||
// 创建会话, 跳转到默认聊天
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
|
||||
// 切换会话
|
||||
function handleChange(item: ConversationItem<ChatSessionVo>) {
|
||||
sessionStore.setCurrentSession(item);
|
||||
router.replace({
|
||||
name: 'chatWithId',
|
||||
params: {
|
||||
id: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 处理组件触发的加载更多事件
|
||||
async function handleLoadMore() {
|
||||
if (!sessionStore.hasMore)
|
||||
return; // 无更多数据时不加载
|
||||
await sessionStore.loadMoreSessions();
|
||||
}
|
||||
|
||||
// 右键菜单
|
||||
function handleMenuCommand(command: string, item: ConversationItem<ChatSessionVo>) {
|
||||
switch (command) {
|
||||
case 'delete':
|
||||
ElMessageBox.confirm('删除后,聊天记录将不可恢复。', '确定删除对话?', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
confirmButtonClass: 'el-button--danger',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
autofocus: false,
|
||||
})
|
||||
.then(() => {
|
||||
// 删除会话
|
||||
sessionStore.deleteSessions([item.id!]);
|
||||
nextTick(() => {
|
||||
if (item.id === active.value) {
|
||||
// 如果删除当前会话 返回到默认页
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 取消删除
|
||||
});
|
||||
break;
|
||||
case 'rename':
|
||||
ElMessageBox.prompt('', '编辑对话名称', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
inputErrorMessage: '请输入对话名称',
|
||||
confirmButtonClass: 'el-button--primary',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
inputValue: item.sessionTitle, // 设置默认值
|
||||
autofocus: false,
|
||||
inputValidator: (value) => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
}).then(({ value }) => {
|
||||
sessionStore
|
||||
.updateSession({
|
||||
id: item.id!,
|
||||
sessionTitle: value,
|
||||
sessionContent: item.sessionContent,
|
||||
})
|
||||
.then(() => {
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
message: '修改成功',
|
||||
});
|
||||
nextTick(() => {
|
||||
// 如果是当前会话,则更新当前选中会话信息
|
||||
if (sessionStore.currentSession?.id === item.id) {
|
||||
sessionStore.setCurrentSession({
|
||||
...item,
|
||||
sessionTitle: value,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="aside-container"
|
||||
:class="{
|
||||
'aside-container-suspended': designStore.isSafeAreaHover,
|
||||
'aside-container-collapse': designStore.isCollapse,
|
||||
// 折叠且未激活悬停时添加 no-delay 类
|
||||
'no-delay': designStore.isCollapse && !designStore.hasActivatedHover,
|
||||
}"
|
||||
>
|
||||
<div class="aside-wrapper">
|
||||
<div v-if="!designStore.isCollapse" class="aside-header">
|
||||
<div class="flex items-center gap-8px hover:cursor-pointer" @click="handleCreatChat">
|
||||
<el-image :src="logo" alt="logo" fit="cover" class="logo-img" />
|
||||
<span class="logo-text max-w-150px text-overflow">意心AI</span>
|
||||
</div>
|
||||
<Collapse class="ml-auto" />
|
||||
</div>
|
||||
|
||||
<div class="aside-body">
|
||||
<div class="creat-chat-btn-wrapper">
|
||||
<div class="creat-chat-btn" @click="handleCreatChat">
|
||||
<el-icon class="add-icon">
|
||||
<Plus />
|
||||
</el-icon>
|
||||
<span class="creat-chat-text">新对话</span>
|
||||
<SvgIcon name="ctrl+k" size="37" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="aside-content">
|
||||
<div v-if="conversationsList.length > 0" class="conversations-wrap overflow-hidden">
|
||||
<Conversations
|
||||
v-model:active="active"
|
||||
:items="conversationsList"
|
||||
:label-max-width="200"
|
||||
:show-tooltip="true"
|
||||
:tooltip-offset="60"
|
||||
show-built-in-menu
|
||||
groupable
|
||||
row-key="id"
|
||||
label-key="sessionTitle"
|
||||
tooltip-placement="right"
|
||||
:load-more="handleLoadMore"
|
||||
:load-more-loading="loadMoreLoading"
|
||||
:items-style="{
|
||||
marginLeft: '8px',
|
||||
userSelect: 'none',
|
||||
borderRadius: '10px',
|
||||
padding: '8px 12px',
|
||||
}"
|
||||
:items-active-style="{
|
||||
backgroundColor: '#fff',
|
||||
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
|
||||
color: 'rgba(0, 0, 0, 0.85)',
|
||||
}"
|
||||
:items-hover-style="{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.04)',
|
||||
}"
|
||||
@menu-command="handleMenuCommand"
|
||||
@change="handleChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<el-empty v-else class="h-full flex-center" description="暂无对话记录" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
// 基础样式
|
||||
.aside-container {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
// z-index: 11;
|
||||
width: var(--sidebar-default-width);
|
||||
height: 100%;
|
||||
pointer-events: auto;
|
||||
background-color: var(--sidebar-background-color);
|
||||
border-right: 0.5px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
|
||||
.aside-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
|
||||
// 侧边栏头部样式
|
||||
.aside-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 36px;
|
||||
margin: 10px 12px 0;
|
||||
.logo-img {
|
||||
box-sizing: border-box;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 4px;
|
||||
overflow: hidden;
|
||||
background-color: #ffffff;
|
||||
border-radius: 50%;
|
||||
img {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
.logo-text {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: rgb(0 0 0 / 85%);
|
||||
transform: skewX(-2deg);
|
||||
}
|
||||
}
|
||||
|
||||
// 侧边栏内容样式
|
||||
.aside-body {
|
||||
.creat-chat-btn-wrapper {
|
||||
padding: 0 12px;
|
||||
.creat-chat-btn {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
padding: 8px 6px;
|
||||
margin-top: 16px;
|
||||
margin-bottom: 6px;
|
||||
color: #0057ff;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
background-color: rgb(0 87 255 / 6%);
|
||||
border: 1px solid rgb(0 102 255 / 15%);
|
||||
border-radius: 12px;
|
||||
&:hover {
|
||||
background-color: rgb(0 87 255 / 12%);
|
||||
}
|
||||
.creat-chat-text {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 22px;
|
||||
}
|
||||
.add-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.svg-icon {
|
||||
height: 24px;
|
||||
margin-left: auto;
|
||||
color: rgb(0 87 255 / 30%);
|
||||
}
|
||||
}
|
||||
}
|
||||
.aside-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
|
||||
// 会话列表高度-基础样式
|
||||
.conversations-wrap {
|
||||
height: calc(100vh - 110px);
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠样式
|
||||
.aside-container-collapse {
|
||||
position: absolute;
|
||||
top: 54px;
|
||||
// z-index: 22;
|
||||
height: auto;
|
||||
max-height: calc(100% - 110px);
|
||||
padding-bottom: 12px;
|
||||
overflow: hidden;
|
||||
|
||||
/* 禁用悬停事件 */
|
||||
pointer-events: none;
|
||||
border: 1px solid rgb(0 0 0 / 8%);
|
||||
border-radius: 15px;
|
||||
box-shadow:
|
||||
0 10px 20px 0 rgb(0 0 0 / 10%),
|
||||
0 0 1px 0 rgb(0 0 0 / 15%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease 0.3s, transform 0.3s ease 0.3s;
|
||||
|
||||
// 指定样式过渡
|
||||
|
||||
// 向左偏移一个宽度
|
||||
transform: translateX(-100%);
|
||||
|
||||
/* 新增:未激活悬停时覆盖延迟 */
|
||||
&.no-delay {
|
||||
transition-delay: 0s, 0s;
|
||||
}
|
||||
}
|
||||
|
||||
// 悬停样式
|
||||
.aside-container-collapse:hover,
|
||||
.aside-container-collapse.aside-container-suspended {
|
||||
height: auto;
|
||||
max-height: calc(100% - 110px);
|
||||
padding-bottom: 12px;
|
||||
overflow: hidden;
|
||||
pointer-events: auto;
|
||||
border: 1px solid rgb(0 0 0 / 8%);
|
||||
border-radius: 15px;
|
||||
box-shadow:
|
||||
0 10px 20px 0 rgb(0 0 0 / 10%),
|
||||
0 0 1px 0 rgb(0 0 0 / 15%);
|
||||
|
||||
// 直接在这里写悬停时的样式(与 aside-container-suspended 一致)
|
||||
opacity: 1;
|
||||
transition: opacity 0.3s ease 0s, transform 0.3s ease 0s;
|
||||
|
||||
// 过渡动画沿用原有设置
|
||||
transform: translateX(15px);
|
||||
|
||||
// 会话列表高度-悬停样式
|
||||
.conversations-wrap {
|
||||
height: calc(100vh - 155px) !important;
|
||||
}
|
||||
}
|
||||
|
||||
// 样式穿透
|
||||
:deep() {
|
||||
// 会话列表背景色
|
||||
.conversations-list {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
// 群组标题样式 和 侧边栏菜单背景色一致
|
||||
.conversation-group-title {
|
||||
padding-left: 12px !important;
|
||||
background-color: var(--sidebar-background-color) !important;
|
||||
}
|
||||
.conversation-group .active-sticky
|
||||
{
|
||||
z-index: 0 ;
|
||||
}
|
||||
.conversation-group .sticky-title{
|
||||
z-index: 0 ;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
804
Yi.Ai.Vue3/src/layouts/components/ChatAside/index.vue
Normal file
804
Yi.Ai.Vue3/src/layouts/components/ChatAside/index.vue
Normal file
@@ -0,0 +1,804 @@
|
||||
<script setup lang="ts">
|
||||
import type { ConversationItem } from 'vue-element-plus-x/types/Conversations';
|
||||
import type { ChatSessionVo } from '@/api/session/types';
|
||||
import { ChatLineSquare, Expand, Fold, MoreFilled, Plus } from '@element-plus/icons-vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { get_session } from '@/api';
|
||||
import { useDesignStore } from '@/stores';
|
||||
import { useSessionStore } from '@/stores/modules/session';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const designStore = useDesignStore();
|
||||
const sessionStore = useSessionStore();
|
||||
|
||||
const sessionId = computed(() => route.params?.id);
|
||||
const conversationsList = computed(() => sessionStore.sessionList);
|
||||
const loadMoreLoading = computed(() => sessionStore.isLoadingMore);
|
||||
const active = ref<string | undefined>();
|
||||
const isCollapsed = computed(() => designStore.isCollapseConversationList);
|
||||
|
||||
// 判断是否为新建对话状态(没有选中任何会话)
|
||||
const isNewChatState = computed(() => !sessionStore.currentSession);
|
||||
|
||||
onMounted(async () => {
|
||||
await sessionStore.requestSessionList();
|
||||
if (conversationsList.value.length > 0 && sessionId.value) {
|
||||
const currentSessionRes = await get_session(`${sessionId.value}`);
|
||||
sessionStore.setCurrentSession(currentSessionRes.data);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => sessionStore.currentSession,
|
||||
(newValue) => {
|
||||
active.value = newValue ? `${newValue.id}` : undefined;
|
||||
},
|
||||
);
|
||||
|
||||
// 创建会话
|
||||
function handleCreatChat() {
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
|
||||
// 切换会话
|
||||
function handleChange(item: ConversationItem<ChatSessionVo>) {
|
||||
sessionStore.setCurrentSession(item);
|
||||
router.replace({
|
||||
name: 'chatConversationWithId',
|
||||
params: {
|
||||
id: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 处理组件触发的加载更多事件
|
||||
async function handleLoadMore() {
|
||||
if (!sessionStore.hasMore)
|
||||
return;
|
||||
await sessionStore.loadMoreSessions();
|
||||
}
|
||||
|
||||
// 右键菜单
|
||||
function handleMenuCommand(command: string, item: ConversationItem<ChatSessionVo>) {
|
||||
switch (command) {
|
||||
case 'delete':
|
||||
ElMessageBox.confirm('删除后,聊天记录将不可恢复。', '确定删除对话?', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
confirmButtonClass: 'el-button--danger',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
autofocus: false,
|
||||
})
|
||||
.then(() => {
|
||||
sessionStore.deleteSessions([item.id!]);
|
||||
nextTick(() => {
|
||||
if (item.id === active.value) {
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 取消删除
|
||||
});
|
||||
break;
|
||||
case 'rename':
|
||||
ElMessageBox.prompt('', '编辑对话名称', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
inputErrorMessage: '请输入对话名称',
|
||||
confirmButtonClass: 'el-button--primary',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
inputValue: item.sessionTitle,
|
||||
autofocus: false,
|
||||
inputValidator: (value) => {
|
||||
return !!value;
|
||||
},
|
||||
}).then(({ value }) => {
|
||||
sessionStore
|
||||
.updateSession({
|
||||
id: item.id!,
|
||||
sessionTitle: value,
|
||||
sessionContent: item.sessionContent,
|
||||
})
|
||||
.then(() => {
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
message: '修改成功',
|
||||
});
|
||||
nextTick(() => {
|
||||
if (sessionStore.currentSession?.id === item.id) {
|
||||
sessionStore.setCurrentSession({
|
||||
...item,
|
||||
sessionTitle: value,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠/展开侧边栏
|
||||
function toggleSidebar() {
|
||||
designStore.setIsCollapseConversationList(!designStore.isCollapseConversationList);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="aside-container"
|
||||
:class="{ 'aside-collapsed': isCollapsed }"
|
||||
>
|
||||
<div class="aside-wrapper">
|
||||
<!-- 头部 -->
|
||||
<div class="aside-header">
|
||||
<!-- 展开状态显示logo和标题 -->
|
||||
<div
|
||||
v-if="!isCollapsed"
|
||||
class="header-content-expanded flex items-center gap-8px"
|
||||
:class="{ 'is-disabled': isNewChatState, 'hover:cursor-pointer': !isNewChatState }"
|
||||
@click="!isNewChatState && handleCreatChat()"
|
||||
>
|
||||
<span class="logo-text max-w-150px text-overflow">会话</span>
|
||||
</div>
|
||||
|
||||
<!-- 折叠状态只显示logo -->
|
||||
<div
|
||||
v-else
|
||||
class="header-content-collapsed flex items-center justify-center hover:cursor-pointer"
|
||||
@click="handleLogoClick"
|
||||
>
|
||||
<el-icon size="20">
|
||||
<ChatLineSquare />
|
||||
</el-icon>
|
||||
</div>
|
||||
|
||||
<!-- 折叠按钮 -->
|
||||
<el-tooltip
|
||||
:content="isCollapsed ? '展开侧边栏' : '折叠侧边栏'"
|
||||
placement="bottom"
|
||||
>
|
||||
<el-button
|
||||
class="collapse-btn"
|
||||
type="text"
|
||||
@click="toggleSidebar"
|
||||
>
|
||||
<el-icon v-if="isCollapsed">
|
||||
<Expand />
|
||||
</el-icon>
|
||||
<el-icon v-else>
|
||||
<Fold />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="aside-body">
|
||||
<!-- 创建会话按钮 -->
|
||||
<div class="creat-chat-btn-wrapper">
|
||||
<div
|
||||
class="creat-chat-btn"
|
||||
:class="{
|
||||
'creat-chat-btn-collapsed': isCollapsed,
|
||||
'is-disabled': isNewChatState
|
||||
}"
|
||||
@click="!isNewChatState && handleCreatChat()"
|
||||
>
|
||||
<el-icon class="add-icon">
|
||||
<Plus />
|
||||
</el-icon>
|
||||
<span v-if="!isCollapsed" class="creat-chat-text">
|
||||
新对话
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 会话列表 -->
|
||||
<div class="aside-content">
|
||||
<div v-if="conversationsList.length > 0" class="conversations-wrap">
|
||||
<Conversations
|
||||
v-model:active="active"
|
||||
:items="conversationsList"
|
||||
:label-max-width="isCollapsed ? 0 : 140"
|
||||
:show-tooltip="!isCollapsed"
|
||||
:tooltip-offset="60"
|
||||
show-built-in-menu
|
||||
groupable
|
||||
row-key="id"
|
||||
label-key="sessionTitle"
|
||||
:tooltip-placement="isCollapsed ? 'right-start' : 'right'"
|
||||
:load-more="handleLoadMore"
|
||||
:load-more-loading="loadMoreLoading"
|
||||
:items-style="{
|
||||
marginLeft: '8px',
|
||||
marginRight: '8px',
|
||||
userSelect: 'none',
|
||||
borderRadius: isCollapsed ? '12px' : '10px',
|
||||
padding: isCollapsed ? '12px 8px' : '8px 12px',
|
||||
justifyContent: isCollapsed ? 'center' : 'space-between',
|
||||
width: isCollapsed ? '64px' : 'auto',
|
||||
height: isCollapsed ? '64px' : 'auto',
|
||||
minHeight: '48px',
|
||||
flexDirection: isCollapsed ? 'column' : 'row',
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
}"
|
||||
:items-active-style="{
|
||||
backgroundColor: '#fff',
|
||||
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
|
||||
color: 'rgba(0, 0, 0, 0.85)',
|
||||
}"
|
||||
:items-hover-style="{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.04)',
|
||||
}"
|
||||
@menu-command="handleMenuCommand"
|
||||
@change="handleChange"
|
||||
@contextmenu="handleContextMenu"
|
||||
>
|
||||
<!-- 自定义折叠状态下的会话项内容 -->
|
||||
<template #default="{ item }">
|
||||
<div class="conversation-item-content">
|
||||
<div v-if="isCollapsed" class="collapsed-item">
|
||||
<div
|
||||
class="avatar-circle"
|
||||
@click="handleChange(item)"
|
||||
@contextmenu="(e) => handleContextMenu(e, item)"
|
||||
>
|
||||
{{ item.sessionTitle?.charAt(0) || 'A' }}
|
||||
</div>
|
||||
<div v-if="item.unreadCount" class="unread-indicator">
|
||||
{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
|
||||
</div>
|
||||
<!-- 折叠状态下的更多操作按钮 -->
|
||||
<div
|
||||
class="collapsed-menu-trigger"
|
||||
@click.stop="(e) => handleCollapsedMenuClick(e, item)"
|
||||
@contextmenu.stop="(e) => handleContextMenu(e, item)"
|
||||
>
|
||||
<el-icon size="14">
|
||||
<MoreFilled />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="expanded-item">
|
||||
<div class="conversation-info">
|
||||
<div class="conversation-title">
|
||||
{{ item.sessionTitle }}
|
||||
</div>
|
||||
<div v-if="item.sessionContent" class="conversation-preview">
|
||||
{{ item.sessionContent.substring(0, 30) }}{{ item.sessionContent.length > 30 ? '...' : '' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Conversations>
|
||||
</div>
|
||||
|
||||
<el-empty
|
||||
v-else
|
||||
class="h-full flex-center"
|
||||
:description="isCollapsed ? '' : '暂无对话记录'"
|
||||
>
|
||||
<template #description>
|
||||
<span v-if="!isCollapsed">暂无对话记录</span>
|
||||
</template>
|
||||
</el-empty>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
// 基础样式
|
||||
.aside-container {
|
||||
height: 100%;
|
||||
border-right: 0.5px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
background-color: var(--sidebar-background-color, #f9fafb);
|
||||
|
||||
// 展开状态 - 240px
|
||||
&:not(.aside-collapsed) {
|
||||
width: 240px;
|
||||
|
||||
.aside-wrapper {
|
||||
width: 240px;
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠状态 - 100px
|
||||
&.aside-collapsed {
|
||||
display: none;
|
||||
|
||||
.aside-wrapper {
|
||||
width: 100px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.aside-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
// 头部样式
|
||||
.aside-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 56px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
|
||||
//background-color: var(--sidebar-header-bg, #ffffff);
|
||||
|
||||
.header-content-expanded {
|
||||
flex: 1;
|
||||
transition: opacity 0.2s ease;
|
||||
|
||||
&.is-disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.header-content-collapsed {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.el-icon {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: rgb(0 0 0 / 85%);
|
||||
transform: skewX(-2deg);
|
||||
}
|
||||
|
||||
.collapse-btn {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--el-text-color-primary);
|
||||
background-color: var(--el-fill-color-light);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.el-icon {
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 内容区域
|
||||
.aside-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 4px;
|
||||
overflow: hidden;
|
||||
|
||||
.creat-chat-btn-wrapper {
|
||||
padding: 12px 8px 4px;
|
||||
|
||||
.creat-chat-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 40px;
|
||||
color: #0057ff;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
background-color: rgb(0 87 255 / 6%);
|
||||
border: 1px solid rgb(0 102 255 / 15%);
|
||||
border-radius: 12px;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover:not(.is-disabled) {
|
||||
background-color: rgb(0 87 255 / 12%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&.is-disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&.creat-chat-btn-collapsed {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.add-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.creat-chat-text {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 22px;
|
||||
margin-left: 6px;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.aside-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
|
||||
.conversations-wrap {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 0 4px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
&:hover::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.conversation-item-content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.collapsed-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.avatar-circle {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
.unread-indicator {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
background-color: #ff4d4f;
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
font-size: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.collapsed-menu-trigger {
|
||||
position: absolute;
|
||||
bottom: 4px;
|
||||
right: 4px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background-color: rgba(0, 0, 0, 0.05);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: all 0.2s ease;
|
||||
z-index: 2;
|
||||
|
||||
.el-icon {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .collapsed-menu-trigger {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.expanded-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
|
||||
.conversation-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin-right: 8px;
|
||||
overflow: hidden;
|
||||
|
||||
.conversation-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
line-height: 1.4;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.conversation-preview {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 样式穿透 - 重点修复溢出问题
|
||||
:deep() {
|
||||
.conversations-list {
|
||||
background-color: transparent !important;
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.conversation-group-title {
|
||||
padding-left: 12px !important;
|
||||
background-color: transparent !important;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
.title-text {
|
||||
opacity: 0.6;
|
||||
font-size: 12px;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
transition: all 0.3s ease;
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
|
||||
&-inner {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
display: flex !important;
|
||||
justify-content: space-between !important;
|
||||
align-items: center !important;
|
||||
}
|
||||
|
||||
&-content {
|
||||
flex: 1 !important;
|
||||
min-width: 0 !important;
|
||||
max-width: calc(100% - 32px) !important;
|
||||
overflow: hidden !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
// 确保操作按钮区域在展开状态下正常显示
|
||||
&-actions {
|
||||
flex-shrink: 0 !important;
|
||||
display: flex !important;
|
||||
align-items: center !important;
|
||||
opacity: 1 !important;
|
||||
visibility: visible !important;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
.el-button {
|
||||
transition: all 0.2s ease;
|
||||
width: 24px !important;
|
||||
height: 24px !important;
|
||||
padding: 0 !important;
|
||||
margin-left: 4px !important;
|
||||
flex-shrink: 0 !important;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.el-icon {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠状态样式
|
||||
.aside-collapsed {
|
||||
.conversation-group-title {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
justify-content: center !important;
|
||||
padding: 12px 8px !important;
|
||||
height: 64px !important;
|
||||
min-height: 64px !important;
|
||||
|
||||
&-label {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
&-actions {
|
||||
// 折叠状态下隐藏默认操作按钮,使用自定义的
|
||||
display: none !important;
|
||||
opacity: 0 !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
|
||||
&-content {
|
||||
max-width: 100% !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 展开状态样式
|
||||
&:not(.aside-collapsed) {
|
||||
.conversation-item {
|
||||
&-actions {
|
||||
display: flex !important;
|
||||
opacity: 1 !important;
|
||||
visibility: visible !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义对话框样式
|
||||
:deep(.collapsed-menu-dialog) {
|
||||
.el-message-box {
|
||||
width: 160px !important;
|
||||
padding: 12px !important;
|
||||
|
||||
&__header {
|
||||
padding: 0 0 8px 0 !important;
|
||||
border-bottom: none !important;
|
||||
}
|
||||
|
||||
&__title {
|
||||
font-size: 14px !important;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
|
||||
&__content {
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
&__headerbtn {
|
||||
top: 8px !important;
|
||||
right: 8px !important;
|
||||
|
||||
.el-icon {
|
||||
font-size: 14px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端适配
|
||||
@media (max-width: 768px) {
|
||||
.aside-container {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 1000;
|
||||
width: 280px !important;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
|
||||
|
||||
&.aside-collapsed {
|
||||
transform: translateX(-100%);
|
||||
width: 100px !important;
|
||||
}
|
||||
|
||||
&:not(.aside-collapsed) {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.aside-wrapper {
|
||||
width: 280px !important;
|
||||
|
||||
.aside-collapsed & {
|
||||
width: 100px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端遮罩层
|
||||
.aside-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
z-index: 999;
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
// 动画
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -30,40 +30,40 @@ const popoverRef = ref();
|
||||
// 弹出面板内容
|
||||
const popoverList = ref([
|
||||
|
||||
{
|
||||
key: '5',
|
||||
title: '控制台',
|
||||
icon: 'settings-4-fill',
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
divider: true,
|
||||
},
|
||||
{
|
||||
key: '7',
|
||||
title: '公告',
|
||||
icon: 'notification-fill',
|
||||
},
|
||||
{
|
||||
key: '8',
|
||||
title: '模型库',
|
||||
icon: 'apps-fill',
|
||||
},
|
||||
{
|
||||
key: '9',
|
||||
title: '文档',
|
||||
icon: 'book-fill',
|
||||
},
|
||||
|
||||
{
|
||||
key: '6',
|
||||
title: '新手引导',
|
||||
icon: 'dashboard-fill',
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
divider: true,
|
||||
},
|
||||
// {
|
||||
// key: '5',
|
||||
// title: '控制台',
|
||||
// icon: 'settings-4-fill',
|
||||
// },
|
||||
// {
|
||||
// key: '3',
|
||||
// divider: true,
|
||||
// },
|
||||
// {
|
||||
// key: '7',
|
||||
// title: '公告',
|
||||
// icon: 'notification-fill',
|
||||
// },
|
||||
// {
|
||||
// key: '8',
|
||||
// title: '模型库',
|
||||
// icon: 'apps-fill',
|
||||
// },
|
||||
// {
|
||||
// key: '9',
|
||||
// title: '文档',
|
||||
// icon: 'book-fill',
|
||||
// },
|
||||
//
|
||||
// {
|
||||
// key: '6',
|
||||
// title: '新手引导',
|
||||
// icon: 'dashboard-fill',
|
||||
// },
|
||||
// {
|
||||
// key: '3',
|
||||
// divider: true,
|
||||
// },
|
||||
{
|
||||
key: '4',
|
||||
title: '退出登录',
|
||||
@@ -92,6 +92,7 @@ const navItems = [
|
||||
{ name: 'dailyTask', label: '每日任务(限时)', icon: 'Trophy' },
|
||||
{ name: 'cardFlip', label: '每周邀请(限时)', icon: 'Present' },
|
||||
// { name: 'usageStatistics2', label: '用量统计2', icon: 'Histogram' },
|
||||
{ name: 'activationCode', label: '激活码兑换', icon: 'MagicStick' },
|
||||
];
|
||||
function openDialog() {
|
||||
dialogVisible.value = true;
|
||||
@@ -103,6 +104,10 @@ function handleConfirm(activeNav: string) {
|
||||
// 导航切换
|
||||
function handleNavChange(nav: string) {
|
||||
activeNav.value = nav;
|
||||
// 同步更新 store 中的 tab 状态,防止下次通过 store 打开同一 tab 时因值未变而不触发 watch
|
||||
if (userStore.userCenterActiveTab !== nav) {
|
||||
userStore.userCenterActiveTab = nav;
|
||||
}
|
||||
}
|
||||
|
||||
// 联系售后
|
||||
@@ -125,7 +130,9 @@ function handleClick(item: any) {
|
||||
ElMessage.warning('暂未开放');
|
||||
break;
|
||||
case '5':
|
||||
openDialog();
|
||||
// 打开控制台
|
||||
popoverRef.value?.hide?.();
|
||||
router.push('/console');
|
||||
break;
|
||||
case '6':
|
||||
handleStartTutorial();
|
||||
@@ -302,6 +309,27 @@ watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 监听 Store 状态,控制用户中心弹窗 (新增) ============
|
||||
watch(() => userStore.isUserCenterVisible, (val) => {
|
||||
dialogVisible.value = val;
|
||||
if (val && userStore.userCenterActiveTab) {
|
||||
activeNav.value = userStore.userCenterActiveTab;
|
||||
}
|
||||
});
|
||||
|
||||
watch(() => userStore.userCenterActiveTab, (val) => {
|
||||
if (val) {
|
||||
activeNav.value = val;
|
||||
}
|
||||
});
|
||||
|
||||
// 监听本地 dialogVisible 变化,同步回 Store(可选,为了保持一致性)
|
||||
watch(dialogVisible, (val) => {
|
||||
if (!val) {
|
||||
userStore.closeUserCenter();
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 暴露方法供外部调用 ============
|
||||
defineExpose({
|
||||
openDialog,
|
||||
@@ -440,6 +468,9 @@ defineExpose({
|
||||
<template #apiKey>
|
||||
<APIKeyManagement />
|
||||
</template>
|
||||
<template #activationCode>
|
||||
<activation-code />
|
||||
</template>
|
||||
<template #dailyTask>
|
||||
<daily-task />
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
// 检查是否在聊天页面
|
||||
const isOnChatPage = computed(() => {
|
||||
return route.path.startsWith('/chat');
|
||||
});
|
||||
|
||||
function goToChat() {
|
||||
router.push('/chat/conversation');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="!isOnChatPage" class="start-chat-btn-container" data-tour="start-chat-btn">
|
||||
<div
|
||||
class="start-chat-btn"
|
||||
title="开始聊天"
|
||||
@click="goToChat"
|
||||
>
|
||||
<el-icon class="chat-icon">
|
||||
<i-ep-chat-dot-round />
|
||||
</el-icon>
|
||||
<span class="btn-text">开始聊天</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.start-chat-btn-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 12px;
|
||||
|
||||
.start-chat-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s;
|
||||
box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.chat-icon {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.btn-text {
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端隐藏文字
|
||||
@media (max-width: 768px) {
|
||||
.start-chat-btn-container {
|
||||
margin-right: 8px;
|
||||
|
||||
.start-chat-btn {
|
||||
padding: 8px;
|
||||
|
||||
.btn-text {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,95 @@
|
||||
<script setup lang="ts">
|
||||
import { useColorMode } from '@vueuse/core';
|
||||
|
||||
// 使用 VueUse 的 useColorMode
|
||||
const mode = useColorMode({
|
||||
attribute: 'class',
|
||||
modes: {
|
||||
light: 'light',
|
||||
dark: 'dark',
|
||||
},
|
||||
});
|
||||
|
||||
// 切换主题
|
||||
function toggleTheme() {
|
||||
mode.value = mode.value === 'dark' ? 'light' : 'dark';
|
||||
}
|
||||
|
||||
// 主题图标
|
||||
const themeIcon = computed(() => {
|
||||
return mode.value === 'dark' ? 'Sunny' : 'Moon';
|
||||
});
|
||||
|
||||
// 主题标题
|
||||
const themeTitle = computed(() => {
|
||||
return mode.value === 'dark' ? '切换到浅色模式' : '切换到深色模式';
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="theme-btn-container" data-tour="theme-btn">
|
||||
<div
|
||||
class="theme-btn"
|
||||
:title="themeTitle"
|
||||
@click="toggleTheme"
|
||||
>
|
||||
<!-- PC端显示文字 + 图标 -->
|
||||
<el-icon class="theme-icon">
|
||||
<component :is="`i-ep-${themeIcon}`" />
|
||||
</el-icon>
|
||||
<span class="pc-text">主题</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.theme-btn-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.theme-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.2s;
|
||||
color: var(--el-text-color-regular);
|
||||
|
||||
&:hover {
|
||||
background-color: var(--el-fill-color-light);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.theme-icon {
|
||||
font-size: 18px;
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
|
||||
&:hover .theme-icon {
|
||||
transform: rotate(20deg);
|
||||
}
|
||||
|
||||
// PC端显示文字
|
||||
.pc-text {
|
||||
display: inline;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端隐藏文字
|
||||
@media (max-width: 768px) {
|
||||
.theme-btn-container {
|
||||
.theme-btn {
|
||||
padding: 8px;
|
||||
|
||||
.pc-text {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,94 +1,50 @@
|
||||
<!-- Header 头部 -->
|
||||
<!--
|
||||
<!– Header 头部 –>
|
||||
<script setup lang="ts">
|
||||
import { onKeyStroke } from '@vueuse/core';
|
||||
import { SIDE_BAR_WIDTH } from '@/config/index';
|
||||
import { useDesignStore, useUserStore } from '@/stores';
|
||||
import { useSessionStore } from '@/stores/modules/session';
|
||||
import { useRouter } from 'vue-router';
|
||||
import logo from '@/assets/images/logo.png';
|
||||
import { useUserStore } from '@/stores';
|
||||
import AiTutorialBtn from './components/AiTutorialBtn.vue';
|
||||
import AnnouncementBtn from './components/AnnouncementBtn.vue';
|
||||
import Avatar from './components/Avatar.vue';
|
||||
import BuyBtn from './components/BuyBtn.vue';
|
||||
import Collapse from './components/Collapse.vue';
|
||||
import ConsoleBtn from './components/ConsoleBtn.vue';
|
||||
import CreateChat from './components/CreateChat.vue';
|
||||
import LoginBtn from './components/LoginBtn.vue';
|
||||
import ModelLibraryBtn from './components/ModelLibraryBtn.vue';
|
||||
import TitleEditing from './components/TitleEditing.vue';
|
||||
import StartChatBtn from './components/StartChatBtn.vue';
|
||||
import ThemeBtn from './components/ThemeBtn.vue';
|
||||
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const designStore = useDesignStore();
|
||||
const sessionStore = useSessionStore();
|
||||
|
||||
const avatarRef = ref();
|
||||
|
||||
const currentSession = computed(() => sessionStore.currentSession);
|
||||
|
||||
onMounted(() => {
|
||||
// 全局设置侧边栏默认宽度 (这个是不变的,一开始就设置)
|
||||
document.documentElement.style.setProperty(`--sidebar-default-width`, `${SIDE_BAR_WIDTH}px`);
|
||||
if (designStore.isCollapse) {
|
||||
document.documentElement.style.setProperty(`--sidebar-left-container-default-width`, ``);
|
||||
}
|
||||
else {
|
||||
document.documentElement.style.setProperty(
|
||||
`--sidebar-left-container-default-width`,
|
||||
`${SIDE_BAR_WIDTH}px`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// 定义 Ctrl+K 的处理函数
|
||||
function handleCtrlK(event: KeyboardEvent) {
|
||||
event.preventDefault(); // 防止默认行为
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
|
||||
// 设置全局的键盘按键监听
|
||||
onKeyStroke(event => event.ctrlKey && event.key.toLowerCase() === 'k', handleCtrlK, {
|
||||
passive: false,
|
||||
});
|
||||
|
||||
// 打开控制台
|
||||
function handleOpenConsole() {
|
||||
avatarRef.value?.openDialog?.();
|
||||
router.push('/console');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="header-container">
|
||||
<div class="header-box relative z-10 top-0 left-0 right-0">
|
||||
<div class="absolute left-0 right-0 top-0 bottom-0 flex items-center flex-row">
|
||||
<div
|
||||
class="overflow-hidden flex h-full items-center flex-row flex-1 w-fit flex-shrink-0 min-w-0"
|
||||
>
|
||||
<div class="w-full flex items-center flex-row">
|
||||
<!-- 左边 -->
|
||||
<div
|
||||
v-if="designStore.isCollapse"
|
||||
class="left-box flex h-full items-center pl-20px gap-12px flex-shrink-0 flex-row"
|
||||
>
|
||||
<Collapse />
|
||||
<CreateChat />
|
||||
<div v-if="currentSession" class="w-0.5px h-30px bg-[rgba(217,217,217)]" />
|
||||
</div>
|
||||
|
||||
<!-- 中间 -->
|
||||
<div class="middle-box flex-1 min-w-0 ml-12px">
|
||||
<TitleEditing />
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-box">
|
||||
<!– 左侧logo和品牌区域 –>
|
||||
<div class="left-section">
|
||||
<div class="brand-container">
|
||||
<el-image :src="logo" alt="logo" fit="contain" class="logo-img" />
|
||||
<span class="brand-text">意心AI</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右边 -->
|
||||
<div class="right-box flex h-full items-center pr-20px flex-shrink-0 mr-auto flex-row">
|
||||
<AnnouncementBtn />
|
||||
<ModelLibraryBtn />
|
||||
<AiTutorialBtn />
|
||||
<ConsoleBtn @open-console="handleOpenConsole" />
|
||||
<BuyBtn v-show="userStore.userInfo" />
|
||||
<Avatar v-show="userStore.userInfo" ref="avatarRef" />
|
||||
<LoginBtn v-show="!userStore.userInfo" />
|
||||
</div>
|
||||
<!– 右侧功能按钮区域 –>
|
||||
<div class="right-section">
|
||||
<StartChatBtn />
|
||||
<AnnouncementBtn />
|
||||
<ModelLibraryBtn />
|
||||
<AiTutorialBtn />
|
||||
<ConsoleBtn @open-console="handleOpenConsole" />
|
||||
<BuyBtn v-show="userStore.userInfo" />
|
||||
<ThemeBtn />
|
||||
<LoginBtn v-show="!userStore.userInfo" />
|
||||
<Avatar v-show="userStore.userInfo" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -98,20 +54,483 @@ function handleOpenConsole() {
|
||||
.header-container {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
height: fit-content;
|
||||
height: var(--header-container-default-height, 60px);
|
||||
|
||||
.header-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
width: calc(
|
||||
100% - var(--sidebar-left-container-default-width, 0px) - var(
|
||||
--sidebar-right-container-default-width,
|
||||
0px
|
||||
)
|
||||
);
|
||||
height: var(--header-container-default-heigth);
|
||||
margin: 0 var(--sidebar-right-container-default-width, 0) 0
|
||||
var(--sidebar-left-container-default-width, 0);
|
||||
height: 100%;
|
||||
padding: 0 16px;
|
||||
background: var(--header-bg-color, #ffffff);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
// 左侧品牌区域
|
||||
.left-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: fit-content;
|
||||
flex-shrink: 0;
|
||||
|
||||
.brand-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.logo-img {
|
||||
width: 36px; // 优化为更合适的大小
|
||||
height: 36px;
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
font-size: 22px; // 减小字体大小
|
||||
font-weight: bold;
|
||||
color: var(--brand-color, #000000);
|
||||
white-space: nowrap;
|
||||
letter-spacing: -0.5px;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
//color: var(--brand-hover-color, #40a9ff);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 右侧功能区域
|
||||
.right-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px; // 优化按钮间距
|
||||
height: 100%;
|
||||
flex-shrink: 0;
|
||||
|
||||
// 统一按钮样式
|
||||
:deep(.menu-button) {
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
-->
|
||||
<!-- Header 头部 -->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import logo from '@/assets/images/logo.png';
|
||||
import ConsoleBtn from '@/layouts/components0/Header/components/ConsoleBtn.vue';
|
||||
import { useUserStore } from '@/stores';
|
||||
import AiTutorialBtn from './components/AiTutorialBtn.vue';
|
||||
import AnnouncementBtn from './components/AnnouncementBtn.vue';
|
||||
import Avatar from './components/Avatar.vue';
|
||||
import BuyBtn from './components/BuyBtn.vue';
|
||||
import LoginBtn from './components/LoginBtn.vue';
|
||||
import ModelLibraryBtn from './components/ModelLibraryBtn.vue';
|
||||
import ThemeBtn from './components/ThemeBtn.vue';
|
||||
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const userStore = useUserStore();
|
||||
|
||||
// 当前激活的菜单项
|
||||
const activeIndex = computed(() => {
|
||||
if (route.path.startsWith('/console'))
|
||||
return 'console';
|
||||
if (route.path.startsWith('/model-library'))
|
||||
return 'model-library';
|
||||
if (route.path.includes('/chat/'))
|
||||
return 'chat';
|
||||
return '';
|
||||
});
|
||||
|
||||
// 导航处理
|
||||
function handleSelect(key: string) {
|
||||
if (key && key !== 'no-route') {
|
||||
router.push(key);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="header-container">
|
||||
<el-menu
|
||||
:default-active="activeIndex"
|
||||
class="header-menu"
|
||||
mode="horizontal"
|
||||
:ellipsis="false"
|
||||
:router="false"
|
||||
@select="handleSelect"
|
||||
>
|
||||
<!-- 左侧品牌区域 -->
|
||||
<div class="menu-left">
|
||||
<div class="brand-container" @click="router.push('/')">
|
||||
<el-image :src="logo" alt="logo" fit="contain" class="logo-img" />
|
||||
<span class="brand-text">意心AI</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧功能区域 -->
|
||||
<div class="menu-right">
|
||||
<!-- AI聊天菜单 -->
|
||||
<el-sub-menu index="chat" class="chat-submenu" popper-class="custom-popover">
|
||||
<template #title>
|
||||
<span class="menu-title">AI聊天</span>
|
||||
</template>
|
||||
<el-menu-item index="/chat/conversation">
|
||||
AI对话
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/chat/image">
|
||||
图片生成
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/chat/video">
|
||||
视频生成
|
||||
</el-menu-item>
|
||||
</el-sub-menu>
|
||||
|
||||
<!-- 公告按钮 -->
|
||||
<el-menu-item class="custom-menu-item" index="no-route">
|
||||
<AnnouncementBtn :is-menu-item="true" />
|
||||
</el-menu-item>
|
||||
|
||||
<!-- 模型库 -->
|
||||
<el-menu-item index="/model-library" class="custom-menu-item">
|
||||
<ModelLibraryBtn :is-menu-item="true" />
|
||||
</el-menu-item>
|
||||
|
||||
<!-- AI教程 -->
|
||||
<el-menu-item class="custom-menu-item" index="no-route">
|
||||
<AiTutorialBtn />
|
||||
</el-menu-item>
|
||||
|
||||
<!-- 控制台菜单 -->
|
||||
<el-sub-menu index="console" class="console-submenu" popper-class="custom-popover">
|
||||
<template #title>
|
||||
<ConsoleBtn />
|
||||
</template>
|
||||
<el-menu-item index="/console/user">
|
||||
用户信息
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/apikey">
|
||||
API密钥
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/recharge-log">
|
||||
充值记录
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/usage">
|
||||
用量统计
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/premium">
|
||||
尊享服务
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/daily-task">
|
||||
每日任务
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/invite">
|
||||
每周邀请
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/console/activation">
|
||||
激活码兑换
|
||||
</el-menu-item>
|
||||
</el-sub-menu>
|
||||
|
||||
<!-- 购买按钮 -->
|
||||
<el-menu-item v-if="userStore.userInfo" class="custom-menu-item" index="no-route">
|
||||
<BuyBtn :is-menu-item="true" />
|
||||
</el-menu-item>
|
||||
|
||||
<!-- 主题切换(暂不显示) -->
|
||||
<el-menu-item v-if="false" class="custom-menu-item" index="no-route">
|
||||
<ThemeBtn :is-menu-item="true" />
|
||||
</el-menu-item>
|
||||
|
||||
<!-- 用户头像 -->
|
||||
<div v-if="userStore.userInfo" class="avatar-container">
|
||||
<Avatar />
|
||||
</div>
|
||||
|
||||
<!-- 登录按钮 -->
|
||||
<el-menu-item v-if="!userStore.userInfo" class="login-menu-item" index="no-route">
|
||||
<LoginBtn :is-menu-item="true" />
|
||||
</el-menu-item>
|
||||
</div>
|
||||
</el-menu>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.header-container {
|
||||
--menu-hover-bg: #f5f5f5;
|
||||
--menu-active-color: var(--el-color-primary);
|
||||
--menu-transition: all 0.2s ease;
|
||||
|
||||
width: 100%;
|
||||
height: var(--header-container-default-height, 64px);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
user-select: none;
|
||||
|
||||
}
|
||||
|
||||
.header-menu {
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 100%;
|
||||
border-bottom: none !important;
|
||||
}
|
||||
|
||||
// 左侧品牌区域
|
||||
.menu-left {
|
||||
flex-shrink: 0;
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
.brand-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
transition: background-color var(--menu-transition);
|
||||
|
||||
&:hover {
|
||||
background-color: var(--menu-hover-bg);
|
||||
}
|
||||
}
|
||||
|
||||
.logo-img {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
flex-shrink: 0;
|
||||
transition: transform var(--menu-transition);
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--brand-color, #000000);
|
||||
white-space: nowrap;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
// 右侧功能区域
|
||||
.menu-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
margin-right: 16px;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
// 公共菜单项样式
|
||||
:deep(.el-menu-item),
|
||||
:deep(.el-sub-menu__title) {
|
||||
height: 100% !important;
|
||||
border-bottom: none !important;
|
||||
padding: 0 12px !important;
|
||||
color: inherit !important;
|
||||
|
||||
&:hover {
|
||||
background-color: transparent !important;
|
||||
color: var(--menu-active-color) !important;
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
background-color: transparent !important;
|
||||
color: var(--menu-active-color) !important;
|
||||
|
||||
.menu-title {
|
||||
color: var(--menu-active-color) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 聊天和控制台子菜单
|
||||
.chat-submenu,
|
||||
.console-submenu {
|
||||
:deep(.el-sub-menu__title) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 1.2rem;
|
||||
font-weight: bold;
|
||||
color: #606266;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
// 自定义按钮菜单项
|
||||
.custom-menu-item,
|
||||
.login-menu-item {
|
||||
:deep(.el-menu-item-content) {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Avatar 容器
|
||||
.avatar-container {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
// 响应式设计
|
||||
@media (max-width: 1280px) {
|
||||
.brand-text {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.menu-left {
|
||||
margin-left: 16px;
|
||||
}
|
||||
|
||||
.menu-right {
|
||||
margin-right: 12px;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
:deep(.el-menu-item),
|
||||
:deep(.el-sub-menu__title) {
|
||||
padding: 0 10px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.brand-container {
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
}
|
||||
|
||||
.logo-img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.avatar-container {
|
||||
padding: 0 8px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.brand-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.logo-img {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
.menu-left {
|
||||
margin-left: 12px;
|
||||
}
|
||||
|
||||
.menu-right {
|
||||
margin-right: 8px;
|
||||
|
||||
// 隐藏按钮文字
|
||||
:deep(.button-text) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
display: none;
|
||||
}
|
||||
|
||||
// 显示图标
|
||||
:deep(.el-icon) {
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.el-menu-item),
|
||||
:deep(.el-sub-menu__title) {
|
||||
padding: 0 8px !important;
|
||||
min-width: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.menu-right {
|
||||
gap: 0;
|
||||
|
||||
:deep(.el-menu-item),
|
||||
:deep(.el-sub-menu__title) {
|
||||
padding: 0 6px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="scss">
|
||||
// 自定义弹出框样式
|
||||
.custom-popover {
|
||||
.el-menu {
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 6px 0;
|
||||
min-width: 160px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
|
||||
|
||||
.el-menu-item {
|
||||
height: 40px;
|
||||
line-height: 40px;
|
||||
padding: 0 20px;
|
||||
margin: 2px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--el-color-primary-light-9);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
color: var(--el-color-primary);
|
||||
background-color: var(--el-color-primary-light-9);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
725
Yi.Ai.Vue3/src/layouts/components0/Aside/index.vue
Normal file
725
Yi.Ai.Vue3/src/layouts/components0/Aside/index.vue
Normal file
@@ -0,0 +1,725 @@
|
||||
<script setup lang="ts">
|
||||
import type { ConversationItem } from 'vue-element-plus-x/types/Conversations';
|
||||
import type { ChatSessionVo } from '@/api/session/types';
|
||||
import { ChatLineSquare, Expand, Fold, MoreFilled, Plus } from '@element-plus/icons-vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { get_session } from '@/api';
|
||||
import { useDesignStore } from '@/stores';
|
||||
import { useSessionStore } from '@/stores/modules/session';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const designStore = useDesignStore();
|
||||
const sessionStore = useSessionStore();
|
||||
|
||||
const sessionId = computed(() => route.params?.id);
|
||||
const conversationsList = computed(() => sessionStore.sessionList);
|
||||
const loadMoreLoading = computed(() => sessionStore.isLoadingMore);
|
||||
const active = ref<string | undefined>();
|
||||
const isCollapsed = computed(() => designStore.isCollapseConversationList);
|
||||
|
||||
onMounted(async () => {
|
||||
await sessionStore.requestSessionList();
|
||||
if (conversationsList.value.length > 0 && sessionId.value) {
|
||||
const currentSessionRes = await get_session(`${sessionId.value}`);
|
||||
sessionStore.setCurrentSession(currentSessionRes.data);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => sessionStore.currentSession,
|
||||
(newValue) => {
|
||||
active.value = newValue ? `${newValue.id}` : undefined;
|
||||
},
|
||||
);
|
||||
|
||||
// 创建会话
|
||||
function handleCreatChat() {
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
|
||||
// 切换会话
|
||||
function handleChange(item: ConversationItem<ChatSessionVo>) {
|
||||
sessionStore.setCurrentSession(item);
|
||||
router.replace({
|
||||
name: 'chatConversationWithId',
|
||||
params: {
|
||||
id: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 处理组件触发的加载更多事件
|
||||
async function handleLoadMore() {
|
||||
if (!sessionStore.hasMore)
|
||||
return;
|
||||
await sessionStore.loadMoreSessions();
|
||||
}
|
||||
|
||||
// 右键菜单
|
||||
function handleMenuCommand(command: string, item: ConversationItem<ChatSessionVo>) {
|
||||
switch (command) {
|
||||
case 'delete':
|
||||
ElMessageBox.confirm('删除后,聊天记录将不可恢复。', '确定删除对话?', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
confirmButtonClass: 'el-button--danger',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
autofocus: false,
|
||||
})
|
||||
.then(() => {
|
||||
sessionStore.deleteSessions([item.id!]);
|
||||
nextTick(() => {
|
||||
if (item.id === active.value) {
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 取消删除
|
||||
});
|
||||
break;
|
||||
case 'rename':
|
||||
ElMessageBox.prompt('', '编辑对话名称', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
inputErrorMessage: '请输入对话名称',
|
||||
confirmButtonClass: 'el-button--primary',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
inputValue: item.sessionTitle,
|
||||
autofocus: false,
|
||||
inputValidator: (value) => {
|
||||
return !!value;
|
||||
},
|
||||
}).then(({ value }) => {
|
||||
sessionStore
|
||||
.updateSession({
|
||||
id: item.id!,
|
||||
sessionTitle: value,
|
||||
sessionContent: item.sessionContent,
|
||||
})
|
||||
.then(() => {
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
message: '修改成功',
|
||||
});
|
||||
nextTick(() => {
|
||||
if (sessionStore.currentSession?.id === item.id) {
|
||||
sessionStore.setCurrentSession({
|
||||
...item,
|
||||
sessionTitle: value,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠/展开侧边栏
|
||||
function toggleSidebar() {
|
||||
designStore.setIsCollapseConversationList(!designStore.isCollapseConversationList);
|
||||
}
|
||||
|
||||
// 点击logo创建新会话(仅在折叠状态)
|
||||
function handleLogoClick() {
|
||||
if (isCollapsed.value) {
|
||||
handleCreatChat();
|
||||
}
|
||||
}
|
||||
|
||||
// 处理右键菜单
|
||||
function handleContextMenu(event: MouseEvent, item: ConversationItem<ChatSessionVo>) {
|
||||
event.preventDefault();
|
||||
// 在折叠状态下触发菜单
|
||||
ElMessageBox.confirm('删除后,聊天记录将不可恢复。', '确定删除对话?', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
confirmButtonClass: 'el-button--danger',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
autofocus: false,
|
||||
})
|
||||
.then(() => {
|
||||
sessionStore.deleteSessions([item.id!]);
|
||||
nextTick(() => {
|
||||
if (item.id === active.value) {
|
||||
sessionStore.createSessionBtn();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 取消删除
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="aside-container"
|
||||
:class="{ 'aside-collapsed': isCollapsed }"
|
||||
>
|
||||
<div class="aside-wrapper">
|
||||
<!-- 头部 -->
|
||||
<div class="aside-header">
|
||||
<!-- 展开状态显示logo和标题 -->
|
||||
<div
|
||||
v-if="!isCollapsed"
|
||||
class="header-content-expanded flex items-center gap-8px hover:cursor-pointer"
|
||||
@click="handleCreatChat"
|
||||
>
|
||||
<span class="logo-text max-w-150px text-overflow">会话</span>
|
||||
</div>
|
||||
|
||||
<!-- 折叠状态只显示logo -->
|
||||
<div
|
||||
v-else
|
||||
class="header-content-collapsed flex items-center justify-center hover:cursor-pointer"
|
||||
@click="handleLogoClick"
|
||||
>
|
||||
<el-icon size="20">
|
||||
<ChatLineSquare />
|
||||
</el-icon>
|
||||
</div>
|
||||
|
||||
<!-- 折叠按钮 -->
|
||||
<el-tooltip
|
||||
:content="isCollapsed ? '展开侧边栏' : '折叠侧边栏'"
|
||||
placement="bottom"
|
||||
>
|
||||
<el-button
|
||||
class="collapse-btn"
|
||||
type="text"
|
||||
@click="toggleSidebar"
|
||||
>
|
||||
<el-icon v-if="isCollapsed">
|
||||
<Expand />
|
||||
</el-icon>
|
||||
<el-icon v-else>
|
||||
<Fold />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="aside-body">
|
||||
<!-- 创建会话按钮 -->
|
||||
<div class="creat-chat-btn-wrapper">
|
||||
<div
|
||||
class="creat-chat-btn"
|
||||
:class="{ 'creat-chat-btn-collapsed': isCollapsed }"
|
||||
@click="handleCreatChat"
|
||||
>
|
||||
<el-icon class="add-icon">
|
||||
<Plus />
|
||||
</el-icon>
|
||||
<span v-if="!isCollapsed" class="creat-chat-text">
|
||||
新对话
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 会话列表 -->
|
||||
<div class="aside-content">
|
||||
<div v-if="conversationsList.length > 0" class="conversations-wrap">
|
||||
<Conversations
|
||||
v-model:active="active"
|
||||
:items="conversationsList"
|
||||
:label-max-width="200"
|
||||
:show-tooltip="!isCollapsed"
|
||||
:tooltip-offset="60"
|
||||
show-built-in-menu
|
||||
groupable
|
||||
row-key="id"
|
||||
label-key="sessionTitle"
|
||||
:tooltip-placement="isCollapsed ? 'right-start' : 'right'"
|
||||
:load-more="handleLoadMore"
|
||||
:load-more-loading="loadMoreLoading"
|
||||
:items-style="{
|
||||
marginLeft: '8px',
|
||||
marginRight: '8px',
|
||||
userSelect: 'none',
|
||||
borderRadius: isCollapsed ? '12px' : '10px',
|
||||
padding: isCollapsed ? '12px 8px' : '8px 12px',
|
||||
justifyContent: isCollapsed ? 'center' : 'space-between',
|
||||
width: isCollapsed ? '64px' : 'auto',
|
||||
height: isCollapsed ? '64px' : 'auto',
|
||||
minHeight: '48px',
|
||||
flexDirection: isCollapsed ? 'column' : 'row',
|
||||
position: 'relative',
|
||||
}"
|
||||
:items-active-style="{
|
||||
backgroundColor: '#fff',
|
||||
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
|
||||
color: 'rgba(0, 0, 0, 0.85)',
|
||||
}"
|
||||
:items-hover-style="{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.04)',
|
||||
}"
|
||||
@menu-command="handleMenuCommand"
|
||||
@change="handleChange"
|
||||
@contextmenu="handleContextMenu"
|
||||
>
|
||||
<!-- 自定义折叠状态下的会话项内容 -->
|
||||
<template #default="{ item }">
|
||||
<div class="conversation-item-content">
|
||||
<div v-if="isCollapsed" class="collapsed-item">
|
||||
<div
|
||||
class="avatar-circle"
|
||||
@contextmenu="(e) => handleContextMenu(e, item)"
|
||||
>
|
||||
{{ item.sessionTitle?.charAt(0) || 'A' }}
|
||||
</div>
|
||||
<div v-if="item.unreadCount" class="unread-indicator">
|
||||
{{ item.unreadCount }}
|
||||
</div>
|
||||
<!-- 折叠状态下的更多操作按钮 -->
|
||||
<div
|
||||
class="collapsed-menu-trigger"
|
||||
@click.stop="handleMenuCommand('rename', item)"
|
||||
@contextmenu.stop="(e) => handleContextMenu(e, item)"
|
||||
>
|
||||
<el-icon size="14">
|
||||
<MoreFilled />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="expanded-item">
|
||||
<div class="conversation-info">
|
||||
<div class="conversation-title">
|
||||
{{ item.sessionTitle }}
|
||||
</div>
|
||||
<div v-if="item.sessionContent" class="conversation-preview">
|
||||
{{ item.sessionContent.substring(0, 30) }}{{ item.sessionContent.length > 30 ? '...' : '' }}
|
||||
</div>
|
||||
</div>
|
||||
<!-- 展开状态下的更多操作按钮(Conversations组件自带) -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</Conversations>
|
||||
</div>
|
||||
|
||||
<el-empty
|
||||
v-else
|
||||
class="h-full flex-center"
|
||||
:description="isCollapsed ? '' : '暂无对话记录'"
|
||||
>
|
||||
<template #description>
|
||||
<span v-if="!isCollapsed">暂无对话记录</span>
|
||||
</template>
|
||||
</el-empty>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
// 基础样式
|
||||
.aside-container {
|
||||
width: 240px;
|
||||
height: 100%;
|
||||
border-right: 0.5px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
background-color: var(--sidebar-background-color, #f9fafb);
|
||||
|
||||
&.aside-collapsed {
|
||||
width: 100px;
|
||||
|
||||
.aside-wrapper {
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
.conversations-wrap {
|
||||
padding: 0 8px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.aside-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 240px;
|
||||
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
// 头部样式
|
||||
.aside-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
height: 56px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
|
||||
background-color: var(--sidebar-header-bg, #ffffff);
|
||||
|
||||
.header-content-expanded {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.header-content-collapsed {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.el-icon {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: rgb(0 0 0 / 85%);
|
||||
transform: skewX(-2deg);
|
||||
}
|
||||
|
||||
.collapse-btn {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--el-text-color-primary);
|
||||
background-color: var(--el-fill-color-light);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
.el-icon {
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 内容区域
|
||||
.aside-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 4px;
|
||||
overflow: hidden;
|
||||
|
||||
.creat-chat-btn-wrapper {
|
||||
padding: 12px 8px 4px;
|
||||
|
||||
.creat-chat-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 40px;
|
||||
color: #0057ff;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
background-color: rgb(0 87 255 / 6%);
|
||||
border: 1px solid rgb(0 102 255 / 15%);
|
||||
border-radius: 12px;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: rgb(0 87 255 / 12%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&.creat-chat-btn-collapsed {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.add-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.creat-chat-text {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 22px;
|
||||
margin-left: 6px;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.aside-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
|
||||
.conversations-wrap {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 0 4px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
&:hover::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.conversation-item-content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.collapsed-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.avatar-circle {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
.unread-indicator {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 2px;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
background-color: #ff4d4f;
|
||||
color: white;
|
||||
border-radius: 8px;
|
||||
font-size: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.collapsed-menu-trigger {
|
||||
position: absolute;
|
||||
bottom: 4px;
|
||||
right: 4px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background-color: rgba(0, 0, 0, 0.05);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: all 0.2s ease;
|
||||
z-index: 2;
|
||||
|
||||
.el-icon {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .collapsed-menu-trigger {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.expanded-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
|
||||
.conversation-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin-right: 8px;
|
||||
|
||||
.conversation-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
line-height: 1.4;
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.conversation-preview {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.4;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 样式穿透 - 重点优化操作按钮区域
|
||||
:deep() {
|
||||
.conversations-list {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
.conversation-group-title {
|
||||
padding-left: 12px !important;
|
||||
background-color: transparent !important;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
.title-text {
|
||||
opacity: 0.6;
|
||||
font-size: 12px;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
transition: all 0.3s ease;
|
||||
|
||||
// 确保操作按钮区域在折叠状态下可见
|
||||
.conversation-item-actions {
|
||||
transition: all 0.3s ease;
|
||||
|
||||
.el-button {
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 折叠状态样式
|
||||
.aside-collapsed {
|
||||
.conversation-group-title {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.conversation-item {
|
||||
justify-content: center !important;
|
||||
padding: 12px 8px !important;
|
||||
height: 64px !important;
|
||||
min-height: 64px !important;
|
||||
|
||||
&-label {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
&-actions {
|
||||
// 隐藏默认的操作按钮,使用自定义的
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端适配
|
||||
@media (max-width: 768px) {
|
||||
.aside-container {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 1000;
|
||||
width: 280px !important;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
|
||||
|
||||
&.aside-collapsed {
|
||||
transform: translateX(-100%);
|
||||
width: 100px !important;
|
||||
}
|
||||
|
||||
&:not(.aside-collapsed) {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.aside-wrapper {
|
||||
width: 280px !important;
|
||||
|
||||
.aside-collapsed & {
|
||||
width: 100px !important;
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端遮罩层
|
||||
.aside-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
z-index: 999;
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
// 动画
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,8 @@
|
||||
<!-- DesignConfig -->
|
||||
<script setup lang="ts"></script>
|
||||
|
||||
<template>
|
||||
<div>配置页面</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss"></style>
|
||||
@@ -0,0 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
// 打开AI使用教程(跳转到外部链接)
|
||||
function openTutorial() {
|
||||
window.open('https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde', '_blank');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ai-tutorial-btn-container" data-tour="ai-tutorial-link">
|
||||
<div
|
||||
class="ai-tutorial-btn"
|
||||
title="点击跳转YiXinAI玩法指南专栏"
|
||||
@click="openTutorial"
|
||||
>
|
||||
<!-- PC端显示文字 -->
|
||||
<span class="pc-text">文档</span>
|
||||
<!-- 移动端显示图标 -->
|
||||
<svg
|
||||
class="mobile-icon w-6 h-6"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 14l9-5-9-5-9 5 9 5z"
|
||||
/>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 14l6.16-3.422A12.083 12.083 0 0118 13.5c0 2.579-3.582 4.5-6 4.5s-6-1.921-6-4.5c0-.432.075-.85.198-1.244L12 14z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.ai-tutorial-btn-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.ai-tutorial-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 1.2rem;
|
||||
font-weight: bold;
|
||||
color: #E6A23C;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
color: #F1B44C;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
// PC端显示文字,隐藏图标
|
||||
.pc-text {
|
||||
display: inline;
|
||||
margin: 0 12px;
|
||||
}
|
||||
|
||||
.mobile-icon {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端显示图标,隐藏文字
|
||||
@media (max-width: 768px) {
|
||||
.ai-tutorial-btn-container {
|
||||
.ai-tutorial-btn {
|
||||
.pc-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobile-icon {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script setup lang="ts">
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useAnnouncementStore } from '@/stores';
|
||||
|
||||
const announcementStore = useAnnouncementStore();
|
||||
const { announcements } = storeToRefs(announcementStore);
|
||||
|
||||
// 计算未读公告数量(系统公告数量)
|
||||
const unreadCount = computed(() => {
|
||||
if (!Array.isArray(announcements.value))
|
||||
return 0;
|
||||
return announcements.value.filter(a => a.type === 'System').length;
|
||||
});
|
||||
|
||||
// 打开公告弹窗
|
||||
function openAnnouncement() {
|
||||
announcementStore.openDialog();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="announcement-btn-container" data-tour="announcement-btn">
|
||||
<el-badge
|
||||
is-dot
|
||||
class="announcement-badge"
|
||||
>
|
||||
<!-- :value="unreadCount" -->
|
||||
<!-- :hidden="unreadCount === 0" -->
|
||||
<!-- :max="99" -->
|
||||
<div
|
||||
class="announcement-btn"
|
||||
title="查看公告"
|
||||
@click="openAnnouncement"
|
||||
>
|
||||
<!-- PC端显示文字 -->
|
||||
<span class="pc-text">公告</span>
|
||||
<!-- 移动端显示图标 -->
|
||||
<svg
|
||||
class="mobile-icon"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
|
||||
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
|
||||
</svg>
|
||||
</div>
|
||||
</el-badge>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.announcement-btn-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.announcement-badge {
|
||||
:deep(.el-badge__content) {
|
||||
background-color: #f56c6c;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.announcement-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 1.2rem;
|
||||
font-weight: bold;
|
||||
color: #409eff;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
color: #66b1ff;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
// PC端显示文字,隐藏图标
|
||||
.pc-text {
|
||||
display: inline;
|
||||
margin: 0 12px;
|
||||
|
||||
}
|
||||
|
||||
.mobile-icon {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端显示图标,隐藏文字
|
||||
@media (max-width: 768px) {
|
||||
.announcement-btn-container {
|
||||
.announcement-btn {
|
||||
.pc-text {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobile-icon {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
499
Yi.Ai.Vue3/src/layouts/components0/Header/components/Avatar.vue
Normal file
499
Yi.Ai.Vue3/src/layouts/components0/Header/components/Avatar.vue
Normal file
@@ -0,0 +1,499 @@
|
||||
<!-- 头像 -->
|
||||
<script setup lang="ts">
|
||||
import { ChatLineRound } from '@element-plus/icons-vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { nextTick, onMounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import Popover from '@/components/Popover/index.vue';
|
||||
import SvgIcon from '@/components/SvgIcon/index.vue';
|
||||
import { useGuideTour } from '@/hooks/useGuideTour';
|
||||
import { useAnnouncementStore, useGuideTourStore, useUserStore } from '@/stores';
|
||||
import { useSessionStore } from '@/stores/modules/session';
|
||||
import { getUserProfilePicture, isUserVip } from '@/utils/user';
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const userStore = useUserStore();
|
||||
const sessionStore = useSessionStore();
|
||||
const guideTourStore = useGuideTourStore();
|
||||
const announcementStore = useAnnouncementStore();
|
||||
const { startUserCenterTour } = useGuideTour();
|
||||
|
||||
/* 弹出面板 开始 */
|
||||
const popoverStyle = ref({
|
||||
width: '200px',
|
||||
padding: '4px',
|
||||
height: 'fit-content',
|
||||
});
|
||||
const popoverRef = ref();
|
||||
|
||||
// 弹出面板内容
|
||||
const popoverList = ref([
|
||||
|
||||
{
|
||||
key: '5',
|
||||
title: '控制台',
|
||||
icon: 'settings-4-fill',
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
divider: true,
|
||||
},
|
||||
{
|
||||
key: '7',
|
||||
title: '公告',
|
||||
icon: 'notification-fill',
|
||||
},
|
||||
{
|
||||
key: '8',
|
||||
title: '模型库',
|
||||
icon: 'apps-fill',
|
||||
},
|
||||
{
|
||||
key: '9',
|
||||
title: '文档',
|
||||
icon: 'book-fill',
|
||||
},
|
||||
|
||||
{
|
||||
key: '6',
|
||||
title: '新手引导',
|
||||
icon: 'dashboard-fill',
|
||||
},
|
||||
{
|
||||
key: '3',
|
||||
divider: true,
|
||||
},
|
||||
{
|
||||
key: '4',
|
||||
title: '退出登录',
|
||||
icon: 'logout-box-r-line',
|
||||
},
|
||||
]);
|
||||
|
||||
const dialogVisible = ref(false);
|
||||
const rechargeLogRef = ref();
|
||||
const activeNav = ref('user');
|
||||
|
||||
// ============ 邀请码分享功能 ============
|
||||
/** 从 URL 获取的邀请码 */
|
||||
const externalInviteCode = ref<string>('');
|
||||
|
||||
const navItems = [
|
||||
{ name: 'user', label: '用户信息', icon: 'User' },
|
||||
// { name: 'role', label: '角色管理', icon: 'Avatar' },
|
||||
// { name: 'permission', label: '权限管理', icon: 'Key' },
|
||||
// { name: 'userInfo', label: '用户信息', icon: 'User' },
|
||||
{ name: 'apiKey', label: 'API密钥', icon: 'Key' },
|
||||
|
||||
{ name: 'rechargeLog', label: '充值记录', icon: 'Document' },
|
||||
{ name: 'usageStatistics', label: '用量统计', icon: 'Histogram' },
|
||||
{ name: 'premiumService', label: '尊享服务', icon: 'ColdDrink' },
|
||||
{ name: 'dailyTask', label: '每日任务(限时)', icon: 'Trophy' },
|
||||
{ name: 'cardFlip', label: '每周邀请(限时)', icon: 'Present' },
|
||||
// { name: 'usageStatistics2', label: '用量统计2', icon: 'Histogram' },
|
||||
{ name: 'activationCode', label: '激活码兑换', icon: 'MagicStick' },
|
||||
];
|
||||
function openDialog() {
|
||||
dialogVisible.value = true;
|
||||
}
|
||||
function handleConfirm(activeNav: string) {
|
||||
ElMessage.success('操作成功');
|
||||
}
|
||||
|
||||
// 导航切换
|
||||
function handleNavChange(nav: string) {
|
||||
activeNav.value = nav;
|
||||
// 同步更新 store 中的 tab 状态,防止下次通过 store 打开同一 tab 时因值未变而不触发 watch
|
||||
if (userStore.userCenterActiveTab !== nav) {
|
||||
userStore.userCenterActiveTab = nav;
|
||||
}
|
||||
}
|
||||
|
||||
// 联系售后
|
||||
function handleContactSupport() {
|
||||
rechargeLogRef.value?.contactCustomerService();
|
||||
}
|
||||
const { startHeaderTour } = useGuideTour();
|
||||
|
||||
// 开始引导教程
|
||||
function handleStartTutorial() {
|
||||
startHeaderTour();
|
||||
}
|
||||
// 点击
|
||||
function handleClick(item: any) {
|
||||
switch (item.key) {
|
||||
case '1':
|
||||
ElMessage.warning('暂未开放');
|
||||
break;
|
||||
case '2':
|
||||
ElMessage.warning('暂未开放');
|
||||
break;
|
||||
case '5':
|
||||
// 打开控制台
|
||||
popoverRef.value?.hide?.();
|
||||
router.push('/console');
|
||||
break;
|
||||
case '6':
|
||||
handleStartTutorial();
|
||||
break;
|
||||
case '7':
|
||||
// 打开公告
|
||||
popoverRef.value?.hide?.();
|
||||
announcementStore.openDialog();
|
||||
break;
|
||||
case '8':
|
||||
// 打开模型库
|
||||
popoverRef.value?.hide?.();
|
||||
router.push('/model-library');
|
||||
break;
|
||||
case '9':
|
||||
// 打开文档
|
||||
popoverRef.value?.hide?.();
|
||||
window.open('https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde', '_blank');
|
||||
break;
|
||||
case '4':
|
||||
popoverRef.value?.hide?.();
|
||||
ElMessageBox.confirm('退出登录不会丢失任何数据,你仍可以登录此账号。', '确认退出登录?', {
|
||||
confirmButtonText: '确认退出',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
confirmButtonClass: 'el-button--danger',
|
||||
cancelButtonClass: 'el-button--info',
|
||||
roundButton: true,
|
||||
autofocus: false,
|
||||
})
|
||||
.then(async () => {
|
||||
// 在这里执行退出方法
|
||||
await userStore.logout();
|
||||
// 清空回话列表并回到默认页
|
||||
await sessionStore.requestSessionList(1, true);
|
||||
await sessionStore.createSessionBtn();
|
||||
ElMessage({
|
||||
type: 'success',
|
||||
message: '退出成功',
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// ElMessage({
|
||||
// type: 'info',
|
||||
// message: '取消',
|
||||
// });
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function openVipGuide() {
|
||||
ElMessageBox.confirm(
|
||||
`
|
||||
<div class="text-center leading-relaxed">
|
||||
<h3 class="text-lg font-bold mb-3">${isUserVip() ? 'YiXinAI-VIP 会员' : '成为 YiXinAI-VIP'}</h3>
|
||||
<p class="mb-2">
|
||||
${
|
||||
isUserVip()
|
||||
? '您已是尊贵会员,享受全部 AI 模型与专属服务。感谢支持!'
|
||||
: '解锁所有 AI 模型,无限加速,专属客服,尽享尊贵体验。'
|
||||
}
|
||||
</p>
|
||||
${
|
||||
isUserVip()
|
||||
? '<p class="text-sm text-gray-500">您可随时访问产品页面查看更多特权内容。</p>'
|
||||
: '<p class="text-sm text-gray-500">点击下方按钮,立即升级为 VIP 会员!</p>'
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
isUserVip() ? '会员状态' : '会员尊享',
|
||||
{
|
||||
confirmButtonText: '前往产品页面',
|
||||
cancelButtonText: '关闭',
|
||||
dangerouslyUseHTMLString: true,
|
||||
type: 'info',
|
||||
center: true,
|
||||
roundButton: true,
|
||||
},
|
||||
)
|
||||
.then(() => {
|
||||
router.push({
|
||||
name: 'products', // 使用命名路由
|
||||
query: { from: isUserVip() ? 'vip' : 'user' }, // 可选:添加来源标识
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 点击右上角关闭或“关闭”按钮,不执行任何操作
|
||||
});
|
||||
}
|
||||
|
||||
// ============ 监听对话框打开事件,切换到邀请码标签页 ============
|
||||
watch(dialogVisible, (newVal) => {
|
||||
if (newVal && externalInviteCode.value) {
|
||||
// 对话框打开后,切换标签页(已通过 :default-active 绑定,会自动响应)
|
||||
// console.log('[Avatar] watch: 对话框已打开,切换到 cardFlip 标签页');
|
||||
nextTick(() => {
|
||||
activeNav.value = 'cardFlip';
|
||||
// console.log('[Avatar] watch: 已设置 activeNav 为', activeNav.value);
|
||||
});
|
||||
}
|
||||
|
||||
// 对话框关闭时,清除邀请码状态和 URL 参数
|
||||
if (!newVal && externalInviteCode.value) {
|
||||
// console.log('[Avatar] watch: 对话框关闭,清除邀请码状态');
|
||||
externalInviteCode.value = '';
|
||||
|
||||
// 清除 URL 中的 inviteCode 参数
|
||||
const url = new URL(window.location.href);
|
||||
if (url.searchParams.has('inviteCode')) {
|
||||
url.searchParams.delete('inviteCode');
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
// console.log('[Avatar] watch: 已清除 URL 中的 inviteCode 参数');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 监听 URL 参数,实现邀请码快捷分享 ============
|
||||
onMounted(() => {
|
||||
// 获取 URL 查询参数
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const inviteCode = urlParams.get('inviteCode');
|
||||
|
||||
if (inviteCode && inviteCode.trim()) {
|
||||
// console.log('[Avatar] onMounted: 检测到邀请码', inviteCode);
|
||||
|
||||
// 保存邀请码
|
||||
externalInviteCode.value = inviteCode.trim();
|
||||
|
||||
// 先设置标签页为 cardFlip
|
||||
activeNav.value = 'cardFlip';
|
||||
// console.log('[Avatar] onMounted: 设置 activeNav 为', activeNav.value);
|
||||
|
||||
// 延迟打开对话框,确保状态已更新
|
||||
nextTick(() => {
|
||||
setTimeout(() => {
|
||||
// console.log('[Avatar] onMounted: 打开用户中心对话框');
|
||||
dialogVisible.value = true;
|
||||
}, 200);
|
||||
});
|
||||
|
||||
// 注意:不立即清除 URL 参数,保留给登录后使用
|
||||
// URL 参数会在对话框关闭时清除
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 监听引导状态,自动打开用户中心并开始引导 ============
|
||||
watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
|
||||
if (shouldStart) {
|
||||
// 清除触发标记
|
||||
guideTourStore.clearUserCenterTourTrigger();
|
||||
|
||||
// 注册导航切换回调
|
||||
guideTourStore.setUserCenterNavChangeCallback((nav: string) => {
|
||||
activeNav.value = nav;
|
||||
});
|
||||
|
||||
// 注册关闭弹窗回调
|
||||
guideTourStore.setUserCenterCloseCallback(() => {
|
||||
dialogVisible.value = false;
|
||||
});
|
||||
|
||||
// 打开用户中心弹窗
|
||||
nextTick(() => {
|
||||
dialogVisible.value = true;
|
||||
|
||||
// 等待弹窗打开后开始引导
|
||||
setTimeout(() => {
|
||||
startUserCenterTour();
|
||||
}, 600);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 监听 Store 状态,控制用户中心弹窗 (新增) ============
|
||||
watch(() => userStore.isUserCenterVisible, (val) => {
|
||||
dialogVisible.value = val;
|
||||
if (val && userStore.userCenterActiveTab) {
|
||||
activeNav.value = userStore.userCenterActiveTab;
|
||||
}
|
||||
});
|
||||
|
||||
watch(() => userStore.userCenterActiveTab, (val) => {
|
||||
if (val) {
|
||||
activeNav.value = val;
|
||||
}
|
||||
});
|
||||
|
||||
// 监听本地 dialogVisible 变化,同步回 Store(可选,为了保持一致性)
|
||||
watch(dialogVisible, (val) => {
|
||||
if (!val) {
|
||||
userStore.closeUserCenter();
|
||||
}
|
||||
});
|
||||
|
||||
// ============ 暴露方法供外部调用 ============
|
||||
defineExpose({
|
||||
openDialog,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center gap-2 ">
|
||||
<!-- 用户信息区域 -->
|
||||
<div class="user-info-display cursor-pointer flex flex-col text-right mr-2 leading-tight" @click="openDialog">
|
||||
<div class="text-sm font-semibold text-gray-800">
|
||||
{{ userStore.userInfo?.user.nick ?? '未登录用户' }}
|
||||
</div>
|
||||
|
||||
<!-- 角色展示 -->
|
||||
<div>
|
||||
<span
|
||||
v-if="isUserVip()"
|
||||
class="inline-block px-2 py-0.5 text-xs text-yellow-700 bg-yellow-100 rounded-full font-semibold"
|
||||
>
|
||||
YiXinAI-VIP
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else
|
||||
class="inline-block px-2 py-0.5 text-xs text-gray-600 bg-gray-100 rounded-full cursor-pointer hover:bg-yellow-50 hover:text-yellow-700 transition"
|
||||
>
|
||||
普通用户
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 头像区域 -->
|
||||
<div class="avatar-container" data-tour="user-avatar">
|
||||
<Popover
|
||||
ref="popoverRef"
|
||||
placement="bottom-end"
|
||||
trigger="clickTarget"
|
||||
:trigger-style="{ cursor: 'pointer' }"
|
||||
popover-class="popover-content"
|
||||
:popover-style="popoverStyle"
|
||||
>
|
||||
<template #trigger>
|
||||
<el-avatar :src="getUserProfilePicture()" :size="28" fit="fit" shape="circle" />
|
||||
</template>
|
||||
|
||||
<div class="popover-content-box shadow-lg">
|
||||
<!-- 用户信息 -->
|
||||
<div class="user-info-box flex items-center gap-8px p-8px rounded-lg mb-2">
|
||||
<el-avatar :src="getUserProfilePicture()" :size="32" fit="fit" shape="circle" />
|
||||
<div class="flex flex-col text-sm">
|
||||
<div class="font-semibold text-gray-800">
|
||||
{{ userStore.userInfo?.user.nick ?? '未登录用户' }}
|
||||
</div>
|
||||
<div class="text-xs text-gray-500">
|
||||
<span
|
||||
v-if="isUserVip()"
|
||||
class="inline-block px-2 py-0.5 text-xs text-yellow-700 bg-yellow-100 rounded-full font-semibold"
|
||||
>
|
||||
YiXinAI-VIP
|
||||
</span>
|
||||
|
||||
<span
|
||||
v-else
|
||||
class="inline-block px-2 py-0.5 text-xs text-gray-600 bg-gray-100 rounded-full cursor-pointer hover:bg-yellow-50 hover:text-yellow-700 transition"
|
||||
>
|
||||
普通用户
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="divder h-1px bg-gray-200 my-4px" />
|
||||
|
||||
<div v-for="item in popoverList" :key="item.key" class="popover-content-box-items h-full">
|
||||
<div
|
||||
v-if="!item.divider"
|
||||
class="popover-content-box-item flex items-center h-full gap-8px p-8px pl-10px pr-12px rounded-lg hover:cursor-pointer hover:bg-[rgba(0,0,0,.04)]"
|
||||
@click="handleClick(item)"
|
||||
>
|
||||
<SvgIcon :name="item.icon!" size="16" class-name="flex-none" />
|
||||
<div class="popover-content-box-item-text font-size-14px text-overflow max-h-120px">
|
||||
{{ item.title }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="item.divider" class="divder h-1px bg-gray-200 my-4px" />
|
||||
</div>
|
||||
</div>
|
||||
</Popover>
|
||||
</div>
|
||||
<nav-dialog
|
||||
v-model="dialogVisible"
|
||||
title="控制台"
|
||||
:nav-items="navItems"
|
||||
:default-active="activeNav"
|
||||
@confirm="handleConfirm"
|
||||
@nav-change="handleNavChange"
|
||||
>
|
||||
<template #extra-actions>
|
||||
<el-tooltip v-if="isUserVip() && activeNav === 'rechargeLog'" content="联系售后" placement="bottom">
|
||||
<el-button circle plain size="small" @click="handleContactSupport">
|
||||
<el-icon color="#07c160">
|
||||
<ChatLineRound />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
|
||||
<!-- 用户管理内容 -->
|
||||
<template #user>
|
||||
<user-management />
|
||||
</template>
|
||||
<!-- 用量统计 -->
|
||||
<template #usageStatistics>
|
||||
<usage-statistics />
|
||||
</template>
|
||||
<!-- 尊享服务 -->
|
||||
<template #premiumService>
|
||||
<premium-service />
|
||||
</template>
|
||||
<!-- 用量统计 -->
|
||||
<!-- <template #usageStatistics2> -->
|
||||
<!-- <usage-statistics2 /> -->
|
||||
<!-- </template> -->
|
||||
|
||||
<!-- 角色管理内容 -->
|
||||
<template #role>
|
||||
<!-- < /> -->
|
||||
</template>
|
||||
|
||||
<!-- 权限管理内容 -->
|
||||
<template #permission>
|
||||
<!-- <permission-management /> -->
|
||||
</template>
|
||||
|
||||
<template #apiKey>
|
||||
<APIKeyManagement />
|
||||
</template>
|
||||
<template #activationCode>
|
||||
<activation-code />
|
||||
</template>
|
||||
<template #dailyTask>
|
||||
<daily-task />
|
||||
</template>
|
||||
<template #cardFlip>
|
||||
<card-flip-activity :external-invite-code="externalInviteCode" />
|
||||
</template>
|
||||
<template #rechargeLog>
|
||||
<recharge-log ref="rechargeLogRef" />
|
||||
</template>
|
||||
</nav-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.popover-content {
|
||||
width: 520px;
|
||||
height: 520px;
|
||||
}
|
||||
.popover-content-box {
|
||||
padding: 8px;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 16px rgb(0 0 0 / 8%);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,68 @@
|
||||
<script setup lang="ts">
|
||||
import { showProductPackage } from '@/utils/product-package';
|
||||
|
||||
// 点击购买按钮
|
||||
function onProductPackage() {
|
||||
showProductPackage();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="buy-btn-container">
|
||||
<el-button
|
||||
class="buy-btn flex items-center gap-2 px-5 py-2 font-semibold shadow-lg"
|
||||
data-tour="buy-btn"
|
||||
@click="onProductPackage"
|
||||
>
|
||||
<span>立即购买</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.buy-btn-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 0 22px 0 0;
|
||||
|
||||
.buy-btn {
|
||||
background: linear-gradient(90deg, #FFD700, #FFC107);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 9999px;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 20px rgba(255, 215, 0, 0.5);
|
||||
background: linear-gradient(90deg, #FFC107, #FFD700);
|
||||
}
|
||||
|
||||
.icon-rocket {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.animate-bounce {
|
||||
animation: bounce 1.2s infinite;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端,屏幕小于756px
|
||||
@media screen and (max-width: 756px) {
|
||||
.buy-btn-container {
|
||||
margin: 0 ;
|
||||
|
||||
.buy-btn {
|
||||
font-size: 12px;
|
||||
max-width: 60px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-4px); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<!-- 侧边栏折叠按钮 -->
|
||||
<script setup lang="ts">
|
||||
import SvgIcon from '@/components/SvgIcon/index.vue';
|
||||
import { useDesignStore } from '@/stores';
|
||||
|
||||
// const { changeCollapse } = useCollapseToggle();
|
||||
const designStore = useDesignStore();
|
||||
|
||||
function handleChangeCollapse() {
|
||||
designStore.setIsCollapseConversationList(!designStore.isCollapseConversationList);
|
||||
// 待定
|
||||
// changeCollapse();
|
||||
// // 每次切换折叠状态,重置安全区状态
|
||||
// designStore.isSafeAreaHover = false;
|
||||
// // 重置首次激活悬停状态
|
||||
// designStore.hasActivatedHover = false;
|
||||
// if (!designStore.isCollapse) {
|
||||
// document.documentElement.style.setProperty(
|
||||
// `--sidebar-left-container-default-width`,
|
||||
// `${SIDE_BAR_WIDTH}px`,
|
||||
// );
|
||||
// }
|
||||
// else {
|
||||
// document.documentElement.style.setProperty(`--sidebar-left-container-default-width`, ``);
|
||||
// }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="collapse-container btn-icon-btn" @click="handleChangeCollapse">
|
||||
<SvgIcon v-if="!designStore.isCollapseConversationList" name="ms-left-panel-close-outline" size="24" />
|
||||
<SvgIcon v-if="designStore.isCollapseConversationList" name="ms-left-panel-open-outline" size="24" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
// .collapse-container {
|
||||
// }
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user