3 Commits

Author SHA1 Message Date
chenchun
1eca2cb273 perf: 优化版本 2025-12-17 16:50:00 +08:00
chenchun
28452b4c07 Merge branch 'ai-hub' into bubblelist 2025-12-17 16:25:37 +08:00
chenchun
63490484e9 feat: 自定义列表 2025-12-17 15:42:13 +08:00
358 changed files with 11704 additions and 37731 deletions

1
.gitignore vendored
View File

@@ -280,4 +280,3 @@ database_backup
package-lock.json
.claude
components.d.ts

View File

@@ -2,8 +2,7 @@
"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/**)",
"Bash(dotnet build:*)"
"Read(//e/code/github/Yi/Yi.Ai.Vue3/**)"
],
"deny": [],
"ask": []

View File

@@ -1,129 +0,0 @@
# 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.

View File

@@ -1,30 +0,0 @@
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();
}

View File

@@ -1,35 +0,0 @@
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();
}

View File

@@ -1,12 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.ActivationCode;
/// <summary>
/// 激活码兑换输入
/// </summary>
public class ActivationCodeRedeemInput
{
/// <summary>
/// 激活码
/// </summary>
public string Code { get; set; } = string.Empty;
}

View File

@@ -1,24 +0,0 @@
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;
}

View File

@@ -1,59 +0,0 @@
using System.ComponentModel.DataAnnotations;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 创建公告输入
/// </summary>
public class AnnouncementCreateInput
{
/// <summary>
/// 标题
/// </summary>
[Required(ErrorMessage = "标题不能为空")]
[StringLength(200, ErrorMessage = "标题不能超过200个字符")]
public string Title { get; set; }
/// <summary>
/// 内容列表
/// </summary>
[Required(ErrorMessage = "内容不能为空")]
[MinLength(1, ErrorMessage = "至少需要一条内容")]
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
[StringLength(500, ErrorMessage = "备注不能超过500个字符")]
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
[StringLength(500, ErrorMessage = "图片URL不能超过500个字符")]
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
[Required(ErrorMessage = "开始时间不能为空")]
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
[Required(ErrorMessage = "公告类型不能为空")]
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
[StringLength(500, ErrorMessage = "跳转链接不能超过500个字符")]
public string? Url { get; set; }
}

View File

@@ -1,59 +0,0 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 公告 DTO后台管理使用
/// </summary>
public class AnnouncementDto
{
/// <summary>
/// 公告ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// 内容列表
/// </summary>
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
public string? Url { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}

View File

@@ -1,29 +0,0 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 获取公告列表输入
/// </summary>
public class AnnouncementGetListInput
{
/// <summary>
/// 搜索关键字
/// </summary>
public string? SearchKey { get; set; }
/// <summary>
/// 跳过数量
/// </summary>
public int SkipCount { get; set; } = 0;
/// <summary>
/// 最大结果数量
/// </summary>
public int MaxResultCount { get; set; } = 10;
/// <summary>
/// 公告类型
/// </summary>
public AnnouncementTypeEnum? Type { get; set; }
}

View File

@@ -1,65 +0,0 @@
using System.ComponentModel.DataAnnotations;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 更新公告输入
/// </summary>
public class AnnouncementUpdateInput
{
/// <summary>
/// 公告ID
/// </summary>
[Required(ErrorMessage = "公告ID不能为空")]
public Guid Id { get; set; }
/// <summary>
/// 标题
/// </summary>
[Required(ErrorMessage = "标题不能为空")]
[StringLength(200, ErrorMessage = "标题不能超过200个字符")]
public string Title { get; set; }
/// <summary>
/// 内容列表
/// </summary>
[Required(ErrorMessage = "内容不能为空")]
[MinLength(1, ErrorMessage = "至少需要一条内容")]
public List<string> Content { get; set; } = new List<string>();
/// <summary>
/// 备注
/// </summary>
[StringLength(500, ErrorMessage = "备注不能超过500个字符")]
public string? Remark { get; set; }
/// <summary>
/// 图片url
/// </summary>
[StringLength(500, ErrorMessage = "图片URL不能超过500个字符")]
public string? ImageUrl { get; set; }
/// <summary>
/// 开始时间
/// </summary>
[Required(ErrorMessage = "开始时间不能为空")]
public DateTime StartTime { get; set; }
/// <summary>
/// 活动结束时间
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// 公告类型
/// </summary>
[Required(ErrorMessage = "公告类型不能为空")]
public AnnouncementTypeEnum Type { get; set; }
/// <summary>
/// 跳转链接
/// </summary>
[StringLength(500, ErrorMessage = "跳转链接不能超过500个字符")]
public string? Url { get; set; }
}

View File

@@ -1,42 +0,0 @@
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; }
}

View File

@@ -1,42 +0,0 @@
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; }
}

View File

@@ -1,14 +0,0 @@
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; }
}

View File

@@ -1,42 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Channel;
/// <summary>
/// AI应用快捷配置DTO
/// </summary>
public class AiAppShortcutDto
{
/// <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; }
}

View File

@@ -1,48 +0,0 @@
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; }
}

View File

@@ -1,101 +0,0 @@
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; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
}

View File

@@ -1,89 +0,0 @@
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; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
}

View File

@@ -1,24 +0,0 @@
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; }
}

View File

@@ -1,107 +0,0 @@
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; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; }
}

View File

@@ -1,65 +0,0 @@
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();
}
}

View File

@@ -1,29 +0,0 @@
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 Guid TokenId { get; set; }
/// <summary>
/// 模型id
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 已选择工具
/// </summary>
public List<string> Tools { get; set; }
}

View File

@@ -1,8 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
public class AgentToolOutput
{
public string Code { get; set; }
public string Name { get; set; }
}

View File

@@ -1,27 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 图片生成输入
/// </summary>
public class ImageGenerationInput
{
/// <summary>
/// 密钥id
/// </summary>
public Guid? TokenId { get; set; }
/// <summary>
/// 提示词
/// </summary>
public string Prompt { get; set; } = string.Empty;
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; } = string.Empty;
/// <summary>
/// 参考图PrefixBase64列表可选包含前缀如 data:image/png;base64,...
/// </summary>
public List<string>? ReferenceImagesPrefixBase64 { get; set; }
}

View File

@@ -1,26 +0,0 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 图片任务分页查询输入
/// </summary>
public class ImageMyTaskPageInput: PagedAllResultRequestDto
{
/// <summary>
/// 提示词
/// </summary>
public string? Prompt { get; set; }
/// <summary>
/// 任务状态筛选(可选)
/// </summary>
public TaskStatusEnum? TaskStatus { get; set; }
/// <summary>
/// 发布状态
/// </summary>
public PublishStatusEnum? PublishStatus { get; set; }
}

View File

@@ -1,31 +0,0 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 图片任务分页查询输入
/// </summary>
public class ImagePlazaPageInput: PagedAllResultRequestDto
{
/// <summary>
/// 分类
/// </summary>
public string? Categories { get; set; }
/// <summary>
/// 提示词
/// </summary>
public string? Prompt { get; set; }
/// <summary>
/// 任务状态筛选(可选)
/// </summary>
public TaskStatusEnum? TaskStatus { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string? UserName{ get; set; }
}

View File

@@ -1,66 +0,0 @@
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>
/// 是否匿名
/// </summary>
public bool IsAnonymous { get; set; }
/// <summary>
/// 生成图片URL
/// </summary>
public string? StoreUrl { get; set; }
/// <summary>
/// 任务状态
/// </summary>
public TaskStatusEnum TaskStatus { get; set; }
/// <summary>
/// 发布状态
/// </summary>
public PublishStatusEnum PublishStatus { get; set; }
/// <summary>
/// 分类标签
/// </summary>
[SqlSugar.SugarColumn( IsJson = true)]
public List<string> Categories { get; set; } = new();
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string? ErrorInfo { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string? UserName { get; set; }
/// <summary>
/// 用户名称Id
/// </summary>
public Guid? UserId { get; set; }
}

View File

@@ -1,47 +0,0 @@
using System.Reflection;
using System.Text.Json.Serialization;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 消息创建结果输出
/// </summary>
public class MessageCreatedOutput
{
/// <summary>
/// 消息类型
/// </summary>
[JsonIgnore]
public ChatMessageTypeEnum TypeEnum { get; set; }
/// <summary>
/// 消息类型
/// </summary>
public string Type => TypeEnum.ToString();
/// <summary>
/// 消息ID
/// </summary>
public Guid MessageId { get; set; }
/// <summary>
/// 消息创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}
/// <summary>
/// 消息类型枚举
/// </summary>
public enum ChatMessageTypeEnum
{
/// <summary>
/// 用户消息
/// </summary>
UserMessage,
/// <summary>
/// 系统消息
/// </summary>
SystemMessage
}

View File

@@ -1,22 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Chat;
/// <summary>
/// 发布图片输入
/// </summary>
public class PublishImageInput
{
/// <summary>
/// 是否匿名
/// </summary>
public bool IsAnonymous { get; set; } = false;
/// <summary>
/// 任务ID
/// </summary>
public Guid TaskId { get; set; }
/// <summary>
/// 分类标签
/// </summary>
public List<string> Categories { get; set; } = new();
}

View File

@@ -1,43 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.DailyTask;
/// <summary>
/// 每日任务配置缓存DTO
/// </summary>
public class DailyTaskConfigCacheDto
{
/// <summary>
/// 任务配置列表
/// </summary>
public List<DailyTaskConfigItem> Tasks { get; set; } = new();
}
/// <summary>
/// 每日任务配置项
/// </summary>
public class DailyTaskConfigItem
{
/// <summary>
/// 任务等级
/// </summary>
public int Level { get; set; }
/// <summary>
/// 需要消耗的Token数量
/// </summary>
public long RequiredTokens { get; set; }
/// <summary>
/// 奖励的Token数量
/// </summary>
public long RewardTokens { get; set; }
/// <summary>
/// 任务名称
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 任务描述
/// </summary>
public string Description { get; set; } = string.Empty;
}

View File

@@ -7,18 +7,4 @@ public class MessageGetListInput:PagedAllResultRequestDto
{
[Required]
public Guid SessionId { get; set; }
}
public class MessageDeleteInput
{
/// <summary>
/// 要删除的消息Id列表
/// </summary>
[Required]
public List<Guid> Ids { get; set; } = new();
/// <summary>
/// 是否同时隐藏后续消息(同一会话中时间大于当前消息的所有消息)
/// </summary>
public bool IsDeleteSubsequent { get; set; } = false;
}

View File

@@ -1,6 +1,4 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class ModelGetListOutput
{
@@ -8,7 +6,13 @@ public class ModelGetListOutput
/// 模型ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 模型分类
/// </summary>
public string Category { get; set; }
/// <summary>
/// 模型id
/// </summary>
@@ -24,6 +28,36 @@ public class ModelGetListOutput
/// </summary>
public string? ModelDescribe { get; set; }
/// <summary>
/// 模型价格
/// </summary>
public double ModelPrice { get; set; }
/// <summary>
/// 模型类型
/// </summary>
public string ModelType { get; set; }
/// <summary>
/// 模型展示状态
/// </summary>
public string ModelShow { get; set; }
/// <summary>
/// 系统提示
/// </summary>
public string SystemPrompt { get; set; }
/// <summary>
/// API 主机地址
/// </summary>
public string ApiHost { get; set; }
/// <summary>
/// API 密钥
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// 备注信息
/// </summary>
@@ -33,23 +67,4 @@ public class ModelGetListOutput
/// 是否为尊享包
/// </summary>
public bool IsPremiumPackage { get; set; }
/// <summary>
/// 是否免费模型
/// </summary>
public bool IsFree { get; set; }
/// <summary>
/// 模型Api类型现支持同一个模型id多种接口格式
/// </summary>
public ModelApiTypeEnum ModelApiType { get; set; }
/// <summary>
/// 模型图标URL
/// </summary>
public string? IconUrl { get; set; }
/// <summary>
/// 供应商分组名称(如OpenAI、Anthropic、Google等)
/// </summary>
public string? ProviderName { get; set; }
}

View File

@@ -1,14 +0,0 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
/// <summary>
/// 排行榜查询输入
/// </summary>
public class RankingGetListInput
{
/// <summary>
/// 排行榜类型0-模型1-工具,不传返回全部
/// </summary>
public RankingTypeEnum? Type { get; set; }
}

View File

@@ -1,41 +0,0 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
/// <summary>
/// 排行榜项DTO
/// </summary>
public class RankingItemDto
{
public Guid Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; } = null!;
/// <summary>
/// Logo地址
/// </summary>
public string? LogoUrl { get; set; }
/// <summary>
/// 得分
/// </summary>
public decimal Score { get; set; }
/// <summary>
/// 提供者
/// </summary>
public string Provider { get; set; } = null!;
/// <summary>
/// 排行榜类型
/// </summary>
public RankingTypeEnum Type { get; set; }
}

View File

@@ -25,17 +25,11 @@ public class RechargeCreateInput
public string Content { get; set; } = string.Empty;
/// <summary>
/// VIP月数为空或0表示永久VIP1个月按31天计算
/// VIP月数为空或0表示永久VIP
/// </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>

View File

@@ -1,24 +0,0 @@
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
/// <summary>
/// 充值记录查询输入
/// </summary>
public class RechargeGetListInput : PagedAllResultRequestDto
{
/// <summary>
/// 是否免费充值金额等于0
/// </summary>
public bool? IsFree { get; set; }
/// <summary>
/// 充值金额最小值
/// </summary>
public decimal? MinRechargeAmount { get; set; }
/// <summary>
/// 充值金额最大值
/// </summary>
public decimal? MaxRechargeAmount { get; set; }
}

View File

@@ -1,15 +1,8 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class SessionCreateAndUpdateInput
{
public string SessionTitle { get; set; }
public string SessionContent { get; set; }
public string? Remark { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum SessionType { get; set; } = SessionTypeEnum.Chat;
}

View File

@@ -1,5 +1,4 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
@@ -8,9 +7,4 @@ public class SessionDto : FullAuditedEntityDto<Guid>
public string SessionTitle { get; set; }
public string SessionContent { get; set; }
public string Remark { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum SessionType { get; set; }
}

View File

@@ -1,14 +1,8 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
using Yi.Framework.Ddd.Application.Contracts;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos;
public class SessionGetListInput : PagedAllResultRequestDto
public class SessionGetListInput:PagedAllResultRequestDto
{
public string? SessionTitle { get; set; }
/// <summary>
/// 会话类型
/// </summary>
public SessionTypeEnum? SessionType { get; set; }
}

View File

@@ -1,42 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 模型Token统计DTO
/// </summary>
public class ModelTokenStatisticsDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 模型名称
/// </summary>
public string ModelName { get; set; }
/// <summary>
/// Token消耗量
/// </summary>
public long Tokens { get; set; }
/// <summary>
/// Token消耗量(万)
/// </summary>
public decimal TokensInWan { get; set; }
/// <summary>
/// 使用次数
/// </summary>
public long Count { get; set; }
/// <summary>
/// 成本(RMB)
/// </summary>
public decimal Cost { get; set; }
/// <summary>
/// 1亿Token成本(RMB)
/// </summary>
public decimal CostPerHundredMillion { get; set; }
}

View File

@@ -1,12 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 利润统计输入
/// </summary>
public class ProfitStatisticsInput
{
/// <summary>
/// 当前成本(RMB)
/// </summary>
public decimal CurrentCost { get; set; }
}

View File

@@ -1,62 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// 利润统计输出
/// </summary>
public class ProfitStatisticsOutput
{
/// <summary>
/// 日期
/// </summary>
public string Date { get; set; }
/// <summary>
/// 尊享包已消耗Token数(单位:个)
/// </summary>
public long TotalUsedTokens { get; set; }
/// <summary>
/// 尊享包已消耗Token数(单位:亿)
/// </summary>
public decimal TotalUsedTokensInHundredMillion { get; set; }
/// <summary>
/// 尊享包剩余库存Token数(单位:个)
/// </summary>
public long TotalRemainingTokens { get; set; }
/// <summary>
/// 尊享包剩余库存Token数(单位:亿)
/// </summary>
public decimal TotalRemainingTokensInHundredMillion { get; set; }
/// <summary>
/// 当前成本(RMB)
/// </summary>
public decimal CurrentCost { get; set; }
/// <summary>
/// 1亿Token成本(RMB)
/// </summary>
public decimal CostPerHundredMillion { get; set; }
/// <summary>
/// 总成本(RMB)
/// </summary>
public decimal TotalCost { get; set; }
/// <summary>
/// 总收益(RMB)
/// </summary>
public decimal TotalRevenue { get; set; }
/// <summary>
/// 利润率(%)
/// </summary>
public decimal ProfitRate { get; set; }
/// <summary>
/// 按200售价计算的成本(RMB)
/// </summary>
public decimal CostAt200Price { get; set; }
}

View File

@@ -1,12 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// Token统计输入
/// </summary>
public class TokenStatisticsInput
{
/// <summary>
/// 指定日期(当天零点)
/// </summary>
public DateTime Date { get; set; }
}

View File

@@ -1,17 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
/// <summary>
/// Token统计输出
/// </summary>
public class TokenStatisticsOutput
{
/// <summary>
/// 日期
/// </summary>
public string Date { get; set; }
/// <summary>
/// 模型统计列表
/// </summary>
public List<ModelTokenStatisticsDto> ModelStatistics { get; set; } = new();
}

View File

@@ -1,22 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 每小时Token使用量统计DTO柱状图
/// </summary>
public class HourlyTokenUsageDto
{
/// <summary>
/// 小时时间点
/// </summary>
public DateTime Hour { get; set; }
/// <summary>
/// 该小时总Token消耗量
/// </summary>
public long TotalTokens { get; set; }
/// <summary>
/// 各模型Token消耗明细
/// </summary>
public List<ModelTokenBreakdownDto> ModelBreakdown { get; set; } = new();
}

View File

@@ -1,27 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 模型今日使用量统计DTO卡片列表
/// </summary>
public class ModelTodayUsageDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// 今日使用次数
/// </summary>
public int UsageCount { get; set; }
/// <summary>
/// 今日消耗总Token数
/// </summary>
public long TotalTokens { get; set; }
/// <summary>
/// 模型图标URL
/// </summary>
public string? IconUrl { get; set; }
}

