Compare commits

...

95 Commits

Author SHA1 Message Date
chenchun
8dcbfcad33 feat: 同步商品价格 2025-12-08 14:08:01 +08:00
ccnetcore
f64fd43951 Merge branch 'abp' into ai-hub 2025-12-07 18:50:37 +08:00
ccnetcore
551597765c perf: 优化sqlsguar分页查询 2025-12-07 18:50:02 +08:00
Gsh
bfda33280a fix: 图标显示优化 2025-12-05 23:32:59 +08:00
chenchun
8d0411f1f4 feat: 完成codefirst 2025-12-04 16:38:37 +08:00
chenchun
3995d4acab Merge branch 'token' into ai-hub 2025-12-04 16:35:17 +08:00
chenchun
6ff5727156 feat: 发布新版 2025-12-04 16:34:58 +08:00
chenchun
f654386dfe feat: 发布新版 2025-12-04 16:33:17 +08:00
chenchun
c03ef82643 feat:完成多token分发 2025-12-04 16:32:30 +08:00
Gsh
525545329b fix: 多api密钥增加分页 2025-11-30 00:04:33 +08:00
Gsh
755cb6f509 feat: 优化token用量查看 2025-11-29 23:44:38 +08:00
Gsh
55469708f0 feat: 新增多token用量查看 2025-11-29 23:29:54 +08:00
ccnetcore
94c52c62fe style: 修改token描述 2025-11-29 18:33:39 +08:00
ccnetcore
37b4709d76 feat: 新增token默认分组 2025-11-29 18:28:42 +08:00
ccnetcore
86555af6ce feat: 完成token下拉框 2025-11-29 18:25:43 +08:00
Gsh
ddb00879f4 feat: 新增多token功能 2025-11-29 17:35:17 +08:00
chenchun
2d0ca08314 feat: 新增功能 启动时初始化 AiHub 的 Message、Token、UsageStatistics 聚合根表并添加相应命名空间 2025-11-27 19:23:44 +08:00
chenchun
b78ecf27d5 feat: 完成token功能 2025-11-27 19:01:16 +08:00
Gsh
02a5f69958 feat: 前端2.4版本 2025-11-26 21:20:14 +08:00
Gsh
cf5bf746ef feat: 模型尊享标识优化 2025-11-25 22:14:48 +08:00
chenchun
0a5e40ee25 feat: 新增 PremiumPackageConst 模型 gpt-5.1-codex-max
在 Yi.Framework.AiHub.Domain.Shared/Consts/PremiumPackageConst.cs 的 premiumModels 列表中添加 "gpt-5.1-codex-max"(并补上末尾换行)。
2025-11-25 14:18:06 +08:00
chenchun
51a266ef58 feat: 在 PremiumPackageConst 中新增 claude-opus-4-5-20251101
文件:Yi.Framework.AiHub.Domain.Shared/Consts/PremiumPackageConst.cs
说明:向 premium package 列表中添加新模型标识 claude-opus-4-5-20251101,以支持该付费包。
2025-11-25 12:42:44 +08:00
chenchun
1f0901c90c feat: 新增功能
- 更新 PremiumPackageConst.ModeIds,新增支持的模型 ID:
  - claude-haiku-4-5-20251001
  - gemini-3-pro-preview
- 文件:Yi.Abp.Net8/module/ai-hub/Yi.Framework.AiHub.Domain.Shared/Consts/PremiumPackageConst.cs
- 目的:扩展可识别的 premium 模型列表,便于后续对新模型的支持与路由处理

注意:修改后需重新编译并在相关使用处确认新模型 ID 的兼容性。
2025-11-25 10:57:08 +08:00
chenchun
a725c06396 fix: 移除对 Usage.TotalTokens 的空检查,始终按 multiplier 四舍五入并赋值
移除 TotalTokens 的 null 判断,避免保留 null 值,统一将其按 multiplier 四舍五入后赋为整数,防止后续使用出现空值异常。
2025-11-25 10:19:11 +08:00
chenchun
54547f0d7c fix: 缩放 ThorChatCompletionsResponse.Usage.TotalTokens 按 multiplier
当 Usage.TotalTokens 不为 null 时,按 multiplier 进行四舍五入缩放;与 PromptTokens/CompletionTokens 的缩放逻辑保持一致,修复 TotalTokens 未被缩放的问题。
2025-11-25 10:18:45 +08:00
chenchun
afe9c8bcae feat: 新增模型列表 IsPremiumPackage 字段并在 AiChatService 中设置
- 在 Yi.Framework.AiHub.Application.Contracts.Dtos.ModelGetListOutput 中新增 bool 属性 IsPremiumPackage。
- 在 Yi.Framework.AiHub.Application.Services.Chat.AiChatService 的模型映射中设置该属性,判断逻辑为 PremiumPackageConst.ModeIds.Contains(x.ModelId)。
- 便于前端区分并展示“尊享包”模型。
2025-11-25 09:59:31 +08:00
chenchun
688d93e5c1 feat: 完成倍率的配置化 2025-11-25 09:54:13 +08:00
chenchun
4c65b2398d fix: 将默认 max_tokens 从 100000 调整为 64000
将 Yi.Framework.AiHub.Domain/AiGateWay/Impl/ThorClaude/Chats/ClaudiaChatCompletionsService.cs 中对外请求的默认 max_tokens 值由 100000 降为 64000。

原因:避免超出模型/服务允许的 token 限制或引发资源/性能异常;仍然允许通过 input.MaxTokens 显式覆盖该默认值。已在本地构建并用简单请求验证变更生效。
2025-11-24 17:42:18 +08:00
chenchun
41435f1aa3 feat: 兼容maxtoken问题 2025-11-24 09:42:40 +08:00
chenchun
20206bbc44 fix: 调整 ThorClaude 聊天默认 max_tokens 从 2048 到 100000
修改文件:
Yi.Framework.AiHub.Domain/AiGateWay/Impl/ThorClaude/Chats/ClaudiaChatCompletionsService.cs

说明:
- 将默认 max_tokens 由 2048 提高到 100000,避免长回复被截断,提升对大输出场景的支持。
- 修改可能影响请求的响应长度与资源消耗,请确认后端/模型能够支持该上限并监控性能与计费变化。
2025-11-20 10:20:19 +08:00
chenchun
f2dc0d1825 fix: 仅对 gpt-5.1-chat 设置 MaxCompletionTokens,gpt-5-mini 单独处理 Temperature/TopP
将原先同时匹配 gpt-5.1-chat 与 gpt-5-mini 的处理拆分为两段:
- gpt-5.1-chat:仍将 MaxTokens 映射到 MaxCompletionTokens,并清空 Temperature/TopP。
- gpt-5-mini:只清空 Temperature/TopP,不再修改 MaxTokens/MaxCompletionTokens。

修复了为 gpt-5-mini 不当设置 MaxCompletionTokens 的问题。
2025-11-18 14:35:58 +08:00
chenchun
51b4d1b072 fix: 请求处理中同时重置 MaxTokens 避免与模型不兼容
在 YiFrameworkAiHubDomainModule 的请求处理器中,当清除 Temperature 与 TopP 时一并将 request.MaxTokens 设为 null,防止在不支持该参数的模型上出现错误或参数冲突。文件:Yi.Framework.AiHub.Domain/YiFrameworkAiHubDomainModule.cs。
2025-11-18 14:33:58 +08:00
chenchun
9180799e4e feat: 为 gpt-5-mini 与 databricks-claude-sonnet-4 添加请求特殊处理 2025-11-18 11:36:18 +08:00
chenchun
9788b9182b fix: 区分 gpt-5.1-chat 与 o1 的请求参数清理逻辑
将原先在同一处理器中对 gpt-5.1-chat 与 o1 一并清除 Temperature/TopP 的逻辑拆分为两个处理器:
- gpt-5.1-chat:清除 Temperature 与 TopP
- o1:仅清除 Temperature

文件:Yi.Framework.AiHub.Domain/YiFrameworkAiHubDomainModule.cs

目的:恢复/调整对不同模型的期望处理,避免对 o1 不必要地清除 TopP。
2025-11-18 11:26:05 +08:00
chenchun
260b9a4795 feat: 支持 gpt-5.1-chat 模型的特殊处理
- 将模型判断从仅 "o1" 扩展为 "gpt-5.1-chat" 或 "o1",对这些模型将 Temperature 置为 null。
- 微调了 User-Agent 字符串的空格并做了小范围的格式清理(增加空行以提升可读性)。
2025-11-18 10:39:34 +08:00
chenchun
9380e3daa8 Merge branch 'card-flip' into ai-hub 2025-11-18 10:27:53 +08:00
chenchun
bb894e14a4 Merge remote-tracking branch 'origin/card-flip' into card-flip
# Conflicts:
#	Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore/Repositories/SqlSugarRepository.cs
2025-11-17 11:22:44 +08:00
chenchun
b492d82442 Merge branch 'abp' into card-flip
# Conflicts:
#	Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore.Abstractions/DbConnOptions.cs
#	Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore/Repositories/SqlSugarRepository.cs
#	Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.Domain.Shared/Caches/FileCacheItem.cs
#	Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
2025-11-17 11:21:14 +08:00
chenchun
5eaffe2ec2 feat: 新增更新并发乐观锁配置与支持
- 在 DbConnOptions 新增 EnabledConcurrencyException(bool,默认 false) 配置项。
- 在 SqlSugarRepository 引入 IAbpLazyServiceProvider,通过 IOptions<DbConnOptions> 延迟获取配置。
- UpdateAsync 改为仅当 EnabledConcurrencyException 为 true 且实体实现 IHasConcurrencyStamp 时,使用 ExecuteCommandWithOptLockAsync 并捕获 VersionExceptions 抛出 AbpDbConcurrencyException;否则回退到原有的 UpdateAsync 实现。
- 清理/调整部分 using 引用,新增 Microsoft.Extensions.Options 与 Volo.Abp.DependencyInjection 引用。

注意:默认值为 false,需在配置中显式开启 EnabledConcurrencyException 才会启用乐观并发校验,开启后会改变之前对带版本实体自动使用乐观锁的行为。
2025-11-17 11:19:15 +08:00
Gsh
d7bcad9da7 feat: 前端打包报错处理 2025-11-17 02:03:10 +08:00
Gsh
04e11d15e2 feat: 新手引导优化 2025-11-17 01:39:13 +08:00
Gsh
97e3dc5eed feat: 公告弹窗优化 2025-11-17 01:20:20 +08:00
Gsh
695bd56a27 feat: 增加新手引导 2025-11-17 01:05:57 +08:00
ccnetcore
7919383be3 feat: 完成v2.3.0发布 2025-11-17 00:43:41 +08:00
ccnetcore
d6cc3c5d96 Merge branch 'abp' into card-flip
# Conflicts:
#	Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore/Repositories/SqlSugarRepository.cs
#	Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.Domain.Shared/Caches/FileCacheItem.cs
2025-11-17 00:43:27 +08:00
Gsh
19f0d05a69 fix: 尊享明细表格优化 2025-11-16 23:00:19 +08:00
Gsh
3c5e575e9b fix: 公告优化 2025-11-16 22:39:42 +08:00
Gsh
f875617de1 fix: 版本号2.3 2025-11-16 22:05:44 +08:00
Gsh
9976e8a6e2 fix: 翻牌机制优化 2025-11-16 22:05:01 +08:00
Gsh
38e8cbc5ca fix: 优化邀请 2025-11-16 21:50:54 +08:00
Gsh
d95c14c903 fix: 优化尊享包记录 2025-11-16 21:39:08 +08:00
ccnetcore
ffb2f2fb4c fix: 修复尊享包查询条件并新增时间范围筛选 2025-11-16 21:32:41 +08:00
ccnetcore
4bd2fc357d refactor: 邀请码逻辑调整,支持双方填写/使用邀请码统计,并移除已被邀请状态字段 2025-11-14 23:53:29 +08:00
chenchun
da23d17af8 feat: 为尊享包 Token 列表新增按是否免费过滤并添加请求 DTO
- 新增 PremiumTokenUsageGetListInput,包含 IsFree 过滤项并继承分页 DTO
- 修改 UsageStatisticsService.GetPremiumTokenUsageListAsync 签名为使用新的输入 DTO,并根据 IsFree 添加 WhereIF 过滤
- 微调 DTO 导入与格式化(PremiumTokenUsageGetListOutput)
2025-11-14 18:00:49 +08:00
chenchun
c1a6046107 feat: 完成公告、尊享记录功能 2025-11-14 17:54:40 +08:00
chenchun
2ec7b5f4fd fix: 修复软删除时空引用异常
在 SqlSugarRepository.cs 中对 ISoftDelete 分支增加 GetByIdAsync 返回 null 的判断,避免在实体为 null 时继续反射赋值导致 NullReferenceException。若实体不存在,直接返回 false。
2025-11-13 16:49:44 +08:00
Gsh
d21f61646a fix: 系统公告与尊享额度明细 2025-11-12 23:08:52 +08:00
chenchun
eecdf442fb feat: 新增公告跳转链接字段 Url
- 在 AnnouncementAggregateRoot、AnnouncementLogDto、AnnouncementCacheDto 中新增 string? Url 属性,用于存储公告的跳转链接。
- 如果需要持久化到数据库,请同步添加对应的迁移/映射配置。
2025-11-12 21:49:31 +08:00
chenchun
8e8338743d fix: 修正 YiXinVip 枚举值及属性(8个月改为7个月,更新价格与显示名) 2025-11-10 17:03:54 +08:00
chenchun
1b4c3cbb8d feat: 支持尊享包用量统计 2025-11-10 15:18:05 +08:00
chenchun
b7756e2112 feat: 新增功能
- 概要
  - 重构并扩展公告相关模型、DTO、服务,新增公告类型、图片与时间字段,调整缓存与查询处理。
  - 新增枚举 AnnouncementTypeEnum。

- 主要改动(简要)
  - Yi.Framework.AiHub.Application.Contracts/Dtos/Announcement/AnnouncementLogDto.cs
    - 新增 ImageUrl、StartTime、EndTime、Type 字段,移除 Date 字段,Title 不再默认空串。
  - Yi.Framework.AiHub.Domain/Entities
    - 重命名 AnnouncementLogAggregateRoot -> AnnouncementAggregateRoot
    - 表名由 Ai_AnnouncementLog 改为 Ai_Announcement(SugarTable 标注)
    - 新增 ImageUrl、StartTime、EndTime、Type、Remark 字段(Remark 已存在,保持)
  - Yi.Framework.AiHub.Domain.Shared/Enums/AnnouncementTypeEnum.cs
    - 新增枚举文件(Activity=1, System=2)
  - Yi.Framework.AiHub.Application.Contracts/IServices/IAnnouncementService.cs
    - GetAsync 返回类型由 AnnouncementOutput 改为 List<AnnouncementLogDto>
  - Yi.Framework.AiHub.Application/Services/AnnouncementService.cs
    - 使用 Mapster 进行 DTO 映射
    - 查询按 StartTime 降序,返回 List<AnnouncementLogDto>,缓存结构简化
  - Yi.Abp.Web/YiAbpWebModule.cs
    - 改为初始化 AnnouncementAggregateRoot 的表(Ai_Announcement)
  - Yi.Ai.Vue3/types/import_meta.d.ts
    - 移除 VITE_BUILD_COMPRESS 环境变量声明

- 重要注意/兼容性提示
  - 接口变更:IAnnouncementService.GetAsync 返回类型已改变,调用方需同步更新(之前返回 AnnouncementOutput 的代码需调整)。
  - 数据库表变更:表名从 Ai_AnnouncementLog -> Ai_Announcement,若需保留历史数据,请在部署前做好数据迁移(重命名表或迁移数据到新表结构),或使用 CodeFirst 初始化新表(当前代码在启动时会 InitTables<AnnouncementAggregateRoot>())。
  - 新增 Mapster 适配(确保项目有 Mapster 依赖)。
  - 前端类型声明移除环境变量后,前端构建/运行脚本若依赖 VITE_BUILD_COMPRESS 需同步调整。
  - 若有缓存结构(AnnouncementCacheDto)或序列化相关约定变更,确认兼容性。

- 建议操作
  - 更新所有使用 IAnnouncementService 的代码(API 层/前端适配返回结构)。
  - 在非生产环境先执行数据迁移验证(保留旧表数据或写迁移脚本)。
  - 确认 Mapster 包已安装并编译通过。
  - 前端项目检查并同步 import_meta.d.ts 变更。
2025-11-10 15:03:02 +08:00
chenchun
cb49059e84 feat: 翻牌与邀请码逻辑重构,新增中奖记录与前7次中奖概率
- CardFlipTaskAggregateRoot.cs
  - 用 WinRecords(Dictionary<int,long>) 替代原先第8/9/10次的各自字段,且以 JSON 存库(SugarColumn IsJson)。
  - 构造函数初始化 WinRecords。
  - 新增 SetWinReward(int flipCount, long amount) 统一记录中奖。

- CardFlipService.cs
  - 读取并展示 WinRecords,按翻牌顺序映射中奖信息(不再依赖单独的第8/9/10字段)。

- CardFlipManager.cs
  - 重构中奖逻辑:
    - 前7次翻牌改为 50% 概率可中奖,奖励范围 1w–3w(新增配置常量 FREE_*)。
    - 统一通过 SetWinReward 记录任意次的中奖金额。
    - GenerateRandomReward 根据最小值自动选单位(1w 或 100w)。
  - 邀请类型翻牌校验由“仅统计被填写次数”改为“统计本周作为邀请人或被邀请人的邀请记录数量”(双方都计入),并据此判断是否可解锁邀请翻牌次数。

- InviteCodeManager.cs
  - 使用邀请码时:
    - 验证规则调整:一个账号只能填写别人的邀请码一次(hasUsedOthersCode 检查)。
    - 邀请记录的语义变化:当使用邀请码时,邀请记录同时代表邀请人和被邀请人各增加一次翻牌机会。
    - 不再将邀请码标记为单次已用;改为增加 UsedCount(一个邀请码可以被多人使用)。
    - 优化日志与提示信息。

- InviteCodeAggregateRoot.cs
  - 移除 IsUsed、UsedTime、UsedByUserId、MarkAsUsed 等单次使用相关字段/方法。
  - 保留 IsUserInvited(被邀请后不能再作为被邀请者使用)和 UsedCount(统计多人使用次数)。

注意事项
- 这是数据结构与业务逻辑的变更,数据库表结构发生变化(新增 WinRecords JSON 字段,移除若干字段)。上线前请准备相应的迁移脚本或数据迁移方案,确保历史中奖数据平滑迁移到 WinRecords。
- 变更会影响相关单元/集成测试、前端展示字段,需同步更新对应测试与界面展示逻辑。
2025-11-07 21:31:18 +08:00
chenchun
690cabfd96 feat: 新增公告功能 2025-11-06 16:59:29 +08:00
chenchun
4521212a90 feat: 新增文件缓存功能
- 在 Yi.Framework.Rbac.Application.Services.FileService 中注入 IMemoryCache,用于缓存文件元数据,减少对仓储的重复读取。
  - 在 Get 方法中通过 key "File:{code}" 缓存 FileCacheItem,设置绝对过期时间为 1 天。
  - 缓存项使用 Mapster 适配为 FileCacheItem,再适配回 FileAggregateRoot(保留现有逻辑判断和路径获取)。
- 新增缓存模型 Yi.Framework.Rbac.Domain.Shared.Caches.FileCacheItem(包含 Id、FileSize、FileName、FilePath、创建/修改信息等)。
- 增加并调整相关 using 引用(Microsoft.Extensions.Caching.Memory、Volo.Abp.Caching、Domain.Shared.Caches)。
- 同时修复了保存多文件时的缩进/空格格式(不影响功能)。
2025-11-06 11:29:21 +08:00
chenchun
771ecd9d81 Merge branch 'abp' into ai-hub
# Conflicts:
#	Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.Application/Services/FileService.cs
2025-11-06 11:23:46 +08:00
chenchun
94834f45c3 perf: 使用 FileStreamResult 流式返回文件,避免一次性读取到内存
改为 FileStream 并返回 FileStreamResult,减小内存占用并支持大型文件;修正变量名拼写并添加 null-forgiving 标记。
2025-11-06 11:13:50 +08:00
chenchun
a9b2979a21 Merge branch 'abp' into ai-hub 2025-11-06 11:00:04 +08:00
chenchun
22ac150acd fix: 修正 FileAggregateRoot.FilePath 的赋值,保存目录路径而非包含文件名的完整路径 2025-11-06 10:58:33 +08:00
Gsh
17337b8d78 fix: 系统公告弹窗前端 2025-11-05 23:12:23 +08:00
chenchun
09fb43ee14 refactor: 修改 YiCrudAppService.DeleteAsync 的参数名 ids -> id
在 Yi.Abp.Net8/framework/Yi.Framework.Ddd.Application/YiCrudAppService.cs 中,将 DeleteAsync 方法的参数名由 ids 改为 id,更新了对应的 XML 注释与对 Repository.DeleteManyAsync 的调用参数。仅为参数重命名,无功能变更。
2025-11-05 16:28:52 +08:00
ccnetcore
477c0e3f2c Merge branch 'invitation' into ai-hub 2025-11-02 13:00:36 +08:00
chenchun
5beef22269 fix: 修复权限判断逻辑(应为 &&,避免始终抛出权限异常)
修正 AiAccountService.GetProfitStatisticsAsync 中的条件判断,原先使用 || 导致即使为 Guo 或 cc 仍被拒绝访问。
2025-10-30 14:48:53 +08:00
chenchun
933cbb91d8 feat: 新增尊享包利润统计接口及 ElCollapseTransition 类型声明
- 在 AiAccountService 中新增 GetProfitStatisticsAsync 接口(GET account/profit-statistics),注入 PremiumPackage 仓储并统计尊享包已消耗/剩余、总成本、总收益、利润率及按200售价的成本估算。接口受授权控制。
- 注入 ISqlSugarRepository<PremiumPackageAggregateRoot> 并在构造函数中赋值。
- 在 types/components.d.ts 中新增 ElCollapseTransition 类型声明,补充前端组件类型提示。
- 注意:接口中对用户权限的判断使用了 "CurrentUser.UserName != \"Guo\" || CurrentUser.UserName != \"cc\"",该逻辑可能有误(应为 &&),建议确认并修正权限校验。
2025-10-30 14:38:58 +08:00
chenchun
cf137f6307 fix: 兼容客户端空值,Contents 为空时返回 "_" 并修正 Content 判空逻辑
修复 AnthropicMessageInput 中对 Content/Contents 的判空处理:
- 当 Contents 为 null 或 Count==0 时返回 "_",以兼容客户端对空值的特殊处理。
- 修正对 Content 的判空逻辑,使用 !string.IsNullOrEmpty(...) 确保非空字符串优先返回,避免将空字符串当作有效内容。
2025-10-29 22:23:09 +08:00
chenchun
3e75792e43 fix: 修复bug - 在可用性检查中支持忽略剩余令牌校验,避免负数用量包被错误过滤
- 将 PremiumPackageAggregateRoot.IsAvailable 增加参数 isVerifyRemainingToken=true,保持默认行为不变,允许按需跳过对 RemainingTokens 的校验。
- 在 UsageStatisticsService 中计算可用包时改为使用 p.IsAvailable(false),仅过滤过期或禁用的包,但不再因 RemainingTokens 为负而将包排除,从而保证统计(如 TotalTokens/RemainingTokens 汇总)包含负数用量的包,修正统计错误。

修改文件:
- Yi.Framework.AiHub.Domain/Entities/PremiumPackageAggregateRoot.cs
- Yi.Framework.AiHub.Application/Services/UsageStatisticsService.cs
2025-10-29 16:34:53 +08:00
chenchun
108ba348f6 feat: 扣减尊享包用量并调整日常任务奖励
- 在 AiGateWayManager 中新增:当请求使用尊享包模型时,按实际使用的 totalTokens 调用 PremiumPackageManager.TryConsumeTokensAsync 扣减用户尊享包用量(仅在 totalTokens > 0 时)。
- 调整 DailyTaskService 中两项日常任务的奖励配置:1000w 消耗奖励由 200w -> 100w,3000w 消耗奖励由 400w -> 200w。
- 兼顾少量格式化优化(if 条件空格调整)。
2025-10-28 17:43:23 +08:00
chenchun
bcdcec40e0 Merge remote-tracking branch 'origin/ai-hub' into ai-hub 2025-10-28 16:13:13 +08:00
chenchun
2ce8baea42 fix: 优化对话异常提示信息
将抛出异常的消息从 "OpenAI对话异常{StatusCode}" 修改为更详细的中文提示,包含 StatusCode 与 Response 内容,便于排查。未改变逻辑,仅调整异常文本。
2025-10-28 16:12:52 +08:00
ccnetcore
609de29e71 feat: AnthropicMessageContent 新增 Signature 字段 2025-10-26 14:51:48 +08:00
ccnetcore
2efed4f4a5 feat: AnthropicThinkingInput 新增 signature、thinking、data、text 字段 2025-10-26 10:38:01 +08:00
ccnetcore
1cc5f2a14f refactor: 注释掉 Furion 统一结果 API 注册,保留 ABP 默认处理方式 2025-09-27 17:26:13 +08:00
橙子
d9997eeb28 !100 update Yi.Abp.Net8/framework/Yi.Framework.AspNetCore/UnifyResult/Fiters/FriendlyExceptionFilter.cs.
Merge pull request !100 from Gary/N/A
2025-09-22 07:14:02 +00:00
Gary
06e77aa8fd update Yi.Abp.Net8/framework/Yi.Framework.AspNetCore/UnifyResult/Fiters/FriendlyExceptionFilter.cs.
判断是否为模型验证错误,如果是,将errors传回,并打印日志

Signed-off-by: Gary <1511313969@qq.com>
2025-09-22 07:13:46 +00:00
橙子
e9e2228f6e !97 岗位状态修改
Merge pull request !97 from 嗳摸嫫/jun
2025-09-22 07:13:45 +00:00
橙子
d516a381d0 !98 update Yi.Abp.Net8/framework/Yi.Framework.Mapster/YiFrameworkMapsterModule.cs.
Merge pull request !98 from Gary/N/A
2025-09-22 07:13:26 +00:00
Gary
4e792ba976 update Yi.Abp.Net8/framework/Yi.Framework.Mapster/YiFrameworkMapsterModule.cs.
自动扫描所有继承IRegister 的Mapster 配置

Signed-off-by: Gary <1511313969@qq.com>
2025-09-22 02:58:59 +00:00
chenchun
f90d3871fa feat: 启用 Furion 统一返回结果并优化过滤器配置
- 在 `YiAbpWebModule` 中启用 `AddFurionUnifyResultApi` 以支持 Furion 风格的统一 API 返回格式
- 调整 `UnifyResultExtensions`,移除 `AbpExceptionFilter` 和 `AbpNoContentActionFilter`,确保统一结果过滤器优先执行
2025-09-16 11:48:36 +08:00
HW-July
6005b9329d 岗位状态修改 2025-08-25 17:12:18 +08:00
橙子
9d4b3e7d0c update README.md.
Signed-off-by: 橙子 <454313500@qq.com>
2025-07-05 07:50:10 +00:00
chenchun
72795382a1 style: 调整样式 2025-07-02 15:03:16 +08:00
橙子
35cdff2afa update README.md.
Signed-off-by: 橙子 <454313500@qq.com>
2025-07-02 06:04:18 +00:00
橙子
dcf547f513 style: 新增赞助
Signed-off-by: 橙子 <454313500@qq.com>
2025-07-02 06:03:28 +00:00
橙子
8660d45f36 update README.md.
Signed-off-by: 橙子 <454313500@qq.com>
2025-07-02 06:01:51 +00:00
橙子
63dd55e7a4 !95 修正分页导致部门结构显示异常。取消后台分页功能,同菜单结构无需分页。
Merge pull request !95 from Po/N/A
2025-07-02 03:49:56 +00:00
Po
40cd89f90c 修正分页导致部门结构显示异常。取消后台分页功能,同菜单结构无需分页。
Signed-off-by: Po <448443959@qq.com>
2025-07-02 02:50:06 +00:00
115 changed files with 8801 additions and 1689 deletions