View File

@@ -1,17 +0,0 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 模型Token堆叠数据DTO用于柱状图
/// </summary>
public class ModelTokenBreakdownDto
{
/// <summary>
/// 模型ID
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// Token消耗量
/// </summary>
public long Tokens { get; set; }
}

View File

@@ -1,20 +0,0 @@
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);
}

View File

@@ -1,4 +1,3 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
@@ -9,42 +8,8 @@ namespace Yi.Framework.AiHub.Application.Contracts.IServices;
public interface IAnnouncementService
{
/// <summary>
/// 获取公告信息(前端首页使用)
/// 获取公告信息
/// </summary>
/// <returns>公告信息</returns>
Task<List<AnnouncementLogDto>> GetAsync();
/// <summary>
/// 获取公告列表(后台管理使用)
/// </summary>
/// <param name="input">查询参数</param>
/// <returns>分页公告列表</returns>
Task<PagedResultDto<AnnouncementDto>> GetListAsync(AnnouncementGetListInput input);
/// <summary>
/// 根据ID获取公告
/// </summary>
/// <param name="id">公告ID</param>
/// <returns>公告详情</returns>
Task<AnnouncementDto> GetByIdAsync(Guid id);
/// <summary>
/// 创建公告
/// </summary>
/// <param name="input">创建输入</param>
/// <returns>创建的公告</returns>
Task<AnnouncementDto> CreateAsync(AnnouncementCreateInput input);
/// <summary>
/// 更新公告
/// </summary>
/// <param name="input">更新输入</param>
/// <returns>更新后的公告</returns>
Task<AnnouncementDto> UpdateAsync(AnnouncementUpdateInput input);
/// <summary>
/// 删除公告
/// </summary>
/// <param name="id">公告ID</param>
Task DeleteAsync(Guid id);
}

View File

@@ -1,96 +0,0 @@
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
#region AI应用快捷配置
/// <summary>
/// 获取AI应用快捷配置列表
/// </summary>
/// <returns>快捷配置列表</returns>
Task<List<AiAppShortcutDto>> GetAppShortcutListAsync();
#endregion
}

View File

@@ -1,16 +0,0 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
/// <summary>
/// 排行榜服务接口
/// </summary>
public interface IRankingService
{
/// <summary>
/// 获取排行榜列表(全量返回)
/// </summary>
/// <param name="input">查询条件</param>
/// <returns>排行榜列表</returns>
Task<List<RankingItemDto>> GetListAsync(RankingGetListInput input);
}

View File

@@ -1,15 +1,9 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
public interface IRechargeService
{
/// <summary>
/// 查询已登录的账户充值记录(分页)
/// </summary>
Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync(RechargeGetListInput input);
/// <summary>
/// 移除用户vip及角色
/// </summary>

View File

@@ -1,19 +0,0 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
/// <summary>
/// 系统使用量统计服务接口
/// </summary>
public interface ISystemUsageStatisticsService
{
/// <summary>
/// 获取利润统计数据
/// </summary>
Task<ProfitStatisticsOutput> GetProfitStatisticsAsync(ProfitStatisticsInput input);
/// <summary>
/// 获取指定日期各模型Token统计
/// </summary>
Task<TokenStatisticsOutput> GetTokenStatisticsAsync(TokenStatisticsInput input);
}

View File

@@ -24,16 +24,4 @@ public interface IUsageStatisticsService
/// </summary>
/// <returns>尊享服务Token用量统计</returns>
Task<PremiumTokenUsageDto> GetPremiumTokenUsageAsync();
/// <summary>
/// 获取当前用户近24小时每小时Token消耗统计柱状图
/// </summary>
/// <returns>每小时Token使用量列表包含各模型堆叠数据</returns>
Task<List<HourlyTokenUsageDto>> GetLast24HoursTokenUsageAsync(UsageStatisticsGetInput input);
/// <summary>
/// 获取当前用户今日各模型使用量统计(卡片列表)
/// </summary>
/// <returns>模型今日使用量列表包含使用次数和总Token</returns>
Task<List<ModelTodayUsageDto>> GetTodayModelUsageAsync(UsageStatisticsGetInput input);
}

View File

@@ -1,130 +0,0 @@
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)
{
var task = await _imageStoreTaskRepository.GetFirstAsync(x => x.Id == args.TaskId);
if (task is null)
{
throw new UserFriendlyException($"{args.TaskId} 图片生成任务不存在");
}
_logger.LogInformation("开始执行图片生成任务TaskId: {TaskId}, ModelId: {ModelId}, UserId: {UserId}",
task.Id, task.ModelId, task.UserId);
try
{
// 构建 Gemini API 请求对象
var parts = new List<object>
{
new { text = task.Prompt }
};
// 添加参考图(如果有)
foreach (var prefixBase64 in task.ReferenceImagesPrefixBase64)
{
var (mimeType, base64Data) = ParsePrefixBase64(prefixBase64);
parts.Add(new
{
inline_data = new
{
mime_type = mimeType,
data = base64Data
}
});
}
var requestObj = new
{
contents = new[]
{
new
{
role = "user", parts = new List<object>
{
new { text = "我只要图片,直接生成图片,不要询问我" }
}
},
new { role = "user", parts }
}
};
var request = JsonSerializer.Deserialize<JsonElement>(
JsonSerializer.Serialize(requestObj));
//里面生成成功已经包含扣款了
await _aiGateWayManager.GeminiGenerateContentImageForStatisticsAsync(
task.Id,
task.ModelId,
request,
task.UserId,
tokenId: task.TokenId);
_logger.LogInformation("图片生成任务完成TaskId: {TaskId}", args.TaskId);
}
catch (Exception ex)
{
var error = $"图片任务失败TaskId: {args.TaskId},错误信息: {ex.Message},错误堆栈:{ex.StackTrace}";
_logger.LogError(ex, error);
task.TaskStatus = TaskStatusEnum.Fail;
task.ErrorInfo = error;
await _imageStoreTaskRepository.UpdateAsync(task);
}
}
/// <summary>
/// 解析带前缀的 Base64 字符串,提取 mimeType 和纯 base64 数据
/// </summary>
private static (string mimeType, string base64Data) ParsePrefixBase64(string prefixBase64)
{
// 默认值
var mimeType = "image/png";
var base64Data = prefixBase64;
if (prefixBase64.Contains(","))
{
var parts = prefixBase64.Split(',');
if (parts.Length == 2)
{
var header = parts[0];
if (header.Contains(":") && header.Contains(";"))
{
mimeType = header.Split(':')[1].Split(';')[0];
}
base64Data = parts[1];
}
}
return (mimeType, base64Data);
}
}

View File

@@ -1,12 +0,0 @@
namespace Yi.Framework.AiHub.Application.Jobs;
/// <summary>
/// 图片生成后台任务参数
/// </summary>
public class ImageGenerationJobArgs
{
/// <summary>
/// 图片任务ID
/// </summary>
public Guid TaskId { get; set; }
}

View File

@@ -1,116 +0,0 @@
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
};
}
}

View File

@@ -1,15 +1,11 @@
using Medallion.Threading;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using SqlSugar;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
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;
@@ -27,33 +23,25 @@ public class DailyTaskService : ApplicationService
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ILogger<DailyTaskService> _logger;
private readonly IDistributedCache<DailyTaskConfigCacheDto> _taskConfigCache;
private IDistributedLockProvider DistributedLock => LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
private const string TaskConfigCacheKey = "AiHub:DailyTaskConfig";
// 默认任务配置当Redis中没有配置时使用
private static readonly List<DailyTaskConfigItem> DefaultTaskConfigs = new()
{
new DailyTaskConfigItem { Level = 1, RequiredTokens = 10000000, RewardTokens = 1000000, Name = "尊享包1000w token任务", Description = "累积使用尊享包 1000w token" },
new DailyTaskConfigItem { Level = 2, RequiredTokens = 30000000, RewardTokens = 2000000, Name = "尊享包3000w token任务", Description = "累积使用尊享包 3000w token" }
};
// 任务配置
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
_taskConfigs = new()
{
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励
};
public DailyTaskService(
ISqlSugarRepository<DailyTaskRewardRecordAggregateRoot> dailyTaskRepository,
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ILogger<DailyTaskService> logger,
ISqlSugarRepository<AiModelEntity> aiModelRepository,
IDistributedCache<DailyTaskConfigCacheDto> taskConfigCache)
ILogger<DailyTaskService> logger)
{
_dailyTaskRepository = dailyTaskRepository;
_messageRepository = messageRepository;
_premiumPackageRepository = premiumPackageRepository;
_logger = logger;
_aiModelRepository = aiModelRepository;
_taskConfigCache = taskConfigCache;
}
/// <summary>
@@ -65,23 +53,20 @@ public class DailyTaskService : ApplicationService
var userId = CurrentUser.GetId();
var today = DateTime.Today;
// 1. 获取任务配置
var taskConfigs = await GetTaskConfigsAsync();
// 2. 统计今日尊享包Token消耗量
// 1. 统计今日尊享包Token消耗量
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
// 3. 查询今日已领取的任务
// 2. 查询今日已领取的任务
var claimedTasks = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today)
.Select(x => new { x.TaskLevel, x.IsRewarded })
.ToListAsync();
// 4. 构建任务列表
// 3. 构建任务列表
var tasks = new List<DailyTaskItem>();
foreach (var config in taskConfigs)
foreach (var (level, config) in _taskConfigs)
{
var claimed = claimedTasks.FirstOrDefault(x => x.TaskLevel == config.Level);
var claimed = claimedTasks.FirstOrDefault(x => x.TaskLevel == level);
int status;
if (claimed != null && claimed.IsRewarded)
@@ -103,7 +88,7 @@ public class DailyTaskService : ApplicationService
tasks.Add(new DailyTaskItem
{
Level = config.Level,
Level = level,
Name = config.Name,
Description = config.Description,
RequiredTokens = config.RequiredTokens,
@@ -128,23 +113,15 @@ 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. 获取任务配置
var taskConfigs = await GetTaskConfigsAsync();
var taskConfig = taskConfigs.FirstOrDefault(x => x.Level == input.TaskLevel);
// 2. 验证任务等级
if (taskConfig == null)
// 1. 验证任务等级
if (!_taskConfigs.TryGetValue(input.TaskLevel, out var taskConfig))
{
throw new UserFriendlyException($"无效的任务等级: {input.TaskLevel}");
}
// 3. 检查是否已领取
// 2. 检查是否已领取
var existingRecord = await _dailyTaskRepository._DbQueryable
.Where(x => x.UserId == userId && x.TaskDate == today && x.TaskLevel == input.TaskLevel)
.FirstAsync();
@@ -154,7 +131,7 @@ public class DailyTaskService : ApplicationService
throw new UserFriendlyException("今日该任务奖励已领取,请明天再来!");
}
// 4. 验证今日Token消耗是否达标
// 3. 验证今日Token消耗是否达标
var todayConsumed = await GetTodayPremiumTokenConsumptionAsync(userId, today);
if (todayConsumed < taskConfig.RequiredTokens)
{
@@ -162,17 +139,18 @@ public class DailyTaskService : ApplicationService
$"Token消耗未达标需要 {taskConfig.RequiredTokens / 10000}w当前 {todayConsumed / 10000}w");
}
// 5. 创建奖励包
// 4. 创建奖励包(使用 PremiumPackageManager
var premiumPackage =
new PremiumPackageAggregateRoot(userId, taskConfig.RewardTokens, $"每日任务:{taskConfig.Name}")
{
PurchaseAmount = 0,
PurchaseAmount = 0, // 奖励不需要付费
Remark = $"{today:yyyy-MM-dd} 每日任务奖励"
};
await _premiumPackageRepository.InsertAsync(premiumPackage);
// 6. 记录领取记录
// 5. 记录领取记录
var record = new DailyTaskRewardRecordAggregateRoot(userId, input.TaskLevel, today, taskConfig.RewardTokens)
{
Remark = $"完成任务{input.TaskLevel},名称:{taskConfig.Name},消耗 {todayConsumed / 10000}w token"
@@ -195,36 +173,13 @@ 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 => premiumModelIds.Contains(x.ModelId)) // 尊享包模型
.Where(x => PremiumPackageConst.ModeIds.Contains(x.ModelId)) // 尊享包模型
.Where(x => x.CreationTime >= today && x.CreationTime < tomorrow)
.SumAsync(x => x.TokenUsage.TotalTokenCount);
return totalTokens;
}
/// <summary>
/// 从Redis获取任务配置如果不存在则写入默认配置
/// </summary>
private async Task<List<DailyTaskConfigItem>> GetTaskConfigsAsync()
{
var cacheData = await _taskConfigCache.GetOrAddAsync(
TaskConfigCacheKey,
() => Task.FromResult(new DailyTaskConfigCacheDto { Tasks = DefaultTaskConfigs }),
() => new DistributedCacheEntryOptions
{
// 不设置过期时间,永久缓存,需要手动更新
}
);
return cacheData?.Tasks ?? DefaultTaskConfigs;
}
}

View File

@@ -1,19 +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;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Services;
@@ -23,18 +18,17 @@ 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<MessageAggregateRoot> messageRepository)
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
{
_accountService = accountService;
_userRepository = userRepository;
_rechargeRepository = rechargeRepository;
_premiumPackageRepository = premiumPackageRepository;
_messageRepository = messageRepository;
}
/// <summary>
@@ -59,7 +53,7 @@ public class AiAccountService : ApplicationService
if (output.IsVip)
{
var recharges = await _rechargeRepository._DbQueryable
.Where(x => x.UserId == userId && x.RechargeType == RechargeTypeEnum.Vip)
.Where(x => x.UserId == userId)
.ToListAsync();
if (recharges.Any())
@@ -82,4 +76,76 @@ public class AiAccountService : ApplicationService
return output;
}
}
/// <summary>
/// 获取利润统计数据
/// </summary>
/// <param name="currentCost">当前成本(RMB)</param>
/// <returns></returns>
[Authorize]
[HttpGet("account/profit-statistics")]
public async Task<string> GetProfitStatisticsAsync([FromQuery] decimal currentCost)
{
if (CurrentUser.UserName != "Guo" && CurrentUser.UserName != "cc")
{
throw new UserFriendlyException("您暂无权限访问");
}
// 1. 获取尊享包总消耗和剩余库存
var premiumPackages = await _premiumPackageRepository._DbQueryable.ToListAsync();
long totalUsedTokens = premiumPackages.Sum(p => p.UsedTokens);
long totalRemainingTokens = premiumPackages.Sum(p => p.RemainingTokens);
// 2. 计算1亿Token成本
decimal costPerHundredMillion = totalUsedTokens > 0
? currentCost / (totalUsedTokens / 100000000m)
: 0;
// 3. 计算总成本(剩余+已使用的总成本)
long totalTokens = totalUsedTokens + totalRemainingTokens;
decimal totalCost = totalTokens > 0
? (totalTokens / 100000000m) * costPerHundredMillion
: 0;
// 4. 获取总收益(RechargeType=PremiumPackage的充值金额总和)
decimal totalRevenue = await _rechargeRepository._DbQueryable
.Where(x => x.RechargeType == Domain.Shared.Enums.RechargeTypeEnum.PremiumPackage)
.SumAsync(x => x.RechargeAmount);
// 5. 计算利润率
decimal profitRate = totalCost > 0
? (totalRevenue / totalCost - 1) * 100
: 0;
// 6. 按200售价计算成本
decimal costAt200Price = totalRevenue > 0
? (totalCost / totalRevenue) * 200
: 0;
// 7. 格式化输出
var today = DateTime.Now;
string dayOfWeek = today.ToString("dddd", new System.Globalization.CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
var result = $@"{today:M月d日} {weekDay}
尊享包已消耗({totalUsedTokens / 100000000m:F2}亿){totalUsedTokens}
尊享包剩余库存({totalRemainingTokens / 100000000m:F2}亿){totalRemainingTokens}
当前成本:{currentCost:F2}RMB
1亿Token成本:{costPerHundredMillion:F2} RMB=1亿 Token
总成本:{totalCost:F2} RMB
总收益:{totalRevenue:F2}RMB
利润率: {profitRate:F1}%
按200售价来算,成本在{costAt200Price:F2}";
return result;
}
}

View File