1
.gitignore vendored
View File

@@ -265,6 +265,7 @@ src/Acme.BookStore.Blazor.Server.Tiered/Logs/*
**/wwwroot/libs/*
public
dist
dist - 副本
.vscode
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Development.json
/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.Production.json

View File

@@ -7,6 +7,12 @@
[![fork](https://gitee.com/ccnetcore/yi/badge/fork.svg?theme=dark)](https://gitee.com/ccnetcore/Yi)
[![license](https://img.shields.io/badge/license-MIT-yellow)](https://gitee.com/ccnetcore/Yi)
本项目 CDN 加速及安全防护由 Tencent EdgeOne 赞助
[亚洲最佳CDN、边缘和安全解决方案 - Tencent EdgeOne](https://edgeone.ai/zh?from=github)
<img src="readme/edgeone.png"/>
[English](README-en.md) | 简体中文
****
## 🍍 简介:
@@ -60,9 +66,9 @@ bbs前端`docker run -d --name yi.bbs -p 18001:18001 -v /home/Yi/Yi.Bbs.Vue3/
Yi社区官网网址Bbs社区正式[ccnetcore.com](https://ccnetcore.com) (已上线,欢迎加入)
Rbac后台演示地址https://ccnetcore.com:1000 用户cc、密码123456
Rbac后台演示地址https://data.ccnetcore.com:1000 用户cc、密码123456
Pure后台演示地址https://ccnetcore.com:1001 用户cc、密码123456
Pure后台演示地址https://data.ccnetcore.com:1001 用户cc、密码123456
## 🍏 支持:

View File

@@ -1,4 +1,4 @@
// MIT 许可证
// MIT 许可证
//
// 版权 © 2020-present 百小僧, 百签科技(广东)有限公司 和所有贡献者
//
@@ -17,25 +17,25 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Validation;
using Yi.Framework.Core.Extensions;
namespace Yi.Framework.AspNetCore.UnifyResult.Fiters;
/// <summary>
/// 友好异常拦截器
/// 友好异常拦截器
/// </summary>
public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
{
/// <summary>
/// 异常拦截
/// 异常拦截
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task OnExceptionAsync(ExceptionContext context)
{
// 排除 WebSocket 请求处理
if (context.HttpContext.IsWebSocketRequest()) return;
@@ -44,20 +44,23 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
// 解析异常信息
var exceptionMetadata = GetExceptionMetadata(context);
IUnifyResultProvider unifyResult = context.GetRequiredService<IUnifyResultProvider>();
var unifyResult = context.GetRequiredService<IUnifyResultProvider>();
// 执行规范化异常处理
context.Result = unifyResult.OnException(context, exceptionMetadata);
// 创建日志记录器
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<FriendlyExceptionFilter>>();
var errorMsg = "";
if (exceptionMetadata.Errors != null) errorMsg = "\n" + JsonConvert.SerializeObject(exceptionMetadata.Errors);
// 记录拦截日常
logger.LogError(context.Exception, context.Exception.Message);
logger.LogError(context.Exception, context.Exception.Message + errorMsg);
}
/// <summary>
/// 获取异常元数据
/// 获取异常元数据
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
@@ -74,22 +77,25 @@ public sealed class FriendlyExceptionFilter : IAsyncExceptionFilter
// 判断是否是 ExceptionContext 或者 ActionExecutedContext
var exception = context is ExceptionContext exContext
? exContext.Exception
: (
context is ActionExecutedContext edContext
? edContext.Exception
: default
);
: context is ActionExecutedContext edContext
? edContext.Exception
: default;
if (exception is AbpValidationException validationException)
{
errors = validationException.ValidationErrors;
isValidationException = true;
}
// 判断是否是友好异常
if (exception is UserFriendlyException friendlyException)
{
int statusCode2 = 500;
var statusCode2 = 500;
int.TryParse(friendlyException.Code, out statusCode2);
isFriendlyException = true;
errorCode = friendlyException.Code;
originErrorCode = friendlyException.Code;
statusCode = statusCode2==0?403:statusCode2;
isValidationException = false;
statusCode = statusCode2 == 0 ? 403 : statusCode2;
errors = friendlyException.Message;
data = friendlyException.Data;
}

View File

@@ -2,6 +2,7 @@
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.SwaggerGen;
using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
using Volo.Abp.AspNetCore.Mvc.Response;
using Yi.Framework.AspNetCore.UnifyResult.Fiters;
namespace Yi.Framework.AspNetCore.UnifyResult;
@@ -20,9 +21,10 @@ public static class UnifyResultExtensions
services.AddTransient<FriendlyExceptionFilter>();
services.AddMvc(options =>
{
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpExceptionFilter));
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpNoContentActionFilter));
options.Filters.AddService<SucceededUnifyResultFilter>(99);
options.Filters.AddService<FriendlyExceptionFilter>(100);
options.Filters.RemoveAll(x => (x as ServiceFilterAttribute)?.ServiceType == typeof(AbpExceptionFilter));
});
return services;
}

View File

@@ -199,11 +199,11 @@ namespace Yi.Framework.Ddd.Application
/// <summary>
/// 批量删除实体
/// </summary>
/// <param name="ids">实体ID集合</param>
/// <param name="id">实体ID集合</param>
[RemoteService(isEnabled: true)]
public virtual async Task DeleteAsync(IEnumerable<TKey> ids)
public virtual async Task DeleteAsync(IEnumerable<TKey> id)
{
await Repository.DeleteManyAsync(ids);
await Repository.DeleteManyAsync(id);
}
/// <summary>

View File

@@ -1,7 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity;
using Volo.Abp.ObjectMapping;
using Yi.Framework.Core;
using Mapster;
namespace Yi.Framework.Mapster
{
@@ -22,7 +23,8 @@ namespace Yi.Framework.Mapster
public override void ConfigureServices(ServiceConfigurationContext context)
{
var services = context.Services;
// 扫描并注册所有映射配置
TypeAdapterConfig.GlobalSettings.Scan(AppDomain.CurrentDomain.GetAssemblies());
// 注册Mapster相关服务
services.AddTransient<IAutoObjectMappingProvider, MapsterAutoObjectMappingProvider>();
services.AddTransient<IObjectMapper, MapsterObjectMapper>();

View File

@@ -60,8 +60,8 @@ namespace Yi.Framework.SqlSugarCore.Abstractions
public bool EnabledSaasMultiTenancy { get; set; } = false;
/// <summary>
/// 并发乐观锁异常,否则不处理
/// 是否开启更新并发乐观锁
/// </summary>
public bool EnabledConcurrencyException { get; set; } = true;
public bool EnabledConcurrencyException { get;set; } = false;
}
}

View File

@@ -1,12 +1,7 @@
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nito.AsyncEx;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Auditing;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities;
@@ -17,18 +12,19 @@ using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.SqlSugarCore.Repositories
{
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity>
where TEntity : class, IEntity, new()
public class SqlSugarRepository<TEntity> : ISqlSugarRepository<TEntity>, IRepository<TEntity> where TEntity : class, IEntity, new()
{
[Obsolete("使用GetDbContextAsync()")]
public ISqlSugarClient _Db => AsyncContext.Run(async () => await GetDbContextAsync());
[Obsolete("使用AsQueryable()")]
public ISugarQueryable<TEntity> _DbQueryable => _Db.Queryable<TEntity>();
private readonly ISugarDbContextProvider<ISqlSugarDbContext> _dbContextProvider;
public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
protected DbConnOptions? Options => LazyServiceProvider?.LazyGetService<IOptions<DbConnOptions>>().Value;
/// <summary>
/// 异步查询执行器
/// </summary>
@@ -64,26 +60,22 @@ namespace Yi.Framework.SqlSugarCore.Repositories
#region Abp模块
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate,
bool includeDetails = true, CancellationToken cancellationToken = default)
public virtual async Task<TEntity?> FindAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
{
return await GetFirstAsync(predicate);
}
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate,
bool includeDetails = true, CancellationToken cancellationToken = default)
public virtual async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = true, CancellationToken cancellationToken = default)
{
return await GetFirstAsync(predicate);
}
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, bool autoSave = false, CancellationToken cancellationToken = default)
{
await this.DeleteAsync(predicate);
}
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate,
CancellationToken cancellationToken = default)
public virtual async Task DeleteDirectAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken = default)
{
await this.DeleteAsync(predicate);
}
@@ -113,71 +105,60 @@ namespace Yi.Framework.SqlSugarCore.Repositories
throw new NotImplementedException();
}
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate,
bool includeDetails = false, CancellationToken cancellationToken = default)
public virtual async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate, bool includeDetails = false, CancellationToken cancellationToken = default)
{
return await GetListAsync(predicate);
}
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task<TEntity> InsertAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
{
return await InsertReturnEntityAsync(entity);
}
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task InsertManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
{
await InsertRangeAsync(entities.ToList());
}
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task<TEntity> UpdateAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
{
await UpdateAsync(entity);
return entity;
}
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task UpdateManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
{
await UpdateRangeAsync(entities.ToList());
}
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task DeleteAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default)
{
await DeleteAsync(entity);
}
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task DeleteManyAsync(IEnumerable<TEntity> entities, bool autoSave = false, CancellationToken cancellationToken = default)
{
await DeleteAsync(entities.ToList());
}
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false,
CancellationToken cancellationToken = default)
public virtual async Task<List<TEntity>> GetListAsync(bool includeDetails = false, CancellationToken cancellationToken = default)
{
return await GetListAsync();
}
public virtual async Task<long> GetCountAsync(CancellationToken cancellationToken = default)
{
return await this.CountAsync(_ => true);
return await this.CountAsync(_=>true);
}
public virtual async Task<List<TEntity>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting,
bool includeDetails = false, CancellationToken cancellationToken = default)
public virtual async Task<List<TEntity>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
{
return await GetPageListAsync(_ => true, skipCount, maxResultCount);
}
#endregion
#region DB快捷操作
public virtual async Task<IDeleteable<TEntity>> AsDeleteable()
{
return (await GetDbSimpleClientAsync()).AsDeleteable();
@@ -192,7 +173,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
return (await GetDbSimpleClientAsync()).AsInsertable(insertObj);
}
public virtual async Task<IInsertable<TEntity>> AsInsertable(TEntity[] insertObjs)
{
return (await GetDbSimpleClientAsync()).AsInsertable(insertObjs);
@@ -232,11 +213,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
return (await GetDbSimpleClientAsync()).AsUpdateable(updateObjs);
}
#endregion
#region SimpleClient模块
public virtual async Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return await (await GetDbSimpleClientAsync()).CountAsync(whereExpression);
@@ -253,6 +232,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
return await (await GetDbSimpleClientAsync()).DeleteAsync(deleteObj);
}
}
public virtual async Task<bool> DeleteAsync(List<TEntity> deleteObjs)
@@ -272,13 +252,13 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
{
return await (await GetDbSimpleClientAsync()).AsUpdateable()
.SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
return await (await GetDbSimpleClientAsync()).AsUpdateable().SetColumns(nameof(ISoftDelete.IsDeleted), true).Where(whereExpression).ExecuteCommandAsync() > 0;
}
else
{
return await (await GetDbSimpleClientAsync()).DeleteAsync(whereExpression);
}
}
public virtual async Task<bool> DeleteByIdAsync(dynamic id)
@@ -286,11 +266,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
{
var entity = await GetByIdAsync(id);
if (entity is null)
{
return false;
}
if (entity == null) return false;
//反射赋值
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, entity);
return await UpdateAsync(entity);
@@ -311,7 +287,6 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
return false;
}
//反射赋值
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
return await UpdateRangeAsync(entities);
@@ -320,6 +295,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
{
return await (await GetDbSimpleClientAsync()).DeleteByIdAsync(ids);
}
}
public virtual async Task<TEntity> GetByIdAsync(dynamic id)
@@ -328,6 +304,7 @@ namespace Yi.Framework.SqlSugarCore.Repositories
}
public virtual async Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> whereExpression)
{
return await (await GetDbSimpleClientAsync()).GetFirstAsync(whereExpression);
@@ -343,19 +320,14 @@ namespace Yi.Framework.SqlSugarCore.Repositories
return await (await GetDbSimpleClientAsync()).GetListAsync(whereExpression);
}
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
int pageNum, int pageSize)
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression, int pageNum, int pageSize)
{
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
new PageModel() { PageIndex = pageNum, PageSize = pageSize });
return await (await AsQueryable()).Where(whereExpression).ToPageListAsync(pageNum, pageSize);
}
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression,
int pageNum, int pageSize, Expression<Func<TEntity, object>>? orderByExpression = null,
OrderByType orderByType = OrderByType.Asc)
public virtual async Task<List<TEntity>> GetPageListAsync(Expression<Func<TEntity, bool>> whereExpression, int pageNum, int pageSize, Expression<Func<TEntity, object>>? orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
return await (await GetDbSimpleClientAsync()).GetPageListAsync(whereExpression,
new PageModel { PageIndex = pageNum, PageSize = pageSize }, orderByExpression, orderByType);
return await (await AsQueryable()).Where(whereExpression) .OrderBy( orderByExpression,orderByType).ToPageListAsync(pageNum, pageSize);
}
public virtual async Task<TEntity> GetSingleAsync(Expression<Func<TEntity, bool>> whereExpression)
@@ -410,9 +382,9 @@ namespace Yi.Framework.SqlSugarCore.Repositories
public virtual async Task<bool> UpdateAsync(TEntity updateObj)
{
if (typeof(TEntity).IsAssignableTo<IHasConcurrencyStamp>()) //带版本号乐观锁更新
if (Options is not null && Options.EnabledConcurrencyException)
{
if (Options is not null && Options.EnabledConcurrencyException)
if (typeof(TEntity).IsAssignableTo<IHasConcurrencyStamp>()) //带版本号乐观锁更新
{
try
{
@@ -426,24 +398,18 @@ namespace Yi.Framework.SqlSugarCore.Repositories
$"{ex.Message}[更新失败ConcurrencyStamp不是最新版本],entityInfo{updateObj}", ex);
}
}
else
{
int num = await (await GetDbSimpleClientAsync())
.Context.Updateable(updateObj).ExecuteCommandAsync();
return num > 0;
}
}
return await (await GetDbSimpleClientAsync()).UpdateAsync(updateObj);
}
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns,
Expression<Func<TEntity, bool>> whereExpression)
public virtual async Task<bool> UpdateAsync(Expression<Func<TEntity, TEntity>> columns, Expression<Func<TEntity, bool>> whereExpression)
{
return await (await GetDbSimpleClientAsync()).UpdateAsync(columns, whereExpression);
}
public virtual async Task<bool> UpdateRangeAsync(List<TEntity> updateObjs)
{
return await (await GetDbSimpleClientAsync()).UpdateRangeAsync(updateObjs);
@@ -452,36 +418,30 @@ namespace Yi.Framework.SqlSugarCore.Repositories
#endregion
}
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>,
IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
public class SqlSugarRepository<TEntity, TKey> : SqlSugarRepository<TEntity>, ISqlSugarRepository<TEntity, TKey>, IRepository<TEntity, TKey> where TEntity : class, IEntity<TKey>, new()
{
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> dbContextProvider) : base(
dbContextProvider)
public SqlSugarRepository(ISugarDbContextProvider<ISqlSugarDbContext> sugarDbContextProvider) : base(sugarDbContextProvider)
{
}
public virtual async Task DeleteAsync(TKey id, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task DeleteAsync(TKey id, bool autoSave = false, CancellationToken cancellationToken = default)
{
await DeleteByIdAsync(id);
}
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false,
CancellationToken cancellationToken = default)
public virtual async Task DeleteManyAsync(IEnumerable<TKey> ids, bool autoSave = false, CancellationToken cancellationToken = default)
{
await DeleteByIdsAsync(ids.Select(x => (object)x).ToArray());
}
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true,
CancellationToken cancellationToken = default)
public virtual async Task<TEntity?> FindAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
{
return await GetByIdAsync(id);
}
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true,
CancellationToken cancellationToken = default)
public virtual async Task<TEntity> GetAsync(TKey id, bool includeDetails = true, CancellationToken cancellationToken = default)
{
return await GetByIdAsync(id);
}
}
}
}

View File

@@ -0,0 +1,22 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 公告缓存 DTO
/// </summary>
public class AnnouncementCacheDto
{
/// <summary>
/// 版本号
/// </summary>
public string Version { get; set; } = string.Empty;
/// <summary>
/// 公告日志列表
/// </summary>
public List<AnnouncementLogDto> Logs { get; set; } = new List<AnnouncementLogDto>();
/// <summary>
/// 跳转链接
/// </summary>
public string? Url { get; set; }
}

View File

@@ -0,0 +1,44 @@
using Yi.Framework.AiHub.Domain.Shared.Enums;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 公告日志 DTO
/// </summary>
public class AnnouncementLogDto
{
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 内容列表
/// </summary>
public List<string> Content { get; set; } = new List<string>();
/// <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; }
}

View File

@@ -0,0 +1,17 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
/// <summary>
/// 公告输出 DTO
/// </summary>
public class AnnouncementOutput
{
/// <summary>
/// 版本号
/// </summary>
public string Version { get; set; } = string.Empty;
/// <summary>
/// 公告日志列表
/// </summary>
public List<AnnouncementLogDto> Logs { get; set; } = new List<AnnouncementLogDto>();
}

View File

@@ -39,12 +39,7 @@ public class CardFlipStatusOutput
/// 本周邀请人数
/// </summary>
public int InvitedCount { get; set; }
/// <summary>
/// 是否已被邀请(被邀请后不可再提供邀请码)
/// </summary>
public bool IsInvited { get; set; }
/// <summary>
/// 翻牌记录
/// </summary>
@@ -54,6 +49,11 @@ public class CardFlipStatusOutput
/// 下次可翻牌提示
/// </summary>
public string? NextFlipTip { get; set; }
/// <summary>
/// 当前用户是否已经填写过邀请码
/// </summary>
public bool IsFilledInviteCode { get; set; }
}
/// <summary>

View File

@@ -62,4 +62,9 @@ public class ModelGetListOutput
/// 备注信息
/// </summary>
public string? Remark { get; set; }
/// <summary>
/// 是否为尊享包
/// </summary>
public bool IsPremiumPackage { get; set; }
}

View File

@@ -0,0 +1,26 @@
using System.ComponentModel.DataAnnotations;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
/// <summary>
/// 创建Token输入
/// </summary>
public class TokenCreateInput
{
/// <summary>
/// 名称(同一用户不能重复)
/// </summary>
[Required(ErrorMessage = "名称不能为空")]
[StringLength(100, ErrorMessage = "名称长度不能超过100个字符")]
public string Name { get; set; }
/// <summary>
/// 过期时间(空为永不过期)
/// </summary>
public DateTime? ExpireTime { get; set; }
/// <summary>
/// 尊享包额度限制(空为不限制)
/// </summary>
public long? PremiumQuotaLimit { get; set; }
}

View File

@@ -0,0 +1,47 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
/// <summary>
/// Token列表输出
/// </summary>
public class TokenGetListOutputDto
{
/// <summary>
/// Token Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// Token密钥
/// </summary>
public string ApiKey { get; set; }
/// <summary>
/// 过期时间(空为永不过期)
/// </summary>
public DateTime? ExpireTime { get; set; }
/// <summary>
/// 尊享包额度限制(空为不限制)
/// </summary>
public long? PremiumQuotaLimit { get; set; }
/// <summary>
/// 尊享包已使用额度
/// </summary>
public long PremiumUsedQuota { get; set; }
/// <summary>
/// 是否禁用
/// </summary>
public bool IsDisabled { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
public class TokenSelectListOutputDto
{
public Guid TokenId { get; set; }
public string Name { get; set; }
public bool IsDisabled { get; set; }
}

View File

@@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
/// <summary>
/// 编辑Token输入
/// </summary>
public class TokenUpdateInput
{
/// <summary>
/// Token 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>
public DateTime? ExpireTime { get; set; }
/// <summary>
/// 尊享包额度限制(空为不限制)
/// </summary>
public long? PremiumQuotaLimit { get; set; }
}

View File

@@ -0,0 +1,12 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
public class PremiumTokenUsageGetListInput : PagedAllResultRequestDto
{
/// <summary>
/// 是否免费
/// </summary>
public bool? IsFree { get; set; }
}

View File

@@ -0,0 +1,57 @@
using Volo.Abp.Application.Dtos;
using Yi.Framework.Ddd.Application.Contracts;
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
public class PremiumTokenUsageGetListOutput : CreationAuditedEntityDto
{
/// <summary>
/// id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// 包名称
/// </summary>
public string PackageName { get; set; }
/// <summary>
/// 总用量总token数
/// </summary>
public long TotalTokens { get; set; }
/// <summary>
/// 剩余用量剩余token数
/// </summary>
public long RemainingTokens { get; set; }
/// <summary>
/// 已使用token数
/// </summary>
public long UsedTokens { get; set; }
/// <summary>
/// 到期时间
/// </summary>
public DateTime? ExpireDateTime { get; set; }
/// <summary>
/// 是否激活
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// 购买金额
/// </summary>
public decimal PurchaseAmount { get; set; }
/// <summary>
/// 备注
/// </summary>
public string? Remark { get; set; }
}

View File

@@ -0,0 +1,27 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
/// <summary>
/// 尊享包不同Token用量占比DTO饼图
/// </summary>
public class TokenPremiumUsageDto
{
/// <summary>
/// Token Id
/// </summary>
public Guid TokenId { get; set; }
/// <summary>
/// Token名称
/// </summary>
public string TokenName { get; set; }
/// <summary>
/// Token消耗量
/// </summary>
public long Tokens { get; set; }
/// <summary>
/// 占比(百分比)
/// </summary>
public decimal Percentage { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace Yi.Framework.AiHub.Application.Contracts.Dtos.UsageStatistics;
public class UsageStatisticsGetInput
{
/// <summary>
/// tokenId
/// </summary>
public Guid? TokenId { get; set; }
}

View File

@@ -0,0 +1,15 @@
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
namespace Yi.Framework.AiHub.Application.Contracts.IServices;
/// <summary>
/// 公告服务接口
/// </summary>
public interface IAnnouncementService
{
/// <summary>
/// 获取公告信息
/// </summary>
/// <returns>公告信息</returns>
Task<List<AnnouncementLogDto>> GetAsync();
}

View File

@@ -11,13 +11,13 @@ public interface IUsageStatisticsService
/// 获取当前用户近7天的Token消耗统计
/// </summary>
/// <returns>每日Token使用量列表</returns>
Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync();
Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync(UsageStatisticsGetInput input);
/// <summary>
/// 获取当前用户各个模型的Token消耗量及占比
/// </summary>
/// <returns>模型Token使用量列表</returns>
Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync();
Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync(UsageStatisticsGetInput input);
/// <summary>
/// 获取当前用户尊享服务Token用量统计

View File

@@ -17,15 +17,18 @@ public class AiAccountService : ApplicationService
private IAccountService _accountService;
private ISqlSugarRepository<AiUserExtraInfoEntity> _userRepository;
private ISqlSugarRepository<AiRechargeAggregateRoot> _rechargeRepository;
private ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
public AiAccountService(
IAccountService accountService,
ISqlSugarRepository<AiUserExtraInfoEntity> userRepository,
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository)
ISqlSugarRepository<AiRechargeAggregateRoot> rechargeRepository,
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
{
_accountService = accountService;
_userRepository = userRepository;
_rechargeRepository = rechargeRepository;
_premiumPackageRepository = premiumPackageRepository;
}
/// <summary>
@@ -72,4 +75,77 @@ 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

@@ -0,0 +1,68 @@
using Mapster;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement;
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 AnnouncementService : ApplicationService, IAnnouncementService
{
private readonly ISqlSugarRepository<AnnouncementAggregateRoot> _announcementRepository;
private readonly IConfiguration _configuration;
private readonly IDistributedCache<AnnouncementCacheDto> _announcementCache;
private const string AnnouncementCacheKey = "AiHub:Announcement";
public AnnouncementService(
ISqlSugarRepository<AnnouncementAggregateRoot> announcementRepository,
IConfiguration configuration,
IDistributedCache<AnnouncementCacheDto> announcementCache)
{
_announcementRepository = announcementRepository;
_configuration = configuration;
_announcementCache = announcementCache;
}
/// <summary>
/// 获取公告信息
/// </summary>
public async Task<List<AnnouncementLogDto>> GetAsync()
{
// 使用 GetOrAddAsync 从缓存获取或添加数据缓存1小时
var cacheData = await _announcementCache.GetOrAddAsync(
AnnouncementCacheKey,
async () => await LoadAnnouncementDataAsync(),
() => new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
}
);
return cacheData?.Logs ?? new List<AnnouncementLogDto>();
}
/// <summary>
/// 从数据库加载公告数据
/// </summary>
private async Task<AnnouncementCacheDto> LoadAnnouncementDataAsync()
{
// 查询所有公告日志,按日期降序排列
var logs = await _announcementRepository._DbQueryable
.OrderByDescending(x => x.StartTime)
.ToListAsync();
// 转换为 DTO
var logDtos = logs.Adapt<List<AnnouncementLogDto>>();
return new AnnouncementCacheDto
{
Logs = logDtos
};
}
}

View File

@@ -51,9 +51,8 @@ public class CardFlipService : ApplicationService, ICardFlipService
// 统计本周邀请人数
var invitedCount = await _inviteCodeManager.GetWeeklyInvitationCountAsync(userId, weekStart);
// 检查用户是否已邀请
var isInvited = await _inviteCodeManager.IsUserInvitedAsync(userId);
//当前用户是否已填写过邀请
var isFilledInviteCode = await _inviteCodeManager.IsFilledInviteCodeAsync(userId);
var output = new CardFlipStatusOutput
{
TotalFlips = task?.TotalFlips ?? 0,
@@ -63,8 +62,8 @@ public class CardFlipService : ApplicationService, ICardFlipService
CanFlip = _cardFlipManager.CanFlipCard(task),
MyInviteCode = inviteCode?.Code,
InvitedCount = invitedCount,
IsInvited = isInvited,
FlipRecords = BuildFlipRecords(task)
FlipRecords = BuildFlipRecords(task),
IsFilledInviteCode = isFilledInviteCode
};
// 生成提示信息
@@ -87,7 +86,7 @@ public class CardFlipService : ApplicationService, ICardFlipService
// 如果中奖,发放奖励
if (result.IsWin)
{
await GrantRewardAsync(userId, result.RewardAmount, $"翻牌活动{input.FlipNumber}中奖");
await GrantRewardAsync(userId, result.RewardAmount, $"翻牌活动-序号{input.FlipNumber}中奖");
}
// 构建输出
@@ -147,7 +146,6 @@ public class CardFlipService : ApplicationService, ICardFlipService
{
MyInviteCode = inviteCode?.Code,
InvitedCount = invitedCount,
IsInvited = inviteCode?.IsUserInvited ?? false,
InvitationHistory = invitationHistory.Select(x => new InvitationHistoryItem
{
InvitedUserName = x.InvitedUserName,
@@ -183,6 +181,9 @@ public class CardFlipService : ApplicationService, ICardFlipService
var flippedOrder = task != null ? _cardFlipManager.GetFlippedOrder(task) : new List<int>();
var flippedNumbers = new HashSet<int>(flippedOrder);
// 获取中奖记录
var winRecords = task?.WinRecords ?? new Dictionary<int, long>();
// 构建记录按照原始序号1-10排列
for (int i = 1; i <= CardFlipManager.TOTAL_MAX_FLIPS; i++)
{
@@ -202,23 +203,11 @@ public class CardFlipService : ApplicationService, ICardFlipService
{
var flipOrderIndex = flippedOrder.IndexOf(i) + 1; // 第几次翻的1-based
// 第8次翻的卡中奖
if (flipOrderIndex == 8)
// 检查这次翻牌是否中奖
if (winRecords.TryGetValue(flipOrderIndex, out var rewardAmount))
{
record.IsWin = true;
record.RewardAmount = task.EighthRewardAmount;
}
// 第9次翻的卡中奖
else if (flipOrderIndex == 9)
{
record.IsWin = true;
record.RewardAmount = task.NinthRewardAmount;
}
// 第10次翻的卡中奖
else if (flipOrderIndex == 10)
{
record.IsWin = true;
record.RewardAmount = task.TenthRewardAmount;
record.RewardAmount = rewardAmount;
}
}
@@ -246,10 +235,10 @@ public class CardFlipService : ApplicationService, ICardFlipService
{
if (status.TotalFlips >= 7)
{
return $"本周使用他人邀请码可解锁{status.RemainingInviteFlips}次翻牌,且必中大奖!每次中奖最大额度将翻倍!";
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌且必中大奖!每次中奖最大额度将翻倍!";
}
return $"本周使用他人邀请码可解锁{status.RemainingInviteFlips}次翻牌,必中大奖!每次中奖最大额度将翻倍!";
return $"本周使用他人邀请码或他人使用你的邀请码,可解锁{status.RemainingInviteFlips}次翻牌必中大奖!每次中奖最大额度将翻倍!";
}
return "继续加油!";

View File

@@ -87,7 +87,8 @@ public class AiChatService : ApplicationService
SystemPrompt = null,
ApiHost = null,
ApiKey = null,
Remark = x.Description
Remark = x.Description,
IsPremiumPackage = PremiumPackageConst.ModeIds.Contains(x.ModelId)
}).ToListAsync();
return output;
}
@@ -134,7 +135,7 @@ public class AiChatService : ApplicationService
//ai网关代理httpcontext
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
CurrentUser.Id, sessionId, cancellationToken);
CurrentUser.Id, sessionId, null, cancellationToken);
}
@@ -171,6 +172,6 @@ public class AiChatService : ApplicationService
//ai网关代理httpcontext
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
CurrentUser.Id, null, cancellationToken);
CurrentUser.Id, null, null, cancellationToken);
}
}

View File

@@ -0,0 +1,245 @@
using Dm.util;
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.Token;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.Ddd.Application.Contracts;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
/// <summary>
/// Token服务
/// </summary>
[Authorize]
public class TokenService : ApplicationService
{
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
public TokenService(
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
{
_tokenRepository = tokenRepository;
_usageStatisticsRepository = usageStatisticsRepository;
}
/// <summary>
/// 获取当前用户的Token列表
/// </summary>
[HttpGet("token/list")]
public async Task<PagedResultDto<TokenGetListOutputDto>> GetListAsync([FromQuery] PagedAllResultRequestDto input)
{
RefAsync<int> total = 0;
var userId = CurrentUser.GetId();
var tokens = await _tokenRepository._DbQueryable
.Where(x => x.UserId == userId)
.OrderByDescending(x => x.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
if (!tokens.Any())
{
return new PagedResultDto<TokenGetListOutputDto>();
}
// 获取尊享包模型ID列表
var premiumModelIds = PremiumPackageConst.ModeIds;
// 批量查询所有Token的尊享包已使用额度
var tokenIds = tokens.Select(t => t.Id).ToList();
var usageStats = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId && tokenIds.Contains(x.TokenId) && premiumModelIds.Contains(x.ModelId))
.GroupBy(x => x.TokenId)
.Select(g => new
{
TokenId = g.TokenId,
UsedQuota = SqlFunc.AggregateSum(g.TotalTokenCount)
})
.ToListAsync();
var result = tokens.Select(t =>
{
var usedQuota = usageStats.FirstOrDefault(u => u.TokenId == t.Id)?.UsedQuota ?? 0;
return new TokenGetListOutputDto
{
Id = t.Id,
Name = t.Name,
ApiKey = t.Token,
ExpireTime = t.ExpireTime,
PremiumQuotaLimit = t.PremiumQuotaLimit,
PremiumUsedQuota = usedQuota,
IsDisabled = t.IsDisabled,
CreationTime = t.CreationTime
};
}).ToList();
return new PagedResultDto<TokenGetListOutputDto>(total, result);
}
[HttpGet("token/select-list")]
public async Task<List<TokenSelectListOutputDto>> GetSelectListAsync()
{
var userId = CurrentUser.GetId();
var tokens = await _tokenRepository._DbQueryable
.Where(x => x.UserId == userId)
.OrderBy(x => x.IsDisabled)
.OrderByDescending(x => x.CreationTime)
.Select(x => new TokenSelectListOutputDto
{
TokenId = x.Id,
Name = x.Name,
IsDisabled = x.IsDisabled
}).ToListAsync();
tokens.Insert(0,new TokenSelectListOutputDto
{
TokenId = Guid.Empty,
Name = "默认",
IsDisabled = false
});
return tokens;
}
/// <summary>
/// 创建Token
/// </summary>
[HttpPost("token")]
public async Task<TokenGetListOutputDto> CreateAsync([FromBody] TokenCreateInput input)
{
var userId = CurrentUser.GetId();
// 检查用户是否为VIP
if (!CurrentUser.IsAiVip())
{
throw new UserFriendlyException("充值成为Vip畅享第三方token服务");
}
// 检查名称是否重复
var exists = await _tokenRepository._DbQueryable
.AnyAsync(x => x.UserId == userId && x.Name == input.Name);
if (exists)
{
throw new UserFriendlyException($"名称【{input.Name}】已存在,请使用其他名称");
}
var token = new TokenAggregateRoot(userId, input.Name)
{
ExpireTime = input.ExpireTime,
PremiumQuotaLimit = input.PremiumQuotaLimit
};
await _tokenRepository.InsertAsync(token);
return new TokenGetListOutputDto
{
Id = token.Id,
Name = token.Name,
ApiKey = token.Token,
ExpireTime = token.ExpireTime,
PremiumQuotaLimit = token.PremiumQuotaLimit,
PremiumUsedQuota = 0,
IsDisabled = token.IsDisabled,
CreationTime = token.CreationTime
};
}
/// <summary>
/// 编辑Token
/// </summary>
[HttpPut("token")]
public async Task UpdateAsync([FromBody] TokenUpdateInput input)
{
var userId = CurrentUser.GetId();
var token = await _tokenRepository._DbQueryable
.FirstAsync(x => x.Id == input.Id && x.UserId == userId);
if (token is null)
{
throw new UserFriendlyException("Token不存在或无权限操作");
}
// 检查名称是否重复(排除自己)
var exists = await _tokenRepository._DbQueryable
.AnyAsync(x => x.UserId == userId && x.Name == input.Name && x.Id != input.Id);
if (exists)
{
throw new UserFriendlyException($"名称【{input.Name}】已存在,请使用其他名称");
}
token.Name = input.Name;
token.ExpireTime = input.ExpireTime;
token.PremiumQuotaLimit = input.PremiumQuotaLimit;
await _tokenRepository.UpdateAsync(token);
}
/// <summary>
/// 删除Token
/// </summary>
[HttpDelete("token/{id}")]
public async Task DeleteAsync(Guid id)
{
var userId = CurrentUser.GetId();
var token = await _tokenRepository._DbQueryable
.FirstAsync(x => x.Id == id && x.UserId == userId);
if (token is null)
{
throw new UserFriendlyException("Token不存在或无权限操作");
}
await _tokenRepository.DeleteAsync(token);
}
/// <summary>
/// 启用Token
/// </summary>
[HttpPost("token/{id}/enable")]
public async Task EnableAsync(Guid id)
{
var userId = CurrentUser.GetId();
var token = await _tokenRepository._DbQueryable
.FirstAsync(x => x.Id == id && x.UserId == userId);
if (token is null)
{
throw new UserFriendlyException("Token不存在或无权限操作");
}
token.Enable();
await _tokenRepository.UpdateAsync(token);
}
/// <summary>
/// 禁用Token
/// </summary>
[HttpPost("token/{id}/disable")]
public async Task DisableAsync(Guid id)
{
var userId = CurrentUser.GetId();
var token = await _tokenRepository._DbQueryable
.FirstAsync(x => x.Id == id && x.UserId == userId);
if (token is null)
{
throw new UserFriendlyException("Token不存在或无权限操作");
}
token.Disable();
await _tokenRepository.UpdateAsync(token);
}
}

View File

@@ -28,8 +28,8 @@ public class DailyTaskService : ApplicationService
private readonly Dictionary<int, (long RequiredTokens, long RewardTokens, string Name, string Description)>
_taskConfigs = new()
{
{ 1, (10000000, 2000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 200w奖励
{ 2, (30000000, 4000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 600w奖励
{ 1, (10000000, 1000000, "尊享包1000w token任务", "累积使用尊享包 1000w token") }, // 1000w消耗 -> 100w奖励
{ 2, (30000000, 2000000, "尊享包3000w token任务", "累积使用尊享包 3000w token") } // 3000w消耗 -> 200w奖励
};
public DailyTaskService(

View File

@@ -76,12 +76,12 @@ public class FileMasterService : ApplicationService
if (input.Stream == true)
{
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId, null, cancellationToken);
userId, null, null, cancellationToken);
}
else
{
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
null,
null, null,
cancellationToken);
}
}

View File

@@ -55,7 +55,9 @@ public class OpenApiService : ApplicationService
{
//前面都是校验,后面才是真正的调用
var httpContext = this._httpContextAccessor.HttpContext;
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
var userId = tokenValidation.UserId;
var tokenId = tokenValidation.TokenId;
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
//如果是尊享包服务,需要校验是是否尊享包足够
@@ -68,17 +70,17 @@ public class OpenApiService : ApplicationService
throw new UserFriendlyException("尊享token包用量不足请先购买尊享token包");
}
}
//ai网关代理httpcontext
if (input.Stream == true)
{
await _aiGateWayManager.CompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId, null, cancellationToken);
userId, null, tokenId, cancellationToken);
}
else
{
await _aiGateWayManager.CompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
null,
null, tokenId,
cancellationToken);
}
}
@@ -93,9 +95,11 @@ public class OpenApiService : ApplicationService
{
var httpContext = this._httpContextAccessor.HttpContext;
Intercept(httpContext);
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
var userId = tokenValidation.UserId;
var tokenId = tokenValidation.TokenId;
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
await _aiGateWayManager.CreateImageForStatisticsAsync(httpContext, userId, null, input);
await _aiGateWayManager.CreateImageForStatisticsAsync(httpContext, userId, null, input, tokenId);
}
/// <summary>
@@ -108,9 +112,11 @@ public class OpenApiService : ApplicationService
{
var httpContext = this._httpContextAccessor.HttpContext;
Intercept(httpContext);
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
var userId = tokenValidation.UserId;
var tokenId = tokenValidation.TokenId;
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
await _aiGateWayManager.EmbeddingForStatisticsAsync(httpContext, userId, null, input);
await _aiGateWayManager.EmbeddingForStatisticsAsync(httpContext, userId, null, input, tokenId);
}
@@ -151,7 +157,9 @@ public class OpenApiService : ApplicationService
{
//前面都是校验,后面才是真正的调用
var httpContext = this._httpContextAccessor.HttpContext;
var userId = await _tokenManager.GetUserIdAsync(GetTokenByHttpContext(httpContext));
var tokenValidation = await _tokenManager.ValidateTokenAsync(GetTokenByHttpContext(httpContext), input.Model);
var userId = tokenValidation.UserId;
var tokenId = tokenValidation.TokenId;
await _aiBlacklistManager.VerifiyAiBlacklist(userId);
// 验证用户是否为VIP
@@ -178,12 +186,12 @@ public class OpenApiService : ApplicationService
if (input.Stream)
{
await _aiGateWayManager.AnthropicCompleteChatStreamForStatisticsAsync(_httpContextAccessor.HttpContext, input,
userId, null, cancellationToken);
userId, null, tokenId, cancellationToken);
}
else
{
await _aiGateWayManager.AnthropicCompleteChatForStatisticsAsync(_httpContextAccessor.HttpContext, input, userId,
null,
null, tokenId,
cancellationToken);
}
}

View File

@@ -1,55 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Services;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Token;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Managers;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
public class TokenService : ApplicationService
{
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly TokenManager _tokenManager;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="tokenRepository"></param>
/// <param name="tokenManager"></param>
public TokenService(ISqlSugarRepository<TokenAggregateRoot> tokenRepository, TokenManager tokenManager)
{
_tokenRepository = tokenRepository;
_tokenManager = tokenManager;
}
/// <summary>
/// 获取token
/// </summary>
/// <returns></returns>
[Authorize]
public async Task<TokenOutput> GetAsync()
{
return new TokenOutput
{
ApiKey = await _tokenManager.GetAsync(CurrentUser.GetId())
};
}
/// <summary>
/// 创建token
/// </summary>
/// <exception cref="UserFriendlyException"></exception>
[Authorize]
public async Task CreateAsync()
{
if (!CurrentUser.IsAiVip())
{
throw new UserFriendlyException("充值成为Vip畅享第三方token服务");
}
await _tokenManager.CreateAsync(CurrentUser.GetId());
}
}

View File

@@ -1,12 +1,18 @@
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.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.OpenApi;
using Yi.Framework.AiHub.Domain.Extensions;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.Ddd.Application.Contracts;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Application.Services;
@@ -20,22 +26,25 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
private readonly ISqlSugarRepository<MessageAggregateRoot> _messageRepository;
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
private readonly ISqlSugarRepository<PremiumPackageAggregateRoot> _premiumPackageRepository;
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
public UsageStatisticsService(
ISqlSugarRepository<MessageAggregateRoot> messageRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository,
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository)
ISqlSugarRepository<PremiumPackageAggregateRoot> premiumPackageRepository,
ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
{
_messageRepository = messageRepository;
_usageStatisticsRepository = usageStatisticsRepository;
_premiumPackageRepository = premiumPackageRepository;
_tokenRepository = tokenRepository;
}
/// <summary>
/// 获取当前用户近7天的Token消耗统计
/// </summary>
/// <returns>每日Token使用量列表</returns>
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync()
public async Task<List<DailyTokenUsageDto>> GetLast7DaysTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
var endDate = DateTime.Today;
@@ -46,6 +55,7 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
.Where(x => x.UserId == userId)
.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)
.GroupBy(x => x.CreationTime.Date)
.Select(g => new
{
@@ -75,17 +85,19 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
/// 获取当前用户各个模型的Token消耗量及占比
/// </summary>
/// <returns>模型Token使用量列表</returns>
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync()
public async Task<List<ModelTokenUsageDto>> GetModelTokenUsageAsync([FromQuery]UsageStatisticsGetInput input)
{
var userId = CurrentUser.GetId();
// 从UsageStatistics表获取各模型的token消耗统计
// 从UsageStatistics表获取各模型的token消耗统计按ModelId聚合因为同一模型可能有多个TokenId的记录
var modelUsages = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.TokenId.HasValue,x => x.TokenId == input.TokenId)
.GroupBy(x => x.ModelId)
.Select(x => new
{
x.ModelId,
x.TotalTokenCount
ModelId = x.ModelId,
TotalTokenCount = SqlFunc.AggregateSum(x.TotalTokenCount)
})
.ToListAsync();
@@ -125,9 +137,9 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
if (premiumPackages.Any())
{
// 过滤掉已过期的包
// 过滤掉已过期、禁用的包,不过滤用量负数的包
var validPackages = premiumPackages
.Where(p => p.IsAvailable())
.Where(p => p.IsAvailable(false))
.ToList();
result.PremiumTotalTokens = validPackages.Sum(x => x.TotalTokens);
@@ -137,4 +149,77 @@ public class UsageStatisticsService : ApplicationService, IUsageStatisticsServic
return result;
}
/// <summary>
/// 获取当前用户尊享服务token用量统计列表
/// </summary>
/// <returns></returns>
[HttpGet("usage-statistics/premium-token-usage/list")]
public async Task<PagedResultDto<PremiumTokenUsageGetListOutput>> GetPremiumTokenUsageListAsync(
PremiumTokenUsageGetListInput input)
{
var userId = CurrentUser.GetId();
RefAsync<int> total = 0;
// 获取尊享包Token信息
var entities = await _premiumPackageRepository._DbQueryable
.Where(x => x.UserId == userId)
.WhereIF(input.IsFree == false, x => x.PurchaseAmount > 0)
.WhereIF(input.IsFree == true, x => x.PurchaseAmount == 0)
.WhereIF(input.StartTime is not null && input.EndTime is not null,
x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderByDescending(x => x.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
return new PagedResultDto<PremiumTokenUsageGetListOutput>(total,
entities.Adapt<List<PremiumTokenUsageGetListOutput>>());
}
/// <summary>
/// 获取当前用户尊享包不同Token用量占比饼图
/// </summary>
/// <returns>各Token的尊享模型用量及占比</returns>
[HttpGet("usage-statistics/premium-token-usage/by-token")]
public async Task<List<TokenPremiumUsageDto>> GetPremiumTokenUsageByTokenAsync()
{
var userId = CurrentUser.GetId();
var premiumModelIds = PremiumPackageConst.ModeIds;
// 从UsageStatistics表获取尊享模型的token消耗统计按TokenId聚合
var tokenUsages = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId && premiumModelIds.Contains(x.ModelId))
.GroupBy(x => x.TokenId)
.Select(x => new
{
TokenId = x.TokenId,
TotalTokenCount = SqlFunc.AggregateSum(x.TotalTokenCount)
})
.ToListAsync();
if (!tokenUsages.Any())
{
return new List<TokenPremiumUsageDto>();
}
// 获取用户的所有Token信息用于名称映射
var tokenIds = tokenUsages.Select(x => x.TokenId).ToList();
var tokens = await _tokenRepository._DbQueryable
.Where(x => x.UserId == userId && tokenIds.Contains(x.Id))
.Select(x => new { x.Id, x.Name })
.ToListAsync();
var tokenNameDict = tokens.ToDictionary(x => x.Id, x => x.Name);
// 计算总token数
var totalTokens = tokenUsages.Sum(x => x.TotalTokenCount);
// 计算各Token占比
var result = tokenUsages.Select(x => new TokenPremiumUsageDto
{
TokenId = x.TokenId,
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;
}
}

View File

@@ -4,5 +4,12 @@ namespace Yi.Framework.AiHub.Domain.Shared.Consts;
public class PremiumPackageConst
{
public static List<string> ModeIds = ["claude-sonnet-4-5-20250929"];
public static List<string> ModeIds =
[
"claude-sonnet-4-5-20250929",
"claude-haiku-4-5-20251001",
"claude-opus-4-5-20251101",
"gemini-3-pro-preview",
"gpt-5.1-codex-max"
];
}

View File

@@ -56,4 +56,9 @@ public class AiModelDescribe
/// 模型额外信息
/// </summary>
public string? ModelExtraInfo { get; set; }
/// <summary>
/// 模型倍率
/// </summary>
public decimal Multiplier { get; set; }
}

View File

@@ -34,7 +34,7 @@ public class AnthropicStreamDto
};
public void SupplementalMultiplier(double multiplier)
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
@@ -130,7 +130,7 @@ public class AnthropicChatCompletionDto
CompletionTokensDetails = null
};
public void SupplementalMultiplier(double multiplier)
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{

View File

@@ -109,8 +109,15 @@ public sealed class AnthropicInput
public class AnthropicThinkingInput
{
[JsonPropertyName("type")] public string? Type { get; set; }
[JsonPropertyName("budget_tokens")] public int? BudgetTokens { get; set; }
[JsonPropertyName("signature")] public string? Signature { get; set; }
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
[JsonPropertyName("data")] public string? Data { get; set; }
[JsonPropertyName("text")] public string? Text { get; set; }
}
public class AnthropicTooChoiceInput

View File

@@ -20,6 +20,8 @@ public class AnthropicMessageContent
[JsonPropertyName("thinking")] public string? Thinking { get; set; }
[JsonPropertyName("signature")] public string? Signature { get; set; }
[JsonPropertyName("input")] public object? Input { get; set; }
[JsonPropertyName("content")]

View File

@@ -22,11 +22,15 @@ public class AnthropicMessageInput
throw new ValidationException("Messages 中 Content 和 Contents 字段不能同时有值");
}
if (Content is not null)
if (!string.IsNullOrEmpty(Content))
{
return Content;
}
// 如果 Contents 为空或 null返回空字符串而不是 null
if (Contents == null || Contents.Count == 0)
{
return "_"; // 兼容客户端空值问题
}
return Contents!;
}
set

View File

@@ -61,7 +61,7 @@ public record ThorChatCompletionsResponse
[JsonPropertyName("error")]
public ThorError? Error { get; set; }
public void SupplementalMultiplier(double multiplier)
public void SupplementalMultiplier(decimal multiplier)
{
if (this.Usage is not null)
{
@@ -73,6 +73,9 @@ public record ThorChatCompletionsResponse
(int)Math.Round((this.Usage.CompletionTokens ?? 0) * multiplier);
this.Usage.PromptTokens =
(int)Math.Round((this.Usage.PromptTokens ?? 0) * multiplier);
this.Usage.TotalTokens =
(int)Math.Round((this.Usage.TotalTokens ?? 0) * multiplier);
}
}
}

View File

@@ -0,0 +1,7 @@
namespace Yi.Framework.AiHub.Domain.Shared.Enums;
public enum AnnouncementTypeEnum
{
Activity=1,
System=2
}

View File

@@ -102,11 +102,6 @@ public enum GoodsTypeEnum
[Price(155.4, 6, 25.9)] [DisplayName("YiXinVip 6 month", "6个月", "年度热销")] [GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip6 = 6,
[Price(183.2, 8, 22.9)]
[DisplayName("YiXinVip 8 month", "8个月推荐", "限时活动,超高性价比")]
[GoodsCategory(GoodsCategoryType.Vip)]
YiXinVip8 = 8,
// 尊享包服务 - 需要VIP资格才能购买
[Price(188.9, 0, 1750)]
[DisplayName("YiXinPremiumPackage 5000W Tokens", "5000万Tokens", "简单尝试")]

View File

@@ -14,8 +14,6 @@ public class AnthropicChatCompletionsService(
ILogger<AnthropicChatCompletionsService> logger)
: IAnthropicChatCompletionService
{
public const double ClaudeMultiplier = 1.3d;
public async Task<AnthropicChatCompletionDto> ChatCompletionsAsync(AiModelDescribe options, AnthropicInput input,
CancellationToken cancellationToken = default)
{
@@ -86,8 +84,7 @@ public class AnthropicChatCompletionsService(
var value =
await response.Content.ReadFromJsonAsync<AnthropicChatCompletionDto>(ThorJsonSerializer.DefaultOptions,
cancellationToken: cancellationToken);
value.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
return value;
}
@@ -169,8 +166,7 @@ public class AnthropicChatCompletionsService(
var result = JsonSerializer.Deserialize<AnthropicStreamDto>(data,
ThorJsonSerializer.DefaultOptions);
result.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
yield return (eventType, result);
}
}

View File

@@ -345,7 +345,7 @@ public sealed class ClaudiaChatCompletionsService(
var response = await client.HttpRequestRaw(options.Endpoint.TrimEnd('/') + "/v1/messages", new
{
model = input.Model,
max_tokens = input.MaxTokens ?? 2048,
max_tokens = input.MaxTokens ?? 64000,
stream = true,
tool_choice,
system = CreateMessage(input.Messages.Where(x => x.Role == "system").ToList(), options),
@@ -716,7 +716,7 @@ public sealed class ClaudiaChatCompletionsService(
output.Usage.PromptTokens = output.Usage.InputTokens;
output.Usage.CompletionTokens = output.Usage.OutputTokens;
output.Usage.TotalTokens = output.Usage.InputTokens + output.Usage.OutputTokens;
output.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
yield return output;
}
}
@@ -873,7 +873,6 @@ public sealed class ClaudiaChatCompletionsService(
}
thor.Usage.TotalTokens = thor.Usage.InputTokens + thor.Usage.OutputTokens;
thor.SupplementalMultiplier(AnthropicChatCompletionsService.ClaudeMultiplier);
return thor;
}
}

View File

@@ -0,0 +1,57 @@
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_Announcement")]
public class AnnouncementAggregateRoot : FullAuditedAggregateRoot<Guid>
{
public AnnouncementAggregateRoot()
{
}
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// 内容列表JSON格式存储
/// </summary>
[SugarColumn(IsJson = true, IsNullable = false)]
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; }
}

View File

@@ -25,9 +25,8 @@ public class CardFlipTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
BonusFlipsUsed = 0;
InviteFlipsUsed = 0;
IsFirstFlipDone = false;
HasNinthReward = false;
HasTenthReward = false;
FlippedOrder = new List<int>();
WinRecords = new Dictionary<int, long>();
}
/// <summary>
@@ -66,34 +65,10 @@ public class CardFlipTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
public bool IsFirstFlipDone { get; set; }
/// <summary>
/// 是否已获得第8次奖励
/// 中奖记录以翻牌顺序为key例如第1次翻牌中奖则key为1奖励金额为value
/// </summary>
public bool HasEighthReward { get; set; }
/// <summary>
/// 第8次奖励金额100-300w
/// </summary>
public long? EighthRewardAmount { get; set; }
/// <summary>
/// 是否已获得第9次奖励
/// </summary>
public bool HasNinthReward { get; set; }
/// <summary>
/// 第9次奖励金额100-500w
/// </summary>
public long? NinthRewardAmount { get; set; }
/// <summary>
/// 是否已获得第10次奖励
/// </summary>
public bool HasTenthReward { get; set; }
/// <summary>
/// 第10次奖励金额100-1000w
/// </summary>
public long? TenthRewardAmount { get; set; }
[SugarColumn(IsJson = true, IsNullable = true)]
public Dictionary<int, long>? WinRecords { get; set; }
/// <summary>
/// 备注信息
@@ -135,33 +110,17 @@ public class CardFlipTaskAggregateRoot : FullAuditedAggregateRoot<Guid>
}
/// <summary>
/// 记录第8次奖励
/// 记录中奖
/// </summary>
/// <param name="flipCount">第几次翻牌1-10</param>
/// <param name="amount">奖励金额</param>
public void SetEighthReward(long amount)
public void SetWinReward(int flipCount, long amount)
{
HasEighthReward = true;
EighthRewardAmount = amount;
}
/// <summary>
/// 记录第9次奖励
/// </summary>
/// <param name="amount">奖励金额</param>
public void SetNinthReward(long amount)
{
HasNinthReward = true;
NinthRewardAmount = amount;
}
/// <summary>
/// 记录第10次奖励
/// </summary>
/// <param name="amount">奖励金额</param>
public void SetTenthReward(long amount)
{
HasTenthReward = true;
TenthRewardAmount = amount;
if (WinRecords == null)
{
WinRecords = new Dictionary<int, long>();
}
WinRecords[flipCount] = amount;
}
}

View File

@@ -20,10 +20,11 @@ public class MessageAggregateRoot : FullAuditedAggregateRoot<Guid>
}
public MessageAggregateRoot(Guid? userId, Guid? sessionId, string content, string role, string modelId,
ThorUsageResponse? tokenUsage)
ThorUsageResponse? tokenUsage, Guid? tokenId = null)
{
UserId = userId;
SessionId = sessionId;
TokenId = tokenId ?? Guid.Empty;
//如果没有会话,不存储对话内容
Content = sessionId is null ? null : content;
Role = role;
@@ -59,6 +60,11 @@ public class MessageAggregateRoot : FullAuditedAggregateRoot<Guid>
public Guid? UserId { get; set; }
public Guid? SessionId { get; set; }
/// <summary>
/// Token密钥Id通过API调用时记录Web调用为Guid.Empty
/// </summary>
public Guid TokenId { get; set; }
[SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
public string? Content { get; set; }

View File

@@ -19,8 +19,6 @@ public class InviteCodeAggregateRoot : FullAuditedAggregateRoot<Guid>
{
UserId = userId;
Code = code;
IsUsed = false;
IsUserInvited = false;
UsedCount = 0;
}
@@ -34,55 +32,16 @@ public class InviteCodeAggregateRoot : FullAuditedAggregateRoot<Guid>
/// </summary>
[SugarColumn(Length = 50)]
public string Code { get; set; } = string.Empty;
/// <summary>
/// 是否已被使用(一个邀请码只能被使用一次
/// </summary>
public bool IsUsed { get; set; }
/// <summary>
/// 邀请码拥有者是否已被他人邀请(被邀请后不可再提供邀请码)
/// </summary>
public bool IsUserInvited { get; set; }
/// <summary>
/// 被使用次数(统计用)
/// 被使用次数(统计用,一个邀请码可以被多人使用
/// </summary>
public int UsedCount { get; set; }
/// <summary>
/// 使用时间
/// </summary>
public DateTime? UsedTime { get; set; }
/// <summary>
/// 使用人ID
/// </summary>
public Guid? UsedByUserId { get; set; }
/// <summary>
/// 备注信息
/// </summary>
[SugarColumn(Length = 500, IsNullable = true)]
public string? Remark { get; set; }
/// <summary>
/// 标记邀请码已被使用
/// </summary>
/// <param name="usedByUserId">使用者ID</param>
public void MarkAsUsed(Guid usedByUserId)
{
IsUsed = true;
UsedTime = DateTime.Now;
UsedByUserId = usedByUserId;
UsedCount++;
}
/// <summary>
/// 标记用户已被邀请
/// </summary>
public void MarkUserAsInvited()
{
IsUserInvited = true;
}
}

View File

@@ -60,4 +60,9 @@ public class AiModelEntity : Entity<Guid>, IOrderNum, ISoftDelete
/// 模型Api类型现支持同一个模型id多种接口格式
/// </summary>
public ModelApiTypeEnum ModelApiType { get; set; }
/// <summary>
/// 模型倍率
/// </summary>
public decimal Multiplier { get; set; } = 1;
}

View File

@@ -5,27 +5,84 @@ using Volo.Abp.Domain.Entities.Auditing;
namespace Yi.Framework.AiHub.Domain.Entities.OpenApi;
[SugarTable("Ai_Token")]
[SugarIndex($"index_{{table}}_{nameof(UserId)}", nameof(UserId), OrderByType.Asc)]
public class TokenAggregateRoot : FullAuditedAggregateRoot<Guid>
{
public TokenAggregateRoot()
{
}
public TokenAggregateRoot(Guid userId)
public TokenAggregateRoot(Guid userId, string name)
{
this.UserId = userId;
this.Token = GenerateToken();
UserId = userId;
Name = name;
Token = GenerateToken();
IsDisabled = false;
}
/// <summary>
/// Token密钥
/// </summary>
public string Token { get; set; }
/// <summary>
/// 用户Id
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// 重置token
/// 名称
/// </summary>
public void ResetToken()
[SugarColumn(Length = 100)]
public string Name { get; set; }
/// <summary>
/// 过期时间(空为永不过期)
/// </summary>
public DateTime? ExpireTime { get; set; }
/// <summary>
/// 尊享包额度限制(空为不限制)
/// </summary>
public long? PremiumQuotaLimit { get; set; }
/// <summary>
/// 是否禁用
/// </summary>
public bool IsDisabled { get; set; }
/// <summary>
/// 检查Token是否可用
/// </summary>
public bool IsAvailable()
{
this.Token = GenerateToken();
if (IsDisabled)
{
return false;
}
if (ExpireTime.HasValue && ExpireTime.Value < DateTime.Now)
{
return false;
}
return true;
}
/// <summary>
/// 禁用Token
/// </summary>
public void Disable()
{
IsDisabled = true;
}
/// <summary>
/// 启用Token
/// </summary>
public void Enable()
{
IsDisabled = false;
}
private string GenerateToken(int length = 36)

View File

@@ -86,14 +86,14 @@ public class PremiumPackageAggregateRoot : FullAuditedAggregateRoot<Guid>
/// 检查是否可用
/// </summary>
/// <returns>是否可用</returns>
public bool IsAvailable()
public bool IsAvailable(bool isVerifyRemainingToken=true)
{
if (!IsActive)
{
return false;
}
if (RemainingTokens <= 0)
if (isVerifyRemainingToken&&RemainingTokens <= 0)
{
return false;
}

View File

@@ -7,16 +7,22 @@ namespace Yi.Framework.AiHub.Domain.Entities;
/// 用量统计
/// </summary>
[SugarTable("Ai_UsageStatistics")]
[SugarIndex($"index_{{table}}_{nameof(UserId)}_{nameof(ModelId)}_{nameof(TokenId)}",
nameof(UserId), OrderByType.Asc,
nameof(ModelId), OrderByType.Asc,
nameof(TokenId), OrderByType.Asc
)]
public class UsageStatisticsAggregateRoot : FullAuditedAggregateRoot<Guid>
{
public UsageStatisticsAggregateRoot()
{
}
public UsageStatisticsAggregateRoot(Guid? userId, string modelId)
public UsageStatisticsAggregateRoot(Guid? userId, string modelId, Guid tokenId)
{
UserId = userId;
ModelId = modelId;
TokenId = tokenId;
}
/// <summary>
@@ -29,6 +35,11 @@ public class UsageStatisticsAggregateRoot : FullAuditedAggregateRoot<Guid>
/// </summary>
public string ModelId { get; set; }
/// <summary>
/// Token密钥Id通过API调用时记录Web调用为Guid.Empty
/// </summary>
public Guid TokenId { get; set; }
/// <summary>
/// 对话次数
/// </summary>

View File

@@ -77,7 +77,8 @@ public class AiGateWayManager : DomainService
ModelName = model.Name,
Description = model.Description,
AppExtraUrl = app.ExtraUrl,
ModelExtraInfo = model.ExtraInfo
ModelExtraInfo = model.ExtraInfo,
Multiplier = model.Multiplier
})
.FirstAsync();
if (aiModelDescribe is null)
@@ -106,6 +107,7 @@ public class AiGateWayManager : DomainService
await foreach (var result in chatService.CompleteChatStreamAsync(modelDescribe, request, cancellationToken))
{
result.SupplementalMultiplier(modelDescribe.Multiplier);
yield return result;
}
}
@@ -118,12 +120,14 @@ public class AiGateWayManager : DomainService
/// <param name="request"></param>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task CompleteChatForStatisticsAsync(HttpContext httpContext,
ThorChatCompletionsRequest request,
Guid? userId = null,
Guid? sessionId = null,
Guid? tokenId = null,
CancellationToken cancellationToken = default)
{
_specialCompatible.Compatible(request);
@@ -134,6 +138,7 @@ public class AiGateWayManager : DomainService
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IChatCompletionService>(modelDescribe.HandlerName);
var data = await chatService.CompleteChatAsync(modelDescribe, request, cancellationToken);
data.SupplementalMultiplier(modelDescribe.Multiplier);
if (userId is not null)
{
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
@@ -142,7 +147,7 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault().Content ?? string.Empty,
ModelId = request.Model,
TokenUsage = data.Usage,
});
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
new MessageInputDto
@@ -151,9 +156,19 @@ public class AiGateWayManager : DomainService
sessionId is null ? "不予存储" : data.Choices?.FirstOrDefault()?.Delta.Content ?? string.Empty,
ModelId = request.Model,
TokenUsage = data.Usage
});
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.Usage, tokenId);
// 扣减尊享token包用量
if (PremiumPackageConst.ModeIds.Contains(request.Model))
{
var totalTokens = data.Usage?.TotalTokens ?? 0;
if (totalTokens > 0)
{
await PremiumPackageManager.TryConsumeTokensAsync(userId.Value, totalTokens);
}
}
}
await response.WriteAsJsonAsync(data, cancellationToken);
@@ -166,6 +181,7 @@ public class AiGateWayManager : DomainService
/// <param name="request"></param>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task CompleteChatStreamForStatisticsAsync(
@@ -173,6 +189,7 @@ public class AiGateWayManager : DomainService
ThorChatCompletionsRequest request,
Guid? userId = null,
Guid? sessionId = null,
Guid? tokenId = null,
CancellationToken cancellationToken = default)
{
var response = httpContext.Response;
@@ -225,7 +242,7 @@ public class AiGateWayManager : DomainService
{
await foreach (var data in completeChatResponse)
{
if (data.Usage is not null&&(data.Usage.CompletionTokens>0||data.Usage.OutputTokens>0))
if (data.Usage is not null && (data.Usage.CompletionTokens > 0 || data.Usage.OutputTokens > 0))
{
tokenUsage = data.Usage;
}
@@ -275,7 +292,7 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty,
ModelId = request.Model,
TokenUsage = tokenUsage,
});
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
new MessageInputDto
@@ -283,9 +300,9 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : backupSystemContent.ToString(),
ModelId = request.Model,
TokenUsage = tokenUsage
});
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
// 扣减尊享token包用量
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
@@ -306,10 +323,11 @@ public class AiGateWayManager : DomainService
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="request"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <exception cref="BusinessException"></exception>
/// <exception cref="Exception"></exception>
public async Task CreateImageForStatisticsAsync(HttpContext context, Guid? userId, Guid? sessionId,
ImageCreateRequest request)
ImageCreateRequest request, Guid? tokenId = null)
{
try
{
@@ -337,7 +355,7 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : request.Prompt,
ModelId = model,
TokenUsage = response.Usage,
});
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
new MessageInputDto
@@ -345,9 +363,9 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : response.Results?.FirstOrDefault()?.Url,
ModelId = model,
TokenUsage = response.Usage
});
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage);
await _usageStatisticsManager.SetUsageAsync(userId, model, response.Usage, tokenId);
// 扣减尊享token包用量
if (userId is not null && PremiumPackageConst.ModeIds.Contains(request.Model))
@@ -371,13 +389,14 @@ public class AiGateWayManager : DomainService
/// 向量生成
/// </summary>
/// <param name="context"></param>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="input"></param>
/// <param name="userId"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <exception cref="Exception"></exception>
/// <exception cref="BusinessException"></exception>
public async Task EmbeddingForStatisticsAsync(HttpContext context, Guid? userId, Guid? sessionId,
ThorEmbeddingInput input)
ThorEmbeddingInput input, Guid? tokenId = null)
{
try
{
@@ -461,7 +480,7 @@ public class AiGateWayManager : DomainService
// TokenUsage = usage
// });
await _usageStatisticsManager.SetUsageAsync(userId, input.Model, usage);
await _usageStatisticsManager.SetUsageAsync(userId, input.Model, usage, tokenId);
}
catch (ThorRateLimitException)
{
@@ -496,6 +515,7 @@ public class AiGateWayManager : DomainService
await foreach (var result in chatService.StreamChatCompletionsAsync(modelDescribe, request, cancellationToken))
{
result.Item2.SupplementalMultiplier(modelDescribe.Multiplier);
yield return result;
}
}
@@ -508,12 +528,14 @@ public class AiGateWayManager : DomainService
/// <param name="request"></param>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task AnthropicCompleteChatForStatisticsAsync(HttpContext httpContext,
AnthropicInput request,
Guid? userId = null,
Guid? sessionId = null,
Guid? tokenId = null,
CancellationToken cancellationToken = default)
{
_specialCompatible.AnthropicCompatible(request);
@@ -524,6 +546,9 @@ public class AiGateWayManager : DomainService
var chatService =
LazyServiceProvider.GetRequiredKeyedService<IAnthropicChatCompletionService>(modelDescribe.HandlerName);
var data = await chatService.ChatCompletionsAsync(modelDescribe, request, cancellationToken);
data.SupplementalMultiplier(modelDescribe.Multiplier);
if (userId is not null)
{
await _aiMessageManager.CreateUserMessageAsync(userId.Value, sessionId,
@@ -532,7 +557,7 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : request.Messages?.FirstOrDefault()?.Content ?? string.Empty,
ModelId = request.Model,
TokenUsage = data.TokenUsage,
});
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId.Value, sessionId,
new MessageInputDto
@@ -540,9 +565,9 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : data.content?.FirstOrDefault()?.text,
ModelId = request.Model,
TokenUsage = data.TokenUsage
});
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.TokenUsage);
await _usageStatisticsManager.SetUsageAsync(userId.Value, request.Model, data.TokenUsage, tokenId);
// 扣减尊享token包用量
var totalTokens = data.TokenUsage.TotalTokens ?? 0;
@@ -562,6 +587,7 @@ public class AiGateWayManager : DomainService
/// <param name="request"></param>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <param name="tokenId">Token IdWeb端传null或Guid.Empty</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task AnthropicCompleteChatStreamForStatisticsAsync(
@@ -569,6 +595,7 @@ public class AiGateWayManager : DomainService
AnthropicInput request,
Guid? userId = null,
Guid? sessionId = null,
Guid? tokenId = null,
CancellationToken cancellationToken = default)
{
var response = httpContext.Response;
@@ -610,7 +637,7 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : request.Messages?.LastOrDefault()?.Content ?? string.Empty,
ModelId = request.Model,
TokenUsage = tokenUsage,
});
}, tokenId);
await _aiMessageManager.CreateSystemMessageAsync(userId, sessionId,
new MessageInputDto
@@ -618,9 +645,9 @@ public class AiGateWayManager : DomainService
Content = sessionId is null ? "不予存储" : backupSystemContent.ToString(),
ModelId = request.Model,
TokenUsage = tokenUsage
});
}, tokenId);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage);
await _usageStatisticsManager.SetUsageAsync(userId, request.Model, tokenUsage, tokenId);
// 扣减尊享token包用量
if (userId.HasValue && tokenUsage is not null)

View File

@@ -19,28 +19,30 @@ public class AiMessageManager : DomainService
/// <summary>
/// 创建系统消息
/// </summary>
/// <param name="sessionId"></param>
/// <param name="userId"></param>
/// <param name="input"></param>
/// <param name="userId">用户Id</param>
/// <param name="sessionId">会话Id</param>
/// <param name="input">消息输入</param>
/// <param name="tokenId">Token IdWeb端传Guid.Empty</param>
/// <returns></returns>
public async Task CreateSystemMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input)
public async Task CreateSystemMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null)
{
input.Role = "system";
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId,input.TokenUsage);
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId);
await _repository.InsertAsync(message);
}
/// <summary>
/// 创建系统消息
/// 创建用户消息
/// </summary>
/// <param name="sessionId"></param>
/// <param name="userId"></param>
/// <param name="input"></param>
/// <param name="userId">用户Id</param>
/// <param name="sessionId">会话Id</param>
/// <param name="input">消息输入</param>
/// <param name="tokenId">Token IdWeb端传Guid.Empty</param>
/// <returns></returns>
public async Task CreateUserMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input)
public async Task CreateUserMessageAsync(Guid? userId, Guid? sessionId, MessageInputDto input, Guid? tokenId = null)
{
input.Role = "user";
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId,input.TokenUsage);
var message = new MessageAggregateRoot(userId, sessionId, input.Content, input.Role, input.ModelId, input.TokenUsage, tokenId);
await _repository.InsertAsync(message);
}
}

View File

@@ -24,6 +24,11 @@ public class CardFlipManager : DomainService
private const int NINTH_FLIP = 9; // 第9次翻牌
private const int TENTH_FLIP = 10; // 第10次翻牌
// 前7次免费翻牌奖励配置
private const long FREE_MIN_REWARD = 10000; // 前7次最小奖励 1w
private const long FREE_MAX_REWARD = 30000; // 前7次最大奖励 3w
private const double FREE_WIN_RATE = 0.5; // 前7次中奖概率 50%
private const long EIGHTH_MIN_REWARD = 1000000; // 第8次最小奖励 100w
private const long EIGHTH_MAX_REWARD = 3000000; // 第8次最大奖励 300w
private const long NINTH_MIN_REWARD = 1000000; // 第9次最小奖励 100w
@@ -112,23 +117,23 @@ public class CardFlipManager : DomainService
throw new UserFriendlyException(GetFlipTypeErrorMessage(flipType));
}
// 如果是邀请类型翻牌,必须验证用户本周填写的邀请数量足够
// 如果是邀请类型翻牌,必须验证用户本周的邀请记录数量足够(包括填写别人的邀请码和别人填写我的邀请码)
if (flipType == FlipType.Invite)
{
// 查询本周已使用的邀请码数量
var weeklyInviteCodeUsedCount = await _invitationRecordRepository._DbQueryable
.Where(x => x.InvitedUserId == userId)
// 查询本周作为邀请人或被邀请人的记录数量(双方都会增加翻牌次数)
var weeklyInviteRecordCount = await _invitationRecordRepository._DbQueryable
.Where(x => x.InviterId == userId || x.InvitedUserId == userId)
.Where(x => x.InvitationTime >= weekStart)
.CountAsync();
// 本周填写的邀请码数量必须 >= 即将使用的邀请翻牌次数
// 例如: 要翻第8次(InviteFlipsUsed=0->1), 需要至少填写了1个邀请码
// 要翻第9次(InviteFlipsUsed=1->2), 需要至少填写了2个邀请码
// 要翻第10次(InviteFlipsUsed=2->3), 需要至少填写了3个邀请码
var requiredInviteCodeCount = task.InviteFlipsUsed + 1;
if (weeklyInviteCodeUsedCount < requiredInviteCodeCount)
// 本周邀请记录数量必须 >= 即将使用的邀请翻牌次数
// 例如: 要翻第8次(InviteFlipsUsed=0->1), 需要至少有1条邀请记录我邀请别人或别人邀请我
// 要翻第9次(InviteFlipsUsed=1->2), 需要至少有2条邀请记录
// 要翻第10次(InviteFlipsUsed=2->3), 需要至少有3条邀请记录
var requiredInviteRecordCount = task.InviteFlipsUsed + 1;
if (weeklyInviteRecordCount < requiredInviteRecordCount)
{
throw new UserFriendlyException($"需本周累积使用{requiredInviteCodeCount}个他人邀请码才能解锁第{task.TotalFlips + 1}次翻牌,您还差一个~");
throw new UserFriendlyException($"需本周累积{requiredInviteRecordCount}次邀请记录(填写别人的邀请码或别人填写你的邀请码)才能解锁第{task.TotalFlips + 1}次翻牌");
}
}
@@ -152,18 +157,7 @@ public class CardFlipManager : DomainService
// 如果中奖,记录奖励金额(用于后续查询显示)
if (result.IsWin)
{
if (flipCount == EIGHTH_FLIP)
{
task.SetEighthReward(result.RewardAmount);
}
else if (flipCount == NINTH_FLIP)
{
task.SetNinthReward(result.RewardAmount);
}
else if (flipCount == TENTH_FLIP)
{
task.SetTenthReward(result.RewardAmount);
}
task.SetWinReward(flipCount, result.RewardAmount);
}
await _cardFlipTaskRepository.UpdateAsync(task);
@@ -223,11 +217,24 @@ public class CardFlipManager : DomainService
IsWin = false
};
// 前7次固定失败
var random = new Random();
// 前7次: 50%概率中奖奖励1w-3w
if (flipCount <= 7)
{
result.IsWin = false;
result.RewardDesc = "很遗憾,未中奖";
// 50%概率中奖
if (random.NextDouble() < FREE_WIN_RATE)
{
var rewardAmount = GenerateRandomReward(FREE_MIN_REWARD, FREE_MAX_REWARD);
result.IsWin = true;
result.RewardAmount = rewardAmount;
result.RewardDesc = $"恭喜获得尊享包 {rewardAmount / 10000m:0.##}w tokens!";
}
else
{
result.IsWin = false;
result.RewardDesc = "很遗憾,未中奖";
}
}
// 第8次中奖 (邀请码解锁)
else if (flipCount == EIGHTH_FLIP)
@@ -271,21 +278,24 @@ public class CardFlipManager : DomainService
}
/// <summary>
/// 生成随机奖励金额 (最小单位100w)
/// 生成随机奖励金额
/// </summary>
private long GenerateRandomReward(long min, long max)
{
var random = new Random();
const long unit = 1000000; // 100w的单位
// 将min和max转换为100w的倍数
// 根据最小值判断单位
// 如果min小于100000则使用1w(10000)作为单位否则使用100w(1000000)作为单位
long unit = min < 100000 ? 10000 : 1000000;
// 将min和max转换为单位的倍数
long minUnits = min / unit;
long maxUnits = max / unit;
// 在倍数范围内随机
long randomUnits = random.Next((int)minUnits, (int)maxUnits + 1);
// 返回100w的倍数
// 返回单位的倍数
return randomUnits * unit;
}

View File

@@ -63,14 +63,19 @@ public class InviteCodeManager : DomainService
}
/// <summary>
/// 统计用户本周邀请人数
/// 统计用户本周邀请人数(别人填写我的邀请码的次数/或者我填写别人邀请码)
/// </summary>
public async Task<int> GetWeeklyInvitationCountAsync(Guid userId, DateTime weekStart)
{
return await _invitationRecordRepository._DbQueryable
var inviterCount= await _invitationRecordRepository._DbQueryable
.Where(x => x.InviterId == userId)
.Where(x => x.InvitationTime >= weekStart)
.CountAsync();
var invitedUserIdCount= await _invitationRecordRepository._DbQueryable
.Where(x => x.InvitedUserId == userId)
.Where(x => x.InvitationTime >= weekStart)
.CountAsync();
return inviterCount + invitedUserIdCount;
}
/// <summary>
@@ -91,7 +96,7 @@ public class InviteCodeManager : DomainService
}
/// <summary>
/// 使用邀请码
/// 使用邀请码(双方都增加翻牌次数)
/// </summary>
/// <param name="userId">使用者ID</param>
/// <param name="inviteCode">邀请码</param>
@@ -118,75 +123,40 @@ public class InviteCodeManager : DomainService
{
throw new UserFriendlyException("不能使用自己的邀请码");
}
// 检查当前用户是否已经填写过别人的邀请码(一辈子只能填写一次)
var hasUsedOthersCode = await IsFilledInviteCodeAsync(userId);
// 验证邀请码是否已被使用
if (inviteCodeEntity.IsUsed)
if (hasUsedOthersCode)
{
throw new UserFriendlyException("该邀请码已被使用");
throw new UserFriendlyException("您已经填写过别人的邀请码了,每个账号只能填写一次");
}
// 验证邀请码拥有者是否已被邀请
if (inviteCodeEntity.IsUserInvited)
{
throw new UserFriendlyException("该用户已被邀请,邀请码无效");
}
// 验证本周邀请码使用次数
var weekStart = CardFlipManager.GetWeekStartDate(DateTime.Now);
var weeklyUseCount = await _invitationRecordRepository._DbQueryable
.Where(x => x.InvitedUserId == userId)
.Where(x => x.InvitationTime >= weekStart)
.CountAsync();
if (weeklyUseCount >= CardFlipManager.MAX_INVITE_FLIPS)
{
throw new UserFriendlyException($"本周邀请码使用次数已达上限({CardFlipManager.MAX_INVITE_FLIPS}次),请下周再来");
}
// 检查当前用户的邀请码信息
var myInviteCode = await _inviteCodeRepository._DbQueryable
.Where(x => x.UserId == userId)
.FirstAsync();
// 标记邀请码为已使用
inviteCodeEntity.MarkAsUsed(userId);
// 增加邀请码被使用次数
inviteCodeEntity.UsedCount++;
await _inviteCodeRepository.UpdateAsync(inviteCodeEntity);
// 标记当前用户已被邀请(仅第一次使用邀请码时标记)
if (myInviteCode == null)
{
myInviteCode = new InviteCodeAggregateRoot(userId, GenerateUniqueInviteCode());
myInviteCode.MarkUserAsInvited();
await _inviteCodeRepository.InsertAsync(myInviteCode);
}
else if (!myInviteCode.IsUserInvited)
{
myInviteCode.MarkUserAsInvited();
await _inviteCodeRepository.UpdateAsync(myInviteCode);
}
// 创建邀请记录
// 创建邀请记录(双方都会因为这条记录增加一次翻牌机会)
var invitationRecord = new InvitationRecordAggregateRoot(
inviteCodeEntity.UserId,
userId,
inviteCode);
await _invitationRecordRepository.InsertAsync(invitationRecord);
_logger.LogInformation($"用户 {userId} 使用邀请码 {inviteCode} 成功");
_logger.LogInformation($"用户 {userId} 使用邀请码 {inviteCode} 成功,邀请人 {inviteCodeEntity.UserId} 和被邀请人 {userId} 都增加一次翻牌机会");
return inviteCodeEntity.UserId;
}
/// <summary>
/// 检查用户是否已邀请
/// 检查用户是否已填写过邀请
/// </summary>
public async Task<bool> IsUserInvitedAsync(Guid userId)
public async Task<bool> IsFilledInviteCodeAsync(Guid userId)
{
var inviteCode = await _inviteCodeRepository._DbQueryable
.Where(x => x.UserId == userId)
.FirstAsync();
return inviteCode?.IsUserInvited ?? false;
// 检查当前用户是否已经填写过别人的邀请码(一辈子只能填写一次)
return await _invitationRecordRepository._DbQueryable
.Where(x => x.InvitedUserId == userId)
.AnyAsync();
}
/// <summary>

View File

@@ -1,64 +1,134 @@
using Volo.Abp.Domain.Services;
using Volo.Abp.Users;
using SqlSugar;
using Volo.Abp.Domain.Services;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.AiHub.Domain.Shared.Consts;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.AiHub.Domain.Managers;
/// <summary>
/// Token验证结果
/// </summary>
public class TokenValidationResult
{
/// <summary>
/// 用户Id
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Token Id
/// </summary>
public Guid TokenId { get; set; }
}
public class TokenManager : DomainService
{
private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;
private readonly ISqlSugarRepository<UsageStatisticsAggregateRoot> _usageStatisticsRepository;
public TokenManager(ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
public TokenManager(
ISqlSugarRepository<TokenAggregateRoot> tokenRepository,
ISqlSugarRepository<UsageStatisticsAggregateRoot> usageStatisticsRepository)
{
_tokenRepository = tokenRepository;
_usageStatisticsRepository = usageStatisticsRepository;
}
public async Task<string?> GetAsync(Guid userId)
{
var entity = await _tokenRepository._DbQueryable.FirstAsync(x => x.UserId == userId);
if (entity is not null)
{
return entity.Token;
}
else
{
return null;
}
}
public async Task CreateAsync(Guid userId)
{
var entity = await _tokenRepository._DbQueryable.FirstAsync(x => x.UserId == userId);
if (entity is not null)
{
entity.ResetToken();
await _tokenRepository.UpdateAsync(entity);
}
else
{
var token = new TokenAggregateRoot(userId);
await _tokenRepository.InsertAsync(token);
}
}
public async Task<Guid> GetUserIdAsync(string? token)
/// <summary>
/// 验证Token并返回用户Id和TokenId
/// </summary>
/// <param name="token">Token密钥</param>
/// <param name="modelId">模型Id用于判断是否是尊享模型需要检查额度</param>
/// <returns>Token验证结果</returns>
public async Task<TokenValidationResult> ValidateTokenAsync(string? token, string? modelId = null)
{
if (token is null)
{
throw new UserFriendlyException("当前请求未包含token", "401");
}
if (token.StartsWith("yi-"))
if (!token.StartsWith("yi-"))
{
var entity = await _tokenRepository._DbQueryable.Where(x => x.Token == token).FirstAsync();
if (entity is null)
{
throw new UserFriendlyException("当前请求token无效", "401");
}
return entity.UserId;
throw new UserFriendlyException("当前请求token非法", "401");
}
throw new UserFriendlyException("当前请求token非法", "401");
var entity = await _tokenRepository._DbQueryable
.Where(x => x.Token == token)
.FirstAsync();
if (entity is null)
{
throw new UserFriendlyException("当前请求token无效", "401");
}
// 检查Token是否被禁用
if (entity.IsDisabled)
{
throw new UserFriendlyException("当前Token已被禁用请启用后再使用", "403");
}
// 检查Token是否过期
if (entity.ExpireTime.HasValue && entity.ExpireTime.Value < DateTime.Now)
{
throw new UserFriendlyException("当前Token已过期请更新过期时间或创建新的Token", "403");
}
// 如果是尊享模型且Token设置了额度限制检查是否超限
if (!string.IsNullOrEmpty(modelId) &&
PremiumPackageConst.ModeIds.Contains(modelId) &&
entity.PremiumQuotaLimit.HasValue)
{
var usedQuota = await GetTokenPremiumUsedQuotaAsync(entity.UserId, entity.Id);
if (usedQuota >= entity.PremiumQuotaLimit.Value)
{
throw new UserFriendlyException($"当前Token的尊享包额度已用完已使用{usedQuota},限制:{entity.PremiumQuotaLimit.Value}请调整额度限制或使用其他Token", "403");
}
}
return new TokenValidationResult
{
UserId = entity.UserId,
TokenId = entity.Id
};
}
}
/// <summary>
/// 获取Token的尊享包已使用额度
/// </summary>
private async Task<long> GetTokenPremiumUsedQuotaAsync(Guid userId, Guid tokenId)
{
var premiumModelIds = PremiumPackageConst.ModeIds;
var usedQuota = await _usageStatisticsRepository._DbQueryable
.Where(x => x.UserId == userId && x.TokenId == tokenId && premiumModelIds.Contains(x.ModelId))
.SumAsync(x => x.TotalTokenCount);
return usedQuota;
}
/// <summary>
/// 获取用户的Token兼容旧接口返回第一个可用的Token
/// </summary>
[Obsolete("请使用 ValidateTokenAsync 方法")]
public async Task<string?> GetAsync(Guid userId)
{
var entity = await _tokenRepository._DbQueryable
.Where(x => x.UserId == userId && !x.IsDisabled)
.OrderBy(x => x.CreationTime)
.FirstAsync();
return entity?.Token;
}
/// <summary>
/// 获取用户Id兼容旧接口
/// </summary>
[Obsolete("请使用 ValidateTokenAsync 方法")]
public async Task<Guid> GetUserIdAsync(string? token)
{
var result = await ValidateTokenAsync(token);
return result.UserId;
}
}

View File

@@ -18,8 +18,10 @@ public class UsageStatisticsManager : DomainService
private IDistributedLockProvider DistributedLock =>
LazyServiceProvider.LazyGetRequiredService<IDistributedLockProvider>();
public async Task SetUsageAsync(Guid? userId, string modelId, ThorUsageResponse? tokenUsage)
public async Task SetUsageAsync(Guid? userId, string modelId, ThorUsageResponse? tokenUsage, Guid? tokenId = null)
{
var actualTokenId = tokenId ?? Guid.Empty;
long inputTokenCount = tokenUsage?.PromptTokens
?? tokenUsage?.InputTokens
?? 0;
@@ -28,10 +30,10 @@ public class UsageStatisticsManager : DomainService
?? tokenUsage?.OutputTokens
?? 0;
await using (await DistributedLock.AcquireLockAsync($"UsageStatistics:{userId?.ToString()}"))
await using (await DistributedLock.AcquireLockAsync($"UsageStatistics:{userId?.ToString()}:{actualTokenId}:{modelId}"))
{
var entity = await _repository._DbQueryable.FirstAsync(x => x.UserId == userId && x.ModelId == modelId);
//存在数据,更
var entity = await _repository._DbQueryable.FirstAsync(x => x.UserId == userId && x.ModelId == modelId && x.TokenId == actualTokenId);
//存在数据,更
if (entity is not null)
{
entity.AddOnceChat(inputTokenCount, outputTokenCount);
@@ -40,7 +42,7 @@ public class UsageStatisticsManager : DomainService
//不存在插入
else
{
var usage = new UsageStatisticsAggregateRoot(userId, modelId);
var usage = new UsageStatisticsAggregateRoot(userId, modelId, actualTokenId);
usage.AddOnceChat(inputTokenCount, outputTokenCount);
await _repository.InsertAsync(usage);
}

View File

@@ -44,6 +44,7 @@ namespace Yi.Framework.AiHub.Domain
nameof(OpenAiChatCompletionsService));
services.AddKeyedTransient<IChatCompletionService, ClaudiaChatCompletionsService>(
nameof(ClaudiaChatCompletionsService));
#endregion
#region Anthropic ChatCompletion
@@ -73,6 +74,34 @@ namespace Yi.Framework.AiHub.Domain
//ai模型特殊性兼容处理
Configure<SpecialCompatibleOptions>(options =>
{
options.Handles.Add(request =>
{
if (request.Model == "gpt-5.1-chat")
{
request.Temperature = null;
request.TopP = null;
request.MaxCompletionTokens = request.MaxTokens;
request.MaxTokens = null;
request.PresencePenalty = null;
}
});
options.Handles.Add(request =>
{
if (request.Model =="gpt-5-mini")
{
request.Temperature = null;
request.TopP = null;
}
});
options.Handles.Add(request =>
{
if (request.Model == "databricks-claude-sonnet-4")
{
request.PresencePenalty = null;
}
});
options.Handles.Add(request =>
{
if (request.Model == "o1")
@@ -101,9 +130,9 @@ namespace Yi.Framework.AiHub.Domain
});
options.Handles.Add(request =>
{
if (request.MaxTokens >= 16384)
if (request.MaxTokens > 128000)
{
request.MaxTokens = 16384;
request.MaxTokens = 128000;
}
});
options.AnthropicHandles.add(request =>
@@ -128,7 +157,7 @@ namespace Yi.Framework.AiHub.Domain
{
builder.ConfigureHttpClient(client =>
{
client.DefaultRequestHeaders.Add("User-Agent","Apifox/1.0.0 (https://apifox.com)");
client.DefaultRequestHeaders.Add("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
client.Timeout = TimeSpan.FromMinutes(10);
});
});

View File

@@ -55,11 +55,11 @@ namespace Yi.Framework.Rbac.Application.Services
{
return new NotFoundResult();
}
var steam = await File.ReadAllBytesAsync(path);
return new FileContentResult(steam, file.GetMimeMapping());
var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return new FileStreamResult(stream, file!.GetMimeMapping());
}
/// <summary>
/// 上传文件
/// </summary>

View File

@@ -51,7 +51,7 @@ namespace Yi.Framework.Rbac.Application.Services.System
.WhereIF(!string.IsNullOrEmpty(input.DeptName), u => u.DeptName.Contains(input.DeptName!))
.WhereIF(input.State is not null, u => u.State == input.State)
.OrderBy(u => u.OrderNum, OrderByType.Asc)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
.ToListAsync();
return new PagedResultDto<DeptGetListOutputDto>
{
Items = await MapToGetListOutputDtosAsync(entities),

View File

@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Yi.Framework.Ddd.Application;
@@ -54,5 +55,25 @@ namespace Yi.Framework.Rbac.Application.Services.System
throw new UserFriendlyException(RoleConst.Exist);
}
}
/// <summary>
/// 更新状态
/// </summary>
/// <param name="id"></param>
/// <param name="state"></param>
/// <returns></returns>
[Route("post/{id}/{state}")]
public async Task<PostGetOutputDto> UpdateStateAsync([FromRoute] Guid id, [FromRoute] bool state)
{
var entity = await _repository.GetByIdAsync(id);
if (entity is null)
{
throw new ApplicationException("岗位未存在");
}
entity.State = state;
await _repository.UpdateAsync(entity);
return await MapToGetOutputDtoAsync(entity);
}
}
}

View File

@@ -1,4 +1,4 @@
namespace Yi.Framework.Rbac.Domain.Shared.Caches;
namespace Yi.Framework.Rbac.Domain.Shared.Caches;
public class FileCacheItem
{

View File

@@ -34,8 +34,7 @@ namespace Yi.Framework.Rbac.Domain.Entities
var type = GetFileType();
var savePath = GetSaveFilePath();
var filePath = Path.Combine(savePath, this.FileName);
this.FilePath = filePath;
this.FilePath = savePath;
}
/// <summary>

View File

@@ -29,13 +29,17 @@ using Volo.Abp.Swashbuckle;
using Yi.Abp.Application;
using Yi.Abp.SqlsugarCore;
using Yi.Framework.AiHub.Application;
using Yi.Framework.AiHub.Application.Services;
using Yi.Framework.AiHub.Domain.Entities;
using Yi.Framework.AiHub.Domain.Entities.Chat;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.AspNetCore;
using Yi.Framework.AspNetCore.Authentication.OAuth;
using Yi.Framework.AspNetCore.Authentication.OAuth.Gitee;
using Yi.Framework.AspNetCore.Authentication.OAuth.QQ;
using Yi.Framework.AspNetCore.Microsoft.AspNetCore.Builder;
using Yi.Framework.AspNetCore.Microsoft.Extensions.DependencyInjection;
using Yi.Framework.AspNetCore.UnifyResult;
using Yi.Framework.BackgroundWorkers.Hangfire;
using Yi.Framework.Bbs.Application;
using Yi.Framework.Bbs.Application.Extensions;
@@ -125,6 +129,7 @@ namespace Yi.Abp.Web
});
//采用furion格式的规范化api默认不开启使用abp优雅的方式
//前置需要将管道工作单元前加上app.Properties.Add("_AbpExceptionHandlingMiddleware_Added",false);
//你没看错。。。
//service.AddFurionUnifyResultApi();
@@ -352,9 +357,9 @@ namespace Yi.Abp.Web
var app = context.GetApplicationBuilder();
app.UseRouting();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<CardFlipTaskAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<InvitationRecordAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<InviteCodeAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<MessageAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<TokenAggregateRoot>();
// app.ApplicationServices.GetRequiredService<ISqlSugarDbContext>().SqlSugarClient.CodeFirst.InitTables<UsageStatisticsAggregateRoot>();
//跨域
app.UseCors(DefaultCorsPolicyName);
@@ -400,8 +405,7 @@ namespace Yi.Abp.Web
app.UseDefaultFiles();
app.UseDirectoryBrowser("/api/app/wwwroot");
// app.Properties.Add("_AbpExceptionHandlingMiddleware_Added",false);
//app.Properties.Add("_AbpExceptionHandlingMiddleware_Added",false);
//工作单元
app.UseUnitOfWork();

View File

@@ -1,7 +0,0 @@
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "sk-lVcGFMOQfXYtZWp1rD4SaBNDNpM270UX2wDqWh",
"ANTHROPIC_BASE_URL": "https://api.token-ai.cn",
"ANTHROPIC_MODEL": "gpt-4o-mini"
}
}

View File

@@ -1,7 +1,7 @@
{
"permissions": {
"allow": [
"WebFetch(domain:www.donet5.com)"
"Bash(npx vue-tsc --noEmit)"
],
"deny": [],
"ask": []

View File

@@ -5,8 +5,6 @@
"ComputedRef": true,
"DirectiveBinding": true,
"EffectScope": true,
"ElMessage": true,
"ElMessageBox": true,
"ExtractDefaultPropTypes": true,
"ExtractPropTypes": true,
"ExtractPublicPropTypes": true,

View File

@@ -112,7 +112,7 @@
<body>
<!-- 加载动画容器 -->
<div id="yixinai-loader" class="loader-container">
<div class="loader-title">意心Ai 2.2</div>
<div class="loader-title">意心Ai 2.5</div>
<div class="loader-subtitle">海外地址仅首次访问预计加载约10秒</div>
<div class="loader-logo">
<div class="pulse-box"></div>

View File

@@ -1,5 +1,4 @@
<script setup lang="ts">
</script>
<template>

View File

@@ -0,0 +1,12 @@
import type { AnnouncementLogDto } from './types';
import { get } from '@/utils/request';
/**
* 获取系统公告和活动数据
* 后端接口: GET /api/app/announcement
* 返回格式: AnnouncementLogDto[]
*/
export function getSystemAnnouncements() {
return get<AnnouncementLogDto[]>('/announcement').json();
}
export * from './types';