@@ -1,10 +1,6 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
@@ -35,9 +31,8 @@ public class AnnouncementService : ApplicationService, IAnnouncementService
}
/// <summary>
/// 获取公告信息(前端首页使用,允许匿名访问)
/// 获取公告信息
/// </summary>
[AllowAnonymous]
public async Task<List<AnnouncementLogDto>> GetAsync()
{
// 使用 GetOrAddAsync 从缓存获取或添加数据缓存1小时
@@ -53,134 +48,18 @@ public class AnnouncementService : ApplicationService, IAnnouncementService
return cacheData?.Logs ?? new List<AnnouncementLogDto>();
}
/// <summary>
/// 获取公告列表(后台管理使用)
/// </summary>
[Authorize(Roles = "admin")]
[HttpGet("announcement/list")]
public async Task<PagedResultDto<AnnouncementDto>> GetListAsync(AnnouncementGetListInput input)
{
var query = _announcementRepository._DbQueryable
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey),
x => x.Title.Contains(input.SearchKey!) || (x.Remark != null && x.Remark.Contains(input.SearchKey!)))
.WhereIF(input.Type.HasValue, x => x.Type == input.Type!.Value)
.OrderByDescending(x => x.StartTime);
var totalCount = await query.CountAsync();
var items = await query
.Skip(input.SkipCount)
.Take(input.MaxResultCount)
.ToListAsync();
return new PagedResultDto<AnnouncementDto>(
totalCount,
items.Adapt<List<AnnouncementDto>>()
);
}
/// <summary>
/// 根据ID获取公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpGet("{id}")]
public async Task<AnnouncementDto> GetByIdAsync(Guid id)
{
var entity = await _announcementRepository.GetByIdAsync(id);
if (entity == null)
{
throw new Exception("公告不存在");
}
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 创建公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpPost]
public async Task<AnnouncementDto> CreateAsync(AnnouncementCreateInput input)
{
var entity = input.Adapt<AnnouncementAggregateRoot>();
await _announcementRepository.InsertAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 更新公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpPut]
public async Task<AnnouncementDto> UpdateAsync(AnnouncementUpdateInput input)
{
var entity = await _announcementRepository.GetByIdAsync(input.Id);
if (entity == null)
{
throw new Exception("公告不存在");
}
// 更新字段
entity.Title = input.Title;
entity.Content = input.Content;
entity.Remark = input.Remark;
entity.ImageUrl = input.ImageUrl;
entity.StartTime = input.StartTime;
entity.EndTime = input.EndTime;
entity.Type = input.Type;
entity.Url = input.Url;
await _announcementRepository.UpdateAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
return entity.Adapt<AnnouncementDto>();
}
/// <summary>
/// 删除公告
/// </summary>
[Authorize(Roles = "admin")]
[HttpDelete("announcement/{id}")]
public async Task DeleteAsync(Guid id)
{
var entity = await _announcementRepository.GetByIdAsync(id);
if (entity == null)
{
throw new Exception("公告不存在");
}
await _announcementRepository.DeleteAsync(entity);
// 清除缓存
await _announcementCache.RemoveAsync(AnnouncementCacheKey);
}
/// <summary>
/// 从数据库加载公告数据
/// </summary>
private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync()
{
// 一次性查出全部公告(不排序)
// 查询所有公告日志,按日期降序排列
var logs = await _announcementRepository._DbQueryable
.OrderByDescending(x => x.StartTime)
.ToListAsync();
var now = DateTime.Now;
// 内存中处理排序
var orderedLogs = logs
.OrderByDescending(x =>
x.StartTime <= now &&
(x.EndTime == null || x.EndTime >= now)
)
.ThenByDescending(x => x.StartTime)
.ToList();
// 转换为 DTO
var logDtos = orderedLogs.Adapt<List<AnnouncementLogDto>>();
var logDtos = logs.Adapt<List<AnnouncementLogDto>>();
return new AnnouncementCacheDto
{
Logs = logDtos

View File

@@ -1,263 +0,0 @@
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(Roles = "admin")]
public class ChannelService : ApplicationService, IChannelService
{
private readonly ISqlSugarRepository<AiAppAggregateRoot, Guid> _appRepository;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
private readonly ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> _appShortcutRepository;
public ChannelService(
ISqlSugarRepository<AiAppAggregateRoot, Guid> appRepository,
ISqlSugarRepository<AiModelEntity, Guid> modelRepository,
ISqlSugarRepository<AiAppShortcutAggregateRoot, Guid> appShortcutRepository)
{
_appRepository = appRepository;
_modelRepository = modelRepository;
_appShortcutRepository = appShortcutRepository;
}
#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,
IsEnabled = input.IsEnabled,
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;
entity.IsEnabled = input.IsEnabled;
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
#region AI应用快捷配置
/// <summary>
/// 获取AI应用快捷配置列表
/// </summary>
[HttpGet("channel/app-shortcut")]
public async Task<List<AiAppShortcutDto>> GetAppShortcutListAsync()
{
var entities = await _appShortcutRepository._DbQueryable
.OrderBy(x => x.OrderNum)
.OrderByDescending(x => x.CreationTime)
.ToListAsync();
return entities.Adapt<List<AiAppShortcutDto>>();
}
#endregion
}

View File

@@ -1,31 +1,22 @@
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;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using System.Text.Json;
using Yi.Framework.AiHub.Domain.Shared.Dtos;
using Yi.Framework.AiHub.Domain.Shared.Dtos.OpenAi;
using Yi.Framework.AiHub.Domain.Shared.Enums;
@@ -41,39 +32,23 @@ 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;
private const string FreeModelId = "DeepSeek-V3-0324";
public AiChatService(IHttpContextAccessor httpContextAccessor,
AiBlacklistManager aiBlacklistManager,
ILogger<AiChatService> logger,
AiGateWayManager aiGateWayManager,
ModelManager modelManager,
PremiumPackageManager premiumPackageManager,
ChatManager chatManager, TokenManager tokenManager, IAccountService accountService,
ISqlSugarRepository<AgentStoreAggregateRoot> agentStoreRepository,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
ISqlSugarRepository<AiModelEntity> aiModelRepository,
ILogger<AiChatService> logger, AiGateWayManager aiGateWayManager, PremiumPackageManager premiumPackageManager)
{
_httpContextAccessor = httpContextAccessor;
_aiBlacklistManager = aiBlacklistManager;
_aiModelRepository = aiModelRepository;
_logger = logger;
_aiGateWayManager = aiGateWayManager;
_modelManager = modelManager;
_premiumPackageManager = premiumPackageManager;
_chatManager = chatManager;
_tokenManager = tokenManager;
_accountService = accountService;
_agentStoreRepository = agentStoreRepository;
_aiModelRepository = aiModelRepository;
}
@@ -91,215 +66,49 @@ public class AiChatService : ApplicationService
}
/// <summary>
/// 获取对话模型列表
/// 获取模型列表
/// </summary>
/// <returns></returns>
public async Task<List<ModelGetListOutput>> GetModelAsync()
{
var output = await _aiModelRepository._DbQueryable
.Where(x => x.IsEnabled == true)
.Where(x => x.ModelType == ModelTypeEnum.Chat)
// .Where(x => x.ModelApiType == ModelApiTypeEnum.Completions)
.Where(x => x.ModelApiType == ModelApiTypeEnum.OpenAi)
.OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput
{
Id = x.Id,
Category = "chat",
ModelId = x.ModelId,
ModelName = x.Name,
ModelDescribe = x.Description,
ModelPrice = 0,
ModelType = "1",
ModelShow = "0",
SystemPrompt = null,
ApiHost = null,
ApiKey = null,
Remark = x.Description,
IsPremiumPackage = x.IsPremium,
ModelApiType = x.ModelApiType,
IconUrl = x.IconUrl,
ProviderName = x.ProviderName
IsPremiumPackage = PremiumPackageConst.ModeIds.Contains(x.ModelId)
}).ToListAsync();
output.ForEach(x =>
{
if (x.ModelId == FreeModelId)
{
x.IsPremiumPackage = false;
x.IsFree = true;
}
});
return output;
}
// /// <summary>
// /// 发送消息
// /// </summary>
// /// <param name="input"></param>
// /// <param name="sessionId"></param>
// /// <param name="cancellationToken"></param>
// [HttpPost("ai-chat/send")]
// [Obsolete]
// public async Task PostSendAsync([FromBody] ThorChatCompletionsRequest input, [FromQuery] Guid? sessionId,
// CancellationToken cancellationToken)
// {
// //除了免费模型,其他的模型都要校验
// if (input.Model!=FreeModelId)
// {
// //有token需要黑名单校验
// if (CurrentUser.IsAuthenticated)
// {
// await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
// if (!CurrentUser.IsAiVip())
// {
// throw new UserFriendlyException("该模型需要VIP用户才能使用请购买VIP后重新登录重试");
// }
// }
// else
// {
// throw new UserFriendlyException("未登录用户只能使用未加速的DeepSeek-R1请登录后重试");
// }
// }
//
// //如果是尊享包服务,需要校验是是否尊享包足够
// if (CurrentUser.IsAuthenticated)
// {
// var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
//
// if (isPremium)
// {
// // 检查尊享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.None);
// }
/// <summary>
/// 发送消息
/// </summary>
/// <param name="input"></param>
/// <param name="sessionId"></param>
/// <param name="cancellationToken"></param>
[HttpPost("ai-chat/FileMaster/send")]
public async Task PostFileMasterSendAsync([FromBody] ThorChatCompletionsRequest input,
[HttpPost("ai-chat/send")]
public async Task PostSendAsync([FromBody] ThorChatCompletionsRequest input, [FromQuery] Guid? sessionId,
CancellationToken cancellationToken)
{
if (!string.IsNullOrWhiteSpace(input.Model))
{
throw new BusinessException("当前接口不支持第三方使用");
}
input.Model = "gpt-5-chat";
if (CurrentUser.IsAuthenticated)
{
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
}
//ai网关代理httpcontext
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
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.TokenId, 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,
tokenValidation.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;
}
/// <summary>
/// 统一发送消息 - 支持4种API类型
/// </summary>
/// <param name="apiType">API类型枚举</param>
/// <param name="input">原始请求体JsonElement</param>
/// <param name="modelId">模型IDGemini格式需要从URL传入</param>
/// <param name="sessionId">会话ID</param>
/// <param name="cancellationToken"></param>
[HttpPost("ai-chat/unified/send")]
public async Task PostUnifiedSendAsync(
[FromQuery] ModelApiTypeEnum apiType,
[FromBody] JsonElement input,
[FromQuery] string modelId,
[FromQuery] Guid? sessionId,
CancellationToken cancellationToken)
{
// 从请求体中提取模型ID如果未从URL传入
if (string.IsNullOrEmpty(modelId))
{
modelId = ExtractModelIdFromRequest(apiType, input);
}
// 除了免费模型,其他的模型都要校验
if (modelId != FreeModelId)
//除了免费模型,其他的模型都要校验
if (!input.Model.Contains("DeepSeek-R1"))
{
//有token需要黑名单校验
if (CurrentUser.IsAuthenticated)
{
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
@@ -314,49 +123,56 @@ public class AiChatService : ApplicationService
}
}
// 如果是尊享包服务,需要校验是否尊享包足够
if (CurrentUser.IsAuthenticated)
//如果是尊享包服务,需要校验是否尊享包足够
if (CurrentUser.IsAuthenticated && PremiumPackageConst.ModeIds.Contains(input.Model))
{
var isPremium = await _modelManager.IsPremiumModelAsync(modelId);
if (isPremium)
// 检查尊享token包用量
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
if (availableTokens <= 0)
{
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(CurrentUser.GetId());
if (availableTokens <= 0)
{
throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包");
}
throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包");
}
}
// 调用统一流式处理
await _aiGateWayManager.UnifiedStreamForStatisticsAsync(
_httpContextAccessor.HttpContext!,
apiType,
input,
modelId,
CurrentUser.Id,
sessionId,
null,
CancellationToken.None);
//ai网关代理httpcontext
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
CurrentUser.Id, sessionId, null, cancellationToken);
}
/// <summary>
/// 从请求体中提取模型ID
/// 发送消息
/// </summary>
private string ExtractModelIdFromRequest(ModelApiTypeEnum apiType, JsonElement input)
/// <param name="input"></param>
/// <param name="cancellationToken"></param>
[HttpPost("ai-chat/FileMaster/send")]
public async Task PostFileMasterSendAsync([FromBody] ThorChatCompletionsRequest input,
CancellationToken cancellationToken)
{
try
if (!string.IsNullOrWhiteSpace(input.Model))
{
if (input.TryGetProperty("model", out var modelProperty))
{
return modelProperty.GetString() ?? string.Empty;
}
}
catch
{
// 忽略解析错误
throw new BusinessException("当前接口不支持第三方使用");
}
throw new UserFriendlyException("无法从请求中获取模型ID请在URL参数中指定modelId");
if (CurrentUser.IsAuthenticated)
{
await _aiBlacklistManager.VerifiyAiBlacklist(CurrentUser.GetId());
if (CurrentUser.IsAiVip())
{
input.Model = "gpt-5-chat";
}
else
{
input.Model = "gpt-4.1-mini";
}
}
else
{
input.Model = "DeepSeek-R1-0528";
}
//ai网关代理httpcontext
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
CurrentUser.Id, null, null, cancellationToken);
}
}

View File

@@ -1,411 +0,0 @@
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
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;
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.Entities.Model;
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;
private readonly TokenManager _tokenManager;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
public AiImageService(
ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageTaskRepository,
IBackgroundJobManager backgroundJobManager,
AiBlacklistManager aiBlacklistManager,
PremiumPackageManager premiumPackageManager,
ModelManager modelManager,
IGuidGenerator guidGenerator,
IWebHostEnvironment webHostEnvironment, TokenManager tokenManager,
ISqlSugarRepository<AiModelEntity> aiModelRepository)
{
_imageTaskRepository = imageTaskRepository;
_backgroundJobManager = backgroundJobManager;
_aiBlacklistManager = aiBlacklistManager;
_premiumPackageManager = premiumPackageManager;
_modelManager = modelManager;
_guidGenerator = guidGenerator;
_webHostEnvironment = webHostEnvironment;
_tokenManager = tokenManager;
_aiModelRepository = aiModelRepository;
}
/// <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);
//校验token
if (input.TokenId is not null)
{
await _tokenManager.ValidateTokenAsync(input.TokenId, input.ModelId);
}
// 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,
ReferenceImagesPrefixBase64 = input.ReferenceImagesPrefixBase64 ?? new List<string>(),
ReferenceImagesUrl = new List<string>(),
TaskStatus = TaskStatusEnum.Processing,
UserId = userId,
UserName = CurrentUser.UserName,
TokenId = input.TokenId,
ModelId = input.ModelId
};
await _imageTaskRepository.InsertAsync(task);
// 入队后台任务
await _backgroundJobManager.EnqueueAsync(new ImageGenerationJobArgs
{
TaskId = task.Id,
});
return task.Id;
}
/// <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,
PublishStatus = task.PublishStatus,
Categories = task.Categories,
CreationTime = task.CreationTime,
ErrorInfo = task.ErrorInfo,
};
}
/// <summary>
/// 上传Base64图片转换为URL
/// </summary>
/// <param name="base64Data">Base64图片数据包含前缀如 data:image/png;base64,</param>
/// <returns>图片访问URL</returns>
[HttpPost("ai-image/upload-base64")]
[AllowAnonymous]
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格式无效");
}
// ==============================
// ✅ 按日期创建目录yyyyMMdd
// ==============================
var dateFolder = DateTime.Now.ToString("yyyyMMdd");
var uploadPath = Path.Combine(
_webHostEnvironment.ContentRootPath,
"wwwroot",
"ai-images",
dateFolder
);
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 $"/wwwroot/ai-images/{dateFolder}/{fileName}";
}
/// <summary>
/// 分页查询我的任务列表
/// </summary>
[HttpGet("ai-image/my-tasks")]
public async Task<PagedResult<ImageTaskOutput>> GetMyTaskPageAsync([FromQuery] ImageMyTaskPageInput input)
{
var userId = CurrentUser.GetId();
RefAsync<int> total = 0;
var output = await _imageTaskRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
.WhereIF(input.PublishStatus is not null, x => x.PublishStatus == input.PublishStatus)
.WhereIF(input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.Select(x => new ImageTaskOutput
{
Id = x.Id,
Prompt = x.Prompt,
StoreUrl = x.StoreUrl,
TaskStatus = x.TaskStatus,
PublishStatus = x.PublishStatus,
Categories = x.Categories,
CreationTime = x.CreationTime,
ErrorInfo = x.ErrorInfo,
UserName = x.UserName,
UserId = x.UserId,
IsAnonymous = x.IsAnonymous
})
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResult<ImageTaskOutput>(total, output);
}
/// <summary>
/// 删除个人图片
/// </summary>
/// <param name="ids"></param>
[HttpDelete("ai-image/my-tasks")]
public async Task DeleteMyTaskAsync([FromQuery] List<Guid> ids)
{
var userId = CurrentUser.GetId();
await _imageTaskRepository.DeleteAsync(x => ids.Contains(x.Id) && x.UserId == userId);
}
/// <summary>
/// 分页查询图片广场(已发布的图片)
/// </summary>
[HttpGet("ai-image/plaza")]
[AllowAnonymous]
public async Task<PagedResult<ImageTaskOutput>> GetPlazaPageAsync([FromQuery] ImagePlazaPageInput input)
{
RefAsync<int> total = 0;
var output = await _imageTaskRepository._DbQueryable
.Where(x => x.PublishStatus == PublishStatusEnum.Published)
.Where(x => x.TaskStatus == TaskStatusEnum.Success)
.WhereIF(input.TaskStatus is not null, x => x.TaskStatus == input.TaskStatus)
.WhereIF(!string.IsNullOrWhiteSpace(input.Prompt), x => x.Prompt.Contains(input.Prompt))
.WhereIF(!string.IsNullOrWhiteSpace(input.Categories),
x => SqlFunc.JsonLike(x.Categories, input.Categories))
.WhereIF(!string.IsNullOrWhiteSpace(input.UserName), x => x.UserName.Contains(input.UserName))
.WhereIF(input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.Select(x => new ImageTaskOutput
{
Id = x.Id,
Prompt = x.Prompt,
IsAnonymous = x.IsAnonymous,
StoreUrl = x.StoreUrl,
TaskStatus = x.TaskStatus,
PublishStatus = x.PublishStatus,
Categories = x.Categories,
CreationTime = x.CreationTime,
ErrorInfo = null,
UserName = x.UserName,
UserId = x.UserId,
})
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
;
output.ForEach(x =>
{
if (x.IsAnonymous)
{
x.UserName = null;
x.UserId = null;
}
});
return new PagedResult<ImageTaskOutput>(total, output);
}
/// <summary>
/// 发布图片到广场
/// </summary>
[HttpPost("ai-image/publish")]
public async Task PublishAsync([FromBody] PublishImageInput input)
{
var userId = CurrentUser.GetId();
var task = await _imageTaskRepository.GetFirstAsync(x => x.Id == input.TaskId && x.UserId == userId);
if (task == null)
{
throw new UserFriendlyException("任务不存在或无权访问");
}
if (task.TaskStatus != TaskStatusEnum.Success)
{
throw new UserFriendlyException("只有已完成的任务才能发布");
}
if (task.PublishStatus == PublishStatusEnum.Published)
{
throw new UserFriendlyException("该任务已发布");
}
//设置发布
task.SetPublish(input.IsAnonymous, input.Categories);
await _imageTaskRepository.UpdateAsync(task);
}
/// <summary>
/// 获取图片模型列表
/// </summary>
/// <returns></returns>
[HttpPost("ai-image/model")]
[AllowAnonymous]
public async Task<List<ModelGetListOutput>> GetModelAsync()
{
var output = await _aiModelRepository._DbQueryable
.Where(x=>x.IsEnabled==true)
.Where(x => x.ModelType == ModelTypeEnum.Image)
.Where(x => x.ModelApiType == ModelApiTypeEnum.GenerateContent)
.OrderByDescending(x => x.OrderNum)
.Select(x => new ModelGetListOutput
{
Id = x.Id,
ModelId = x.ModelId,
ModelName = x.Name,
ModelDescribe = x.Description,
Remark = x.Description,
IsPremiumPackage = x.IsPremium
}).ToListAsync();
return output;
}
}
/// <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;
}
}

View File

@@ -35,59 +35,8 @@ public class MessageService : ApplicationService
var entities = await _repository._DbQueryable
.Where(x => x.SessionId == input.SessionId)
.Where(x=>x.UserId == userId)
.Where(x => !x.IsHidden)
.OrderBy(x => x.Id)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<MessageDto>(total, entities.Adapt<List<MessageDto>>());
}
/// <summary>
/// 删除消息(软删除,标记为隐藏)
/// </summary>
/// <param name="input">删除参数包含消息Id列表和是否删除后续消息的开关</param>
[Authorize]
public async Task DeleteAsync([FromQuery] MessageDeleteInput input)
{
var userId = CurrentUser.GetId();
// 获取要删除的消息
var messages = await _repository._DbQueryable
.Where(x => input.Ids.Contains(x.Id))
.Where(x => x.UserId == userId)
.ToListAsync();
if (messages.Count == 0)
{
return;
}
// 标记当前消息为隐藏
var idsToHide = messages.Select(x => x.Id).ToList();
// 如果需要删除后续消息
if (input.IsDeleteSubsequent)
{
foreach (var message in messages)
{
// 获取同一会话中时间大于当前消息的所有消息Id
var subsequentIds = await _repository._DbQueryable
.Where(x => x.SessionId == message.SessionId)
.Where(x => x.UserId == userId)
.Where(x => x.CreationTime > message.CreationTime)
.Where(x => !x.IsHidden)
.Select(x => x.Id)
.ToListAsync();
idsToHide.AddRange(subsequentIds);
}
idsToHide = idsToHide.Distinct().ToList();
}
// 批量更新为隐藏状态
await _repository._Db.Updateable<MessageAggregateRoot>()
.SetColumns(x => x.IsHidden == true)
.Where(x => idsToHide.Contains(x.Id))
.ExecuteCommandAsync();
}
}

View File

@@ -1,12 +1,10 @@
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;
@@ -20,12 +18,10 @@ 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, ModelManager modelManager)
public ModelService(ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
{
_modelRepository = modelRepository;
_modelManager = modelManager;
}
/// <summary>
@@ -35,9 +31,8 @@ public class ModelService : ApplicationService, IModelService
{
RefAsync<int> total = 0;
// 查询所有未删除且已启用的模型使用WhereIF动态添加筛选条件
// 查询所有未删除的模型使用WhereIF动态添加筛选条件
var modelIds = (await _modelRepository._DbQueryable
.Where(x => x.IsEnabled)
.WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), x =>
x.Name.Contains(input.SearchKey) || x.ModelId.Contains(input.SearchKey))
.WhereIF(input.ProviderNames is not null, x =>
@@ -46,13 +41,13 @@ 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 => x.IsPremium)
.WhereIF(input.IsPremiumOnly == true, x =>
PremiumPackageConst.ModeIds.Contains(x.ModelId))
.GroupBy(x => x.ModelId)
.Select(x => x.ModelId)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total));
var entities = await _modelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
.Where(x => x.IsEnabled)
.OrderBy(x => x.OrderNum)
.OrderBy(x => x.Name).ToListAsync();
@@ -66,7 +61,7 @@ public class ModelService : ApplicationService, IModelService
MultiplierShow = x.First().MultiplierShow,
ProviderName = x.First().ProviderName,
IconUrl = x.First().IconUrl,
IsPremium = x.First().IsPremium,
IsPremium = PremiumPackageConst.ModeIds.Contains(x.First().ModelId),
OrderNum = x.First().OrderNum
}).ToList();
@@ -79,13 +74,14 @@ public class ModelService : ApplicationService, IModelService
public async Task<List<string>> GetProviderListAsync()
{
var providers = await _modelRepository._DbQueryable
.Where(x => x.IsEnabled)
.Where(x => !x.IsDeleted)
.Where(x => !string.IsNullOrEmpty(x.ProviderName))
.GroupBy(x => x.ProviderName)
.OrderBy(x => x.ProviderName)
.Select(x => x.ProviderName)
.ToListAsync();
return providers!;
return providers;
}
/// <summary>
@@ -119,13 +115,4 @@ public class ModelService : ApplicationService, IModelService
return Task.FromResult(options);
}
/// <summary>
/// 清除尊享模型ID缓存
/// </summary>
[HttpPost("model/clear-premium-cache")]
public async Task ClearPremiumModelCacheAsync()
{
await _modelManager.ClearPremiumModelIdsCacheAsync();
}
}

View File

@@ -84,8 +84,7 @@ public class SessionService : CrudAppService<SessionAggregateRoot, SessionDto, G
RefAsync<int> total = 0;
var userId = CurrentUser.GetId();
var entities = await _repository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.SessionType.HasValue, x => x.SessionType == input.SessionType!.Value)
.Where(x=>x.UserId == userId)
.OrderByDescending(x => x.Id)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<SessionDto>(total, entities.Adapt<List<SessionDto>>());

View File

@@ -7,10 +7,8 @@ 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;
@@ -25,16 +23,13 @@ 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,
ModelManager modelManager)
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
{
_tokenRepository = tokenRepository;
_usageStatisticsRepository = usageStatisticsRepository;
_modelManager = modelManager;
}
/// <summary>
@@ -56,8 +51,8 @@ public class TokenService : ApplicationService
return new PagedResultDto<TokenGetListOutputDto>();
}
// 通过ModelManager获取尊享包模型ID列表
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
// 获取尊享包模型ID列表
var premiumModelIds = PremiumPackageConst.ModeIds;
// 批量查询所有Token的尊享包已使用额度
var tokenIds = tokens.Select(t => t.Id).ToList();
@@ -91,7 +86,7 @@ public class TokenService : ApplicationService
}
[HttpGet("token/select-list")]
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync([FromQuery] bool? includeDefault = true)
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync()
{
var userId = CurrentUser.GetId();
var tokens = await _tokenRepository._DbQueryable
@@ -104,17 +99,13 @@ public class TokenService : ApplicationService
Name = x.Name,
IsDisabled = x.IsDisabled
}).ToListAsync();
if (includeDefault == true)
tokens.Insert(0,new TokenSelectListOutputDto
{
tokens.Insert(0, new TokenSelectListOutputDto
{
TokenId = Guid.Empty,
Name = "默认",
IsDisabled = false
});
}
TokenId = Guid.Empty,
Name = "默认",
IsDisabled = false
});
return tokens;
}

View File