View File

@@ -0,0 +1,18 @@
// 公告类型(对应后端 AnnouncementTypeEnum
export type AnnouncementType = 'Activity' | 'System'
// 公告DTO对应后端 AnnouncementLogDto
export interface AnnouncementLogDto {
/** 标题 */
title: string
/** 内容列表 */
content: string[]
/** 图片url */
imageUrl?: string | null
/** 开始时间(系统公告时间、活动开始时间) */
startTime: string
/** 活动结束时间 */
endTime?: string | null
/** 公告类型(系统、活动) */
type: AnnouncementType
}

View File

@@ -7,9 +7,10 @@ export interface CardFlipStatusOutput {
canFlip: boolean; // 是否可以翻牌
myInviteCode?: string; // 用户的邀请码
invitedCount: number; // 本周邀请人数
isInvited: boolean; // 是否已被邀请
// isInvited: boolean; // 是否已被邀请
flipRecords: CardFlipRecord[]; // 翻牌记录
nextFlipTip?: string; // 下次可翻牌提示
isFilledInviteCode: boolean;// 当前用户是否已经填写过邀请码
}
// 翻牌记录

View File

@@ -1,3 +1,4 @@
export * from './announcement'
export * from './auth';
export * from './chat';
export * from './model';

View File

@@ -1,9 +1,8 @@
import type { GetSessionListVO } from './types';
import { get, post } from '@/utils/request';
import { del, get, post, put } from '@/utils/request';
// 获取当前用户的模型列表
export function getModelList() {
// return get<GetSessionListVO[]>('/system/model/modelList');
return get<GetSessionListVO[]>('/ai-chat/model').json();
}
// 申请ApiKey
@@ -21,10 +20,99 @@ export function getRechargeLog() {
}
// 查询用户近7天token消耗
export function getLast7DaysTokenUsage() {
return get<any>('/usage-statistics/last7Days-token-usage').json();
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getLast7DaysTokenUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/last7Days-token-usage?tokenId=${tokenId}`
: '/usage-statistics/last7Days-token-usage';
return get<any>(url).json();
}
// 查询用户token消耗各模型占比
export function getModelTokenUsage() {
return get<any>('/usage-statistics/model-token-usage').json();
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getModelTokenUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/model-token-usage?tokenId=${tokenId}`
: '/usage-statistics/model-token-usage';
return get<any>(url).json();
}
// 获取当前用户得token列表
export function getTokenList(params?: {
skipCount?: number;
maxResultCount?: number;
orderByColumn?: string;
isAsc?: string;
}) {
// 构建查询参数
const queryParams = new URLSearchParams();
if (params?.skipCount !== undefined) {
queryParams.append('SkipCount', params.skipCount.toString());
}
if (params?.maxResultCount !== undefined) {
queryParams.append('MaxResultCount', params.maxResultCount.toString());
}
if (params?.orderByColumn) {
queryParams.append('OrderByColumn', params.orderByColumn);
}
if (params?.isAsc) {
queryParams.append('IsAsc', params.isAsc);
}
const queryString = queryParams.toString();
const url = queryString ? `/token/list?${queryString}` : '/token/list';
return get<any>(url).json();
}
// 创建token
export function createToken(data: any) {
return post<any>('/token', data).json();
}
// 编辑token
export function editToken(data: any) {
return put('/token', data).json();
}
// 删除token
export function deleteToken(id: string) {
return del(`/token/${id}`).json();
}
// 启用token
export function enableToken(id: string) {
return post(`/token/${id}/enable`).json();
}
// 禁用token
export function disableToken(id: string) {
return post(`/token/${id}/disable`).json();
}
// 新增接口2
// 获取可选择的token信息
export function getSelectableTokenInfo() {
return get<any>('/token/select-list').json();
}
/*
返回数据
[
{
"tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"isDisabled": true
}
] */
// 获取当前用户尊享包不同token用量占比饼图
export function getPremiumPackageTokenUsage() {
return get<any>('/usage-statistics/premium-token-usage/by-token').json();
}
/* 返回数据
[
{
"tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"tokenName": "string",
"tokens": 0,
"percentage": 0
}
] */