@@ -1,11 +1,9 @@
using System.Text.Json;
using Microsoft.AspNetCore.Http;
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;
@@ -27,27 +25,24 @@ public class OpenApiService : ApplicationService
private readonly ILogger<OpenApiService> _logger;
private readonly TokenManager _tokenManager;
private readonly AiGateWayManager _aiGateWayManager;
private readonly ModelManager _modelManager;
private readonly ISqlSugarRepository<AiModelEntity> _aiModelRepository;
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,
ModelManager modelManager, AiBlacklistManager aiBlacklistManager,
IAccountService accountService, PremiumPackageManager premiumPackageManager, ISqlSugarRepository<ImageStoreTaskAggregateRoot> imageStoreRepository, ISqlSugarRepository<AiModelEntity> aiModelRepository)
ISqlSugarRepository<AiModelEntity> aiModelRepository, AiBlacklistManager aiBlacklistManager,
IAccountService accountService, PremiumPackageManager premiumPackageManager)
{
_httpContextAccessor = httpContextAccessor;
_logger = logger;
_tokenManager = tokenManager;
_aiGateWayManager = aiGateWayManager;
_modelManager = modelManager;
_aiModelRepository = aiModelRepository;
_aiBlacklistManager = aiBlacklistManager;
_accountService = accountService;
_premiumPackageManager = premiumPackageManager;
_imageStoreRepository = imageStoreRepository;
_aiModelRepository = aiModelRepository;
}
/// <summary>
@@ -67,9 +62,7 @@ public class OpenApiService : ApplicationService
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
//如果是尊享包服务,需要校验是是否尊享包足够
var isPremium = await _modelManager.IsPremiumModelAsync(input.Model);
if (isPremium)
if (PremiumPackageConst.ModeIds.Contains(input.Model))
{
// 检查尊享token包用量
var availableTokens = await _premiumPackageManager.GetAvailableTokensAsync(userId);
@@ -83,13 +76,13 @@ public class OpenApiService : ApplicationService
if (input.Stream == true)
{
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId, null, tokenId,CancellationToken.None);
userId, null, tokenId, cancellationToken);
}
else
{
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
null, tokenId,
CancellationToken.None);
cancellationToken);
}
}
@@ -197,18 +190,18 @@ public class OpenApiService : ApplicationService
{
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
input,
userId, null, tokenId, CancellationToken.None);
userId, null, tokenId, cancellationToken);
}
else
{
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId,
null, tokenId,
CancellationToken.None);
cancellationToken);
}
}
/// <summary>
/// 响应-Openai新规范 (尊享服务专用)
/// </summary>
@@ -247,79 +240,20 @@ public class OpenApiService : ApplicationService
//ai网关代理httpcontext
if (input.Stream == true)
{
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
input,
userId, null, tokenId, CancellationToken.None);
await _aiGateWayManager.OpenAiResponsesStreamForStatisticsAsync(_httpContextAccessor.HttpContext,
input,
userId, null, tokenId, cancellationToken);
}
else
{
await _aiGateWayManager.OpenAiResponsesAsyncForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId,
null, tokenId,
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);
cancellationToken);
}
}
#region
private string? GetTokenByHttpContext(HttpContext httpContext)
@@ -330,13 +264,6 @@ 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"];

View File

@@ -122,15 +122,11 @@ 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,
tokenAmount,
packageName,
order.GoodsType,
order.TotalAmount,
"自助充值",
expireMonths: null // 尊享包不设置过期时间,或者可以根据需求设置
);

View File

@@ -1,38 +0,0 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Services;
using Yi.Framework.AiHub.Application.Contracts.Dtos;
using Yi.Framework.AiHub.Application.Contracts.IServices;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// 排行榜服务
/// </summary>
public class RankingService : ApplicationService, IRankingService
{
private readonly ISqlSugarRepository<RankingItemAggregateRoot, Guid> _repository;
public RankingService(ISqlSugarRepository<RankingItemAggregateRoot, Guid> repository)
{
_repository = repository;
}
/// <summary>
/// 获取排行榜列表(全量返回,按得分降序)
/// </summary>
[HttpGet("ranking/list")]
[AllowAnonymous]
public async Task<List<RankingItemDto>> GetListAsync([FromQuery] RankingGetListInput input)
{
var query = _repository._DbQueryable
.WhereIF(input.Type.HasValue, x => x.Type == input.Type!.Value)
.OrderByDescending(x => x.Score);
var entities = await query.ToListAsync();
return entities.Adapt<List<RankingItemDto>>();
}
}

View File

@@ -1,8 +1,6 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Recharge;
@@ -37,29 +35,19 @@ namespace Yi.Framework.AiHub.Application.Services
}
/// <summary>
/// 查询已登录的账户充值记录(分页)
/// 查询已登录的账户充值记录
/// </summary>
/// <returns></returns>
[Route("recharge/account")]
[Authorize]
public async Task<PagedResultDto<RechargeGetListOutput>> GetListByAccountAsync([FromQuery]RechargeGetListInput input)
public async Task<List<RechargeGetListOutput>> GetListByAccountAsync()
{
var userId = CurrentUser.Id;
RefAsync<int> total = 0;
var entities = await _repository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.StartTime.HasValue, x => x.CreationTime >= input.StartTime!.Value)
.WhereIF(input.EndTime.HasValue, x => x.CreationTime <= input.EndTime!.Value)
.WhereIF(input.IsFree == true, x => x.RechargeAmount == 0)
.WhereIF(input.IsFree == false, x => x.RechargeAmount > 0)
.WhereIF(input.MinRechargeAmount.HasValue, x => x.RechargeAmount >= input.MinRechargeAmount!.Value)
.WhereIF(input.MaxRechargeAmount.HasValue, x => x.RechargeAmount <= input.MaxRechargeAmount!.Value)
var entities = await _repository._DbQueryable.Where(x => x.UserId == userId)
.OrderByDescending(x => x.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
.ToListAsync();
var output = entities.Adapt<List<RechargeGetListOutput>>();
return new PagedResultDto<RechargeGetListOutput>(total, output);
return output;
}
/// <summary>
@@ -67,24 +55,13 @@ namespace Yi.Framework.AiHub.Application.Services
/// </summary>
/// <param name="input">充值输入参数</param>
/// <returns></returns>
[RemoteService(isEnabled:false)]
[HttpPost("recharge/vip")]
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
@@ -98,9 +75,9 @@ namespace Yi.Framework.AiHub.Application.Services
? maxExpireTime.Value
: DateTime.Now;
// 计算新的过期时间
expireDateTime = baseDateTime.AddDays(totalDays);
expireDateTime = baseDateTime.AddMonths(input.Months.Value);
}
// 如果总天数为0表示永久VIPExpireDateTime保持为null
// 如果月数为空或0表示永久VIPExpireDateTime保持为null
// 创建充值记录
var rechargeRecord = new AiRechargeAggregateRoot

View File

@@ -1,203 +0,0 @@
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Globalization;
using Volo.Abp.Application.Services;
using Yi.Framework.AiHub.Application.Contracts.Dtos.SystemStatistics;
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.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// 系统使用量统计服务实现
/// </summary>
[Authorize(Roles = "admin")]
public class SystemUsageStatisticsService : ApplicationService, ISystemUsageStatisticsService
{
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<AiModelEntity, Guid> _modelRepository;
public SystemUsageStatisticsService(
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<AiModelEntity, Guid> modelRepository)
{
_premiumPackageRepository = premiumPackageRepository;
_rechargeRepository = rechargeRepository;
_messageRepository = messageRepository;
_modelRepository = modelRepository;
}
/// <summary>
/// 获取利润统计数据
/// </summary>
[HttpPost("system-statistics/profit")]
public async Task<ProfitStatisticsOutput> GetProfitStatisticsAsync(ProfitStatisticsInput input)
{
// 1. 获取尊享包总消耗和剩余库存
var premiumPackages = await _premiumPackageRepository._DbQueryable.ToListAsync();
long totalUsedTokens = premiumPackages.Sum(p => p.UsedTokens);
long totalRemainingTokens = premiumPackages.Sum(p => p.RemainingTokens);
// 2. 计算1亿Token成本
decimal costPerHundredMillion = totalUsedTokens > 0
? input.CurrentCost / (totalUsedTokens / 100000000m)
: 0;
// 3. 计算总成本(剩余+已使用的总成本)
long totalTokens = totalUsedTokens + totalRemainingTokens;
decimal totalCost = totalTokens > 0
? (totalTokens / 100000000m) * costPerHundredMillion
: 0;
// 4. 获取总收益(RechargeType=PremiumPackage的充值金额总和)
decimal totalRevenue = await _rechargeRepository._DbQueryable
.Where(x => x.RechargeType == Domain.Shared.Enums.RechargeTypeEnum.PremiumPackage)
.SumAsync(x => x.RechargeAmount);
// 5. 计算利润率
decimal profitRate = totalCost > 0
? (totalRevenue / totalCost - 1) * 100
: 0;
// 6. 按200售价计算成本
decimal costAt200Price = totalRevenue > 0
? (totalCost / totalRevenue) * 200
: 0;
// 7. 格式化日期
var today = DateTime.Now;
string dayOfWeek = today.ToString("dddd", new CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
return new ProfitStatisticsOutput
{
Date = $"{today:M月d日} {weekDay}",
TotalUsedTokens = totalUsedTokens,
TotalUsedTokensInHundredMillion = totalUsedTokens / 100000000m,
TotalRemainingTokens = totalRemainingTokens,
TotalRemainingTokensInHundredMillion = totalRemainingTokens / 100000000m,
CurrentCost = input.CurrentCost,
CostPerHundredMillion = costPerHundredMillion,
TotalCost = totalCost,
TotalRevenue = totalRevenue,
ProfitRate = profitRate,
CostAt200Price = costAt200Price
};
}
/// <summary>
/// 获取指定日期各模型Token统计
/// </summary>
[HttpPost("system-statistics/token")]
public async Task<TokenStatisticsOutput> GetTokenStatisticsAsync(TokenStatisticsInput input)
{
var day = input.Date.Date;
var nextDay = day.AddDays(1);
// 1. 获取所有尊享模型(包含被禁用的),按ModelId去重
var premiumModels = await _modelRepository._DbQueryable
.Where(x => x.IsPremium)
.ToListAsync();
if (premiumModels.Count == 0)
{
return new TokenStatisticsOutput
{
Date = FormatDate(day),
ModelStatistics = new List<ModelTokenStatisticsDto>()
};
}
// 按ModelId去重,保留第一个模型的名称
var distinctModels = premiumModels
.GroupBy(x => x.ModelId)
.Select(g => g.First())
.ToList();
var modelIds = distinctModels.Select(x => x.ModelId).ToList();
// 2. 查询指定日期内各模型的Token使用统计
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);
// 3. 构建结果列表,使用去重后的模型列表
var result = new List<ModelTokenStatisticsDto>();
foreach (var model in distinctModels)
{
modelStatDict.TryGetValue(model.ModelId, out var stat);
long tokens = stat?.Tokens ?? 0;
long count = stat?.Count ?? 0;
// 这里成本设为0,因为需要前端传入或者从配置中获取
decimal cost = 0;
decimal costPerHundredMillion = tokens > 0 && cost > 0
? cost / (tokens / 100000000m)
: 0;
result.Add(new ModelTokenStatisticsDto
{
ModelId = model.ModelId,
ModelName = model.Name,
Tokens = tokens,
TokensInWan = tokens / 10000m,
Count = count,
Cost = cost,
CostPerHundredMillion = costPerHundredMillion
});
}
return new TokenStatisticsOutput
{
Date = FormatDate(day),
ModelStatistics = result
};
}
private string FormatDate(DateTime date)
{
string dayOfWeek = date.ToString("dddd", new CultureInfo("zh-CN"));
string weekDay = dayOfWeek switch
{
"星期一" => "周1",
"星期二" => "周2",
"星期三" => "周3",
"星期四" => "周4",
"星期五" => "周5",
"星期六" => "周6",
"星期日" => "周日",
_ => dayOfWeek
};
return $"{date:M月d日} {weekDay}";
}
}

View File

@@ -9,10 +9,8 @@ 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;
@@ -29,27 +27,24 @@ 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,
ModelManager modelManager)
ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
{
_messageRepository = messageRepository;
_usageStatisticsRepository = usageStatisticsRepository;
_premiumPackageRepository = premiumPackageRepository;
_tokenRepository = tokenRepository;
_modelManager = modelManager;
}
/// <summary>
/// 获取当前用户近7天的Token消耗统计
/// </summary>
/// <returns>每日Token使用量列表</returns>
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery] UsageStatisticsGetInput input)
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var endDate = DateTime.Today;
@@ -58,9 +53,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
// 从Message表统计近7天的token消耗
var dailyUsage = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "system")
.Where(x => x.Role == "assistant" || x.Role == "system")
.Where(x => x.CreationTime >= startDate && x.CreationTime < endDate.AddDays(1))
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
.GroupBy(x => x.CreationTime.Date)
.Select(g => new
{
@@ -90,14 +85,14 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户各个模型的Token消耗量及占比
/// </summary>
/// <returns>模型Token使用量列表</returns>
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery] UsageStatisticsGetInput input)
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
// 从UsageStatistics表获取各模型的token消耗统计按ModelId聚合因为同一模型可能有多个TokenId的记录
var modelUsages = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
.GroupBy(x => x.ModelId)
.Select(x => new
{
@@ -186,9 +181,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
{
var userId = CurrentUser.GetId();
// 通过ModelManager获取所有尊享模型的ModelId列表
var premiumModelIds = await _modelManager.GetPremiumModelIdsAsync();
var premiumModelIds = PremiumPackageConst.ModeIds;
// 从UsageStatistics表获取尊享模型的token消耗统计按TokenId聚合
var tokenUsages = await _usageStatisticsRepository._DbQueryable
@@ -222,133 +215,11 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
var result = tokenUsages.Select(x => new TokenPremiumUsageDto
{
TokenId = x.TokenId,
TokenName = x.TokenId == Guid.Empty
? "默认"
: (tokenNameDict.TryGetValue(x.TokenId, out var name) ? name : "其他"),
TokenName = x.TokenId == Guid.Empty ? "默认" : (tokenNameDict.TryGetValue(x.TokenId, out var name) ? name : "其他"),
Tokens = x.TotalTokenCount,
Percentage = totalTokens > 0 ? Math.Round((decimal)x.TotalTokenCount / totalTokens * 100, 2) : 0
}).OrderByDescending(x => x.Tokens).ToList();
return result;
}
/// <summary>
/// 获取当前用户近24小时每小时Token消耗统计柱状图
/// </summary>
/// <returns>每小时Token使用量列表包含各模型堆叠数据</returns>
public async Task<List<HourlyTokenUsageDto>> GetLast24HoursTokenUsageAsync(
[FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var now = DateTime.Now;
var startTime = now.AddHours(-23); // 滚动24小时从23小时前到现在
var startHour = new DateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, 0, 0);
// 从Message表查询近24小时的数据只选择需要的字段
var messages = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "system")
.Where(x => x.CreationTime >= startHour)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.Select(x => new
{
x.CreationTime,
x.ModelId,
x.TokenUsage.TotalTokenCount
})
.ToListAsync();
// 在内存中按小时和模型分组统计
var hourlyGrouped = messages
.GroupBy(x => new
{
Hour = new DateTime(x.CreationTime.Year, x.CreationTime.Month, x.CreationTime.Day, x.CreationTime.Hour,
0, 0),
x.ModelId
})
.Select(g => new
{
g.Key.Hour,
g.Key.ModelId,
Tokens = g.Sum(x => x.TotalTokenCount)
})
.ToList();
// 生成完整的24小时数据
var result = new List<HourlyTokenUsageDto>();
for (int i = 0; i < 24; i++)
{
var hour = startHour.AddHours(i);
var hourData = hourlyGrouped.Where(x => x.Hour == hour).ToList();
var modelBreakdown = hourData.Select(x => new ModelTokenBreakdownDto
{
ModelId = x.ModelId,
Tokens = x.Tokens
}).ToList();
result.Add(new HourlyTokenUsageDto
{
Hour = hour,
TotalTokens = modelBreakdown.Sum(x => x.Tokens),
ModelBreakdown = modelBreakdown
});
}
return result;
}
/// <summary>
/// 获取当前用户今日各模型使用量统计(卡片列表)
/// </summary>
/// <returns>模型今日使用量列表包含使用次数和总Token</returns>
public async Task<List<ModelTodayUsageDto>> GetTodayModelUsageAsync([FromQuery] UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var todayStart = DateTime.Today; // 今天凌晨0点
var tomorrowStart = todayStart.AddDays(1);
// 从Message表查询今天的数据只选择需要的字段
var messages = await _messageRepository._DbQueryable
.Where(x => x.UserId == userId)
.Where(x => x.Role == "system")
.Where(x => x.CreationTime >= todayStart && x.CreationTime < tomorrowStart)
.WhereIF(input.TokenId.HasValue, x => x.TokenId == input.TokenId)
.Select(x => new
{
x.ModelId,
x.TokenUsage.TotalTokenCount
})
.ToListAsync();
// 在内存中按模型分组统计
var modelStats = messages
.GroupBy(x => x.ModelId)
.Select(g => new ModelTodayUsageDto
{
ModelId = g.Key,
UsageCount = g.Count(),
TotalTokens = g.Sum(x => x.TotalTokenCount)
})
.OrderByDescending(x => x.TotalTokens)
.ToList();
if (modelStats.Count > 0)
{
var modelIds = modelStats.Select(x => x.ModelId).ToList();
var modelDic = await _modelManager._aiModelRepository._DbQueryable.Where(x => modelIds.Contains(x.ModelId))
.Distinct()
.Where(x=>x.IsEnabled)
.ToDictionaryAsync<string>(x => x.ModelId, y => y.IconUrl);
modelStats.ForEach(x =>
{
if (modelDic.TryGetValue(x.ModelId, out var icon))
{
x.IconUrl = icon;
}
});
}
return modelStats;
}
}

View File

@@ -2,10 +2,6 @@
<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" />

View File

@@ -1,7 +1,3 @@
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;

View File

@@ -1,16 +0,0 @@
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; }
}

View File

@@ -11,21 +11,6 @@ public class PremiumPackageConst
"claude-opus-4-5-20251101",
"gemini-3-pro-preview",
"gpt-5.1-codex-max",
"gpt-5.2",
"gemini-3-pro-high",
"gemini-3-pro-image-preview",
"gpt-5.2-codex-xhigh",
"gpt-5.2-codex",
"glm-4.7",
"yi-claude-sonnet-4-5-20250929",
"yi-claude-haiku-4-5-20251001",
"yi-claude-opus-4-5-20251101",
"yi-gpt-5.2",
"yi-gpt-5.2-codex",
"yi-gemini-3-pro-high",
"yi-gemini-3-pro",
"gpt-5.2"
];
}

View File

@@ -1,6 +1,4 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Domain.Shared.Dtos;
namespace Yi.Framework.AiHub.Domain.Shared.Dtos;
public class AiModelDescribe
{
@@ -63,14 +61,4 @@ public class AiModelDescribe
/// 模型倍率
/// </summary>
public decimal Multiplier { get; set; }
/// <summary>
/// 是否为尊享模型
/// </summary>
public bool IsPremium { get; set; }
/// <summary>
/// 模型类型(聊天/图片等)
/// </summary>
public ModelTypeEnum ModelType { get; set; }
}

View File

@@ -18,7 +18,39 @@ public class AnthropicStreamDto
[JsonPropertyName("usage")] public AnthropicCompletionDtoUsage? Usage { get; set; }
[JsonPropertyName("error")] public AnthropicStreamErrorDto? Error { get; set; }
[JsonIgnore]
public ThorUsageResponse TokenUsage => new ThorUsageResponse
{
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
OutputTokens = Usage?.OutputTokens,
InputTokensDetails = null,
CompletionTokens = Usage?.OutputTokens,
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
Usage?.OutputTokens,
PromptTokensDetails = null,
CompletionTokensDetails = null
};
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
this.Usage.CacheCreationInputTokens =
(int)Math.Round((this.Usage.CacheCreationInputTokens ?? 0) * multiplier);
this.Usage.CacheReadInputTokens =
(int)Math.Round((this.Usage.CacheReadInputTokens ?? 0) * multiplier);
this.Usage.InputTokens =
(int)Math.Round((this.Usage.InputTokens ?? 0) * multiplier);
this.Usage.OutputTokens =
(int)Math.Round((this.Usage.OutputTokens ?? 0) * multiplier);
}
}
}
public class AnthropicStreamErrorDto
@@ -39,11 +71,6 @@ public class AnthropicChatCompletionDtoDelta
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
[JsonPropertyName("stop_reason")] public string? StopReason { get; set; }
[JsonPropertyName("signature")] public string? Signature { get; set; }
[JsonPropertyName("stop_sequence")] public string? StopSequence { get; set; }
}
public class AnthropicChatCompletionDtoContentBlock
@@ -88,7 +115,38 @@ public class AnthropicChatCompletionDto
public object stop_sequence { get; set; }
public AnthropicCompletionDtoUsage? Usage { get; set; }
[JsonIgnore]
public ThorUsageResponse TokenUsage => new ThorUsageResponse
{
PromptTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
InputTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens,
OutputTokens = Usage?.OutputTokens,
InputTokensDetails = null,
CompletionTokens = Usage?.OutputTokens,
TotalTokens = Usage?.InputTokens + Usage?.CacheCreationInputTokens + Usage?.CacheReadInputTokens +
Usage?.OutputTokens,
PromptTokensDetails = null,
CompletionTokensDetails = null
};
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
this.Usage.CacheCreationInputTokens =
(int)Math.Round((this.Usage?.CacheCreationInputTokens ?? 0) * multiplier);
this.Usage.CacheReadInputTokens =
(int)Math.Round((this.Usage?.CacheReadInputTokens ?? 0) * multiplier);
this.Usage.InputTokens =
(int)Math.Round((this.Usage?.InputTokens ?? 0) * multiplier);
this.Usage.OutputTokens =
(int)Math.Round((this.Usage?.OutputTokens ?? 0) * multiplier);
}
}
}
public class AnthropicChatCompletionDtoContent
@@ -108,7 +166,6 @@ public class AnthropicChatCompletionDtoContent
[JsonPropertyName("partial_json")] public string? PartialJson { get; set; }
public string? signature { get; set; }
}
public class AnthropicCompletionDtoUsage
@@ -124,12 +181,6 @@ public class AnthropicCompletionDtoUsage
[JsonPropertyName("output_tokens")] public int? OutputTokens { get; set; }
[JsonPropertyName("server_tool_use")] public AnthropicServerToolUse? ServerToolUse { get; set; }
[JsonPropertyName("cache_creation")] public object? CacheCreation { get; set; }
[JsonPropertyName("service_tier")] public string? ServiceTier { get; set; }
}
public class AnthropicServerToolUse

View File

@@ -133,5 +133,28 @@ public class AnthropicMessageTool
[JsonPropertyName("description")] public string? Description { get; set; }
[JsonPropertyName("input_schema")] public object? InputSchema { get; set; }
[JsonPropertyName("input_schema")] public Input_schema? InputSchema { get; set; }
}
public class Input_schema
{
[JsonPropertyName("type")] public string? Type { get; set; }
[JsonPropertyName("properties")] public Dictionary<string, InputSchemaValue>? Properties { get; set; }
[JsonPropertyName("required")] public string[]? Required { get; set; }
}
public class InputSchemaValue
{
public string? type { get; set; }
public string? description { get; set; }
public InputSchemaValueItems? items { get; set; }
}
public class InputSchemaValueItems
{
public string? type { get; set; }
}

View File