View File

@@ -1,5 +1,61 @@
import { get, post } from '@/utils/request';
// 尊享包用量明细DTO
export interface PremiumTokenUsageDto {
/** id */
id: string;
/** 用户ID */
userId: string;
/** 包名称 */
packageName: string;
/** 总用量总token数 */
totalTokens: number;
/** 剩余用量剩余token数 */
remainingTokens: number;
/** 已使用token数 */
usedTokens: number;
/** 到期时间 */
expireDateTime?: string;
/** 是否激活 */
isActive: boolean;
/** 购买金额 */
purchaseAmount: number;
/** 备注 */
remark?: string;
/** 创建时间 */
creationTime?: string;
/** 创建者ID */
creatorId?: string;
}
// 查询参数接口 - 匹配后端 PagedAllResultRequestDto
export interface PremiumTokenUsageQueryParams {
/** 查询开始时间 */
startTime?: string;
/** 查询结束时间 */
endTime?: string;
/** 排序列名 */
orderByColumn?: string;
/** 排序方向ascending/descending */
isAsc?: string;
/** 跳过数量(分页) */
skipCount?: number;
/** 最大返回数量(分页) */
maxResultCount?: number;
/** 是否免费 */
isFree?: boolean;
// 是否为升序排序
isAscending?: boolean;
}
// 分页响应接口
export interface PagedResult<T> {
/** 数据列表 */
items: T[];
/** 总数量 */
totalCount: number;
}
// 获取用户信息
export function getUserInfo() {
return get<any>('/account/ai').json();
@@ -24,3 +80,63 @@ export function getWechatAuth(data: any) {
export function getPremiumTokenPackage() {
return get<any>('/usage-statistics/premium-token-usage').json();
}
// 获取尊享包用量明细列表
export function getPremiumTokenUsageList(params?: PremiumTokenUsageQueryParams) {
return get<PagedResult<PremiumTokenUsageDto>>('/usage-statistics/premium-token-usage/list', params).json();
}
// 查询条件的后端dto,其他查询或者排序由前端自己实现:
// using Volo.Abp.Application.Dtos;
//
// namespace Yi.Framework.Ddd.Application.Contracts
// {
// /// <summary>
// /// 分页查询请求DTO包含时间范围和自定义排序功能
// /// </summary>
// public class PagedAllResultRequestDto : PagedAndSortedResultRequestDto, IPagedAllResultRequestDto
// {
// /// <summary>
// /// 查询开始时间
// /// </summary>
// public DateTime? StartTime { get; set; }
//
// /// <summary>
// /// 查询结束时间
// /// </summary>
// public DateTime? EndTime { get; set; }
//
// /// <summary>
// /// 排序列名
// /// </summary>
// public string? OrderByColumn { get; set; }
//
// /// <summary>
// /// 排序方向ascending/descending
// /// </summary>
// public string? IsAsc { get; set; }
//
// /// <summary>
// /// 是否为升序排序
// /// </summary>
// public bool IsAscending => string.Equals(IsAsc, "ascending", StringComparison.OrdinalIgnoreCase);
//
// private string? _sorting;
//
// /// <summary>
// /// 排序表达式
// /// </summary>
// public override string? Sorting
// {
// get
// {
// if (!string.IsNullOrWhiteSpace(OrderByColumn))
// {
// return $"{OrderByColumn} {(IsAscending ? "ASC" : "DESC")}";
// }
// return _sorting;
// }
// set => _sorting = value;
// }
// }
// }

View File

@@ -7,6 +7,7 @@ import { getQrCode, getQrCodeResult, getUserInfo } from '@/api';
import { useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session.ts';
import { WECHAT_QRCODE_TYPE } from '@/utils/user.ts';
import { useGuideTour } from '@/hooks/useGuideTour';
const props = defineProps({
type: {
@@ -29,6 +30,7 @@ const userStore = useUserStore();
const router = useRouter();
const sessionStore = useSessionStore();
const isQrCodeError = ref(false);
const { startFullTour } = useGuideTour();
// 二维码倒计时实例
const { start: qrStart, stop: qrStop } = useCountdown(shallowRef(600), {
interval: 1000,
@@ -126,6 +128,11 @@ async function handleLoginSuccess(token: string, refreshToken: string) {
stopPolling();
userStore.setToken(token, refreshToken);
const resUserInfo = await getUserInfo();
// 判断是否为新用户注册时间小于1小时
const creationTime = resUserInfo.data.user.creationTime; // 格式: "2024-11-01 12:01:34"
const isNewUser = checkIsNewUser(creationTime);
userStore.setUserInfo(resUserInfo.data);
// 提示用户
ElMessage.success('登录成功');
@@ -133,6 +140,34 @@ async function handleLoginSuccess(token: string, refreshToken: string) {
await router.replace('/');
await sessionStore.requestSessionList(1, true);
userStore.closeLoginDialog();
// 如果是新用户延迟500ms后自动触发新手引导
if (isNewUser) {
setTimeout(() => {
startFullTour();
}, 500);
}
}
// 判断是否为新用户注册时间距离当前时间小于1小时
function checkIsNewUser(creationTimeStr: string): boolean {
try {
// 解析注册时间字符串 "2024-11-01 12:01:34"
const creationTime = new Date(creationTimeStr.replace(' ', 'T'));
const currentTime = new Date();
// 计算时间差(毫秒)
const timeDiff = currentTime.getTime() - creationTime.getTime();
// 1小时 = 60分钟 * 60秒 * 1000毫秒 = 3600000毫秒
const oneHourInMs = 60 * 60 * 1000;
return timeDiff < oneHourInMs;
}
catch (error) {
console.error('解析注册时间失败:', error);
return false;
}
}
// 处理注册授权

View File

@@ -2,22 +2,17 @@
<script setup lang="ts">
import type { GetSessionListVO } from '@/api/model/types';
import { Lock } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import Popover from '@/components/Popover/index.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';
import { useUserStore } from '@/stores';
import { useModelStore } from '@/stores/modules/model';
import { showProductPackage } from '@/utils/product-package.ts';
import { isUserVip } from '@/utils/user';
const router = useRouter();
const userStore = useUserStore();
const modelStore = useModelStore();
// 检查模型是否可用
function isModelAvailable(item: GetSessionListVO) {
return isUserVip() || item.modelId?.includes('DeepSeek-R1-0528') || userStore.userInfo?.user?.userName === 'cc';
return isUserVip() || item.modelId?.includes('DeepSeek-R1-0528');
}
onMounted(async () => {
@@ -88,11 +83,6 @@ function handleModelClick(item: GetSessionListVO) {
)
.then(() => {
showProductPackage();
// router.push({
// name: 'products', // 使用命名路由
// query: { from: isUserVip() ? 'vip' : 'user' }, // 可选:添加来源标识
// });
})
.catch(() => {
// 点击右上角关闭或“关闭”按钮,不执行任何操作
@@ -109,11 +99,16 @@ function handleModelClick(item: GetSessionListVO) {
规则2金色光泽VIP/付费)
规则3彩色流光尊享/高级)
-------------------------------- */
function getModelStyleClass(modelName: any) {
const name = modelName.toLowerCase();
function getModelStyleClass(mode: any) {
if (!mode) {
return;
}
// isPremiumPackage
const name = mode.modelName.toLowerCase();
const isPremiumPackage = mode.isPremiumPackage;
// 规则3彩色流光
if (name.includes('claude-sonnet-4-5-20250929')) {
if (isPremiumPackage) {
return `
text-transparent bg-clip-text
bg-[linear-gradient(45deg,#ff0000,#ff8000,#ffff00,#00ff00,#00ffff,#0000ff,#8000ff,#ff0080)]
@@ -156,7 +151,7 @@ function getWrapperClass(item: GetSessionListVO) {
</script>
<template>
<div class="model-select">
<div class="model-select" data-tour="model-select">
<Popover
ref="popoverRef"
placement="top-start"
@@ -174,7 +169,7 @@ function getWrapperClass(item: GetSessionListVO) {
<div class="model-select-box-icon">
<SvgIcon name="models" size="12" />
</div>
<div :class="getModelStyleClass(currentModelName)" class="model-select-box-text font-size-12px">
<div :class="getModelStyleClass(modelStore.currentModelInfo)" class="model-select-box-text font-size-12px">
{{ currentModelName }}
</div>
</div>
@@ -195,7 +190,7 @@ function getWrapperClass(item: GetSessionListVO) {
:offset="[12, 0]"
>
<template #trigger>
<span :class="getModelStyleClass(item.modelName)">
<span :class="getModelStyleClass(item)">
{{ item.modelName }}
</span>
</template>

View File

@@ -1,4 +1,5 @@
<script setup lang="ts">
// 图标文档 https://remixicon.com/
const props = defineProps<{
className?: string;
name: string;

File diff suppressed because it is too large Load Diff

View File

@@ -98,7 +98,7 @@ function toggleFullscreen() {
<div class="dialog-container">
<!-- 左侧导航 -->
<div class="nav-side">
<div class="nav-side" data-tour="user-nav-menu">
<el-menu
:default-active="activeNav"
class="nav-menu"
@@ -108,6 +108,7 @@ function toggleFullscreen() {
v-for="item in navItems"
:key="item.name"
:index="item.name"
:data-tour="`nav-${item.name}`"
>
<template #title>
<el-icon v-if="item.icon">

View File

@@ -792,7 +792,7 @@ function generateShareContent(): string {
return `
🎁 【意心Ai】我来邀请你翻牌抽奖分享我的限时邀请码~
使用我的邀请码可为你解锁1次额外翻牌机会最大可白嫖官方Claude4.5 220RMB额度 Token💰
填写我的邀请码咱们双方各增加1次翻牌机会最大可白嫖官方Claude4.5 220RMB额度 Token💰
👉 点击链接立即参与我的专属邀请码链接:
${shareLink}
@@ -948,6 +948,7 @@ function getCardClass(record: CardFlipRecord): string[] {
type="primary"
size="small"
icon="Gift"
data-tour="my-invite-code-btn"
@click="showMyInviteCodeDialog = true"
>
我的邀请码
@@ -956,6 +957,7 @@ function getCardClass(record: CardFlipRecord): string[] {
type="warning"
size="small"
icon="Unlock"
data-tour="use-invite-code-btn"
@click="inviteCodeDialog = true"
>
使用邀请码
@@ -964,7 +966,7 @@ function getCardClass(record: CardFlipRecord): string[] {
</div>
<!-- 翻牌区域 -->
<div class="cards-section" :class="{ 'shuffle-mode': isShuffling }">
<div class="cards-section" :class="{ 'shuffle-mode': isShuffling }" data-tour="card-flip-area">
<!-- 洗牌动画遮罩提示 -->
<div v-if="isShuffling" class="shuffle-overlay">
<div class="shuffle-tip">
@@ -1094,27 +1096,42 @@ function getCardClass(record: CardFlipRecord): string[] {
class="invite-dialog"
>
<div class="invite-dialog-content">
<p class="dialog-tip">
输入好友的邀请码可增加翻牌次数必定中奖每次奖励最大额度翻倍使用其他人邀请码自己的邀请码将失效
</p>
<el-input
v-model="inputInviteCode"
placeholder="请输入8位邀请码"
maxlength="8"
clearable
size="large"
class="code-input"
>
<template #prefix>
<span style="font-size: 20px;">🎫</span>
</template>
</el-input>
<!-- 已填写过邀请码的提示 -->
<div v-if="taskData?.isFilledInviteCode" class="already-filled-box">
<span class="filled-icon"></span>
<p class="filled-text">
您已填写过邀请码每人仅能填写一次他人邀请码
</p>
</div>
<template v-else>
<p class="dialog-tip">
输入好友的邀请码双方各增加1次翻牌机会必定中奖每次奖励最大额度翻倍
</p>
<el-input
v-model="inputInviteCode"
placeholder="请输入8位邀请码"
maxlength="8"
clearable
size="large"
class="code-input"
>
<template #prefix>
<span style="font-size: 20px;">🎫</span>
</template>
</el-input>
</template>
</div>
<template #footer>
<el-button @click="inviteCodeDialog = false">
取消
</el-button>
<el-button type="primary" :loading="loading" @click="handleUseInviteCode">
<el-button
v-if="!taskData?.isFilledInviteCode"
type="primary"
:loading="loading"
@click="handleUseInviteCode"
>
确认使用
</el-button>
</template>
@@ -1129,16 +1146,8 @@ function getCardClass(record: CardFlipRecord): string[] {
class="my-invite-dialog"
>
<div class="my-invite-dialog-content">
<!-- 已使用过邀请码的提示 -->
<div v-if="taskData?.isInvited" class="invite-disabled-box">
<span class="disabled-icon">🔒</span>
<p class="disabled-text">
您已使用过他人的邀请码无法生成自己的邀请码
</p>
</div>
<!-- 显示已有的邀请码 -->
<div v-else-if="taskData?.myInviteCode" class="my-invite-code-display">
<div v-if="taskData?.myInviteCode" class="my-invite-code-display">
<div class="code-box">
<span class="code-text">{{ taskData.myInviteCode }}</span>
</div>
@@ -1158,9 +1167,20 @@ function getCardClass(record: CardFlipRecord): string[] {
复制分享链接
</el-button>
</div>
<!-- 显示当前用户是否已填写过邀请码 -->
<div v-if="taskData?.isFilledInviteCode" class="filled-status-info">
<span class="status-icon"></span>
<span class="status-text">您已填写过他人邀请码</span>
</div>
<div v-else class="unfilled-status-info">
<span class="status-icon">💡</span>
<span class="status-text">您还可以填写他人邀请码获得额外机会</span>
</div>
<p class="invite-tip">
💌 分享给好友好友使用后可解锁最后3次翻牌机会
💌 分享给好友好友填写您的邀请码后<br>
<strong>双方各增加1次翻牌机会</strong>
</p>
<div class="share-preview">
<div class="share-preview-title">
📱 分享预览
@@ -1174,7 +1194,7 @@ function getCardClass(record: CardFlipRecord): string[] {
<!-- 生成邀请码 -->
<div v-else class="generate-invite-box">
<p class="generate-tip">
您还没有邀请码生成后可以分享给好友
您还没有邀请码生成后分享给好友<strong>双方各增加1次翻牌机会</strong>
</p>
<el-button
type="primary"
@@ -2050,6 +2070,28 @@ function getCardClass(record: CardFlipRecord): string[] {
font-size: 16px;
}
}
.already-filled-box {
text-align: center;
padding: 24px 16px;
background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
border: 1px solid #bae6fd;
border-radius: 12px;
.filled-icon {
font-size: 48px;
display: block;
margin-bottom: 12px;
}
.filled-text {
font-size: 15px;
color: #0369a1;
line-height: 1.6;
margin: 0;
font-weight: 500;
}
}
}
/* 我的邀请码对话框样式 */
@@ -2109,7 +2151,45 @@ function getCardClass(record: CardFlipRecord): string[] {
font-size: 13px;
color: #909399;
line-height: 1.5;
margin: 0 0 16px 0;
margin: 0 0 12px 0;
strong {
color: #f56c6c;
font-weight: 600;
}
}
.filled-status-info,
.unfilled-status-info {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 12px;
border-radius: 8px;
margin-bottom: 12px;
font-size: 13px;
font-weight: 500;
}
.filled-status-info {
background: #f0fdf4;
border: 1px solid #86efac;
color: #166534;
.status-icon {
font-size: 16px;
}
}
.unfilled-status-info {
background: #fefce8;
border: 1px solid #fde047;
color: #854d0e;
.status-icon {
font-size: 16px;
}
}
.share-preview {
@@ -2169,6 +2249,11 @@ function getCardClass(record: CardFlipRecord): string[] {
color: #606266;
margin-bottom: 20px;
line-height: 1.6;
strong {
color: #f56c6c;
font-weight: 600;
}
}
.el-button {

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
<script lang="ts" setup>
import { Clock, Coin, TrophyBase, WarningFilled } from '@element-plus/icons-vue';
import { getPremiumTokenPackage } from '@/api/user';
import { showProductPackage } from '@/utils/product-package.ts';
import PremiumPackageInfo from './PremiumPackageInfo.vue';
import PremiumUsageList from './PremiumUsageList.vue';
// 尊享服务数据
const loading = ref(false);
@@ -14,59 +14,8 @@ const packageData = ref<any>({
expireDate: '', // 过期时间
});
// 计算属性
const usagePercent = computed(() => {
if (packageData.value.totalQuota === 0)
return 0;
return Number(((packageData.value.usedQuota / packageData.value.totalQuota) * 100).toFixed(2));
});
const remainingPercent = computed(() => {
if (packageData.value.totalQuota === 0)
return 0;
return Number(((packageData.value.remainingQuota / packageData.value.totalQuota) * 100).toFixed(2));
});
// 获取进度条颜色(基于剩余百分比)
const progressColor = computed(() => {
const percent = remainingPercent.value;
if (percent <= 10)
return '#f56c6c'; // 红色 - 剩余很少
if (percent <= 30)
return '#e6a23c'; // 橙色 - 剩余较少
return '#67c23a'; // 绿色 - 剩余充足
});
// 格式化数字 - 转换为万为单位
function formatNumber(num: number): string {
if (num === 0)
return '0';
const wan = num / 10000;
// 保留2位小数去掉末尾的0
return wan.toFixed(2).replace(/\.?0+$/, '');
}
// 格式化原始数字(带千分位)
function formatRawNumber(num: number): string {
return num.toLocaleString();
}
/*
前端已准备好后端需要提供以下API
接口地址: GET /account/premium/token-package
返回数据格式:
{
"success": true,
"data": {
"totalQuota": 1000000, // 购买总额度
"usedQuota": 350000, // 已使用额度
"remainingQuota": 650000, // 剩余额度(可选,前端会自动计算)
"usagePercentage": 35, // 使用百分比(可选)
"packageName": "尊享VIP套餐", // 套餐名称(可选)
"expireDate": "2024-12-31" // 过期时间(可选)
}
} */
// 子组件引用
const usageListRef = ref<InstanceType<typeof PremiumUsageList>>();
// 获取尊享服务Token包数据
async function fetchPremiumTokenPackage() {
@@ -103,434 +52,86 @@ async function fetchPremiumTokenPackage() {
}
}
// 刷新数据
// 刷新所有数据
function refreshData() {
fetchPremiumTokenPackage();
usageListRef.value?.refresh();
}
onMounted(() => {
fetchPremiumTokenPackage();
});
function onProductPackage() {
showProductPackage();
}
</script>
<template>
<div v-loading="loading" class="premium-service">
<div class="header">
<h2>
<el-icon><TrophyBase /></el-icon>
尊享服务
</h2>
<el-button
type="primary"
size="small"
@click="refreshData"
>
刷新数据
</el-button>
<div class="premium-service">
<!-- 套餐信息 -->
<div data-tour="premium-package-info">
<PremiumPackageInfo
:package-data="packageData"
:loading="loading"
@refresh="refreshData"
/>
</div>
<!-- 套餐信息卡片 -->
<el-card class="package-card" shadow="hover">
<template #header>
<div class="card-header">
<el-icon class="header-icon">
<Coin />
</el-icon>
<span class="header-title">{{ packageData.packageName }}</span>
</div>
</template>
<div class="package-content">
<!-- 统计数据 -->
<div class="stats-grid">
<div class="stat-item total">
<div class="stat-label">
购买总额度
</div>
<div class="stat-value">
{{ formatNumber(packageData.totalQuota) }}
</div>
<div class="stat-unit">
Tokens
</div>
<div class="stat-raw" :title="`原始值: ${formatRawNumber(packageData.totalQuota)} Tokens`">
({{ formatRawNumber(packageData.totalQuota) }})
</div>
</div>
<div class="stat-item used">
<div class="stat-label">
已用额度
</div>
<div class="stat-value">
{{ formatNumber(packageData.usedQuota) }}
</div>
<div class="stat-unit">
Tokens
</div>
<div class="stat-raw" :title="`原始值: ${formatRawNumber(packageData.usedQuota)} Tokens`">
({{ formatRawNumber(packageData.usedQuota) }})
</div>
</div>
<div class="stat-item remaining">
<div class="stat-label">
剩余额度
</div>
<div class="stat-value">
{{ formatNumber(packageData.remainingQuota) }}
</div>
<div class="stat-unit">
Tokens
</div>
<div class="stat-raw" :title="`原始值: ${formatRawNumber(packageData.remainingQuota)} Tokens`">
({{ formatRawNumber(packageData.remainingQuota) }})
</div>
</div>
</div>
<!-- 进度条 -->
<div class="progress-section">
<div class="progress-header">
<span class="progress-label">剩余进度</span>
<span class="progress-percent" :style="{ color: progressColor }">
{{ remainingPercent }}%
</span>
</div>
<el-progress
:percentage="remainingPercent"
:color="progressColor"
:stroke-width="20"
:show-text="false"
/>
<div class="progress-legend">
<div class="legend-item">
<span class="legend-dot " :style="{ background: progressColor }" />
<span class="legend-text">剩余: {{ remainingPercent }}%</span>
</div>
<div class="legend-item">
<span class="legend-dot used-dot" />
<span class="legend-text">已使用: {{ usagePercent }}%</span>
</div>
</div>
</div>
<!-- 购买提示卡片额度不足时显示 -->
<el-card
v-if="remainingPercent < 20"
class="warning-card"
shadow="hover"
>
<div class="warning-content">
<el-icon class="warning-icon" color="#e6a23c">
<WarningFilled />
</el-icon>
<div class="warning-text">
<h3>额度即将用完</h3>
<p>您的Token额度已使用{{ usagePercent }}%剩余额度较少建议及时充值</p>
</div>
<el-button type="warning" @click="onProductPackage()">
立即充值
</el-button>
</div>
</el-card>
<!-- 过期时间 -->
<div v-if="packageData.expireDate" class="expire-info">
<el-icon><Clock /></el-icon>
<span>有效期至: {{ packageData.expireDate }}</span>
</div>
<!-- 温馨提示 -->
<el-alert
class="tips-alert"
type="info"
:closable="false"
show-icon
>
<template #title>
<div class="tips-content">
<p>温馨提示</p>
<ul>
<li>Token额度根据不同模型消耗速率不同</li>
<li>建议合理使用避免额度过快消耗</li>
<li>额度不足时请及时充值避免影响使用</li>
</ul>
</div>
</template>
</el-alert>
</div>
</el-card>
<!-- 额度明细列表 -->
<div class="usage-list-wrapper" data-tour="premium-usage-list">
<PremiumUsageList ref="usageListRef" />
</div>
</div>
</template>
<style scoped>
<style scoped lang="scss">
.premium-service {
padding: 20px;
position: relative;
padding: 24px;
height: 100%;
overflow-y: auto;
background: linear-gradient(to bottom, #f8f9fa 0%, #ffffff 100%);
// 美化滚动条
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: #f1f3f5;
border-radius: 4px;
}
&::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
border-radius: 4px;
&:hover {
background: linear-gradient(180deg, #5568d3 0%, #65408b 100%);
}
}
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
.usage-list-wrapper {
margin-top: 24px;
animation: slideInUp 0.4s ease-out;
}
.header h2 {
display: flex;
align-items: center;
margin: 0;
font-size: 20px;
color: #333;
}
.header .el-icon {
margin-right: 8px;
color: #f59e0b;
}
/* 套餐卡片 */
.package-card {
margin-bottom: 20px;
border-radius: 12px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.card-header {
display: flex;
align-items: center;
gap: 8px;
font-size: 18px;
font-weight: 600;
color: #333;
}
.header-icon {
font-size: 20px;
color: #f59e0b;
}
.package-content {
display: flex;
flex-direction: column;
gap: 24px;
}
/* 统计数据网格 */
.stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
.stat-item {
padding: 20px;
border-radius: 8px;
text-align: center;
transition: transform 0.2s;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.stat-item:hover {
transform: translateY(-4px);
}
.stat-item.total {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.stat-item.used {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.stat-item.remaining {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.stat-label {
font-size: 14px;
opacity: 0.9;
margin-bottom: 8px;
}
.stat-value {
font-size: 28px;
font-weight: 700;
margin-bottom: 4px;
}
.stat-unit {
font-size: 12px;
opacity: 0.8;
}
.stat-raw {
font-size: 11px;
opacity: 0.7;
margin-top: 4px;
cursor: help;
transition: opacity 0.2s;
}
.stat-raw:hover {
opacity: 1;
}
/* 进度条部分 */
.progress-section {
padding: 20px;
background: #f7f8fa;
border-radius: 8px;
}
.progress-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.progress-label {
font-size: 16px;
font-weight: 600;
color: #333;
}
.progress-percent {
font-size: 20px;
font-weight: 700;
}
.progress-legend {
display: flex;
justify-content: center;
gap: 24px;
margin-top: 12px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-dot {
width: 12px;
height: 12px;
border-radius: 50%;
}
.used-dot {
background: #409eff;
}
.remaining-dot {
background: #e4e7ed;
}
.legend-text {
font-size: 14px;
color: #606266;
}
/* 过期信息 */
.expire-info {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
background: #f0f9ff;
border-radius: 6px;
color: #0369a1;
font-size: 14px;
}
/* 温馨提示 */
.tips-alert {
border-radius: 8px;
}
.tips-content p {
margin: 0 0 8px 0;
font-weight: 600;
}
.tips-content ul {
margin: 0;
padding-left: 20px;
}
.tips-content li {
margin: 4px 0;
font-size: 13px;
}
/* 警告卡片 */
.warning-card {
border-radius: 12px;
border: 2px solid #e6a23c;
background: #fef3e9;
}
.warning-content {
display: flex;
align-items: center;
gap: 16px;
}
.warning-icon {
font-size: 40px;
flex-shrink: 0;
}
.warning-text {
flex: 1;
}
.warning-text h3 {
margin: 0 0 8px 0;
color: #e6a23c;
font-size: 18px;
}
.warning-text p {
margin: 0;
color: #606266;
font-size: 14px;
@keyframes slideInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 响应式布局 */
@media (max-width: 768px) {
.premium-service {
padding: 10px;
padding: 12px;
}
.stats-grid {
grid-template-columns: 1fr;
gap: 12px;
}
.stat-value {
font-size: 24px;
}
.progress-legend {
flex-direction: column;
gap: 8px;
}
.warning-content {
flex-direction: column;
text-align: center;
.usage-list-wrapper {
margin-top: 16px;
}
}
</style>

View File

@@ -0,0 +1,826 @@
<script lang="ts" setup>
import type { PremiumTokenUsageDto, PremiumTokenUsageQueryParams } from '@/api/user';
import { Clock, Refresh } from '@element-plus/icons-vue';
import { getPremiumTokenUsageList } from '@/api/user';
// 额度明细列表
const usageList = ref<PremiumTokenUsageDto[]>([]);
const listLoading = ref(false);
const totalCount = ref(0);
// 查询参数
const queryParams = ref<PremiumTokenUsageQueryParams>({
skipCount: 0,
maxResultCount: 10,
});
// 当前页码
const currentPage = ref(1);
const pageSize = ref(10);
// 筛选条件
const dateRange = ref<[Date, Date] | null>(null);
const freeFilter = ref<boolean | null>(null);
// 快捷时间选择
const shortcuts = [
{
text: '最近一周',
value: () => {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
return [start, end];
},
},
{
text: '最近一个月',
value: () => {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
return [start, end];
},
},
{
text: '最近三个月',
value: () => {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
return [start, end];
},
},
];
// 格式化数字 - 转换为万为单位
function formatNumber(num: number): string {
if (num === 0)
return '0';
const wan = num / 10000;
return wan.toFixed(2).replace(/\.?0+$/, '');
}
// 格式化日期时间
function formatDateTime(dateTime: string): string {
return new Date(dateTime).toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
// 获取使用率颜色
function getUsageColor(used: number, total: number): string {
if (total === 0)
return '#e4e7ed';
const percent = (used / total) * 100;
if (percent >= 90)
return '#f56c6c'; // 红色
if (percent >= 70)
return '#e6a23c'; // 橙色
return '#409eff'; // 蓝色
}
// 获取额度明细列表
async function fetchUsageList(resetPage = false) {
if (resetPage) {
currentPage.value = 1;
}
listLoading.value = true;
try {
const params: PremiumTokenUsageQueryParams = {
skipCount: currentPage.value,
maxResultCount: queryParams.value.maxResultCount,
startTime: queryParams.value.startTime,
endTime: queryParams.value.endTime,
orderByColumn: queryParams.value.orderByColumn,
isAsc: queryParams.value.isAsc,
isFree: queryParams.value.isFree,
};
console.log('发送到后端的参数:', params);
const res = await getPremiumTokenUsageList(params);
console.log('后端返回结果:', res);
if (res.data) {
usageList.value = res.data.items || [];
totalCount.value = res.data.totalCount || 0;
}
}
catch (error) {
console.error('获取额度明细列表失败:', error);
ElMessage.error('获取额度明细列表失败');
usageList.value = [];
totalCount.value = 0;
}
finally {
listLoading.value = false;
}
}
// 处理分页
function handlePageChange(page: number) {
console.log('切换页码:', page);
currentPage.value = page;
fetchUsageList();
}
// 处理每页大小变化
function handleSizeChange(size: number) {
console.log('修改每页大小:', size);
pageSize.value = size;
queryParams.value.maxResultCount = size;
currentPage.value = 1;
fetchUsageList();
}
// 处理排序(使用 OrderByColumn 和 IsAsc
function handleSortChange({ prop, order }: { prop: string; order: string | null }) {
console.log('排序变化:', { prop, order });
if (order) {
queryParams.value.orderByColumn = prop;
queryParams.value.isAsc = order === 'ascending' ? 'ascending' : 'descending';
}
else {
queryParams.value.orderByColumn = undefined;
queryParams.value.isAsc = undefined;
}
fetchUsageList(true);
}
// 处理时间筛选
function handleDateChange(value: [Date, Date] | null) {
console.log('时间筛选变化:', value);
if (value && value.length === 2) {
// 设置开始时间为当天00:00:00
const startDate = new Date(value[0]);
startDate.setHours(0, 0, 0, 0);
// 设置结束时间为当天23:59:59
const endDate = new Date(value[1]);
endDate.setHours(23, 59, 59, 999);
queryParams.value.startTime = startDate.toISOString();
queryParams.value.endTime = endDate.toISOString();
console.log('时间范围:', {
start: queryParams.value.startTime,
end: queryParams.value.endTime,
});
}
else {
queryParams.value.startTime = undefined;
queryParams.value.endTime = undefined;
}
fetchUsageList(true); // 重置到第一页并获取数据
}
// 重置筛选
function resetFilters() {
console.log('重置所有筛选条件');
dateRange.value = null;
freeFilter.value = null;
// 重置后端查询参数
queryParams.value = {
maxResultCount: pageSize.value,
orderByColumn: undefined,
isAsc: undefined,
startTime: undefined,
endTime: undefined,
isFree: undefined,
};
fetchUsageList(true);
}
// 处理是否免费筛选
function handleFreeFilterChange(value: boolean | null) {
console.log('是否免费筛选:', value);
queryParams.value.isFree = value === null ? undefined : value;
fetchUsageList(true);
}
// 判断是否有活动的筛选条件
const hasActiveFilters = computed(() => {
return !!dateRange.value || freeFilter.value !== null;
});
// 对外暴露刷新方法
defineExpose({
refresh: fetchUsageList,
});
onMounted(() => {
fetchUsageList();
});
</script>
<template>
<el-card v-loading="listLoading" class="usage-list-card" shadow="hover">
<template #header>
<div class="list-header">
<div class="header-left">
<el-icon class="header-icon">
<i-ep-document />
</el-icon>
<div class="header-text">
<span class="header-title">尊享包额度明细</span>
<!-- <span class="header-subtitle">Premium Package Usage Details</span> -->
</div>
</div>
<div class="header-right">
<el-tag v-if="totalCount > 0" type="primary" size="default" class="count-tag" effect="plain">
<el-icon><i-ep-data-line /></el-icon>
{{ totalCount }} 条记录
</el-tag>
</div>
</div>
</template>
<!-- 筛选工具栏 -->
<div class="filter-toolbar">
<div class="filter-row">
<div class="filter-item">
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator=""
start-placeholder="开始日期"
end-placeholder="结束日期"
size="default"
:shortcuts="shortcuts"
class="date-picker"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
:editable="false"
@change="handleDateChange"
/>
</div>
<div class="filter-item">
<el-select
v-model="freeFilter"
placeholder="全部类型"
clearable
size="default"
class="free-select"
@change="handleFreeFilterChange"
>
<el-option label="免费" :value="true" />
<el-option label="付费" :value="false" />
</el-select>
</div>
<div class="filter-actions">
<el-button
v-if="hasActiveFilters"
size="default"
@click="resetFilters"
>
<el-icon><i-ep-refresh-left /></el-icon>
重置
</el-button>
<el-button
type="primary"
size="default"
:icon="Refresh"
@click="fetchUsageList"
>
刷新
</el-button>
</div>
</div>
</div>
<!-- 数据表格 -->
<el-table
:data="usageList"
stripe
class="usage-table"
empty-text="暂无数据"
border
@sort-change="handleSortChange"
>
<el-table-column prop="packageName" label="包名称" min-width="200" sortable show-overflow-tooltip align="center" header-align="center" resizable>
<template #default="{ row }">
<div class="package-name-cell">
<el-icon class="package-icon" color="#409eff">
<i-ep-box />
</el-icon>
<span>{{ row.packageName }}</span>
</div>
</template>
</el-table-column>
<el-table-column label="总额度" min-width="130" prop="totalTokens" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<div class="token-cell">
<span class="token-value">{{ formatNumber(row.totalTokens) }}</span>
<span class="token-unit"></span>
</div>
</template>
</el-table-column>
<el-table-column label="已使用" min-width="130" prop="usedTokens" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<div class="token-cell used">
<span class="token-value">{{ formatNumber(row.usedTokens) }}</span>
<span class="token-unit"></span>
</div>
</template>
</el-table-column>
<el-table-column label="剩余" min-width="130" prop="remainingTokens" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<div class="token-cell remaining">
<span
class="token-value"
:style="{ color: row.remainingTokens > 0 ? '#67c23a' : '#f56c6c', fontWeight: '600' }"
>
{{ formatNumber(row.remainingTokens) }}
</span>
<span class="token-unit"></span>
</div>
</template>
</el-table-column>
<el-table-column label="使用率" min-width="130" align="center" header-align="center" resizable>
<template #default="{ row }">
<div class="usage-progress-cell">
<el-progress
:percentage="row.totalTokens > 0 ? Number(((row.usedTokens / row.totalTokens) * 100).toFixed(1)) : 0"
:color="getUsageColor(row.usedTokens, row.totalTokens)"
:stroke-width="8"
:show-text="true"
:text-inside="false"
>
<template #default="{ percentage }">
<span class="percentage-text">{{ percentage }}%</span>
</template>
</el-progress>
</div>
</template>
</el-table-column>
<el-table-column label="购买金额" min-width="110" prop="purchaseAmount" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<span class="amount-cell">¥{{ row.purchaseAmount.toFixed(2) }}</span>
</template>
</el-table-column>
<el-table-column label="状态" min-width="90" prop="isActive" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<el-tag :type="row.isActive ? 'success' : 'info'" size="small" effect="dark">
{{ row.isActive ? '激活' : '未激活' }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="创建时间" min-width="170" prop="creationTime" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<div v-if="row.creationTime" class="creation-cell">
<el-icon class="creation-icon">
<Clock />
</el-icon>
<span>{{ formatDateTime(row.creationTime) }}</span>
</div>
<span v-else class="no-data">-</span>
</template>
</el-table-column>
<el-table-column label="到期时间" min-width="170" prop="expireDateTime" sortable align="center" header-align="center" resizable>
<template #default="{ row }">
<div v-if="row.expireDateTime" class="expire-cell">
<el-icon class="expire-icon">
<Clock />
</el-icon>
<span>{{ formatDateTime(row.expireDateTime) }}</span>
</div>
<span v-else class="no-data">-</span>
</template>
</el-table-column>
<el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip align="center" header-align="center" resizable>
<template #default="{ row }">
<span class="remark-cell">{{ row.remark || '-' }}</span>
</template>
</el-table-column>
</el-table>
<!-- 空状态 -->
<div v-if="!usageList.length && !listLoading" class="empty-container">
<el-empty :description="hasActiveFilters ? '当前筛选条件下无数据' : '暂无明细记录'">
<el-button v-if="hasActiveFilters" type="primary" @click="resetFilters">
清除筛选
</el-button>
</el-empty>
</div>
<!-- 分页 -->
<div v-if="totalCount > 0" class="pagination-container">
<el-pagination
v-model:current-page="currentPage"
v-model:page-size="pageSize"
:page-sizes="[10, 20, 50, 100]"
:total="totalCount"
layout="total, sizes, prev, pager, next, jumper"
prev-text="上一页"
next-text="下一页"
@size-change="handleSizeChange"
@current-change="handlePageChange"
/>
</div>
</el-card>
</template>
<style scoped lang="scss">
/* 额度明细列表卡片 */
.usage-list-card {
border-radius: 16px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
border: 1px solid #f0f2f5;
transition: all 0.3s;
&:hover {
box-shadow: 0 8px 24px rgba(102, 126, 234, 0.12);
border-color: #667eea;
}
:deep(.el-card__header) {
background: linear-gradient(to bottom, #fafbfc 0%, #ffffff 100%);
border-bottom: 2px solid #f0f2f5;
}
}
.list-header {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.list-header .header-left {
display: flex;
align-items: center;
gap: 12px;
}
.header-icon {
font-size: 24px;
color: #f59e0b;
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
padding: 8px;
border-radius: 8px;
}
.header-text {
display: flex;
flex-direction: column;
gap: 4px;
}
.header-title {
font-size: 18px;
font-weight: 700;
color: #1a1a1a;
}
.header-subtitle {
font-size: 13px;
color: #909399;
}
.header-right {
display: flex;
align-items: center;
gap: 12px;
}
.count-tag {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 16px;
font-weight: 600;
border-radius: 20px;
.el-icon {
font-size: 14px;
}
}
/* 筛选工具栏 */
.filter-toolbar {
margin-bottom: 20px;
padding: 20px;
background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
border-radius: 12px;
border: 1px solid #e8eaed;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.filter-row {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
}
.filter-tip {
display: flex;
align-items: center;
gap: 6px;
margin-top: 12px;
padding: 8px 12px;
background: #fff;
border-radius: 4px;
font-size: 13px;
color: #606266;
border-left: 3px solid #409eff;
}
.filter-item {
flex: 0 0 auto;
}
.date-picker {
width: 320px;
}
.free-select {
width: 140px;
}
.filter-actions {
margin-left: auto;
display: flex;
gap: 8px;
}
/* 表格样式 */
.usage-table {
width: 100%;
}
.package-name-cell {
display: flex;
align-items: center;
gap: 8px;
}
.package-icon {
font-size: 16px;
flex-shrink: 0;
}
.usage-progress-cell {
display: flex;
align-items: center;
gap: 8px;
padding: 0 12px;
}
.usage-progress-cell :deep(.el-progress) {
flex: 1;
}
.usage-progress-cell :deep(.el-progress__text) {
font-size: 13px !important;
font-weight: 600;
min-width: 45px;
text-align: right;
}
.percentage-text {
font-size: 13px;
font-weight: 600;
}
.token-cell {
display: flex;
align-items: baseline;
gap: 4px;
justify-content: center;
}
.token-value {
font-size: 14px;
font-weight: 500;
color: #303133;
}
.token-unit {
font-size: 12px;
color: #909399;
}
.amount-cell {
font-weight: 600;
color: #f56c6c;
}
.creation-cell {
display: flex;
align-items: center;
gap: 6px;
color: #606266;
}
.creation-icon {
font-size: 14px;
color: #67c23a;
}
.expire-cell {
display: flex;
align-items: center;
gap: 6px;
color: #606266;
}
.expire-icon {
font-size: 14px;
color: #909399;
}
.remark-cell {
color: #606266;
font-size: 13px;
}
.no-data {
color: #c0c4cc;
}
/* 空状态 */
.empty-container {
padding: 40px 0;
}
/* 分页容器 */
.pagination-container {
margin-top: 20px;
padding: 20px 0;
display: flex;
justify-content: center;
border-top: 2px solid #f0f2f5;
:deep(.el-pagination) {
gap: 8px;
.btn-prev,
.btn-next {
border-radius: 8px;
padding: 0 16px;
border: 1px solid #dcdfe6;
background: #fff;
font-weight: 500;
&:hover {
color: #667eea;
border-color: #667eea;
background: #f5f7fa;
}
}
.el-pager li {
border-radius: 8px;
min-width: 36px;
height: 36px;
line-height: 36px;
border: 1px solid transparent;
transition: all 0.3s;
&:hover {
color: #667eea;
background: #f5f7fa;
}
&.is-active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
border-color: transparent;
}
}
.el-pagination__sizes {
.el-select {
.el-input__wrapper {
border-radius: 8px;
}
}
}
.el-pagination__jump {
.el-input__wrapper {
border-radius: 8px;
}
}
}
}
/* 响应式布局 */
@media (max-width: 768px) {
.list-header {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.header-icon {
font-size: 20px;
padding: 6px;
}
.header-title {
font-size: 16px;
}
.header-subtitle {
font-size: 12px;
}
.header-right {
width: 100%;
}
.count-tag {
width: 100%;
justify-content: center;
}
/* 移动端筛选工具栏 */
.filter-toolbar {
padding: 16px;
}
.filter-row {
flex-direction: column;
align-items: stretch;
gap: 10px;
}
.filter-item {
width: 100%;
}
.date-picker,
.free-select {
width: 100%;
}
.filter-actions {
margin-left: 0;
display: flex;
gap: 8px;
}
.filter-actions .el-button {
flex: 1;
}
/* 移动端分页 */
.pagination-container {
padding: 16px 0;
}
.pagination-container :deep(.el-pagination) {
flex-wrap: wrap;
justify-content: center;
gap: 6px;
.btn-prev,
.btn-next {
padding: 0 12px;
font-size: 13px;
}
.el-pager li {
min-width: 32px;
height: 32px;
line-height: 32px;
font-size: 13px;
}
}
}
/* 平板适配 */
@media (min-width: 769px) and (max-width: 1024px) {
.filter-row {
gap: 10px;
}
.search-input {
width: 180px;
}
.date-picker {
width: 280px;
}
}
</style>

View File

@@ -0,0 +1,358 @@
<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { computed, ref, watch } from 'vue';
interface TokenFormData {
id?: string;
name: string;
expireTime: string;
premiumQuotaLimit: number | null;
quotaUnit: string;
}
interface Props {
visible: boolean;
mode: 'create' | 'edit';
formData?: TokenFormData;
}
const props = withDefaults(defineProps<Props>(), {
visible: false,
mode: 'create',
formData: () => ({
name: '',
expireTime: '',
premiumQuotaLimit: 0,
quotaUnit: '万',
}),
});
const emit = defineEmits<{
'update:visible': [value: boolean];
'confirm': [data: TokenFormData];
}>();
const localFormData = ref<TokenFormData>({
name: '',
expireTime: '',
premiumQuotaLimit: 0,
quotaUnit: '万',
});
const submitting = ref(false);
const neverExpire = ref(false); // 永不过期开关
const unlimitedQuota = ref(false); // 无限制额度开关
const quotaUnitOptions = [
{ label: '个', value: '个', multiplier: 1 },
{ label: '十', value: '十', multiplier: 10 },
{ label: '百', value: '百', multiplier: 100 },
{ label: '千', value: '千', multiplier: 1000 },
{ label: '万', value: '万', multiplier: 10000 },
{ label: '亿', value: '亿', multiplier: 100000000 },
];
// 监听visible变化重置表单
watch(() => props.visible, (newVal) => {
if (newVal) {
if (props.mode === 'edit' && props.formData) {
// 编辑模式:转换后端数据为展示数据
const quota = props.formData.premiumQuotaLimit || 0;
let displayValue = quota;
let unit = '个';
// 判断是否无限制
unlimitedQuota.value = quota === 0;
if (!unlimitedQuota.value) {
// 自动选择合适的单位
if (quota >= 100000000 && quota % 100000000 === 0) {
displayValue = quota / 100000000;
unit = '亿';
}
else if (quota >= 10000 && quota % 10000 === 0) {
displayValue = quota / 10000;
unit = '万';
}
else if (quota >= 1000 && quota % 1000 === 0) {
displayValue = quota / 1000;
unit = '千';
}
else if (quota >= 100 && quota % 100 === 0) {
displayValue = quota / 100;
unit = '百';
}
else if (quota >= 10 && quota % 10 === 0) {
displayValue = quota / 10;
unit = '十';
}
}
// 判断是否永不过期
neverExpire.value = !props.formData.expireTime;
localFormData.value = {
...props.formData,
premiumQuotaLimit: displayValue,
quotaUnit: unit,
};
}
else {
// 新增模式:重置表单
localFormData.value = {
name: '',
expireTime: '',
premiumQuotaLimit: 1,
quotaUnit: '万',
};
neverExpire.value = false;
unlimitedQuota.value = false;
}
submitting.value = false;
}
});
// 监听永不过期开关
watch(neverExpire, (newVal) => {
if (newVal) {
localFormData.value.expireTime = '';
}
});
// 监听无限制开关
watch(unlimitedQuota, (newVal) => {
if (newVal) {
localFormData.value.premiumQuotaLimit = 0;
}
});
// 关闭对话框
function handleClose() {
if (submitting.value)
return;
emit('update:visible', false);
}
// 确认提交
async function handleConfirm() {
if (!localFormData.value.name.trim()) {
ElMessage.warning('请输入API密钥名称');
return;
}
if (!neverExpire.value && !localFormData.value.expireTime) {
ElMessage.warning('请选择过期时间');
return;
}
if (!unlimitedQuota.value && localFormData.value.premiumQuotaLimit <= 0) {
ElMessage.warning('请输入有效的配额限制');
return;
}
submitting.value = true;
try {
// 将展示值转换为实际值
let actualQuota = null;
if (!unlimitedQuota.value) {
const unit = quotaUnitOptions.find(u => u.value === localFormData.value.quotaUnit);
actualQuota = localFormData.value.premiumQuotaLimit * (unit?.multiplier || 1);
}
const submitData: TokenFormData = {
...localFormData.value,
expireTime: neverExpire.value ? '' : localFormData.value.expireTime,
premiumQuotaLimit: actualQuota,
};
emit('confirm', submitData);
}
finally {
// 注意:这里不设置 submitting.value = false
// 因为父组件会关闭对话框watch会重置状态
}
}
const dialogTitle = computed(() => props.mode === 'create' ? '新增 API密钥' : '编辑 API密钥');
</script>
<template>
<el-dialog
:model-value="visible"
:title="dialogTitle"
width="540px"
:close-on-click-modal="false"
:show-close="!submitting"
@close="handleClose"
>
<el-form :model="localFormData" label-width="110px" label-position="right">
<el-form-item label="API密钥名称" required>
<el-input
v-model="localFormData.name"
placeholder="例如:生产环境、测试环境、开发环境"
maxlength="50"
show-word-limit
clearable
:disabled="submitting"
>
<template #prefix>
<el-icon><i-ep-collection-tag /></el-icon>
</template>
</el-input>
</el-form-item>
<el-form-item label="过期时间">
<div class="form-item-with-switch">
<el-switch
v-model="neverExpire"
active-text="永不过期"
:disabled="submitting"
class="expire-switch"
/>
<el-date-picker
v-if="!neverExpire"
v-model="localFormData.expireTime"
type="datetime"
placeholder="选择过期时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DDTHH:mm:ss"
style="width: 100%"
clearable
:disabled="submitting"
:disabled-date="(time: Date) => time.getTime() < Date.now()"
>
<template #prefix>
<el-icon><i-ep-clock /></el-icon>
</template>
</el-date-picker>
</div>
<div v-if="!neverExpire" class="form-hint">
<el-icon><i-ep-warning /></el-icon>
API密钥将在过期时间后自动失效
</div>
</el-form-item>
<el-form-item label="配额限制">
<div class="form-item-with-switch">
<el-switch
v-model="unlimitedQuota"
active-text="无限制"
:disabled="submitting"
class="quota-switch"
/>
<div v-if="!unlimitedQuota" class="quota-input-group">
<el-input-number
v-model="localFormData.premiumQuotaLimit"
:min="1"
:precision="0"
:controls="true"
controls-position="right"
placeholder="请输入配额"
class="quota-number"
:disabled="submitting"
/>
<el-select
v-model="localFormData.quotaUnit"
class="quota-unit"
placeholder="单位"
:disabled="submitting"
>
<el-option
v-for="option in quotaUnitOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</div>
</div>
<div v-if="!unlimitedQuota" class="form-hint">
<el-icon><i-ep-info-filled /></el-icon>
超出配额后API密钥将无法继续使用
</div>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button :disabled="submitting" @click="handleClose">
取消
</el-button>
<el-button
type="primary"
:loading="submitting"
:disabled="submitting"
@click="handleConfirm"
>
{{ mode === 'create' ? '创建' : '保存' }}
</el-button>
</div>
</template>
</el-dialog>
</template>
<style scoped lang="scss">
.form-item-with-switch {
width: 100%;
display: flex;
flex-direction: column;
gap: 12px;
}
.expire-switch,
.quota-switch {
--el-switch-on-color: #67c23a;
}
.quota-input-group {
display: flex;
gap: 10px;
width: 100%;
}
.quota-number {
flex: 1;
:deep(.el-input__wrapper) {
width: 100%;
}
}
.quota-unit {
width: 100px;
}
.form-hint {
display: flex;
align-items: center;
gap: 6px;
margin-top: 8px;
padding: 8px 12px;
font-size: 13px;
color: #606266;
background: #f4f4f5;
border-radius: 6px;
border-left: 3px solid #409eff;
.el-icon {
font-size: 14px;
color: #409eff;
flex-shrink: 0;
}
}
.dialog-footer {
display: flex;
justify-content: flex-end;
gap: 12px;
}
:deep(.el-form-item__label) {
font-weight: 600;
color: #303133;
}
:deep(.el-input__prefix) {
color: #909399;
}
</style>

View File

@@ -11,7 +11,7 @@ import {
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { getLast7DaysTokenUsage, getModelTokenUsage } from '@/api';
import { getLast7DaysTokenUsage, getModelTokenUsage, getSelectableTokenInfo } from '@/api';
// 注册必要的组件
echarts.use([
@@ -48,16 +48,54 @@ const totalTokens = ref(0);
const usageData = ref<any[]>([]);
const modelUsageData = ref<any[]>([]);
// Token选择相关
const selectedTokenId = ref<string>(''); // 空字符串表示查询全部
const tokenOptions = ref<any[]>([]);
const tokenOptionsLoading = ref(false);
// 计算属性:是否有模型数据
const hasModelData = computed(() => modelUsageData.value.length > 0);
// 计算属性当前选择的token名称
const selectedTokenName = computed(() => {
if (!selectedTokenId.value)
return '全部API密钥';
const token = tokenOptions.value.find(t => t.tokenId === selectedTokenId.value);
return token?.name || '未知API密钥';
});
// 获取可选择的Token列表
async function fetchTokenOptions() {
try {
tokenOptionsLoading.value = true;
const res = await getSelectableTokenInfo();
if (res.data) {
// 不再过滤禁用的token全部显示
tokenOptions.value = res.data;
}
}
catch (error) {
console.error('获取API密钥列表失败:', error);
ElMessage.error('获取TAPI密钥列表失败');
}
finally {
tokenOptionsLoading.value = false;
}
}
// Token选择变化
function handleTokenChange() {
fetchUsageData();
}
// 获取用量数据
async function fetchUsageData() {
loading.value = true;
try {
const tokenId = selectedTokenId.value || undefined;
const [res, res2] = await Promise.all([
getLast7DaysTokenUsage(),
getModelTokenUsage(),
getLast7DaysTokenUsage(tokenId),
getModelTokenUsage(tokenId),
]);
usageData.value = res.data || [];
@@ -235,49 +273,47 @@ function updatePieChart() {
formatter: '{a} <br/>{b}: {c} tokens ({d}%)',
},
legend: {
orient: isManyItems ? 'vertical' : 'horizontal',
right: isManyItems ? 10 : 'auto',
bottom: isManyItems ? 0 : 10,
type: isManyItems ? 'scroll' : 'plain',
pageIconColor: '#3a4de9',
pageIconInactiveColor: '#ccc',
pageTextStyle: { color: '#333' },
itemGap: isSmallContainer ? 5 : 10,
itemWidth: isSmallContainer ? 15 : 25,
itemHeight: isSmallContainer ? 10 : 14,
textStyle: {
fontSize: isSmallContainer ? 10 : 12,
},
formatter(name: string) {
return name.length > 15 ? `${name.substring(0, 12)}...` : name;
},
data: data.map(item => item.name),
show: false, // 隐藏图例,使用标签线代替
},
series: [
{
name: '模型用量',
type: 'pie',
radius: ['50%', '70%'],
center: isManyItems ? ['40%', '50%'] : ['50%', '50%'],
avoidLabelOverlap: false,
center: ['50%', '50%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2,
},
label: {
show: false,
position: 'center',
show: true,
position: 'outside',
formatter: '{b}: {d}%',
fontSize: 13,
fontWeight: 600,
color: '#333',
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontSize: 16,
fontWeight: 'bold',
},
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.3)',
},
},
labelLine: {
show: false,
show: true,
length: 15,
length2: 10,
lineStyle: {
width: 1.5,
},
},
data,
},
@@ -453,6 +489,7 @@ watch([pieContainerSize.width, barContainerSize.width], () => {
onMounted(() => {
initCharts();
fetchTokenOptions();
fetchUsageData();
});
@@ -475,19 +512,56 @@ onBeforeUnmount(() => {
<el-icon><PieChart /></el-icon>
Token用量统计
</h2>
<el-button
:icon="FullScreen"
circle
plain
size="small"
@click="toggleFullscreen"
/>
<div class="header-actions">
<el-select
v-model="selectedTokenId"
placeholder="选择API密钥"
clearable
filterable
:loading="tokenOptionsLoading"
class="token-selector"
@change="handleTokenChange"
>
<el-option label="全部Token" value="">
<div class="token-option">
<el-icon class="option-icon all-icon">
<i-ep-folder-opened />
</el-icon>
<span class="option-label">全部Token</span>
</div>
</el-option>
<el-option
v-for="token in tokenOptions"
:key="token.tokenId"
:label="token.name"
:value="token.tokenId"
:disabled="token.isDisabled"
>
<div class="token-option" :class="{ 'disabled-token': token.isDisabled }">
<el-icon class="option-icon" :class="{ 'disabled-icon': token.isDisabled }">
<i-ep-key />
</el-icon>
<span class="option-label">{{ token.name }}</span>
<el-tag v-if="token.isDisabled" type="info" size="small" effect="plain" class="disabled-tag">
已禁用
</el-tag>
</div>
</el-option>
</el-select>
<el-button
:icon="FullScreen"
circle
plain
size="small"
@click="toggleFullscreen"
/>
</div>
</div>
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">📊 近七天每日Token消耗量</span>
<span class="card-title">📊 近七天每日Token消耗量{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
<el-tag type="primary" size="large" effect="dark">
近七日总计: {{ totalTokens }} tokens
</el-tag>
@@ -501,7 +575,7 @@ onBeforeUnmount(() => {
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">🥧 各模型Token消耗占比</span>
<span class="card-title">🥧 各模型Token消耗占比{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
</div>
</template>
<div class="chart-container">
@@ -512,7 +586,7 @@ onBeforeUnmount(() => {
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">📈 各模型总Token消耗量</span>
<span class="card-title">📈 各模型总Token消耗量{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
</div>
</template>
<div class="chart-container">
@@ -560,6 +634,62 @@ onBeforeUnmount(() => {
border-bottom: 2px solid #e9ecef;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.token-selector {
width: 240px;
}
.token-option {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
&.disabled-token {
opacity: 0.6;
.option-label {
text-decoration: line-through;
color: #909399;
}
}
}
.option-icon {
color: #667eea;
font-size: 16px;
flex-shrink: 0;
&.all-icon {
color: #409eff;
}
&.disabled-icon {
color: #c0c4cc;
}
}
.option-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.disabled-tag {
margin-left: auto;
flex-shrink: 0;
font-size: 11px;
padding: 0 6px;
height: 18px;
line-height: 18px;
}
.header h2 {
display: flex;
align-items: center;

View File

@@ -0,0 +1,301 @@
import type { Activity, Announcement, CarouselItem, SystemAnnouncementResponse } from '@/api'
/**
* 模拟数据 - 系统公告
* 这些数据可以用于开发和测试实际使用时应从后端API获取
*/
// 轮播图数据
export const mockCarousels: CarouselItem[] = [
{
id: 1,
imageUrl: 'https://images.unsplash.com/photo-1607827448387-a67db1383b59?w=800&h=400&fit=crop',
title: '新年特惠活动',
link: '/activity/1',
},
{
id: 2,
imageUrl: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=800&h=400&fit=crop',
title: '新功能上线',
link: '/activity/2',
},
{
id: 3,
imageUrl: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&h=400&fit=crop',
title: '限时优惠',
link: '/activity/3',
},
]
// 活动数据
export const mockActivities: Activity[] = [
{
id: 1,
title: '新年特惠活动',
description: '参与新年特惠活动即可获得丰厚奖励。活动期间充值即送额外积分最高可获得50%额外积分奖励!',
content: `
<h2>活动详情</h2>
<p>为了感谢各位用户的支持,我们特别推出新年特惠活动!</p>
<h3>活动时间</h3>
<p>2025年1月1日 00:00 - 2025年1月31日 23:59</p>
<h3>活动规则</h3>
<ul>
<li>充值满100元赠送10%积分</li>
<li>充值满500元赠送20%积分</li>
<li>充值满1000元赠送30%积分</li>
<li>充值满5000元赠送50%积分</li>
</ul>
<h3>注意事项</h3>
<ol>
<li>每个用户在活动期间最多可参与5次</li>
<li>赠送的积分将在充值成功后24小时内到账</li>
<li>本活动最终解释权归平台所有</li>
</ol>
<blockquote>
机会难得,不要错过!
</blockquote>
`,
coverImage: 'https://images.unsplash.com/photo-1607827448387-a67db1383b59?w=1200&h=600&fit=crop',
startTime: '2025-01-01T00:00:00Z',
endTime: '2025-01-31T23:59:59Z',
status: 'active',
createdAt: '2024-12-25T10:00:00Z',
updatedAt: '2024-12-26T15:30:00Z',
},
{
id: 2,
title: 'AI功能免费体验',
description: '全新AI功能上线限时免费体验。包括智能对话、图像生成、代码辅助等多项功能。',
content: `
<h2>新功能介绍</h2>
<p>我们很高兴地宣布全新的AI功能已经正式上线</p>
<h3>功能亮点</h3>
<ul>
<li><strong>智能对话</strong>: 更自然的对话体验,支持上下文理解</li>
<li><strong>图像生成</strong>: 通过文字描述生成精美图片</li>
<li><strong>代码辅助</strong>: 智能代码补全和错误检测</li>
<li><strong>文档分析</strong>: 快速提取文档关键信息</li>
</ul>
<h3>体验时间</h3>
<p>2025年1月1日 - 2025年2月28日</p>
<p>在体验期间,所有功能完全免费使用!</p>
`,
coverImage: 'https://images.unsplash.com/photo-1557683316-973673baf926?w=1200&h=600&fit=crop',
startTime: '2025-01-01T00:00:00Z',
endTime: '2025-02-28T23:59:59Z',
status: 'active',
createdAt: '2024-12-28T08:00:00Z',
updatedAt: '2024-12-28T08:00:00Z',
},
{
id: 3,
title: '推荐好友得奖励',
description: '邀请好友注册使用,双方均可获得积分奖励。推荐越多,奖励越多!',
content: `
<h2>推荐计划</h2>
<p>邀请您的朋友一起体验我们的服务,双方都能获得丰厚奖励!</p>
<h3>奖励规则</h3>
<ul>
<li>好友通过您的邀请链接注册您和好友各得50积分</li>
<li>好友首次充值您额外获得其充值金额10%的积分</li>
<li>推荐5位好友额外奖励200积分</li>
<li>推荐10位好友额外奖励500积分</li>
</ul>
<h3>如何参与</h3>
<ol>
<li>登录您的账户</li>
<li>进入"推荐好友"页面</li>
<li>复制您的专属邀请链接</li>
<li>分享给您的朋友</li>
</ol>
`,
status: 'active',
createdAt: '2024-12-20T10:00:00Z',
},
]
// 公告数据
export const mockAnnouncements: Announcement[] = [
{
id: 1,
title: '系统维护升级公告',
content: `
<p>尊敬的用户:</p>
<p>为了给您提供更好的服务体验,我们计划于<strong>2025年1月10日 22:00 - 2025年1月11日 02:00</strong>对系统进行维护升级。</p>
<h3>维护内容</h3>
<ul>
<li>优化系统性能,提升响应速度</li>
<li>修复已知问题</li>
<li>更新安全补丁</li>
<li>新增部分功能</li>
</ul>
<h3>影响范围</h3>
<p>维护期间,系统将暂时无法访问,给您带来不便敬请谅解。</p>
<p>如有紧急问题请联系客服service@example.com</p>
<p>感谢您的理解与支持!</p>
`,
type: 'latest',
isImportant: true,
publishTime: '2025-01-05T10:00:00Z',
createdAt: '2025-01-05T09:30:00Z',
},
{
id: 2,
title: '隐私政策更新通知',
content: `
<p>尊敬的用户:</p>
<p>我们更新了隐私政策,新政策将于<strong>2025年1月15日</strong>生效。</p>
<h3>主要变更</h3>
<ul>
<li>明确了数据收集和使用范围</li>
<li>增加了用户数据控制权说明</li>
<li>完善了第三方数据共享规则</li>
</ul>
<p>详细内容请查看完整的<a href="/privacy-policy" target="_blank">隐私政策</a>。</p>
<p>如有疑问,欢迎联系我们。</p>
`,
type: 'latest',
isImportant: false,
publishTime: '2025-01-03T14:00:00Z',
createdAt: '2025-01-03T13:30:00Z',
},
{
id: 3,
title: 'API接口升级通知',
content: `
<p>开发者们注意:</p>
<p>我们的API接口将进行版本升级新版本为<code>v2.0</code>。</p>
<h3>升级时间</h3>
<p>2025年2月1日</p>
<h3>主要变化</h3>
<ul>
<li>优化了响应数据结构</li>
<li>新增多个端点</li>
<li>提升了并发处理能力</li>
</ul>
<p>旧版本API将继续维护至2025年6月1日。</p>
`,
type: 'history',
isImportant: false,
publishTime: '2024-12-28T10:00:00Z',
createdAt: '2024-12-28T09:00:00Z',
},
{
id: 4,
title: '新年假期客服安排',
content: `
<p>尊敬的用户:</p>
<p>新年假期期间1月1日-1月3日客服工作时间调整为</p>
<ul>
<li>在线客服10:00 - 18:00</li>
<li>邮件客服:正常响应,回复时间可能延迟</li>
</ul>
<p>1月4日起恢复正常工作时间。</p>
`,
type: 'history',
isImportant: false,
publishTime: '2024-12-25T15:00:00Z',
createdAt: '2024-12-25T14:00:00Z',
},
{
id: 5,
title: '用户协议更新',
content: `
<p>我们更新了用户服务协议,主要涉及:</p>
<ul>
<li>账户安全责任条款</li>
<li>服务使用规范</li>
<li>争议解决方式</li>
</ul>
<p>继续使用服务即表示您同意新的用户协议。</p>
`,
type: 'history',
isImportant: false,
publishTime: '2024-12-20T10:00:00Z',
createdAt: '2024-12-20T09:00:00Z',
},
]
// 完整的系统公告响应数据
export const mockSystemAnnouncementData: SystemAnnouncementResponse = {
carousels: mockCarousels,
activities: mockActivities,
announcements: mockAnnouncements,
}
/**
* 模拟API延迟
*/
export function mockDelay(ms: number = 500): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
/**
* 模拟获取系统公告API
*/
export async function getMockSystemAnnouncements(): Promise<{ data: SystemAnnouncementResponse }> {
await mockDelay()
return { data: mockSystemAnnouncementData }
}
/**
* 模拟获取活动详情API
*/
export async function getMockActivityDetail(id: string | number) {
await mockDelay()
const activity = mockActivities.find(a => a.id.toString() === id.toString())
if (!activity) {
throw new Error('活动不存在')
}
return {
data: {
...activity,
views: Math.floor(Math.random() * 10000) + 1000,
participantCount: Math.floor(Math.random() * 1000) + 100,
},
}
}
/**
* 模拟获取公告详情API
*/
export async function getMockAnnouncementDetail(id: string | number) {
await mockDelay()
const announcement = mockAnnouncements.find(a => a.id.toString() === id.toString())
if (!announcement) {
throw new Error('公告不存在')
}
return {
data: {
...announcement,
views: Math.floor(Math.random() * 10000) + 1000,
},
}
}

View File

@@ -0,0 +1,334 @@
import { driver } from 'driver.js';
import { useGuideTourStore } from '@/stores';
import 'driver.js/dist/driver.css';
// 引导步骤接口
interface TourStep {
element: string;
popover: {
title: string;
description: string;
side?: 'top' | 'right' | 'bottom' | 'left';
align?: 'start' | 'center' | 'end';
};
onHighlightStarted?: () => void;
onDeselected?: () => void;
}
export function useGuideTour() {
const guideTourStore = useGuideTourStore();
// 创建 driver 实例
const driverInstance = ref<ReturnType<typeof driver> | null>(null);
// 初始化 driver
function initDriver() {
driverInstance.value = driver({
showProgress: true,
animate: true,
allowClose: true,
overlayClickNext: false,
stagePadding: 10,
stageRadius: 8,
popoverClass: 'guide-tour-popover',
nextBtnText: '下一步',
prevBtnText: '上一步',
doneBtnText: '完成',
progressText: '{{current}} / {{total}}',
onDestroyed: () => {
guideTourStore.setCurrentPhase('idle');
},
});
}
// Header 区域引导步骤(包含聊天功能)
const headerSteps: TourStep[] = [
{
element: '[data-tour="tutorial-btn"]',
popover: {
title: '新手教程',
description: '欢迎使用意心AI-YiXinAI点击这里可以随时重新查看新手引导教程帮助您快速了解系统功能。',
side: 'bottom',
align: 'center',
},
},
{
element: '[data-tour="model-select"]',
popover: {
title: '模型选择',
description: '点击这里可以切换不同的AI模型每个模型有不同的特点和能力。VIP用户可以更多高级模型。',
side: 'top',
align: 'start',
},
},
{
element: '[data-tour="chat-sender"]',
popover: {
title: '对话输入框',
description: '在这里输入您的问题或指令按回车或点击发送按钮即可与AI对话。支持语音输入',
side: 'top',
align: 'center',
},
},
{
element: '[data-tour="announcement-btn"]',
popover: {
title: '公告/活动',
description: '这里会显示系统公告和最新活动信息,请及时查看以获取重要通知和福利活动。',
side: 'bottom',
align: 'center',
},
},
{
element: '[data-tour="ai-tutorial-link"]',
popover: {
title: 'AI使用教程',
description: '点击这里可以跳转到YiXinAI玩法指南专栏学习更多AI使用技巧和最佳实践。',
side: 'bottom',
align: 'center',
},
},
{
element: '[data-tour="buy-btn"]',
popover: {
title: '立即购买',
description: '点击这里可以成为VIP会员和升级尊享服务享受更多专属服务和权益。',
side: 'bottom',
align: 'center',
},
},
{
element: '[data-tour="user-avatar"]',
popover: {
title: '用户中心',
description: '点击头像可以进入用户中心管理您的账户信息、查看使用统计、API密钥等。接下来将为您详细介绍用户中心的各项功能。',
side: 'bottom',
align: 'end',
},
},
];
// 用户中心弹窗引导步骤
const userCenterSteps: TourStep[] = [
{
element: '[data-tour="user-nav-menu"]',
popover: {
title: '导航菜单',
description: '左侧是功能导航菜单,您可以切换不同的功能模块。接下来我们将逐一介绍各个功能。',
side: 'right',
align: 'start',
},
},
{
element: '[data-tour="nav-user"]',
popover: {
title: '用户信息',
description: '查看您的个人信息,包括头像、昵称等。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('user');
},
},
{
element: '[data-tour="nav-apiKey"]',
popover: {
title: 'API密钥',
description: '管理您的API密钥用于第三方接入和开发集成。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('apiKey');
},
},
{
element: '[data-tour="nav-rechargeLog"]',
popover: {
title: '充值记录',
description: '查看您的充值历史和交易记录,了解消费明细。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('rechargeLog');
},
},
{
element: '[data-tour="nav-usageStatistics"]',
popover: {
title: '用量统计',
description: '查看您的AI模型使用情况和消费统计掌握使用详情。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('usageStatistics');
},
},
{
element: '[data-tour="nav-premiumService"]',
popover: {
title: '尊享服务',
description: '了解尊享服务包专属特权和服务,我们将详细介绍这个页面的功能。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('premiumService');
},
},
{
element: '[data-tour="premium-package-info"]',
popover: {
title: '套餐信息',
description: '这里显示您的尊享服务套餐详情,包括总额度、已使用额度、剩余额度等信息。',
side: 'left',
align: 'start',
},
},
{
element: '[data-tour="premium-usage-list"]',
popover: {
title: '额度明细列表',
description: '查看您的额度使用明细记录,包括每次使用的时间、消耗的额度等详细信息。',
side: 'left',
align: 'start',
},
},
{
element: '[data-tour="nav-dailyTask"]',
popover: {
title: '每日任务',
description: '完成每日任务获取额外奖励,提升您的使用体验。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('dailyTask');
},
},
{
element: '[data-tour="nav-cardFlip"]',
popover: {
title: '每周邀请',
description: '邀请好友加入,获得丰厚奖励。接下来将详细介绍这个页面的各项功能。',
side: 'right',
align: 'center',
},
onHighlightStarted: () => {
guideTourStore.changeUserCenterNav('cardFlip');
},
},
{
element: '[data-tour="card-flip-area"]',
popover: {
title: '每周免费翻牌',
description: '每周您有10次免费翻牌机会前7次为基础免费次数。翻牌可获得Token奖励幸运值随着翻牌次数增加而提升。',
side: 'left',
align: 'start',
},
},
{
element: '[data-tour="use-invite-code-btn"]',
popover: {
title: '使用邀请码',
description: '输入好友的邀请码双方各增加1次翻牌机会填写邀请码后第8-10次翻牌必定中奖每次奖励最大额度翻倍',
side: 'left',
align: 'center',
},
},
{
element: '[data-tour="my-invite-code-btn"]',
popover: {
title: '我的邀请码',
description: '生成您的专属邀请码分享给好友。好友使用您的邀请码后双方各获得1次额外翻牌机会。您可以复制邀请码或分享带邀请码的链接。',
side: 'left',
align: 'center',
},
},
];
// 开始 Header 引导
async function startHeaderTour() {
if (!driverInstance.value) {
initDriver();
}
guideTourStore.setCurrentPhase('header');
// 等待 DOM 更新
await nextTick();
// 配置完成回调,触发用户中心引导
driverInstance.value?.setConfig({
onDestroyStarted: () => {
if (!driverInstance.value?.hasNextStep()) {
// Header 引导完成,触发打开用户中心弹窗
guideTourStore.triggerUserCenterTour();
}
driverInstance.value?.destroy();
},
});
driverInstance.value?.setSteps(headerSteps);
driverInstance.value?.drive();
}
// 开始用户中心引导
async function startUserCenterTour() {
if (!driverInstance.value) {
initDriver();
}
guideTourStore.setCurrentPhase('userCenter');
// 等待弹窗完全打开
await new Promise(resolve => setTimeout(resolve, 500));
// 配置完成回调,关闭弹窗并标记引导完成
driverInstance.value?.setConfig({
onDestroyStarted: () => {
if (!driverInstance.value?.hasNextStep()) {
// 用户中心引导完成,先关闭弹窗
guideTourStore.closeUserCenterDialog();
// 等待弹窗关闭后标记整个引导流程完成
setTimeout(() => {
guideTourStore.markTourCompleted();
}, 500);
}
driverInstance.value?.destroy();
},
});
driverInstance.value?.setSteps(userCenterSteps);
driverInstance.value?.drive();
}
// 开始完整引导流程
async function startFullTour() {
await startHeaderTour();
}
// 销毁 driver 实例
function destroyTour() {
if (driverInstance.value) {
driverInstance.value.destroy();
driverInstance.value = null;
}
}
// 组件卸载时清理
onUnmounted(() => {
destroyTour();
});
return {
startHeaderTour,
startUserCenterTour,
startFullTour,
destroyTour,
};
}

View File

@@ -1,13 +1,15 @@
<!-- 纵向布局作为基础布局 -->
<script setup lang="ts">
import SystemAnnouncementDialog from '@/components/SystemAnnouncementDialog/index.vue';
import { useSafeArea } from '@/hooks/useSafeArea';
import { useWindowWidthObserver } from '@/hooks/useWindowWidthObserver';
import Aside from '@/layouts/components/Aside/index.vue';
import Header from '@/layouts/components/Header/index.vue';
import Main from '@/layouts/components/Main/index.vue';
import { useDesignStore } from '@/stores';
import { useAnnouncementStore, useDesignStore } from '@/stores';
const designStore = useDesignStore();
const announcementStore = useAnnouncementStore();
const isCollapse = computed(() => designStore.isCollapse);
@@ -24,6 +26,16 @@ useSafeArea({
/** 监听窗口大小变化,折叠侧边栏 */
useWindowWidthObserver();
// 应用加载时检查是否需要显示公告弹窗
onMounted(() => {
console.log('announcementStore.shouldShowDialog--', announcementStore.shouldShowDialog);
// 检查是否应该显示弹窗(只有"关闭一周"且未超过7天才不显示
// 数据获取已移至 SystemAnnouncementDialog 组件内部,每次打开弹窗时都会获取最新数据
if (announcementStore.shouldShowDialog) {
announcementStore.openDialog();
}
});
</script>
<template>
@@ -39,6 +51,8 @@ useWindowWidthObserver();
</el-main>
</el-container>
</el-container>
<!-- 系统公告弹窗 -->
<SystemAnnouncementDialog />
</template>
<style lang="scss" scoped>

View File

@@ -385,5 +385,8 @@ function handleMenuCommand(command: string, item: ConversationItem<ChatSessionVo
{
z-index: 0 ;
}
.conversation-group .sticky-title{
z-index: 0 ;
}
}
</style>

View File

@@ -0,0 +1,88 @@
<script setup lang="ts">
// 打开AI使用教程跳转到外部链接
function openTutorial() {
window.open('https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde', '_blank');
}
</script>
<template>
<div class="ai-tutorial-btn-container" data-tour="ai-tutorial-link">
<div
class="ai-tutorial-btn"
title="点击跳转YiXinAI玩法指南专栏"
@click="openTutorial"
>
<!-- PC端显示文字 -->
<span class="pc-text">AI使用教程</span>
<!-- 移动端显示图标 -->
<svg
class="mobile-icon w-6 h-6"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 14l9-5-9-5-9 5 9 5z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 14l6.16-3.422A12.083 12.083 0 0118 13.5c0 2.579-3.582 4.5-6 4.5s-6-1.921-6-4.5c0-.432.075-.85.198-1.244L12 14z"
/>
</svg>
</div>
</div>
</template>
<style scoped lang="scss">
.ai-tutorial-btn-container {
display: flex;
align-items: center;
.ai-tutorial-btn {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 1.2rem;
font-weight: bold;
color: #E6A23C;
transition: all 0.2s;
&:hover {
color: #F1B44C;
transform: translateY(-1px);
}
// PC端显示文字隐藏图标
.pc-text {
display: inline;
margin: 0 12px;
}
.mobile-icon {
display: none;
}
}
}
// 移动端显示图标,隐藏文字
@media (max-width: 768px) {
.ai-tutorial-btn-container {
.ai-tutorial-btn {
.pc-text {
display: none;
}
.mobile-icon {
display: inline;
}
}
}
}
</style>

View File

@@ -0,0 +1,100 @@
<script setup lang="ts">
import { Bell } from '@element-plus/icons-vue';
import { storeToRefs } from 'pinia';
import { useAnnouncementStore } from '@/stores';
const announcementStore = useAnnouncementStore();
const { announcements } = storeToRefs(announcementStore);
// 计算未读公告数量(系统公告数量)
const unreadCount = computed(() => {
if (!Array.isArray(announcements.value))
return 0;
return announcements.value.filter(a => a.type === 'System').length;
});
// 打开公告弹窗
function openAnnouncement() {
announcementStore.openDialog();
}
</script>
<template>
<div class="announcement-btn-container" data-tour="announcement-btn">
<el-badge
is-dot
class="announcement-badge"
>
<!-- :value="unreadCount" -->
<!-- :hidden="unreadCount === 0" -->
<!-- :max="99" -->
<div
class="announcement-btn"
@click="openAnnouncement"
>
<!-- PC端显示文字 -->
<span class="pc-text">公告</span>
<!-- 移动端显示图标 -->
<el-icon class="mobile-icon" :size="20">
<Bell />
</el-icon>
</div>
</el-badge>
</div>
</template>
<style scoped lang="scss">
.announcement-btn-container {
display: flex;
align-items: center;
.announcement-badge {
:deep(.el-badge__content) {
background-color: #f56c6c;
border: none;
}
}
.announcement-btn {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 1.2rem;
font-weight: bold;
color: #409eff;
transition: all 0.2s;
&:hover {
color: #66b1ff;
transform: translateY(-1px);
}
// PC端显示文字隐藏图标
.pc-text {
display: inline;
margin: 0 12px;
}
.mobile-icon {
display: none;
}
}
}
// 移动端显示图标,隐藏文字
@media (max-width: 768px) {
.announcement-btn-container {
.announcement-btn {
.pc-text {
display: none;
}
.mobile-icon {
display: inline;
}
}
}
}
</style>

View File

@@ -6,7 +6,8 @@ import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import Popover from '@/components/Popover/index.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';
import { useUserStore } from '@/stores';
import { useGuideTour } from '@/hooks/useGuideTour';
import { useGuideTourStore, useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session';
import { showProductPackage } from '@/utils/product-package';
import { getUserProfilePicture, isUserVip } from '@/utils/user';
@@ -15,6 +16,8 @@ const router = useRouter();
const userStore = useUserStore();
const sessionStore = useSessionStore();
const guideTourStore = useGuideTourStore();
const { startUserCenterTour } = useGuideTour();
// const src = computed(
// () => userStore.userInfo?.avatar ?? 'https://avatars.githubusercontent.com/u/76239030',
@@ -48,6 +51,11 @@ const popoverList = ref([
title: '用户中心',
icon: 'settings-4-fill',
},
{
key: '6',
title: '新手引导',
icon: 'dashboard-fill',
},
{
key: '3',
divider: true,
@@ -97,7 +105,12 @@ function handleNavChange(nav: string) {
function handleContactSupport() {
rechargeLogRef.value?.contactCustomerService();
}
const { startHeaderTour } = useGuideTour();
// 开始引导教程
function handleStartTutorial() {
startHeaderTour();
}
// 点击
function handleClick(item: any) {
switch (item.key) {
@@ -110,6 +123,9 @@ function handleClick(item: any) {
case '5':
openDialog();
break;
case '6':
handleStartTutorial();
break;
case '4':
popoverRef.value?.hide?.();
ElMessageBox.confirm('退出登录不会丢失任何数据,你仍可以登录此账号。', '确认退出登录?', {
@@ -243,55 +259,41 @@ onMounted(() => {
// URL 参数会在对话框关闭时清除
}
});
// ============ 监听引导状态,自动打开用户中心并开始引导 ============
watch(() => guideTourStore.shouldStartUserCenterTour, (shouldStart) => {
if (shouldStart) {
// 清除触发标记
guideTourStore.clearUserCenterTourTrigger();
// 注册导航切换回调
guideTourStore.setUserCenterNavChangeCallback((nav: string) => {
activeNav.value = nav;
});
// 注册关闭弹窗回调
guideTourStore.setUserCenterCloseCallback(() => {
dialogVisible.value = false;
});
// 打开用户中心弹窗
nextTick(() => {
dialogVisible.value = true;
// 等待弹窗打开后开始引导
setTimeout(() => {
startUserCenterTour();
}, 600);
});
}
});
</script>
<template>
<div class="flex items-center gap-2">
<!-- <div class="text-1.2xl font-bold text-gray-800 hover:text-blue-600 transition-colors"> -->
<!-- <a -->
<!-- href="https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde" -->
<!-- target="_blank" -->
<!-- class="flex items-center gap-2 group" -->
<!-- style="color: #E6A23C;" -->
<!-- title="点击跳转YiXinAI玩法指南专栏" -->
<!-- > -->
<!-- AI使用教程 -->
<!-- </a> -->
<!-- </div> -->
<div class="text-1.2xl font-bold text-gray-800 hover:text-blue-600 transition-colors">
<a
href="https://ccnetcore.com/article/3a1bc4d1-6a7d-751d-91cc-2817eb2ddcde"
target="_blank"
class="flex items-center gap-2 group"
style="color: #E6A23C;"
title="点击跳转YiXinAI玩法指南专栏"
>
<!-- PC端显示文字 -->
<span class="pc-text">AI使用教程</span>
<!-- 移动端显示图标这里用一个示例SVG实际可以换成你想要的 -->
<svg
class="inline md:hidden w-6 h-6 text-yellow-500"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 14l9-5-9-5-9 5 9 5z"
/>
<path
stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 14l6.16-3.422A12.083 12.083 0 0118 13.5c0 2.579-3.582 4.5-6 4.5s-6-1.921-6-4.5c0-.432.075-.85.198-1.244L12 14z"
/>
</svg>
</a>
</div>
<el-button
class="buy-btn flex items-center gap-2 px-5 py-2 font-semibold shadow-lg"
data-tour="buy-btn"
@click="onProductPackage"
>
<span>立即购买</span>
@@ -321,7 +323,7 @@ onMounted(() => {
</div>
<!-- 头像区域 -->
<div class="avatar-container">
<div class="avatar-container" data-tour="user-avatar">
<Popover
ref="popoverRef"
placement="bottom-end"
@@ -491,22 +493,4 @@ onMounted(() => {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
/* 默认 PC 端文字显示,图标隐藏 */
.pc-text {
display: inline;
}
.mobile-icon {
display: none;
}
/* 移动端显示图标,隐藏文字 */
@media (max-width: 768px) {
.pc-text {
display: none;
}
.mobile-icon {
display: inline;
}
}
</style>

View File

@@ -0,0 +1,75 @@
<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue';
import { useGuideTour } from '@/hooks/useGuideTour';
const { startHeaderTour } = useGuideTour();
// 开始引导教程
function handleStartTutorial() {
startHeaderTour();
}
</script>
<template>
<div class="tutorial-btn-container" data-tour="tutorial-btn">
<div
class="tutorial-btn"
@click="handleStartTutorial"
>
<!-- PC端显示文字 -->
<span class="pc-text">新手引导</span>
<!-- 移动端显示图标 -->
<el-icon class="mobile-icon" :size="20">
<QuestionFilled />
</el-icon>
</div>
</div>
</template>
<style scoped lang="scss">
.tutorial-btn-container {
display: flex;
align-items: center;
.tutorial-btn {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 1.2rem;
font-weight: bold;
color: #409eff;
transition: all 0.2s;
&:hover {
color: #66b1ff;
transform: translateY(-1px);
}
// PC端显示文字隐藏图标
.pc-text {
display: inline;
margin: 0 12px;
}
.mobile-icon {
display: none;
}
}
}
// 移动端显示图标,隐藏文字
@media (max-width: 768px) {
.tutorial-btn-container {
.tutorial-btn {
.pc-text {
display: none;
}
.mobile-icon {
display: inline;
}
}
}
}
</style>

View File

@@ -4,6 +4,8 @@ import { onKeyStroke } from '@vueuse/core';
import { SIDE_BAR_WIDTH } from '@/config/index';
import { useDesignStore, useUserStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session';
import AiTutorialBtn from './components/AiTutorialBtn.vue';
import AnnouncementBtn from './components/AnnouncementBtn.vue';
import Avatar from './components/Avatar.vue';
import Collapse from './components/Collapse.vue';
import CreateChat from './components/CreateChat.vue';
@@ -69,6 +71,8 @@ onKeyStroke(event => event.ctrlKey && event.key.toLowerCase() === 'k', handleCtr
<!-- 右边 -->
<div class="right-box flex h-full items-center pr-20px flex-shrink-0 mr-auto flex-row">
<AnnouncementBtn />
<AiTutorialBtn />
<Avatar v-show="userStore.userInfo" />
<LoginBtn v-show="!userStore.userInfo" />
</div>

View File

@@ -0,0 +1,373 @@
<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
// import { getActivityDetail } from '@/api'
// import type { ActivityDetailResponse } from '@/api'
const route = useRoute();
const router = useRouter();
const loading = ref(false);
// const activityDetail = ref<ActivityDetailResponse | null>(null)
const activityDetail = ref<any | null>(null);
// 获取活动详情
async function fetchActivityDetail() {
const id = route.params.id as string;
if (!id)
return;
loading.value = true;
try {
// const res = await getActivityDetail(id)
// activityDetail.value = res.data
}
catch (error) {
console.error('获取活动详情失败:', error);
ElMessage.error('获取活动详情失败');
}
finally {
loading.value = false;
}
}
// 返回上一页
function goBack() {
router.back();
}
// 格式化时间
function formatDateTime(time?: string) {
if (!time)
return '-';
const date = new Date(time);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
// 页面加载时获取详情
onMounted(() => {
fetchActivityDetail();
});
</script>
<template>
<div class="activity-detail-page">
<el-card v-loading="loading" class="detail-card">
<template #header>
<div class="card-header">
<el-button type="primary" link @click="goBack">
<el-icon><i-ep-arrow-left /></el-icon>
返回
</el-button>
</div>
</template>
<div v-if="activityDetail" class="detail-content">
<!-- 活动头部 -->
<div class="detail-header">
<h1 class="detail-title">
{{ activityDetail.title }}
</h1>
<div class="detail-meta">
<el-tag
v-if="activityDetail.status === 'active'"
type="success"
size="large"
>
进行中
</el-tag>
<el-tag
v-else-if="activityDetail.status === 'expired'"
type="info"
size="large"
>
已结束
</el-tag>
<span class="meta-item">
<el-icon><i-ep-view /></el-icon>
浏览 {{ activityDetail.views || 0 }}
</span>
<span class="meta-item">
<el-icon><i-ep-user /></el-icon>
参与 {{ activityDetail.participantCount || 0 }}
</span>
</div>
</div>
<!-- 活动封面 -->
<div v-if="activityDetail.coverImage" class="detail-cover">
<img :src="activityDetail.coverImage" :alt="activityDetail.title">
</div>
<!-- 活动描述 -->
<div class="detail-description">
<h3>活动简介</h3>
<p>{{ activityDetail.description }}</p>
</div>
<!-- 活动时间 -->
<div class="detail-time">
<el-descriptions :column="2" border>
<el-descriptions-item label="开始时间">
{{ formatDateTime(activityDetail.startTime) }}
</el-descriptions-item>
<el-descriptions-item label="结束时间">
{{ formatDateTime(activityDetail.endTime) }}
</el-descriptions-item>
<el-descriptions-item label="发布时间">
{{ formatDateTime(activityDetail.createdAt) }}
</el-descriptions-item>
<el-descriptions-item label="更新时间">
{{ formatDateTime(activityDetail.updatedAt) }}
</el-descriptions-item>
</el-descriptions>
</div>
<!-- 活动详细内容 -->
<div class="detail-body">
<h3>活动详情</h3>
<div class="content-html" v-html="activityDetail.content" />
</div>
</div>
<el-empty v-else description="暂无活动详情" />
</el-card>
</div>
</template>
<style scoped lang="scss">
.activity-detail-page {
padding: 24px;
background: #f5f7fa;
min-height: 100vh;
.detail-card {
max-width: 1200px;
margin: 0 auto;
}
.card-header {
display: flex;
align-items: center;
}
.detail-content {
.detail-header {
margin-bottom: 24px;
padding-bottom: 24px;
border-bottom: 1px solid #e4e7ed;
.detail-title {
margin: 0 0 16px 0;
font-size: 28px;
font-weight: 600;
color: #303133;
line-height: 1.4;
}
.detail-meta {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
.meta-item {
display: flex;
align-items: center;
gap: 4px;
font-size: 14px;
color: #606266;
.el-icon {
font-size: 16px;
}
}
}
}
.detail-cover {
margin-bottom: 24px;
border-radius: 8px;
overflow: hidden;
img {
width: 100%;
height: auto;
display: block;
}
}
.detail-description {
margin-bottom: 24px;
padding: 20px;
background: #f9fafb;
border-radius: 8px;
h3 {
margin: 0 0 12px 0;
font-size: 18px;
font-weight: 600;
color: #303133;
}
p {
margin: 0;
font-size: 15px;
color: #606266;
line-height: 1.8;
}
}
.detail-time {
margin-bottom: 24px;
}
.detail-body {
h3 {
margin: 0 0 16px 0;
font-size: 18px;
font-weight: 600;
color: #303133;
}
.content-html {
font-size: 15px;
color: #303133;
line-height: 1.8;
:deep(img) {
max-width: 100%;
height: auto;
border-radius: 4px;
}
:deep(p) {
margin: 12px 0;
}
:deep(h1),
:deep(h2),
:deep(h3),
:deep(h4),
:deep(h5),
:deep(h6) {
margin: 20px 0 12px;
font-weight: 600;
color: #303133;
}
:deep(ul),
:deep(ol) {
padding-left: 24px;
margin: 12px 0;
}
:deep(li) {
margin: 8px 0;
}
:deep(blockquote) {
margin: 16px 0;
padding: 12px 16px;
background: #f5f7fa;
border-left: 4px solid #409eff;
color: #606266;
}
:deep(code) {
padding: 2px 6px;
background: #f5f7fa;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 14px;
}
:deep(pre) {
margin: 16px 0;
padding: 16px;
background: #282c34;
border-radius: 4px;
overflow-x: auto;
code {
background: none;
padding: 0;
color: #abb2bf;
}
}
}
}
}
}
// 移动端适配
@media screen and (max-width: 768px) {
.activity-detail-page {
padding: 12px;
.detail-card {
:deep(.el-card__header) {
padding: 12px;
}
:deep(.el-card__body) {
padding: 12px;
}
}
.detail-content {
.detail-header {
margin-bottom: 16px;
padding-bottom: 16px;
.detail-title {
font-size: 20px;
}
.detail-meta {
gap: 8px;
.meta-item {
font-size: 12px;
}
}
}
.detail-description {
padding: 12px;
margin-bottom: 16px;
h3 {
font-size: 16px;
}
p {
font-size: 14px;
}
}
.detail-time {
margin-bottom: 16px;
:deep(.el-descriptions__label) {
font-size: 12px;
}
:deep(.el-descriptions__content) {
font-size: 12px;
}
}
.detail-body {
h3 {
font-size: 16px;
}
.content-html {
font-size: 14px;
}
}
}
}
}
</style>

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