@@ -1,266 +0,0 @@
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
{
/// <summary>
/// 从请求体中提取用户最后一条消息内容
/// 路径: contents[last].parts[last].text
/// </summary>
public static string GetLastUserContent(JsonElement request)
{
var contents = request.GetPath("contents");
if (!contents.HasValue || contents.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var contentsArray = contents.Value.EnumerateArray().ToList();
if (contentsArray.Count == 0)
{
return string.Empty;
}
var lastContent = contentsArray[^1];
var parts = lastContent.GetPath("parts");
if (!parts.HasValue || parts.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var partsArray = parts.Value.EnumerateArray().ToList();
if (partsArray.Count == 0)
{
return string.Empty;
}
// 获取最后一个 part 的 text
var lastPart = partsArray[^1];
return lastPart.GetPath("text").GetString() ?? string.Empty;
}
/// <summary>
/// 从响应中提取文本内容(非 thought 类型)
/// 路径: candidates[0].content.parts[].text (where thought != true)
/// </summary>
public static string GetTextContent(JsonElement response)
{
var candidates = response.GetPath("candidates");
if (!candidates.HasValue || candidates.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
var candidatesArray = candidates.Value.EnumerateArray().ToList();
if (candidatesArray.Count == 0)
{
return string.Empty;
}
var parts = candidatesArray[0].GetPath("content", "parts");
if (!parts.HasValue || parts.Value.ValueKind != JsonValueKind.Array)
{
return string.Empty;
}
// 遍历所有 parts只取非 thought 的 text
foreach (var part in parts.Value.EnumerateArray())
{
var isThought = part.GetPath("thought").GetBool();
if (!isThought)
{
var text = part.GetPath("text").GetString();
if (!string.IsNullOrEmpty(text))
{
return text;
}
}
}
return string.Empty;
}
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>
/// 获取图片 base64包含 data:image 前缀)
/// Step 1: 递归遍历整个 JSON 查找最后一个 base64
/// Step 2: 从 text 中查找 markdown 图片
/// </summary>
public static string GetImagePrefixBase64(JsonElement response)
{
// Step 1: 递归遍历整个 JSON 查找最后一个 base64
string? lastBase64 = null;
string? lastMimeType = null;
CollectLastBase64(response, ref lastBase64, ref lastMimeType);
if (!string.IsNullOrEmpty(lastBase64))
{
var mimeType = lastMimeType ?? "image/png";
return $"data:{mimeType};base64,{lastBase64}";
}
// Step 2: 从 text 中查找 markdown 图片
return FindMarkdownImageInResponse(response);
}
/// <summary>
/// 递归遍历 JSON 查找最后一个 base64
/// </summary>
private static void CollectLastBase64(JsonElement element, ref string? lastBase64, ref string? lastMimeType, int minLength = 100)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
string? currentMimeType = null;
string? currentData = null;
foreach (var prop in element.EnumerateObject())
{
var name = prop.Name.ToLowerInvariant();
// 记录 mimeType / mime_type
if (name is "mimetype" or "mime_type" && prop.Value.ValueKind == JsonValueKind.String)
{
currentMimeType = prop.Value.GetString();
}
// 记录 data 字段(检查是否像 base64
else if (name == "data" && prop.Value.ValueKind == JsonValueKind.String)
{
var val = prop.Value.GetString();
if (!string.IsNullOrEmpty(val) && val.Length >= minLength && LooksLikeBase64(val))
{
currentData = val;
}
}
else
{
// 递归处理其他属性
CollectLastBase64(prop.Value, ref lastBase64, ref lastMimeType, minLength);
}
}
// 如果当前对象有 data更新为"最后一个"
if (currentData != null)
{
lastBase64 = currentData;
lastMimeType = currentMimeType;
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
CollectLastBase64(item, ref lastBase64, ref lastMimeType, minLength);
}
break;
}
}
/// <summary>
/// 检查字符串是否像 base64
/// </summary>
private static bool LooksLikeBase64(string str)
{
// 常见图片 base64 开头: JPEG(/9j/), PNG(iVBOR), GIF(R0lGO), WebP(UklGR)
if (str.StartsWith("/9j/") || str.StartsWith("iVBOR") ||
str.StartsWith("R0lGO") || str.StartsWith("UklGR"))
{
return true;
}
// 检查前100个字符是否都是 base64 合法字符
return str.Take(100).All(c => char.IsLetterOrDigit(c) || c == '+' || c == '/' || c == '=');
}
/// <summary>
/// 递归查找 text 字段中的 markdown 图片
/// </summary>
private static string FindMarkdownImageInResponse(JsonElement element)
{
var allTexts = new List<string>();
CollectTextFields(element, allTexts);
// 从最后一个 text 开始查找
for (int i = allTexts.Count - 1; i >= 0; i--)
{
var text = allTexts[i];
// markdown 图片格式: ![image](data:image/png;base64,xxx)
var startMarker = "(data:image/";
var startIndex = text.IndexOf(startMarker, StringComparison.Ordinal);
if (startIndex < 0)
{
continue;
}
startIndex += 1; // 跳过 "("
var endIndex = text.IndexOf(')', startIndex);
if (endIndex > startIndex)
{
return text.Substring(startIndex, endIndex - startIndex);
}
}
return string.Empty;
}
/// <summary>
/// 递归收集所有 text 字段
/// </summary>
private static void CollectTextFields(JsonElement element, List<string> texts)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var prop in element.EnumerateObject())
{
if (prop.Name == "text" && prop.Value.ValueKind == JsonValueKind.String)
{
var val = prop.Value.GetString();
if (!string.IsNullOrEmpty(val))
{
texts.Add(val);
}
}
else
{
CollectTextFields(prop.Value, texts);
}
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
CollectTextFields(item, texts);
}
break;
}
}
}

View File

@@ -1,138 +0,0 @@
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,
/// <summary>
/// 0【888w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 8880000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "888w 尊享Token", content: "888w活动赠送福利包")]
Premium888WFree = 200,
/// <summary>
/// 0【666w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 6660000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "666w 尊享Token", content: "666w活动赠送福利包")]
Premium666WFree = 201,
/// <summary>
/// 0【100w 尊享Token】活动包
/// </summary>
[ActivationCodeGoods(price: 0, tokenAmount: 1000000, vipMonths: 0, isCombo: false, isReusable: false,
isSameTypeOnce: false, displayName: "100w 尊享Token", content: "100w活动赠送福利包")]
Premium100WFree = 202,
}
public static class ActivationCodeGoodsTypeEnumExtensions
{
public static ActivationCodeGoodsAttribute? GetGoods(this ActivationCodeGoodsTypeEnum goodsType)
{
var fieldInfo = goodsType.GetType().GetField(goodsType.ToString());
return fieldInfo?.GetCustomAttribute<ActivationCodeGoodsAttribute>();
}
}

View File

@@ -99,8 +99,8 @@ public enum GoodsTypeEnum
[Price(83.7, 3, 27.9)] [DisplayName("YiXinVip 3 month", "3个月", "短期体验")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip3 = 3,
[Price(91.6, 4, 22.9)] [DisplayName("YiXinVip 4 month", "4个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip5 = 14,
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip6 = 6,
// 尊享包服务 - 需要VIP资格才能购买
[Price(188.9, 0, 1750)]
@@ -110,23 +110,10 @@ public enum GoodsTypeEnum
PremiumPackage5000W = 101,
[Price(248.9, 0, 3500)]
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens", "极致性价比")]
[DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens(推荐)", "极致性价比")]
[GoodsCategory(GoodsCategoryType.PremiumPackage)]
[TokenAmount(100000000)]
PremiumPackage10000W = 102,
//
// [Price(238.9, 0, 3500)]
// [DisplayName("YiXinPremiumPackage 10000W Tokens", "1亿Tokens2026元旦限购", "活动9.5折特价")]
// [GoodsCategory(GoodsCategoryType.PremiumPackage)]
// [TokenAmount(100000000)]
// PremiumPackage10000W_2026 = 103,
//
// [Price(398.9, 0, 7000)]
// [DisplayName("YiXinPremiumPackage 20000W Tokens", "2亿Tokens2026元旦限购", "史上最低8.8折")]
// [GoodsCategory(GoodsCategoryType.PremiumPackage)]
// [TokenAmount(200000000)]
// PremiumPackage20000W_2026 = 104,
}
public static class GoodsTypeEnumExtensions

View File

@@ -4,15 +4,12 @@ namespace Yi.Framework.AiHub.Domain.Shared.Enums;
public enum ModelApiTypeEnum
{
[Description("OpenAi Completions")]
Completions,
[Description("OpenAI")]
OpenAi,
[Description("Claude Messages")]
Messages,
[Description("Claude")]
Claude,
[Description("OpenAi Responses")]
Responses,
[Description("Gemini GenerateContent")]
GenerateContent
[Description("Response")]
Response
}

View File

@@ -1,17 +0,0 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
/// <summary>
/// 发布状态枚举
/// </summary>
public enum PublishStatusEnum
{
/// <summary>
/// 未发布
/// </summary>
Unpublished = 0,
/// <summary>
/// 已发布
/// </summary>
Published = 1
}

View File

@@ -1,17 +0,0 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
/// <summary>
/// 排行榜类型枚举
/// </summary>
public enum RankingTypeEnum
{
/// <summary>
/// 模型
/// </summary>
Model = 0,
/// <summary>
/// 工具
/// </summary>
Tool = 1
}

View File

@@ -1,17 +0,0 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
/// <summary>
/// 会话类型枚举
/// </summary>
public enum SessionTypeEnum
{
/// <summary>
/// 普通聊天
/// </summary>
Chat = 0,
/// <summary>
/// Agent智能体
/// </summary>
Agent = 1
}

View File

@@ -1,8 +0,0 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
public enum TaskStatusEnum
{
Processing,
Success,
Fail
}

View File

@@ -2,7 +2,6 @@
<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>

View File

@@ -1,30 +0,0 @@
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);
}

View File

@@ -107,6 +107,35 @@ 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;
}
}

View File

@@ -73,24 +73,18 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
options.Endpoint,
response.StatusCode, error);
var message = $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode.GetHashCode()}】ErrorId【{errorId}】";
if (error.Contains("prompt is too long") || error.Contains("提示词太长")||error.Contains("input tokens exceeds the model's maximum context length"))
{
message += $", tip: 当前提示词过长,上下文已达到上限,如在 claudecode中使用建议执行/compact压缩当前会话或开启新会话后重试";
}
logger.LogError(
$"Anthropic非流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception(message);
throw new Exception( $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode}】Response【{error}】");
}
var value =
await response.Content.ReadFromJsonAsync<AnthropicChatCompletionDto>(ThorJsonSerializer.DefaultOptions,
cancellationToken: cancellationToken);
return value;
}
@@ -115,6 +109,9 @@ public class AnthropicChatCompletionsService(
{ "anthropic-version", "2023-06-01" }
};
var isThinking = input.Model.EndsWith("thinking");
input.Model = input.Model.Replace("-thinking", string.Empty);
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/v1/messages", input, string.Empty,
headers);
@@ -124,19 +121,12 @@ public class AnthropicChatCompletionsService(
// 大于等于400的状态码都认为是异常
if (response.StatusCode >= HttpStatusCode.BadRequest)
{
Guid errorId = Guid.NewGuid();
var error = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
logger.LogError("OpenAI对话异常 请求地址:{Address}, StatusCode: {StatusCode} Response: {Response}",
options.Endpoint,
response.StatusCode, error);
var message = $"恭喜你运气爆棚遇到了错误尊享包对话异常StatusCode【{response.StatusCode.GetHashCode()}】ErrorId【{errorId}】";
if (error.Contains("prompt is too long") || error.Contains("提示词太长")||error.Contains("input tokens exceeds the model's maximum context length"))
{
message += $", tip: 当前提示词过长,上下文已达到上限,如在 claudecode中使用建议执行/compact压缩当前会话或开启新会话后重试";
}
logger.LogError(
$"Anthropic流式对话异常 请求地址:{options.Endpoint},ErrorId{errorId}, StatusCode: {response.StatusCode.GetHashCode()}, Response: {error}");
throw new Exception(message);
throw new Exception("OpenAI对话异常" + response.StatusCode);
}
using var stream = new StreamReader(await response.Content.ReadAsStreamAsync(cancellationToken));
@@ -174,12 +164,6 @@ public class AnthropicChatCompletionsService(
data = line[OpenAIConstant.Data.Length..].Trim();
// 处理流结束标记
if (data == "[DONE]")
{
break;
}
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data,
ThorJsonSerializer.DefaultOptions);

View File

@@ -9,9 +9,7 @@ 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,
@@ -21,18 +19,8 @@ public sealed class OpenAiChatCompletionsService(
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(
requestUri,
options?.Endpoint.TrimEnd('/') + "/chat/completions",
chatCompletionCreate, options.ApiKey);
openai?.SetTag("Model", chatCompletionCreate.Model);
@@ -142,16 +130,8 @@ public sealed class OpenAiChatCompletionsService(
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(
requestUri,
options?.Endpoint.TrimEnd('/') + "/chat/completions",
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
openai?.SetTag("Model", chatCompletionCreate.Model);
@@ -172,8 +152,7 @@ public sealed class OpenAiChatCompletionsService(
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());

View File

@@ -22,16 +22,7 @@ public class OpenAiResponseService(ILogger<OpenAiResponseService> logger,IHttpCl
var client = httpClientFactory.CreateClient();
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);
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/responses", input, options.ApiKey);
openai?.SetTag("Model", input.Model);
openai?.SetTag("Response", response.StatusCode.ToString());
@@ -95,17 +86,8 @@ 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(
requestUri,
options?.Endpoint.TrimEnd('/') + "/responses",
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
openai?.SetTag("Model", chatCompletionCreate.Model);

View File

@@ -23,17 +23,9 @@ 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(
requestUri,
options?.Endpoint.TrimEnd('/') + "/chat/completions",
chatCompletionCreate, options.ApiKey);
openai?.SetTag("Model", chatCompletionCreate.Model);
@@ -100,6 +92,40 @@ 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;
}
}
@@ -116,16 +142,8 @@ 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(
requestUri,
options?.Endpoint.TrimEnd('/') + "/chat/completions",
chatCompletionCreate, options.ApiKey).ConfigureAwait(false);
openai?.SetTag("Model", chatCompletionCreate.Model);

View File

@@ -1,101 +0,0 @@
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;
}
}

View File

@@ -1,23 +0,0 @@
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);
}
}
}

View File

@@ -1,46 +0,0 @@
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; }
}

View File

@@ -1,50 +0,0 @@
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; }
}

View File

@@ -1,45 +0,0 @@
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;
}
}

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