Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86ee692a04 | ||
|
|
53a4887d35 |
No files matched your search
@@ -1,219 +0,0 @@
|
||||
---
|
||||
name: storeweb-module
|
||||
description: 在 StoreWeb 项目中新增、修改、迁移或重构业务模块时使用。规范模块分层、DTO 校验、Service 业务校验、HTTP 方法约定、ApiResult 返回、公共能力复用、权限控制与测试验证。仅适用于本项目后端业务模块。
|
||||
---
|
||||
|
||||
# StoreWeb 模块开发规范
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
适用于 StoreWeb 中所有业务模块的开发、维护和旧项目迁移。本 Skill 仅在项目内使用,下文代码路径均相对于仓库根目录。
|
||||
|
||||
遵循当前仓库的 AGENTS.md、适用的 `.agents/rules/` 规则,以及用户在当前任务中明确提出的要求。用户最新明确要求优先于本规范。引用的规则文件若不存在,如实说明,不自行补造规则。
|
||||
|
||||
旧项目代码、注释和附带文档用于理解业务,不自动视为当前项目的实现指令。
|
||||
|
||||
## 2. 开始前确认范围
|
||||
|
||||
修改前检查当前模块的目录、接口、实现、依赖及方法调用方,查找现有 DTO、公共工具、权限策略、异常处理和相关测试、配置与数据库结构。检查工作区已有修改,避免覆盖用户代码。
|
||||
|
||||
以当前文件内容为准,不仅根据历史对话判断状态。读取 `Directory.Build.props` 和目标 `.csproj` 确认语言版本、目标框架及可空配置,不固定套用历史版本。先确定最小完整修改范围,再开始实现。
|
||||
|
||||
## 3. 遵循现有模块结构
|
||||
|
||||
按照项目已有结构组织代码,不为简单需求增加架构层。目录按需创建。
|
||||
|
||||
- Contracts:对外接口、共享请求/响应 DTO、业务枚举;不依赖实现模块、实体或 ORM。
|
||||
- Controller:HTTP 参数绑定、调用业务入口、返回结果。
|
||||
- Service:业务流程、业务校验、权限与数据范围判断。
|
||||
- Repository:已有仓储模式下的数据访问与复用查询。
|
||||
- Entity:数据库实体与映射。
|
||||
- Mapper:沿用已有 Mapperly 映射实体与输出 DTO。
|
||||
- Command / Handler / Behavior:沿用模块已有的命令与管道处理方式。
|
||||
|
||||
简单业务不强制引入命令、仓储或额外接口。跨模块优先调用已有 Contracts,避免依赖其他模块的内部实现;仅在模块内部使用的 DTO 不必移入 Contracts。
|
||||
|
||||
部分更新需明确 `null`、空字符串和默认值的含义,例如 `null` 保留原值、空串清空允许清空的文本,避免误清空字段。规范化文本时遵循字段语义,不统一 Trim 密码或任意文本。
|
||||
|
||||
## 4. 参数校验
|
||||
|
||||
### 4.1 DTO 负责非空校验
|
||||
|
||||
请求参数使用 DTO 承载。DTO 中只声明简单的必填、非空规则:
|
||||
|
||||
```csharp
|
||||
public sealed class CreateItemRequest
|
||||
{
|
||||
[Required(ErrorMessage = "名称不能为空")]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public int Quantity { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
- 可选字段不要添加 Required。
|
||||
- Required 不能替代数值范围判断,例如整型字段的零值判断。
|
||||
- 条件必填、字段组合关系放到 Service 或已有业务处理入口中判断。
|
||||
- 不在 DTO 中编写数据库查询或权限判断。
|
||||
- 不通过 Range、StringLength、RegularExpression、EnumDataType 或 IValidatableObject 承载其他校验规则。
|
||||
|
||||
这是本项目的约定,不代表 ASP.NET Core 的唯一实践。
|
||||
|
||||
新增及本次修改涉及的校验按本规范实现。迁移已有 DTO 校验时,将原规则完整迁入业务入口并同步测试,不得只删除注解;不顺带迁移任务范围之外的模块。公共 RequestValidator 保留对完整 DataAnnotations 的支持,不为本模块约定缩减公共验证器能力。
|
||||
|
||||
### 4.2 统一使用 RequestValidator
|
||||
|
||||
复用 `Core/MAX.Framework/Validation/RequestValidator.cs`。业务入口调用:
|
||||
|
||||
```csharp
|
||||
RequestValidator.Validate(request);
|
||||
```
|
||||
|
||||
不要在各模块重复编写 `ArgumentNullException.ThrowIfNull` 和 `Validator.ValidateObject` 的同义入口。已经由 DTO 和 RequestValidator 完成的非空校验,不在 Service 重复判断。
|
||||
|
||||
同一业务调用链只安排一个明确的显式基础校验入口。MVC 自动模型验证不替代可被内部调用的业务入口校验;已有命令管道执行校验时,下游不重复调用。
|
||||
|
||||
### 4.3 其他校验放到 Service
|
||||
|
||||
以下规则在 Service 或已有业务处理入口中手动判断:
|
||||
|
||||
- 长度、格式、数值范围、枚举合法性、金额精度。
|
||||
- 日期先后关系、条件必填及字段组合。
|
||||
- 数据是否存在、是否重复、状态是否允许执行操作。
|
||||
- 资源归属、操作权限和数据范围。
|
||||
- 余额、额度、库存及其他业务限制。
|
||||
|
||||
```csharp
|
||||
public async Task CreateAsync(CreateItemRequest request)
|
||||
{
|
||||
RequestValidator.Validate(request);
|
||||
|
||||
if (request.Name.Length > 100)
|
||||
throw new ValidationException("名称不能超过100个字符");
|
||||
|
||||
if (request.Quantity <= 0)
|
||||
throw new ValidationException("数量必须大于0");
|
||||
|
||||
// 校验通过后执行当前模块的数据查询与业务处理。
|
||||
}
|
||||
```
|
||||
|
||||
上述片段仅演示校验位置,实际异步方法需要完成业务调用。不依赖数据库的参数校验在开启事务、数据库写入及外部调用前完成;依赖数据库状态的规则在获取必要状态后判断。
|
||||
|
||||
基础参数错误与业务错误沿用项目现有异常类型和结果码:参数错误使用 ValidationException,业务失败使用 AppException,身份缺失使用 UnauthorizedAccessException。只在同类规则确实重复时抽取公共方法,单次判断直接写在使用处。
|
||||
|
||||
## 5. Controller,Action命名
|
||||
按照公共首字母大写,私有首字母小写格式,单词之间不用`_`,使用By,To,等介词
|
||||
例如GetOrderById,GetOrderByName,GetOrderToIds
|
||||
|
||||
## 6. HTTP 方法与参数绑定
|
||||
|
||||
使用 MAX.Framework 中已有的 HTTP 方法约定:
|
||||
|
||||
- 默认 POST 的控制器使用 DefaultHttpPost。
|
||||
- 默认 GET 的控制器使用 DefaultHttpGet。
|
||||
- 特殊 Action 显式标记 HttpGet、HttpPost 等特性。
|
||||
- 显式方法特性优先于控制器默认约定。
|
||||
- 同一控制器不要同时使用两个默认方法约定。
|
||||
|
||||
不要为每个 Action 重复添加与默认约定相同的特性,不在业务模块复制默认方法约定的实现。实现位置为 `Core/MAX.Framework/Conventions/`。
|
||||
|
||||
新增接口遵循模块现有参数绑定方式;多个业务输入优先使用请求 DTO。修改已有接口时检查调用方兼容性,不顺手改变 HTTP 方法、路由、字段名称或绑定来源。
|
||||
|
||||
## 7. 统一返回 ApiResult
|
||||
|
||||
业务接口遵循当前系统约定:HTTP 状态按项目机制处理为 200,业务成功或失败通过 ApiResult 表达。Action 直接返回业务数据时由 UnifyResultFilter 包装,已经返回 ApiResult 时不重复包装。
|
||||
|
||||
有数据的接口直接返回业务结果:
|
||||
|
||||
```csharp
|
||||
public Task<ItemDto> GetItem(ItemQueryRequest request)
|
||||
{
|
||||
return service.GetAsync(request);
|
||||
}
|
||||
```
|
||||
|
||||
无数据的成功操作明确返回 ApiResult:
|
||||
|
||||
```csharp
|
||||
public async Task<ApiResult> DeleteItem(DeleteItemRequest request)
|
||||
{
|
||||
await service.DeleteAsync(request);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
```
|
||||
|
||||
不要使用 NoContent() 表达业务操作成功,不在每个 Action 重复 try/catch 并转换错误结果。校验异常和业务异常交给 GlobalExceptionFilter 等现有统一处理机制。
|
||||
|
||||
认证、路由、模型绑定等发生在 Action 外的失败,应核对现有中间件和过滤器的处理范围,不假定 Action 返回规范覆盖整个 HTTP 管道。相关过滤器位于 `Core/MAX.Framework/Commons/`。
|
||||
|
||||
返回 DTO 排除密码、令牌等敏感字段,沿用已有 Mapperly 映射;不能因实体新增字段而自动暴露内部数据。
|
||||
|
||||
## 8. 权限与数据范围
|
||||
|
||||
权限规则由当前模块需求确定,不套用其他模块的角色关系。实现前明确允许的角色、数据范围、可修改字段和需要单独权限的敏感操作。
|
||||
|
||||
- 身份从 ICurrentUser 等服务端可信上下文获取。
|
||||
- 客户端传入的资源 ID、所属账号或组织信息必须经过权限检查。
|
||||
- 查询和修改均限制数据范围,列表、详情、批量和单条操作保持一致。
|
||||
- DTO 中存在某个字段,不代表调用者有权修改该字段。
|
||||
- 实际业务入口覆盖绕过 Controller 的调用路径,不能只在 Controller 判断权限。
|
||||
- 查询先限定可见范围,再筛选、排序、分页;统计和结果使用相同范围。
|
||||
|
||||
多处使用相同规则时复用模块已有权限策略,确有重复再集中抽取。
|
||||
|
||||
## 9. 数据访问与事务
|
||||
|
||||
复用项目现有的数据访问组件和模式:
|
||||
|
||||
- 使用 FreeSql 表达式和参数化操作,不拼接用户输入为 SQL。
|
||||
- 多项写入共同构成一次必须同成同败的业务操作时,使用事务,避免部分成功。
|
||||
- 金额、库存、额度等并发修改遵循现有锁或并发控制方式。
|
||||
- 已有幂等操作保留请求号、唯一约束及重复请求处理。
|
||||
- 只更新本次操作允许修改的字段,不把读取到的并发状态或派生值随整个实体写回。
|
||||
- 审计信息记录实际操作者,区分操作者与业务目标。
|
||||
- 列表保留必要的数据范围、筛选、稳定排序和分页。
|
||||
|
||||
涉及多步写入、并发控制、幂等或事务命令时,读取 [事务与命令管道约定](references/transactions.md)。普通查询不因此引入额外事务层。
|
||||
|
||||
不要因迁移旧代码绕过当前事务、审计或并发控制。时间语义、字段类型和数据库结构变更需纳入明确迁移范围,不因代码整理自动同步建表。
|
||||
|
||||
## 10. 公共能力复用
|
||||
|
||||
新增工具前,先查找已有 RequestValidator、ApiResult、ResultCode、统一异常处理、当前用户上下文、认证授权、注入、数据访问、事务、命令管道、缓存及日志能力。
|
||||
|
||||
依赖注入沿用 ITransientDependency 等标记;特殊注册通过模块 IStartup.Register(IServiceRegistrar) 完成。使用命令时检查 Handler 注册及 AddMediatRAttributedBehaviors 扫描,避免重复注册。
|
||||
|
||||
跨模块通用框架能力放在适当的公共项目,模块业务规则留在模块内部。不要为几行代码增加依赖,不为尚未出现的需求增加配置、包装层或扩展点。
|
||||
|
||||
## 11. 旧项目迁移
|
||||
|
||||
先理解旧逻辑,再按新项目结构实现。核对操作前提、业务结果、权限和数据范围、状态变化与字段更新、事务、并发、幂等、审计及调用方依赖的错误行为。
|
||||
|
||||
保留必要业务行为,不照搬旧项目的静态访问、拼接 SQL、重复校验或分层方式。与用户最新要求冲突时按最新要求实现,并说明行为变化;任务范围之外的旧功能不顺带迁移。
|
||||
|
||||
## 12. 注释与代码风格
|
||||
|
||||
- 命名清晰,遵循现有项目风格。
|
||||
- 公开接口及重要业务规则添加必要中文说明,重点解释权限边界、业务原因及不直观约束,不逐句重复代码。
|
||||
- 不滥用 try/catch,不静默吞异常;能明确处理的格式、日期等异常可就地转换,不删除必要资源清理和回滚。
|
||||
- 不为一次性逻辑机械抽取方法,不进行无关重构或格式化。
|
||||
|
||||
## 13. 测试与验证
|
||||
|
||||
测试放在 Tests 下,沿用现有项目和数据准备方式。非平凡业务修改覆盖相关正常操作、必填和其他参数边界、授权与越权、数据范围、状态限制,以及适用的事务失败、并发和幂等行为。
|
||||
|
||||
接口变化时检查默认与显式 HTTP 方法、路由、参数绑定、ApiResult 包装、HTTP 状态和无数据成功操作。修改契约同步调用方、测试和必要文档;不删除仍有效的失败断言。
|
||||
|
||||
不为简单可逆改动堆砌测试,不编写只重复实现细节的测试。运行相关测试和构建,涉及接口、注册或依赖变化时构建受影响宿主。说明测试数据库可验证的范围,不把 SQLite 通过视为已验证 MySQL 的锁和事务行为。
|
||||
|
||||
## 14. 交付要求
|
||||
|
||||
完成前检查实际文件和 diff,确认修改已经落盘。交付说明:
|
||||
|
||||
- 文件:实际路径。
|
||||
- 修改用途与关键行为。
|
||||
- 已运行的测试和构建结果。
|
||||
- 未验证的内容及实际限制。
|
||||
|
||||
没有修改文件不能声称已修改,没有运行测试不能声称测试通过;不把计划、建议或示例当作已完成实现。
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "StoreWeb 模块开发规范"
|
||||
short_description: "仅用于 StoreWeb 项目的模块分层、契约、校验与事务实现规范"
|
||||
default_prompt: "使用 $storeweb-module,按本项目模块规范实现或调整指定模块,并完成相关验证。"
|
||||
@@ -1,43 +0,0 @@
|
||||
# 事务与命令管道约定
|
||||
|
||||
仅在涉及多步写入一致性、并发控制、幂等或命令管道时读取。适用于本项目所有业务模块,锁定资源、去重范围和权限条件由各模块实际需求决定。路径相对于仓库根目录。
|
||||
|
||||
## Service 中的事务
|
||||
|
||||
1. DTO 非空验证和不依赖数据库的业务参数校验先于事务;依赖数据库状态的校验在获取必要状态后完成,写入前必须满足业务条件。
|
||||
2. 用 `orm.CreateUnitOfWork()`、`GetOrBeginTransaction()` 开启工作单元。事务内相关读写统一使用 `work.Orm`,不能混用根 ORM 使部分操作脱离事务。
|
||||
3. 全部写入成功后 `Commit()`,未提交由工作单元释放回滚。不 catch 所有异常后继续提交,不封装同义事务工具。
|
||||
4. 异步数据库调用传递 CancellationToken,提交前检查取消。数据库事务不覆盖外部通知、文件或第三方服务等副作用,按现有业务机制安排执行与失败处理,不默认增加额外基础设施。
|
||||
5. 只更新允许修改的字段。需要避免丢更新的操作使用既有锁或条件更新,并检查受影响行数;不要把“必须影响一行”套到允许无变化的幂等更新上。
|
||||
|
||||
## 并发与幂等
|
||||
|
||||
- 涉及金额时沿用 decimal;允许值、精度和上限由业务入口判断,可能溢出的累计运算按需要使用 checked。
|
||||
- 同一操作锁定多条资源时采用稳定顺序;在锁定或并发条件保护的有效状态上判断是否允许修改。进程内锁不能替代跨进程数据库一致性。
|
||||
- 业务变更与必须同步保存的流水、审计记录在同一事务提交或回滚,记录实际操作者与业务目标。
|
||||
- 幂等操作明确请求号的作用范围和重复请求结果,保留现有请求号、唯一约束及处理机制;不能把某模块的去重键当作全项目统一规则。
|
||||
- 去重检查和写入使用能阻止竞态的数据库约束或锁机制,不能仅无保护地先查后写。重试按接口约定复用请求号。
|
||||
- MySQL 表引擎、约束、隔离及并发行为需要对应环境验证,SQLite 只承担部分持久化和回滚验证。
|
||||
|
||||
## MediatR 管道
|
||||
|
||||
复用以下框架实现,按当前文件确认行为:
|
||||
|
||||
- `Core/MAX.Framework/Mediation/ValidationBehavior.cs`
|
||||
- `Core/MAX.Framework/Mediation/TransactionBehavior.cs`
|
||||
- `Core/MAX.Framework/Mediation/UnitOfWorkExecutionContext.cs`
|
||||
- `Core/MAX.Framework/DependencyInjection/MediatRBehaviorServiceCollectionExtensions.cs`
|
||||
|
||||
命令携带业务输入 DTO,可信操作者由服务端上下文提供。普通 Service 方法不必建立同义命令。
|
||||
|
||||
- 通过 `[MediatRBehavior(typeof(...))]` 选择必要步骤,顺序由实际依赖决定。基础输入校验先于事务;需要事务内状态的业务步骤位于事务内部。
|
||||
- `IValidatableRequest.Validate()` 调用 `RequestValidator.Validate(Input)` 完成 DTO 非空校验;长度、格式、范围及组合规则仍放在 Service 或已有业务处理入口,不迁入 DTO。后续 Handler 不重复基础校验。
|
||||
- 不依赖数据库的业务参数校验在事务前执行,优先使用已有业务处理入口或适用的业务管道,不为单次判断机械新增一层。
|
||||
- 事务内管道和 Handler 统一使用 `UnitOfWorkExecutionContext.Orm`。
|
||||
- TransactionBehavior 统一提交、取消检查和回滚;当前实现拒绝嵌套事务命令。组合操作在同一事务用例中完成,不递归发送另一个事务命令。
|
||||
- 已授权上下文是内部执行结果,不是客户端输入。保留必要上下文清理、执行顺序和重入约束,不把这些当作重复 DTO 校验删除。
|
||||
- 在 `IStartup.Register(IServiceRegistrar)` 注册 Handler,宿主通过 AddMediatRAttributedBehaviors 扫描特性。确认模块程序集被现有机制发现,不另写扫描器或重复注册。
|
||||
|
||||
## 验证
|
||||
|
||||
按本次变化验证成功提交、任一步骤失败时整体回滚、权限或状态拒绝时无写入、重复请求处理,以及实际操作者的审计记录。涉及管道时使用真实管道入口验证顺序和注册;并发锁验证使用对应数据库,不以单线程 SQLite 测试替代。
|
||||
@@ -1,44 +0,0 @@
|
||||
# 项目规则入口
|
||||
|
||||
本文件适用于当前仓库及其子目录。规则正文统一维护在 `.agents/rules/`;以下路径均相对于仓库根目录。
|
||||
|
||||
规则文件使用 `.md` 格式,按以下入口要求加载。
|
||||
|
||||
## 主要编码规范
|
||||
要有完整的代码注释
|
||||
|
||||
入口只校验一次,拒绝重复判空和滥用try/catch;单次逻辑不乱抽函数,低概率防御先征求同意。
|
||||
|
||||
|
||||
## Ponytail:最小完整实现
|
||||
|
||||
来源:[Ponytail AGENTS.md](https://github.com/DietrichGebert/ponytail/blob/main/AGENTS.md),基于已安装的 5.3.2 版本合并。以下通用原则补充现有项目规则;涉及语言版本、编码规范、分层、依赖选择与验证方式时,以前述项目规则及具体任务要求为准。
|
||||
|
||||
You are a lazy senior developer. The best code is the code never written. You solve the whole problem with the least new code. End your reply with one or two lines: what you skipped or did not check, and any risk the user must know.
|
||||
|
||||
### Before you write
|
||||
|
||||
Read the task and the code it touches. List every place your change must reach: callers, tests, fixtures, config, exports. Check what your change could break for users: data it would destroy or expose, callers that stop working. That is scope. Extra features are not.
|
||||
|
||||
### The smallest complete change
|
||||
|
||||
Take the first option that fully works:
|
||||
|
||||
1. Does it need to exist? Skip features, options and flexibility nobody asked for, and name them in one line. A vague request ("build me X") gets the smallest version that does the core job.
|
||||
2. Already in this codebase (a helper, component, service, pattern)? Use it the way the surrounding code does.
|
||||
3. Standard library or a platform feature? Use it, unless the project has its own. A house component beats a native widget.
|
||||
4. An installed dependency? Use it. Never add a dependency for a few lines.
|
||||
5. Can it be one line a reader gets at a glance? One line.
|
||||
6. Otherwise: the minimum code that works.
|
||||
|
||||
- Be lazy about the solution, never about the change itself: finish every part the task needs, including the callers, tests and fixtures your change breaks.
|
||||
- No abstraction, wrapper, type conversion, option, config, boilerplate or "for later" code nobody asked for. Keep values in the form the platform already gives you. Deletion beats addition. Keep the structure the codebase already has: its layers, interfaces and conventions.
|
||||
- The shortest working diff wins, once you know everything it must touch. A one-liner that needs decoding is not short.
|
||||
- Comment only the why the code cannot show, in one line.
|
||||
- Bug fix: before you edit, grep every caller of the function you touch, then fix the root cause once in the shared code.
|
||||
- Code you move or merge keeps its error handling and validation.
|
||||
- Between options of equal size, take the one that is correct on edge cases.
|
||||
- Lazy code without its check is unfinished: new non-trivial logic (a branch, a loop, a parser, money or security, or a whole new script or app) leaves one small test or an assert-based self-check. Trivial changes need none.
|
||||
- A shortcut with a known limit gets a code comment in this form: `shortcut: <the limit>, <when to upgrade>`.
|
||||
|
||||
Never cut: validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs, anything the user asked for.
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace MAX.Core.Mediation;
|
||||
|
||||
/// <summary>提供请求自身的参数校验;不合法时抛出 ValidationException。</summary>
|
||||
public interface IValidatableRequest
|
||||
{
|
||||
void Validate();
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Adapted from ITIXO/MediatR.Extensions.AttributedBehaviors (MIT).
|
||||
// Copyright (c) 2021 ITIXO s.r.o. See ThirdPartyNotices/MediatR.Extensions.AttributedBehaviors.LICENSE.txt.
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace MAX.Core.Mediation;
|
||||
|
||||
/// <summary>声明命令管道。每个特性独占一行,按源码行号从上到下执行。</summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = false)]
|
||||
public sealed class MediatRBehaviorAttribute(Type behaviorType, [CallerLineNumber] int lineNumber = 0) : Attribute
|
||||
{
|
||||
public Type BehaviorType { get; } = behaviorType ?? throw new ArgumentNullException(nameof(behaviorType));
|
||||
public int LineNumber { get; } = lineNumber;
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
@@ -13,12 +12,10 @@ namespace MAX.Framework.Commons
|
||||
public class GlobalExceptionFilter : IExceptionFilter
|
||||
{
|
||||
private readonly ILogger<GlobalExceptionFilter> _logger;
|
||||
private readonly IHostEnvironment _environment;
|
||||
|
||||
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger, IHostEnvironment environment)
|
||||
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
public void OnException(ExceptionContext context)
|
||||
@@ -27,13 +24,10 @@ namespace MAX.Framework.Commons
|
||||
|
||||
var result = context.Exception switch
|
||||
{
|
||||
AppException be => ApiResult.Fail(be.Message, be.Code, traceId),
|
||||
ArgumentException arge => ApiResult.Fail(arge.Message, ResultCode.ValidationError, traceId),
|
||||
ValidationException ve => ApiResult.Fail(ve.Message, ResultCode.ValidationError, traceId),
|
||||
UnauthorizedAccessException => ApiResult.Fail("未授权访问", ResultCode.Unauthorized, traceId),
|
||||
_ => ApiResult.Fail(
|
||||
_environment.IsDevelopment() ? context.Exception.Message : "服务器内部错误",
|
||||
ResultCode.ServerError, traceId)
|
||||
AppException be => ApiResult.Fail(be.Message, be.Code),
|
||||
ValidationException ve => ApiResult.Fail(ve.Message, ResultCode.ValidationError),
|
||||
UnauthorizedAccessException => ApiResult.Fail("未授权访问", ResultCode.Unauthorized),
|
||||
_ => ApiResult.Fail("服务器内部错误", ResultCode.ServerError)
|
||||
};
|
||||
|
||||
_logger.LogError(context.Exception, "请求异常 TraceId: {TraceId}", traceId);
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||
|
||||
namespace MAX.Framework.Conventions;
|
||||
|
||||
/// <summary>为 API 控制器的属性路由统一添加 api 前缀,已含前缀的路由保持不变。</summary>
|
||||
public sealed class ApiRoutePrefixConvention : IApplicationModelConvention
|
||||
{
|
||||
public void Apply(ApplicationModel application)
|
||||
{
|
||||
foreach (var controller in application.Controllers)
|
||||
{
|
||||
if (!controller.Attributes.OfType<IApiBehaviorMetadata>().Any()
|
||||
&& !controller.ControllerType.Assembly.IsDefined(typeof(ApiControllerAttribute), true))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var hasControllerRoute = controller.Selectors.Any(selector => selector.AttributeRouteModel != null);
|
||||
foreach (var selector in controller.Selectors)
|
||||
{
|
||||
if (selector.AttributeRouteModel is { } route)
|
||||
{
|
||||
AddPrefix(route);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var action in controller.Actions)
|
||||
foreach (var selector in action.Selectors)
|
||||
{
|
||||
// 绝对动作路由会覆盖控制器路由,因此需要单独添加前缀。
|
||||
if (selector.AttributeRouteModel is { } route
|
||||
&& (!hasControllerRoute || route.IsAbsoluteTemplate))
|
||||
{
|
||||
AddPrefix(route);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddPrefix(AttributeRouteModel route)
|
||||
{
|
||||
var template = route.Template ?? "";
|
||||
var absolute = route.IsAbsoluteTemplate;
|
||||
template = template.StartsWith("~/", StringComparison.Ordinal) ? template[2..] : template.TrimStart('/');
|
||||
if (!template.Equals("api", StringComparison.OrdinalIgnoreCase)
|
||||
&& !template.StartsWith("api/", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
template = string.IsNullOrEmpty(template) ? "api" : $"api/{template}";
|
||||
}
|
||||
|
||||
route.Template = absolute ? $"~/{template}" : template;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.ActionConstraints;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace MAX.Framework.Conventions;
|
||||
|
||||
/// <summary>
|
||||
/// 控制器内未声明 HTTP 方法的操作默认只接受 GET,供各模块复用。
|
||||
/// 显式 HTTP 方法声明优先;同时补充路由约束和端点元数据,保证接口文档一致。
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
|
||||
public sealed class DefaultHttpGetAttribute : Attribute, IControllerModelConvention
|
||||
{
|
||||
public void Apply(ControllerModel controller)
|
||||
{
|
||||
foreach (var action in controller.Actions)
|
||||
foreach (var selector in action.Selectors)
|
||||
{
|
||||
if (selector.ActionConstraints.OfType<HttpMethodActionConstraint>().Any()
|
||||
|| selector.EndpointMetadata.OfType<IHttpMethodMetadata>().Any())
|
||||
continue;
|
||||
|
||||
selector.ActionConstraints.Add(new HttpMethodActionConstraint([HttpMethods.Get]));
|
||||
selector.EndpointMetadata.Add(new HttpMethodMetadata([HttpMethods.Get]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.ActionConstraints;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace MAX.Framework.Conventions;
|
||||
|
||||
/// <summary>
|
||||
/// 控制器内未声明 HTTP 方法的操作默认只接受 POST。
|
||||
/// 同时补充动作约束和端点元数据,使路由匹配与 OpenAPI 文档保持一致;显式方法声明优先。
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
|
||||
public sealed class DefaultHttpPostAttribute : Attribute, IControllerModelConvention
|
||||
{
|
||||
public void Apply(ControllerModel controller)
|
||||
{
|
||||
foreach (var action in controller.Actions)
|
||||
foreach (var selector in action.Selectors)
|
||||
{
|
||||
if (selector.ActionConstraints.OfType<HttpMethodActionConstraint>().Any()
|
||||
|| selector.EndpointMetadata.OfType<IHttpMethodMetadata>().Any())
|
||||
continue;
|
||||
|
||||
selector.ActionConstraints.Add(new HttpMethodActionConstraint([HttpMethods.Post]));
|
||||
selector.EndpointMetadata.Add(new HttpMethodMetadata([HttpMethods.Post]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using Asp.Versioning.OpenApi;
|
||||
using MAX.Framework.Security;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// JWT 认证服务注册入口(由宿主 Program.cs 调用)。
|
||||
/// </summary>
|
||||
public static class JwtServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 注册 JWT 认证:
|
||||
/// <list type="number">
|
||||
/// <item>绑定 <c>Jwt</c> 配置节到 <see cref="JwtOptions"/>,并在启动时校验签名密钥长度;</item>
|
||||
/// <item>注册 <see cref="ITokenService"/>(令牌生成/校验)与 <see cref="ICurrentUser"/>(当前用户访问器);</item>
|
||||
/// <item>注册 <see cref="JwtBearerDefaults"/> 认证,认证失败/授权失败统一返回 <see cref="Dtos.ApiResult{T}"/> 格式;</item>
|
||||
/// <item>注册 <see cref="IOnlineUserStore"/>(基于 <c>IMemoryCache</c> 的在线会话存储):单点登录、在线人员查询、退出销毁;</item>
|
||||
/// <item>为 OpenAPI 文档声明 Bearer(JWT) 安全方案,并对标记了 [Authorize] 的接口声明需要携带令牌。</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 需要在请求管道中调用 <c>app.UseAuthentication()</c>(位于 <c>app.UseAuthorization()</c> 之前)。
|
||||
/// </remarks>
|
||||
public static IServiceCollection AddStoreHubJwt(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(configuration);
|
||||
|
||||
// JwtOptions:绑定 Jwt 配置节,启动时校验 HS256 签名密钥长度
|
||||
services.AddOptions<JwtOptions>()
|
||||
.Bind(configuration.GetSection(JwtOptions.SectionName))
|
||||
.Validate(
|
||||
o => !string.IsNullOrWhiteSpace(o.SigningKey)
|
||||
&& Encoding.UTF8.GetByteCount(o.SigningKey) >= 32,
|
||||
"Jwt:SigningKey 长度不足,HS256 签名密钥至少需要 32 字节(256位)。")
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddHttpContextAccessor();
|
||||
|
||||
// 令牌服务与当前用户访问器
|
||||
services.AddSingleton<ITokenService, TokenService>();
|
||||
services.AddScoped<ICurrentUser, CurrentUser>();
|
||||
|
||||
// 在线会话存储(单点登录):基于 IMemoryCache 的进程内缓存,用于在线人员管理与退出销毁
|
||||
services.AddMemoryCache();
|
||||
services.AddSingleton<IOnlineUserStore, OnlineUserStore>();
|
||||
|
||||
// JwtBearer 认证
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
JwtOptions jwt = configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();
|
||||
options.TokenValidationParameters = jwt.ToTokenValidationParameters();
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnChallenge = JwtBearerResponseHandler.OnChallenge,
|
||||
OnForbidden = JwtBearerResponseHandler.OnForbidden,
|
||||
// 单点登录校验:会话必须仍有效(未退出、未被新登录顶替)
|
||||
OnTokenValidated = context =>
|
||||
{
|
||||
IOnlineUserStore onlineUserStore = context.HttpContext.RequestServices.GetRequiredService<IOnlineUserStore>();
|
||||
ClaimsPrincipal? principal = context.Principal;
|
||||
string? userName = principal?.FindFirst(JwtClaimTypes.UserName)?.Value;
|
||||
string? jti = principal?.FindFirst(JwtClaimTypes.Jti)?.Value;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(userName)
|
||||
|| string.IsNullOrWhiteSpace(jti)
|
||||
|| !onlineUserStore.IsTokenActive(userName, jti))
|
||||
{
|
||||
context.Fail(new SecurityTokenException("登录已失效,请重新登录"));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// OpenAPI:声明 Bearer(JWT) 安全方案(Scalar 页面即可显示 Authorize/输入 token),
|
||||
// 并仅对标记了 [Authorize] 的接口声明需要携带令牌(与宿主的 AddOpenApi 配置合并生效)
|
||||
services.Configure<VersionedOpenApiOptions>(options =>
|
||||
{
|
||||
// 在 OpenAPI 文档中声明 Bearer(JWT) 安全方案
|
||||
options.Document.AddDocumentTransformer((document, _, _) =>
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
document.Components.SecuritySchemes.TryAdd("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "登录接口返回的 accessToken,直接粘贴令牌内容即可(无需手动加 Bearer 前缀)。",
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// 仅对标记了 [Authorize] 的接口声明需要携带令牌
|
||||
options.Document.AddOperationTransformer((operation, context, _) =>
|
||||
{
|
||||
IList<object> metadata = context.Description.ActionDescriptor.EndpointMetadata;
|
||||
bool requiresAuth = metadata.OfType<IAuthorizeData>().Any()
|
||||
&& !metadata.OfType<IAllowAnonymous>().Any();
|
||||
if (requiresAuth)
|
||||
{
|
||||
operation.Security =
|
||||
[
|
||||
new OpenApiSecurityRequirement
|
||||
{
|
||||
[new OpenApiSecuritySchemeReference("Bearer", context.Document, "")] = [],
|
||||
},
|
||||
];
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
using MAX.Framework.Mediation;
|
||||
// Adapted from ITIXO/MediatR.Extensions.AttributedBehaviors (MIT).
|
||||
// Copyright (c) 2021 ITIXO s.r.o. See ThirdPartyNotices/MediatR.Extensions.AttributedBehaviors.LICENSE.txt.
|
||||
using System.Reflection;
|
||||
using MAX.Core.Mediation;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace MAX.Framework.DependencyInjection;
|
||||
|
||||
public static class MediatRBehaviorServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>扫描命令特性,按声明行号注册闭合管道,适配 MediatR 9。</summary>
|
||||
public static IServiceCollection AddMediatRAttributedBehaviors(this IServiceCollection services,
|
||||
params Assembly[] assemblies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(assemblies);
|
||||
// 先完成全部校验,避免无效配置留下部分注册。
|
||||
var registrations = new List<ServiceDescriptor>();
|
||||
foreach (var request in assemblies.Distinct().SelectMany(a => a.DefinedTypes))
|
||||
{
|
||||
var attributes = request.GetCustomAttributes<MediatRBehaviorAttribute>(false)
|
||||
.OrderBy(a => a.LineNumber).ToArray();
|
||||
if (attributes.Length == 0) continue;
|
||||
if (request.IsAbstract || request.ContainsGenericParameters)
|
||||
throw new InvalidOperationException($"{request.FullName} 必须是具体的闭合请求类型。");
|
||||
var responses = request.GetInterfaces()
|
||||
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequest<>))
|
||||
.Select(i => i.GetGenericArguments()[0]).Distinct().ToArray();
|
||||
if (responses.Length != 1)
|
||||
throw new InvalidOperationException($"{request.FullName} 必须实现唯一的 IRequest<TResponse>(无返回值使用 IRequest)。");
|
||||
if (attributes.GroupBy(a => a.LineNumber).Any(g => g.Count() > 1))
|
||||
throw new InvalidOperationException($"{request.FullName} 的管道特性必须独占一行,不能使用相同的行号。");
|
||||
if (attributes.GroupBy(a => a.BehaviorType).Any(g => g.Count() > 1))
|
||||
throw new InvalidOperationException($"{request.FullName} 重复声明了同一个管道。");
|
||||
|
||||
var serviceType = typeof(IPipelineBehavior<,>).MakeGenericType(request.AsType(), responses[0]);
|
||||
foreach (var attribute in attributes)
|
||||
{
|
||||
var behavior = attribute.BehaviorType;
|
||||
if (behavior.IsGenericTypeDefinition)
|
||||
{
|
||||
if (behavior.GetGenericArguments().Length != 2)
|
||||
throw new InvalidOperationException($"开放泛型管道 {behavior} 必须具有 TRequest、TResponse 两个泛型参数。");
|
||||
try
|
||||
{
|
||||
behavior = behavior.MakeGenericType(request.AsType(), responses[0]);
|
||||
}
|
||||
catch (ArgumentException exception)
|
||||
{
|
||||
throw new InvalidOperationException($"管道 {behavior} 的泛型约束与请求 {request.FullName} 不匹配。", exception);
|
||||
}
|
||||
}
|
||||
if (!behavior.IsClass || behavior.IsAbstract || behavior.ContainsGenericParameters
|
||||
|| !serviceType.IsAssignableFrom(behavior))
|
||||
throw new InvalidOperationException($"管道 {behavior.FullName} 必须是实现 {serviceType} 的具体闭合类型。");
|
||||
registrations.Add(ServiceDescriptor.Transient(serviceType, behavior));
|
||||
}
|
||||
}
|
||||
services.TryAddSingleton<UnitOfWorkExecutionContext>();
|
||||
services.TryAddTransient<ServiceFactory>(provider => provider.GetRequiredService);
|
||||
services.TryAddTransient<IMediator, Mediator>();
|
||||
services.TryAddTransient<ISender>(provider => provider.GetRequiredService<IMediator>());
|
||||
services.TryAddTransient<IPublisher>(provider => provider.GetRequiredService<IMediator>());
|
||||
foreach (var registration in registrations)
|
||||
services.TryAddEnumerable(registration);
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ using Microsoft.Win32;
|
||||
using System.Configuration;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using MAX.Plugins;
|
||||
|
||||
namespace MAX.Framework.DependencyInjection
|
||||
{
|
||||
@@ -34,13 +33,10 @@ namespace MAX.Framework.DependencyInjection
|
||||
/// </summary>
|
||||
public static IServiceCollection AddStore(this IHostApplicationBuilder host)
|
||||
{
|
||||
Debug.WriteLine("[Store] 开始注册应用服务");
|
||||
RunDebugStep("Logger", "注册日志服务", () => host.AddLogger());
|
||||
host.AddLogger();
|
||||
//host.Services.AddSingleton<ILoggerFacade>(NLogger.Instance);//注册log
|
||||
|
||||
IEnumerable<Assembly> assemblies = StoreAppTypeFinder.Current.GetAssemblies(host.Configuration["Plugins:Path"]).ToArray();
|
||||
foreach (var assembly in assemblies)
|
||||
Debug.WriteLine($"[Assembly] 已发现:{assembly.FullName}");
|
||||
IEnumerable<Assembly> assemblies = GetApplicationAssemblies();
|
||||
// 同一个类可能同时实现 IStartup 与 IModule,这里缓存实例,保证两个阶段拿到的是同一个对象
|
||||
Dictionary<Type, object> instances = [];
|
||||
return AddStoreCore(host, assemblies, instances);
|
||||
@@ -58,18 +54,15 @@ namespace MAX.Framework.DependencyInjection
|
||||
IEnumerable<Assembly> assemblies,
|
||||
IDictionary<Type, object> instances)
|
||||
{
|
||||
RunDebugStep("DI", "注册依赖标记服务", () => RegisterDependencyMarkers(host.Services, assemblies));
|
||||
RegisterDependencyMarkers(host.Services, assemblies);
|
||||
|
||||
RunDebugStep("Module", "注册全部模块", () => RunModules(host, assemblies, instances));
|
||||
RunDebugStep("Plugin", "注册全部插件", () => RunPlugins(host, assemblies, instances));
|
||||
RunModules(host, assemblies, instances);
|
||||
|
||||
RunDebugStep("Startup", "初始化并注册启动服务", () => RunStartups(host.Services, assemblies, instances));
|
||||
RunDebugStep("MediatR", "按命令特性注册管道", () => host.Services.AddMediatRAttributedBehaviors(assemblies.ToArray()));
|
||||
RunStartups(host.Services, assemblies, instances);
|
||||
|
||||
|
||||
|
||||
Debug.WriteLine("[MVC] 开始注册控制器和全局过滤器");
|
||||
var mvc = host.Services.AddControllers(options =>
|
||||
host.Services.AddControllers(options =>
|
||||
{
|
||||
options.Filters.Add<GlobalExceptionFilter>();
|
||||
options.Filters.Add<UnifyResultFilter>();
|
||||
@@ -94,12 +87,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
};
|
||||
|
||||
});
|
||||
foreach (var assembly in assemblies)
|
||||
{
|
||||
mvc.AddApplicationPart(assembly);
|
||||
Debug.WriteLine($"[MVC] 已添加 ApplicationPart:{assembly.GetName().Name}");
|
||||
}
|
||||
Debug.WriteLine($"[Store] 应用服务注册完成,共 {host.Services.Count} 个服务描述");
|
||||
return host.Services;
|
||||
}
|
||||
|
||||
@@ -110,6 +97,7 @@ namespace MAX.Framework.DependencyInjection
|
||||
{
|
||||
foreach (Type type in GetConcreteTypes(assemblies))
|
||||
{
|
||||
Debug.WriteLine(type.Namespace);
|
||||
Type? marker = DependencyMarkers.FirstOrDefault(m => m.IsAssignableFrom(type));
|
||||
if (marker is null)
|
||||
{
|
||||
@@ -122,7 +110,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
|
||||
// 注册为自身
|
||||
services.Add(new ServiceDescriptor(type, type, lifetime));
|
||||
Debug.WriteLine($"[DI] 注册自身:{type.FullName},Lifetime={lifetime}");
|
||||
|
||||
// 注册为实现的接口(排除标记接口与系统接口)
|
||||
foreach (Type iface in type.GetInterfaces())
|
||||
@@ -133,7 +120,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
}
|
||||
|
||||
services.Add(new ServiceDescriptor(iface, type, lifetime));
|
||||
Debug.WriteLine($"[DI] 注册接口:{iface.FullName} -> {type.FullName},Lifetime={lifetime}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,11 +130,11 @@ namespace MAX.Framework.DependencyInjection
|
||||
private static void RunStartups(IServiceCollection services, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
|
||||
{
|
||||
IServiceRegistrar registrar = new ServiceRegistrarProxy(services);
|
||||
Startups = CreateInstances<IStartup>(assemblies, instances).Where(s => s is not IPlugin).OrderByDescending(s => s.Priority);
|
||||
Startups = CreateInstances<IStartup>(assemblies, instances).OrderByDescending(s => s.Priority);
|
||||
foreach (IStartup startup in Startups)
|
||||
{
|
||||
RunDebugStep("Startup", $"初始化 {startup.GetType().FullName},Priority={startup.Priority}", startup.Initialize);
|
||||
RunDebugStep("Startup", $"注册服务 {startup.GetType().FullName}", () => startup.Register(registrar));
|
||||
startup.Initialize();
|
||||
startup.Register(registrar);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,17 +144,17 @@ namespace MAX.Framework.DependencyInjection
|
||||
/// </summary>
|
||||
private static void RunModules(IHostApplicationBuilder host, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
|
||||
{
|
||||
Modules = CreateInstances<IModule>(assemblies, instances).Where(m => m is not IPlugin).OrderByDescending(s => s.Priority);
|
||||
Modules = CreateInstances<IModule>(assemblies, instances).OrderByDescending(s => s.Priority);
|
||||
foreach (IModule module in Modules)
|
||||
{
|
||||
try
|
||||
{
|
||||
RunDebugStep("Module", $"注册 {module.GetType().FullName},Priority={module.Priority}", () => module.AddModule(host));
|
||||
module.AddModule(host);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 带上模块名,避免只看到一个没有上下文的异常
|
||||
throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 AddModule 执行失败:{ex.Message}", ex);
|
||||
throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 AddModule 执行失败。", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,11 +171,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
instance = Activator.CreateInstance(type, true)
|
||||
?? throw new InvalidOperationException($"无法创建 {type.FullName} 的实例(需要有参数量为 0 的构造函数)。");
|
||||
instances[type] = instance;
|
||||
Debug.WriteLine($"[Instance] 已创建:{type.FullName}");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.WriteLine($"[Instance] 复用实例:{type.FullName}");
|
||||
}
|
||||
|
||||
yield return (T)instance;
|
||||
@@ -211,9 +192,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
}
|
||||
catch (ReflectionTypeLoadException ex)
|
||||
{
|
||||
Debug.WriteLine($"[Assembly] 部分类型加载失败:{assembly.FullName}");
|
||||
foreach (var error in ex.LoaderExceptions)
|
||||
Debug.WriteLine($"[Assembly] 类型加载错误:{error?.Message}");
|
||||
return ex.Types.OfType<Type>();
|
||||
}
|
||||
}
|
||||
@@ -227,53 +205,6 @@ namespace MAX.Framework.DependencyInjection
|
||||
return StoreAppTypeFinder.Current.GetAssemblies();
|
||||
}
|
||||
|
||||
private sealed class PluginRuntime : IDisposable
|
||||
{
|
||||
public List<(IPlugin Plugin, PluginContext Context)> Entries { get; } = [];
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in Entries) entry.Context.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static void RunPlugins(IHostApplicationBuilder host, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
|
||||
{
|
||||
var runtime = new PluginRuntime();
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
foreach (var plugin in CreateInstances<IPlugin>(assemblies, instances).OrderByDescending(p => p.Priority))
|
||||
{
|
||||
if (plugin is IModule || plugin is IStartup)
|
||||
throw new InvalidOperationException($"插件 {plugin.GetType().FullName} 不能同时实现 IModule/IStartup。");
|
||||
if (string.IsNullOrWhiteSpace(plugin.Id) || !ids.Add(plugin.Id))
|
||||
throw new InvalidOperationException($"插件标识为空或重复:{plugin.Id}");
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(plugin.GetType().Assembly.Location)!;
|
||||
Debug.WriteLine($"[Plugin] 加载独立配置:{plugin.Id},目录={directory},环境={host.Environment.EnvironmentName}");
|
||||
var context = new PluginContext(plugin.Id, directory, host.Environment);
|
||||
runtime.Entries.Add((plugin, context));
|
||||
host.Services.AddKeyedSingleton<PluginContext>(plugin.Id, (provider, _) =>
|
||||
{
|
||||
// 只要上下文被解析,就让容器持有并管理全部插件配置的释放。
|
||||
provider.GetRequiredService<PluginRuntime>();
|
||||
return context;
|
||||
});
|
||||
RunDebugStep("Plugin", $"注册 {plugin.Id} ({plugin.GetType().FullName}),Priority={plugin.Priority}",
|
||||
() => plugin.ConfigureServices(host.Services, context));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine($"[Plugin] 注册失败:{plugin.Id},{ex.Message}");
|
||||
throw new InvalidOperationException($"插件 {plugin.Id} ({plugin.GetType().Assembly.Location}) 注册失败:{ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
host.Services.AddSingleton(_ => runtime);
|
||||
}
|
||||
catch { runtime.Dispose(); throw; }
|
||||
}
|
||||
|
||||
private static bool IsSystemInterface(Type type)
|
||||
{
|
||||
return type.Namespace is null
|
||||
@@ -282,40 +213,18 @@ namespace MAX.Framework.DependencyInjection
|
||||
}
|
||||
|
||||
|
||||
private static void RunDebugStep(string category, string description, Action action)
|
||||
{
|
||||
Debug.WriteLine($"[{category}] 开始:{description}");
|
||||
try
|
||||
{
|
||||
action();
|
||||
Debug.WriteLine($"[{category}] 完成:{description}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine($"[{category}] 失败:{description},{ex.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static IApplicationBuilder UseStore(this IApplicationBuilder app)
|
||||
{
|
||||
Debug.WriteLine("[Store] 开始装配应用管道");
|
||||
RunDebugStep("Middleware", "注册统一状态码中间件", () => app.UseMiddleware<UnifyStatusCodeMiddleware>());
|
||||
foreach (var (plugin, context) in app.ApplicationServices.GetRequiredService<PluginRuntime>().Entries)
|
||||
{
|
||||
try { RunDebugStep("Plugin", $"装配管道 {plugin.Id}", () => plugin.Configure(app, context)); }
|
||||
catch (Exception ex) { throw new InvalidOperationException($"插件 {plugin.Id} 管道装配失败:{ex.Message}", ex); }
|
||||
}
|
||||
app.UseMiddleware<UnifyStatusCodeMiddleware>();
|
||||
foreach (IStartup startup in Startups)
|
||||
{
|
||||
RunDebugStep("Startup", $"执行启动回调 {startup.GetType().FullName}", () => startup.Start((app as IHost).Services));
|
||||
startup.Start((app as IHost).Services);
|
||||
}
|
||||
|
||||
foreach (IModule module in Modules)
|
||||
{
|
||||
RunDebugStep("Module", $"装配管道 {module.GetType().FullName}", () => module.UseModule(app));
|
||||
module.UseModule(app);
|
||||
}
|
||||
Debug.WriteLine("[Store] 应用管道装配完成");
|
||||
return app;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,132 +1,18 @@
|
||||
using MAX.Core.Reflections;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using MAX.Core.Reflections;
|
||||
|
||||
namespace MAX.Framework.DependencyInjection;
|
||||
|
||||
/// <summary>发现宿主程序集及独立发布的插件;入口过滤统一使用 Match。</summary>
|
||||
namespace MAX.Framework.DependencyInjection
|
||||
{
|
||||
/// <summary>
|
||||
/// 本应用的类型查找器:在 AppTypeFinder 默认前缀(MAX. / Nexus.)之外,
|
||||
/// 增加 StoreHub、KJD 前缀,用于发现宿主和各业务模块的程序集。
|
||||
/// </summary>
|
||||
internal sealed class StoreAppTypeFinder : AppTypeFinder
|
||||
{
|
||||
public static StoreAppTypeFinder Current { get; } = new();
|
||||
private readonly Dictionary<string, AssemblyDependencyResolver> resolvers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly object gate = new();
|
||||
private bool registered;
|
||||
|
||||
protected override List<string> AvailablePrefix() => ["Store"];
|
||||
|
||||
public override List<Assembly> GetAssemblies() => GetAssemblies(null);
|
||||
|
||||
public List<Assembly> GetAssemblies(string? pluginPath)
|
||||
protected override List<string> AvailablePrefix()
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var path = Path.GetFullPath(string.IsNullOrWhiteSpace(pluginPath) ? "Plugins" : pluginPath, AppContext.BaseDirectory);
|
||||
if (!Directory.Exists(path))
|
||||
return base.GetAssemblies();
|
||||
|
||||
// 每个独立发布目录由入口 .deps.json 标识,避免把共享框架副本当作插件。
|
||||
var entries = Directory.GetFiles(path, "*.deps.json", SearchOption.AllDirectories)
|
||||
.Select(file => file[..^".deps.json".Length] + ".dll")
|
||||
.Where(file => Match(Path.GetFileName(file)))
|
||||
.OrderBy(file => file, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(entry))
|
||||
throw new FileNotFoundException("插件入口 DLL 不存在。", entry);
|
||||
resolvers.TryAdd(entry, new AssemblyDependencyResolver(entry));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new InvalidOperationException($"无法初始化插件 {entry}。", ex);
|
||||
}
|
||||
}
|
||||
if (!registered)
|
||||
{
|
||||
AssemblyLoadContext.Default.Resolving += Resolve;
|
||||
AssemblyLoadContext.Default.ResolvingUnmanagedDll += ResolveNative;
|
||||
registered = true;
|
||||
}
|
||||
|
||||
var plugins = new List<Assembly>();
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = Load(entry);
|
||||
ValidateDependencies(assembly);
|
||||
assembly.GetTypes(); // 插件类型加载失败必须在启动时暴露。
|
||||
plugins.Add(assembly);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var detail = ex is ReflectionTypeLoadException types
|
||||
? string.Join("; ", types.LoaderExceptions.Select(error => error?.Message)) : ex.Message;
|
||||
throw new InvalidOperationException($"加载插件 {entry} 失败:{detail}", ex);
|
||||
}
|
||||
}
|
||||
return base.GetAssemblies().Concat(plugins).DistinctBy(a => a.FullName).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
private static Assembly Load(string path)
|
||||
{
|
||||
var name = AssemblyName.GetAssemblyName(path);
|
||||
var existing = AssemblyLoadContext.Default.Assemblies.FirstOrDefault(a =>
|
||||
string.Equals(a.GetName().Name, name.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing is null)
|
||||
return AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(path));
|
||||
if (!string.Equals(existing.FullName, name.FullName, StringComparison.OrdinalIgnoreCase))
|
||||
throw new FileLoadException($"程序集版本冲突:请求 {name.FullName},已加载 {existing.FullName}。", path);
|
||||
return existing;
|
||||
}
|
||||
|
||||
private void ValidateDependencies(Assembly assembly)
|
||||
{
|
||||
foreach (var reference in assembly.GetReferencedAssemblies())
|
||||
{
|
||||
// 宿主 .deps.json 优先;插件发布目录中的副本仍须满足相同身份。
|
||||
var candidate = ResolvePath(reference);
|
||||
AssemblyLoadContext.Default.LoadFromAssemblyName(reference);
|
||||
if (candidate is not null)
|
||||
{
|
||||
Load(candidate);
|
||||
// 不强制遍历第三方库所有可选功能依赖;插件类型所需依赖由 GetTypes 校验。
|
||||
return ["Store"];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string? ResolvePath(AssemblyName name)
|
||||
{
|
||||
string? result = null;
|
||||
foreach (var (entry, resolver) in resolvers)
|
||||
{
|
||||
var candidate = resolver.ResolveAssemblyToPath(name);
|
||||
if (candidate is null) continue;
|
||||
var identity = AssemblyName.GetAssemblyName(candidate);
|
||||
if (result is not null && !string.Equals(AssemblyName.GetAssemblyName(result).FullName, identity.FullName, StringComparison.OrdinalIgnoreCase))
|
||||
throw new FileLoadException($"插件依赖冲突:{result} 与 {candidate}(插件 {entry})。");
|
||||
result ??= candidate;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Assembly? Resolve(AssemblyLoadContext context, AssemblyName name)
|
||||
{
|
||||
var path = ResolvePath(name);
|
||||
return path is null ? null : Load(path);
|
||||
}
|
||||
|
||||
private IntPtr ResolveNative(Assembly assembly, string name)
|
||||
{
|
||||
// 优先使用请求程序集所属插件目录,避免原生库跨插件误匹配。
|
||||
foreach (var (entry, resolver) in resolvers.OrderByDescending(pair =>
|
||||
assembly.Location.StartsWith(Path.GetDirectoryName(pair.Key)! + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var path = resolver.ResolveUnmanagedDllToPath(name);
|
||||
if (path is not null) return System.Runtime.InteropServices.NativeLibrary.Load(path);
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
using Asp.Versioning.OpenApi;
|
||||
using MAX.Framework.Security;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace MAX.Framework.DependencyInjection;
|
||||
|
||||
public static class TokenAuthServiceCollectionExtensions
|
||||
{
|
||||
// Compatibility entry point; authentication no longer uses JWT.
|
||||
public static IServiceCollection AddStoreHubJwt(this IServiceCollection services, IConfiguration configuration)
|
||||
=> services.AddStoreHubTokenAuth(configuration);
|
||||
|
||||
public static IServiceCollection AddStoreHubTokenAuth(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<TokenAuthOptions>().Bind(configuration.GetSection("TokenAuth"))
|
||||
.Validate(o => o.IdleDays > 0 && o.IdleDays <= 36500 && o.AbsoluteMaxDays > 0 && o.AbsoluteMaxDays <= 36500
|
||||
&& o.RenewIntervalMinutes > 0 && o.RenewIntervalMinutes < o.IdleDays * 1440
|
||||
&& o.CacheSeconds >= 0 && o.CacheSeconds <= 86400 && o.MaxDevicesPerUser >= 0,
|
||||
"TokenAuth 配置无效:有效期必须为正,续期间隔必须小于闲置有效期,缓存和设备数不能为负。")
|
||||
.ValidateOnStart();
|
||||
services.AddMemoryCache();
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddSingleton<TokenService>();
|
||||
services.AddSingleton<ITokenService>(sp => sp.GetRequiredService<TokenService>());
|
||||
services.AddSingleton<IOnlineUserStore, OnlineUserStore>();
|
||||
services.AddScoped<ICurrentUser, CurrentUser>();
|
||||
services.AddAuthentication("Bearer").AddScheme<AuthenticationSchemeOptions, TokenAuthenticationHandler>("Bearer", _ => { });
|
||||
services.Configure<VersionedOpenApiOptions>(options =>
|
||||
{
|
||||
// 在 OpenAPI 文档中声明 Bearer 安全方案
|
||||
options.Document.AddDocumentTransformer((document, _, _) =>
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
document.Components.SecuritySchemes.TryAdd("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "Opaque",
|
||||
Description = "登录接口返回的 accessToken,直接粘贴令牌内容即可(无需手动加 Bearer 前缀)。",
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// 仅对标记了 [Authorize] 的接口声明需要携带令牌
|
||||
options.Document.AddOperationTransformer((operation, context, _) =>
|
||||
{
|
||||
IList<object> metadata = context.Description.ActionDescriptor.EndpointMetadata;
|
||||
bool requiresAuth = metadata.OfType<IAuthorizeData>().Any()
|
||||
&& !metadata.OfType<IAllowAnonymous>().Any();
|
||||
if (requiresAuth)
|
||||
{
|
||||
operation.Security =
|
||||
[
|
||||
new OpenApiSecurityRequirement
|
||||
{
|
||||
[new OpenApiSecuritySchemeReference("Bearer", context.Document, "")] = [],
|
||||
},
|
||||
];
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -34,10 +34,6 @@ namespace MAX.Framework.Dtos
|
||||
/// <summary>提示信息</summary>
|
||||
public string? Msg { get; init; }
|
||||
|
||||
/// <summary>失败请求的跟踪标识,用于关联服务器日志。</summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? TraceId { get; init; }
|
||||
|
||||
/// <summary>请求是否成功</summary>
|
||||
public bool Success => Code == ResultCode.Success;
|
||||
|
||||
@@ -56,7 +52,7 @@ namespace MAX.Framework.Dtos
|
||||
public static implicit operator ApiResult<T>(ApiResult result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
return new ApiResult<T> { Code = result.Code, Msg = result.Msg, TraceId = result.TraceId, Data = default };
|
||||
return new ApiResult<T> { Code = result.Code, Msg = result.Msg, Data = default };
|
||||
}
|
||||
|
||||
public static ApiResult<T> Ok(T data, string msg = "操作成功")
|
||||
@@ -89,10 +85,10 @@ namespace MAX.Framework.Dtos
|
||||
public static ApiResult Ok()
|
||||
=> new ApiResult { Code = ResultCode.Success, Msg = "操作成功" };
|
||||
|
||||
public static ApiResult Fail(string msg = "操作失败", int code = ResultCode.Fail, string? traceId = null)
|
||||
public static ApiResult Fail(string msg = "操作失败", int code = ResultCode.Fail)
|
||||
{
|
||||
ValidateFailureCode(code);
|
||||
return new ApiResult { Code = code, Msg = msg, TraceId = traceId };
|
||||
return new ApiResult { Code = code, Msg = msg };
|
||||
}
|
||||
|
||||
internal static void ValidateFailureCode(int code)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
@@ -14,6 +14,7 @@
|
||||
<PackageReference Include="FreeSql" Version="3.5.311" />
|
||||
<PackageReference Include="FreeSql.Provider.MySql" Version="3.5.311" />
|
||||
<PackageReference Include="FreeSql.Repository" Version="3.5.311" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="3.0.1" />
|
||||
<PackageReference Include="Riok.Mapperly" Version="4.3.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
@@ -25,7 +26,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
|
||||
<ProjectReference Include="..\MAX.Plugins\MAX.Plugins.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
using FreeSql;
|
||||
using MediatR;
|
||||
|
||||
namespace MAX.Framework.Mediation;
|
||||
|
||||
/// <summary>为通过特性选择的命令管理事务;所有读写使用执行上下文中的 ORM。</summary>
|
||||
public sealed class TransactionBehavior<TRequest, TResponse>(
|
||||
IFreeSql freeSql, UnitOfWorkExecutionContext context) : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>
|
||||
{
|
||||
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
|
||||
RequestHandlerDelegate<TResponse> next)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (context.IsActive)
|
||||
throw new InvalidOperationException("不支持嵌套事务命令,请在同一个命令处理器内完成事务操作");
|
||||
using var work = freeSql.CreateUnitOfWork();
|
||||
work.GetOrBeginTransaction();
|
||||
using var execution = context.Enter(work.Orm);
|
||||
var response = await next();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
work.Commit();
|
||||
return response;
|
||||
// 未提交时,工作单元释放自动回滚;执行上下文同时清理。
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using System.Threading;
|
||||
|
||||
namespace MAX.Framework.Mediation;
|
||||
|
||||
/// <summary>沿当前异步调用链传递事务 ORM,隔离并行命令的执行状态。</summary>
|
||||
public sealed class UnitOfWorkExecutionContext
|
||||
{
|
||||
private readonly AsyncLocal<IFreeSql?> _current = new();
|
||||
|
||||
public IFreeSql Orm => _current.Value
|
||||
?? throw new InvalidOperationException("当前操作必须在事务管道内执行");
|
||||
|
||||
public bool IsActive => _current.Value != null;
|
||||
|
||||
internal IDisposable Enter(IFreeSql orm)
|
||||
{
|
||||
if (IsActive)
|
||||
throw new InvalidOperationException("不支持嵌套事务命令,请在同一个命令处理器内完成事务操作");
|
||||
_current.Value = orm;
|
||||
return new ExecutionScope(this);
|
||||
}
|
||||
|
||||
private sealed class ExecutionScope(UnitOfWorkExecutionContext context) : IDisposable
|
||||
{
|
||||
public void Dispose() => context._current.Value = null;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using MAX.Core.Mediation;
|
||||
using MediatR;
|
||||
|
||||
namespace MAX.Framework.Mediation;
|
||||
|
||||
/// <summary>执行请求自身的参数校验,验证通过后才进入后续管道。</summary>
|
||||
public sealed class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : IRequest<TResponse>, IValidatableRequest
|
||||
{
|
||||
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
|
||||
RequestHandlerDelegate<TResponse> next)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
request.Validate();
|
||||
return next();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,34 @@
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>持久化会话存储;同账号可有多个有效会话。</summary>
|
||||
/// <summary>
|
||||
/// 在线用户会话存储:基于 <see cref="Microsoft.Extensions.Caching.Memory.IMemoryCache"/> 的进程内实现,
|
||||
/// 用于单点登录(同一用户仅保留最新会话)、在线人员管理与退出销毁。
|
||||
/// </summary>
|
||||
public interface IOnlineUserStore
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户登录/刷新会话:同用户的新登录会覆盖旧会话,旧令牌立即失效(单点登录)。
|
||||
/// </summary>
|
||||
void SignIn(OnlineUserInfo info);
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定登录账户、指定令牌会话是否仍然有效(未被退出、未被新登录顶替)。
|
||||
/// </summary>
|
||||
bool IsTokenActive(string userName, string jti);
|
||||
/// <summary>撤销账号全部会话,用于修改密码、禁用等安全操作。</summary>
|
||||
|
||||
/// <summary>
|
||||
/// 退出登录:销毁该账户的在线会话,令牌立即失效。
|
||||
/// </summary>
|
||||
void SignOut(string userName);
|
||||
/// <summary>只撤销指定会话,用于当前客户端退出登录。</summary>
|
||||
void SignOutSession(string userName, string jti);
|
||||
/// <summary>未过期且未撤销的会话列表,不代表浏览器仍然打开。</summary>
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前在线人员列表。
|
||||
/// </summary>
|
||||
IReadOnlyList<OnlineUserInfo> GetOnlineUsers();
|
||||
/// <summary>有效会话数。</summary>
|
||||
|
||||
/// <summary>
|
||||
/// 当前在线人数。
|
||||
/// </summary>
|
||||
int Count { get; }
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
@@ -24,14 +24,14 @@ public class TokenResult
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库令牌服务:生成与校验访问令牌。
|
||||
/// JWT 令牌服务:生成与校验访问令牌。
|
||||
/// </summary>
|
||||
public interface ITokenService
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据声明集合生成访问令牌
|
||||
/// </summary>
|
||||
TokenResult CreateToken(IEnumerable<Claim> claims, string? loginIp = null, string? deviceId = null, string? deviceName = null);
|
||||
TokenResult CreateToken(IEnumerable<Claim> claims);
|
||||
|
||||
/// <summary>
|
||||
/// 校验令牌,校验失败返回 null
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using MAX.Framework.Dtos;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>
|
||||
/// JwtBearer 认证失败/授权失败时,统一返回 <see cref="ApiResult{T}"/> 格式的 JSON 响应。
|
||||
/// </summary>
|
||||
internal static class JwtBearerResponseHandler
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 未携带令牌或令牌无效(401)
|
||||
/// </summary>
|
||||
public static Task OnChallenge(JwtBearerChallengeContext context)
|
||||
{
|
||||
context.HandleResponse();
|
||||
return WriteAsync(context.HttpContext, StatusCodes.Status401Unauthorized, "未授权:请先登录或携带有效的访问令牌");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已认证但无权限(403)
|
||||
/// </summary>
|
||||
public static Task OnForbidden(ForbiddenContext context)
|
||||
{
|
||||
return WriteAsync(context.HttpContext, StatusCodes.Status403Forbidden, "禁止访问:当前账号没有权限执行该操作");
|
||||
}
|
||||
|
||||
private static async Task WriteAsync(HttpContext httpContext, int statusCode, string message)
|
||||
{
|
||||
httpContext.Response.StatusCode = statusCode;
|
||||
httpContext.Response.ContentType = "application/json; charset=utf-8";
|
||||
|
||||
string body = JsonSerializer.Serialize(ApiResult.Fail(message, statusCode), JsonOptions);
|
||||
await httpContext.Response.WriteAsync(body, Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>
|
||||
/// JWT 配置选项,默认绑定配置节 <c>Jwt</c>。
|
||||
/// </summary>
|
||||
public class JwtOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 配置节名称
|
||||
/// </summary>
|
||||
public const string SectionName = "Jwt";
|
||||
|
||||
/// <summary>
|
||||
/// 签发者
|
||||
/// </summary>
|
||||
public string Issuer { get; set; } = "StoreHub";
|
||||
|
||||
/// <summary>
|
||||
/// 受众
|
||||
/// </summary>
|
||||
public string Audience { get; set; } = "StoreHub.Client";
|
||||
|
||||
/// <summary>
|
||||
/// 签名密钥(HS256,至少 32 字节)
|
||||
/// </summary>
|
||||
public string SigningKey { get; set; } = "StoreHub-Development-SigningKey-0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// <summary>
|
||||
/// 令牌有效期(分钟)
|
||||
/// </summary>
|
||||
public int ExpiresMinutes { get; set; } = 120;
|
||||
|
||||
/// <summary>
|
||||
/// 时钟偏移(分钟),容忍客户端与服务器的时间偏差
|
||||
/// </summary>
|
||||
public int ClockSkewMinutes { get; set; } = 5;
|
||||
|
||||
/// <summary>
|
||||
/// 是否校验签发者
|
||||
/// </summary>
|
||||
public bool ValidateIssuer { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否校验受众
|
||||
/// </summary>
|
||||
public bool ValidateAudience { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否校验有效期
|
||||
/// </summary>
|
||||
public bool ValidateLifetime { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 根据当前选项构建 <see cref="TokenValidationParameters"/>,用于 JwtBearer 中间件与令牌校验。
|
||||
/// </summary>
|
||||
public TokenValidationParameters ToTokenValidationParameters()
|
||||
{
|
||||
byte[] keyBytes = Encoding.UTF8.GetBytes(SigningKey);
|
||||
return new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
|
||||
ValidateIssuer = ValidateIssuer,
|
||||
ValidIssuer = Issuer,
|
||||
ValidateAudience = ValidateAudience,
|
||||
ValidAudience = Audience,
|
||||
ValidateLifetime = ValidateLifetime,
|
||||
ClockSkew = TimeSpan.FromMinutes(ClockSkewMinutes),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>登录会话展示 DTO;Jti 为数据库 Token 记录 ID。</summary>
|
||||
/// <summary>
|
||||
/// 在线用户会话信息(单点登录:同一用户仅保留一个有效会话)。
|
||||
/// </summary>
|
||||
public class OnlineUserInfo
|
||||
{
|
||||
public string Jti { get; set; } = string.Empty;
|
||||
/// <summary>登录账户(唯一,作为会话键)</summary>
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>用户昵称</summary>
|
||||
public string NickName { get; set; } = string.Empty;
|
||||
/// <summary>服务端观察到的客户端 IP;反向代理需配置受信任的转发头。</summary>
|
||||
public string LoginIp { get; set; } = string.Empty;
|
||||
/// <summary>UTC 登录时间。</summary>
|
||||
|
||||
/// <summary>当前有效会话的令牌唯一标识(jti)</summary>
|
||||
public string Jti { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>登录时间(本地时间)</summary>
|
||||
public DateTime LoginTime { get; set; }
|
||||
/// <summary>UTC 当前滑动到期时间。</summary>
|
||||
|
||||
/// <summary>会话过期时间(本地时间,与令牌 exp 一致)</summary>
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
/// <summary>UTC 撤销时间;保留记录供后续面板查询。</summary>
|
||||
public DateTime? RevokedAt { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,22 +1,80 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>Compatibility facade for existing session management callers.</summary>
|
||||
public sealed class OnlineUserStore(IFreeSql db, TokenService tokens) : IOnlineUserStore
|
||||
/// <summary>
|
||||
/// 基于 <see cref="IMemoryCache"/> 的在线用户会话存储。
|
||||
/// </summary>
|
||||
public class OnlineUserStore : IOnlineUserStore
|
||||
{
|
||||
public void SignIn(OnlineUserInfo info) => throw new NotSupportedException("请通过 ITokenService 签发数据库令牌");
|
||||
public void SignOut(string userName) => tokens.Revoke(userName);
|
||||
public void SignOutSession(string userName, string jti) => tokens.Revoke(userName, jti);
|
||||
public bool IsTokenActive(string userName, string jti) => GetOnlineUsers().Any(x => x.UserName == userName && x.Jti == jti);
|
||||
private const string CacheKeyPrefix = "online:user:";
|
||||
private readonly IMemoryCache _cache;
|
||||
// 在线人员索引:IMemoryCache 不提供公共枚举 API,这里用字典维护便于查询在线列表
|
||||
private readonly ConcurrentDictionary<string, OnlineUserInfo> _onlineIndex = new(StringComparer.Ordinal);
|
||||
|
||||
public OnlineUserStore(IMemoryCache cache)
|
||||
{
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SignIn(OnlineUserInfo info)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(info);
|
||||
|
||||
// 以登录账户为键覆盖写入:旧会话(jti)被顶替,实现单点登录
|
||||
_cache.Set(GetKey(info.UserName), info, new MemoryCacheEntryOptions
|
||||
{
|
||||
// 缓存条目与令牌同时过期,过期后自动失效
|
||||
AbsoluteExpiration = info.ExpiresAt,
|
||||
});
|
||||
_onlineIndex[info.UserName] = info;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsTokenActive(string userName, string jti)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return _cache.TryGetValue(GetKey(userName), out OnlineUserInfo? info)
|
||||
&& info is not null
|
||||
&& string.Equals(info.Jti, jti, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SignOut(string userName)
|
||||
{
|
||||
_cache.Remove(GetKey(userName));
|
||||
_onlineIndex.TryRemove(userName, out _);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<OnlineUserInfo> GetOnlineUsers()
|
||||
{
|
||||
var now = tokens.CurrentTime;
|
||||
var cutoff = tokens.AbsoluteCutoff;
|
||||
return db.Select<UserToken, TokenAccount>()
|
||||
.InnerJoin((t, u) => t.UserName == u.UserName)
|
||||
.Where((t, u) => !t.Revoked && t.ExpiresAt > now && t.CreatedAt > cutoff)
|
||||
.OrderByDescending((t, u) => t.CreatedAt)
|
||||
.ToList((t, u) => new OnlineUserInfo { Jti = t.Id.ToString(), UserName = u.UserName,
|
||||
NickName = u.NickName, LoginIp = t.Ip ?? "", LoginTime = t.CreatedAt, ExpiresAt = t.ExpiresAt });
|
||||
DateTime now = DateTime.Now;
|
||||
List<OnlineUserInfo> result = [];
|
||||
foreach (KeyValuePair<string, OnlineUserInfo> pair in _onlineIndex)
|
||||
{
|
||||
if (pair.Value.ExpiresAt > now)
|
||||
{
|
||||
result.Add(pair.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
_onlineIndex.TryRemove(pair.Key, out _);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Count => GetOnlineUsers().Count;
|
||||
|
||||
private static string GetKey(string userName) => $"{CacheKeyPrefix}{userName}";
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
# 数据库 Token 认证
|
||||
|
||||
部署前执行同目录 `user_tokens.sql`,在现有业务库 `wxxd` 中建立唯一的新表;应用不自动修改表结构。
|
||||
启动:`dotnet run --project Store.API/Store.Api.csproj`。宿主使用 `AddStoreHubTokenAuth`,管道继续使用 `UseAuthentication` / `UseAuthorization`。
|
||||
|
||||
登录接口仍返回 `tokenType`、`token`、`expiresInMinutes`,可选传入 `deviceId`、`deviceName`(各最多 100 字符)。
|
||||
客户端按 `Authorization: Bearer {token}` 发送;Token 是 32 字节安全随机数的标准 Base64(44 字符),数据库仅存 SHA256 十六进制哈希。
|
||||
`expiresInMinutes` 表示签发时的闲置有效期;服务端使用滑动过期,客户端无需刷新令牌。
|
||||
|
||||
`TokenAuth` 默认配置:IdleDays=7、AbsoluteMaxDays=30、RenewIntervalMinutes=10、CacheSeconds=30、MaxDevicesPerUser=0。
|
||||
全部时间按 UTC 保存(DATETIME 不带时区);每次使用达到续期间隔才条件更新到期时间,绝不超过创建时间加绝对期限。
|
||||
内存缓存使用固定到期时间,命中不会延长缓存寿命。缓存期间仍检查闲置及绝对期限。
|
||||
|
||||
每次登录创建新记录;相同非空 deviceId 会替换其旧记录。未提供 deviceId 的登录按独立设备计数。
|
||||
设备数为 0 时无限制,为 1 时单点登录,为 N 时保留最多 N 个有效会话,超限撤销最早的会话。
|
||||
签发在事务中锁定现有用户行,使多实例的并发登录也遵守数量限制。MySQL 业务用户表需使用 InnoDB。
|
||||
退出当前会话、修改密码后的全部会话撤销以及设备替换统一更新 Revoked 并清除当前实例缓存。
|
||||
|
||||
多实例下其他实例最多延迟 CacheSeconds 秒获知撤销;要求每次查库时设置 CacheSeconds=0。
|
||||
用户信息在缓存未命中时从实际 `wxxd.user` 表读取 id/user_name/nick_name;当前用户表没有 IsEnabled 或 Role 字段,因此未假设这些字段或新增角色策略。
|
||||
数据库故障向上抛出,由宿主处理错误,认证不会在数据库不可用时绕过校验。
|
||||
|
||||
切换后旧 JWT 失效,用户需要重新登录。旧 auth_login_session 表不再使用,保留供人工归档。
|
||||
开发固定凭据配置位于 `TokenAuth:DevelopmentToken`(Enabled、Token、UserName):基础配置禁用,`appsettings.Development.json` 开启,仅 Development 环境生效。
|
||||
使用相同的 Bearer 请求头即可测试;固定凭据不查询数据库、不创建会话、不参与滑动过期和退出吊销。关闭 Enabled 或修改 Token 可使其失效。
|
||||
保留 AddStoreHubJwt 名称作为注册入口的兼容别名;JwtClaimTypes 仅保留现有声明字段名称。
|
||||
校验:`dotnet test Tests/Store.Security.Tests/Store.Security.Tests.csproj`,使用独立 SQLite 临时库,不连接业务 MySQL。
|
||||
测试涵盖重启持久化、滑动/绝对过期、设备限制、缓存撤销与开发凭据的环境限制;MySQL 行锁行为仍需部署环境验证。
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
public sealed class TokenAuthOptions
|
||||
{
|
||||
public int IdleDays { get; set; } = 7;
|
||||
public int AbsoluteMaxDays { get; set; } = 30;
|
||||
public int RenewIntervalMinutes { get; set; } = 10;
|
||||
public int CacheSeconds { get; set; } = 30;
|
||||
public int MaxDevicesPerUser { get; set; }
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using MAX.Framework.Dtos;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
public sealed class TokenAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger, UrlEncoder encoder, ITokenService tokens,
|
||||
IConfiguration configuration, IHostEnvironment environment)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var header = Request.Headers.Authorization.ToString();
|
||||
if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) return AuthenticateResult.NoResult();
|
||||
var token = header[7..].Trim();
|
||||
// 固定凭据仅供开发调试,生产环境即使误开启配置也不能使用。
|
||||
var development = configuration.GetSection("TokenAuth:DevelopmentToken");
|
||||
if (environment.IsDevelopment() && development.GetValue<bool>("Enabled")
|
||||
&& !string.IsNullOrWhiteSpace(development["Token"])
|
||||
&& !string.IsNullOrWhiteSpace(development["UserName"])
|
||||
&& string.Equals(token, development["Token"], StringComparison.Ordinal))
|
||||
{
|
||||
var identity = new ClaimsIdentity([
|
||||
new Claim(JwtClaimTypes.UserName, development["UserName"]!),
|
||||
new Claim(JwtClaimTypes.NickName, "开发测试用户")], Scheme.Name);
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
|
||||
}
|
||||
var principal = await tokens.ValidateTokenAsync(token);
|
||||
return principal == null ? AuthenticateResult.Fail("登录已失效,请重新登录")
|
||||
: AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name));
|
||||
}
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = 401;
|
||||
Response.Headers.WWWAuthenticate = "Bearer";
|
||||
return Response.WriteAsJsonAsync(ApiResult.Fail("未授权:请先登录或携带有效的访问令牌", 401));
|
||||
}
|
||||
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = 403;
|
||||
return Response.WriteAsJsonAsync(ApiResult.Fail("禁止访问:当前账号没有权限执行该操作", 403));
|
||||
}
|
||||
}
|
||||
@@ -1,148 +1,129 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.JsonWebTokens;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
/// <summary>Opaque database tokens. All timestamps use UTC.</summary>
|
||||
public sealed class TokenService(IFreeSql db, IOptions<TokenAuthOptions> options, IMemoryCache cache,
|
||||
TimeProvider clock) : ITokenService
|
||||
/// <summary>
|
||||
/// 基于 <see cref="JwtOptions"/> 的 JWT 令牌服务。
|
||||
/// </summary>
|
||||
public class TokenService : ITokenService
|
||||
{
|
||||
private readonly TokenAuthOptions settings = options.Value;
|
||||
// Serialize local cache reads/writes and revocations to prevent stale cache resurrection.
|
||||
internal object Gate { get; } = new();
|
||||
private sealed record CachedToken(UserToken Token, TokenAccount Account);
|
||||
private static string Key(string hash) => "token-auth:" + hash;
|
||||
private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||
// MySQL DATETIME is timezone-free; preserve UTC wall time without provider-local conversion.
|
||||
private DateTime Now => DateTime.SpecifyKind(DateTimeOffset.FromUnixTimeSeconds(clock.GetUtcNow().ToUnixTimeSeconds()).UtcDateTime, DateTimeKind.Unspecified);
|
||||
private readonly JwtOptions _options;
|
||||
private readonly IOnlineUserStore _onlineUserStore;
|
||||
|
||||
internal DateTime CurrentTime => Now;
|
||||
internal DateTime AbsoluteCutoff => Now.AddDays(-settings.AbsoluteMaxDays);
|
||||
public TokenService(IOptions<JwtOptions> options, IOnlineUserStore onlineUserStore)
|
||||
{
|
||||
_options = options.Value;
|
||||
_onlineUserStore = onlineUserStore;
|
||||
}
|
||||
|
||||
public TokenResult CreateToken(IEnumerable<Claim> claims, string? loginIp = null,
|
||||
string? deviceId = null, string? deviceName = null)
|
||||
/// <inheritdoc />
|
||||
public TokenResult CreateToken(IEnumerable<Claim> claims)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(claims);
|
||||
var name = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value;
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
if (deviceId?.Length > 100 || deviceName?.Length > 100 || loginIp?.Length > 64)
|
||||
throw new ArgumentException("设备信息或 IP 超出允许长度");
|
||||
deviceId = string.IsNullOrWhiteSpace(deviceId) ? null : deviceId;
|
||||
lock (Gate)
|
||||
|
||||
DateTime now = DateTime.Now;
|
||||
DateTime expires = now.AddMinutes(_options.ExpiresMinutes);
|
||||
string jti = Guid.NewGuid().ToString("N");
|
||||
|
||||
List<Claim> allClaims = [.. claims, new Claim(JwtClaimTypes.Jti, jti)];
|
||||
|
||||
SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(_options.SigningKey));
|
||||
JsonWebTokenHandler handler = new();
|
||||
|
||||
string token = handler.CreateToken(new SecurityTokenDescriptor
|
||||
{
|
||||
var now = Now;
|
||||
var plain = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||
var expires = now.AddDays(Math.Min(settings.IdleDays, settings.AbsoluteMaxDays));
|
||||
var revokedHashes = new List<string>();
|
||||
db.Transaction(() =>
|
||||
{
|
||||
// Lock the account row so concurrent logins on different instances respect the limit.
|
||||
var account = db.Select<TokenAccount>().Where(x => x.UserName == name).ForUpdate().First()
|
||||
?? throw new InvalidOperationException("用户不存在,无法签发令牌");
|
||||
var cutoff = now.AddDays(-settings.AbsoluteMaxDays);
|
||||
var active = db.Select<UserToken>().Where(x => x.UserName == account.UserName && !x.Revoked
|
||||
&& x.ExpiresAt > now && x.CreatedAt > cutoff).OrderBy(x => x.CreatedAt).OrderBy(x => x.Id).ToList();
|
||||
var remove = active.Where(x => deviceId != null && x.DeviceId == deviceId).ToList();
|
||||
var remaining = active.Except(remove).ToList();
|
||||
if (settings.MaxDevicesPerUser > 0)
|
||||
remove.AddRange(remaining.Take(Math.Max(0, remaining.Count - settings.MaxDevicesPerUser + 1)));
|
||||
foreach (var old in remove)
|
||||
{
|
||||
db.Update<UserToken>().Set(x => x.Revoked, true).Where(x => x.Id == old.Id).ExecuteAffrows();
|
||||
revokedHashes.Add(old.TokenHash);
|
||||
}
|
||||
db.Insert(new UserToken { TokenHash = Hash(plain), UserName = account.UserName, DeviceId = deviceId,
|
||||
DeviceName = deviceName, Ip = loginIp, CreatedAt = now, LastUsedAt = now, ExpiresAt = expires })
|
||||
.ExecuteAffrows();
|
||||
Issuer = _options.Issuer,
|
||||
Audience = _options.Audience,
|
||||
Claims = ToClaimDictionary(allClaims),
|
||||
NotBefore = now,
|
||||
Expires = expires,
|
||||
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
|
||||
});
|
||||
foreach (var hash in revokedHashes) cache.Remove(Key(hash));
|
||||
return new TokenResult { Token = plain, ExpiresInMinutes = (uint)(expires - now).TotalMinutes };
|
||||
|
||||
// 注册在线会话(单点登录:同用户的新登录会顶替旧会话,旧令牌立即失效)
|
||||
RegisterSession(allClaims, jti, now, expires);
|
||||
|
||||
return new TokenResult
|
||||
{
|
||||
Token = token,
|
||||
ExpiresInMinutes = (uint)_options.ExpiresMinutes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ClaimsPrincipal?> ValidateTokenAsync(string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
JsonWebTokenHandler handler = new();
|
||||
TokenValidationResult result = await handler.ValidateTokenAsync(token, _options.ToTokenValidationParameters());
|
||||
if (!result.IsValid)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
ClaimsPrincipal principal = new(result.ClaimsIdentity);
|
||||
|
||||
// 单点登录校验:会话必须仍然有效(未被退出、未被新登录顶替)
|
||||
string? userName = principal.FindFirst(JwtClaimTypes.UserName)?.Value;
|
||||
string? jti = principal.FindFirst(JwtClaimTypes.Jti)?.Value;
|
||||
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti) || !_onlineUserStore.IsTokenActive(userName, jti))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return principal;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Task<ClaimsPrincipal?> ValidateTokenAsync(string token)
|
||||
/// <summary>
|
||||
/// 将令牌声明注册为在线会话。
|
||||
/// </summary>
|
||||
private void RegisterSession(IEnumerable<Claim> claims, string jti, DateTime loginTime, DateTime expiresAt)
|
||||
{
|
||||
// Only accept the canonical Base64 representation of 32 bytes.
|
||||
Span<byte> bytes = stackalloc byte[32];
|
||||
if (token is null || token.Length != 44 || !Convert.TryFromBase64String(token, bytes, out var length)
|
||||
|| length != 32 || Convert.ToBase64String(bytes) != token)
|
||||
return Task.FromResult<ClaimsPrincipal?>(null);
|
||||
lock (Gate)
|
||||
string? userName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value;
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
var hash = Hash(token);
|
||||
var now = Now;
|
||||
cache.TryGetValue<CachedToken>(Key(hash), out var entry);
|
||||
if (entry == null)
|
||||
{
|
||||
var row = db.Select<UserToken>().Where(x => x.TokenHash == hash).First();
|
||||
if (row == null || row.Revoked || row.ExpiresAt <= now || row.CreatedAt.AddDays(settings.AbsoluteMaxDays) <= now)
|
||||
return Task.FromResult<ClaimsPrincipal?>(null);
|
||||
var account = db.Select<TokenAccount>().Where(x => x.UserName == row.UserName).First();
|
||||
if (account == null) return Task.FromResult<ClaimsPrincipal?>(null);
|
||||
entry = new(row, account);
|
||||
return; // 未携带登录账户的令牌不纳入在线会话管理
|
||||
}
|
||||
var t = entry.Token;
|
||||
var absolute = t.CreatedAt.AddDays(settings.AbsoluteMaxDays);
|
||||
if (t.Revoked || t.ExpiresAt <= now || absolute <= now)
|
||||
|
||||
_onlineUserStore.SignIn(new OnlineUserInfo
|
||||
{
|
||||
cache.Remove(Key(hash));
|
||||
return Task.FromResult<ClaimsPrincipal?>(null);
|
||||
UserName = userName,
|
||||
NickName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.NickName)?.Value ?? string.Empty,
|
||||
Jti = jti,
|
||||
LoginTime = loginTime,
|
||||
ExpiresAt = expiresAt,
|
||||
});
|
||||
}
|
||||
if (now - t.LastUsedAt >= TimeSpan.FromMinutes(settings.RenewIntervalMinutes))
|
||||
|
||||
/// <summary>
|
||||
/// 将声明集合转换为 <see cref="SecurityTokenDescriptor.Claims"/> 所需的字典;
|
||||
/// 相同类型的多个声明合并为数组。
|
||||
/// </summary>
|
||||
private static Dictionary<string, object> ToClaimDictionary(IEnumerable<Claim> claims)
|
||||
{
|
||||
var next = now.AddDays(settings.IdleDays);
|
||||
if (next > absolute) next = absolute;
|
||||
// Conditional update never renews expired/revoked tokens or overwrites a newer renewal.
|
||||
var changed = db.Update<UserToken>().Set(x => x.LastUsedAt, now).Set(x => x.ExpiresAt, next)
|
||||
.Where(x => x.Id == t.Id && !x.Revoked && x.ExpiresAt > now && x.LastUsedAt == t.LastUsedAt)
|
||||
.ExecuteAffrows();
|
||||
if (changed == 0)
|
||||
Dictionary<string, object> result = new(StringComparer.Ordinal);
|
||||
foreach (IGrouping<string, Claim> group in claims.GroupBy(c => c.Type, StringComparer.Ordinal))
|
||||
{
|
||||
cache.Remove(Key(hash));
|
||||
var current = db.Select<UserToken>().Where(x => x.Id == t.Id).First();
|
||||
if (current == null || current.Revoked || current.ExpiresAt <= now
|
||||
|| current.CreatedAt.AddDays(settings.AbsoluteMaxDays) <= now)
|
||||
return Task.FromResult<ClaimsPrincipal?>(null);
|
||||
t = current;
|
||||
entry = new(current, entry.Account);
|
||||
object[] values = group.Select(c => (object)c.Value).ToArray();
|
||||
result[group.Key] = values.Length == 1 ? values[0] : values;
|
||||
}
|
||||
else
|
||||
{
|
||||
t.LastUsedAt = now;
|
||||
t.ExpiresAt = next;
|
||||
}
|
||||
}
|
||||
if (settings.CacheSeconds > 0 && !cache.TryGetValue(Key(hash), out object? _))
|
||||
{
|
||||
var ttl = TimeSpan.FromSeconds(settings.CacheSeconds);
|
||||
if (ttl > t.ExpiresAt - now) ttl = t.ExpiresAt - now;
|
||||
if (ttl > absolute - now) ttl = absolute - now;
|
||||
cache.Set(Key(hash), entry, ttl);
|
||||
}
|
||||
ClaimsPrincipal principal = new(new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, t.UserName.ToString()),
|
||||
new Claim(JwtClaimTypes.UserName, entry.Account.UserName),
|
||||
new Claim(JwtClaimTypes.NickName, entry.Account.NickName),
|
||||
new Claim(JwtClaimTypes.Jti, t.Id.ToString())], "Bearer"));
|
||||
return Task.FromResult<ClaimsPrincipal?>(principal);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Revoke(string userName, string? sessionId = null)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
var user = db.Select<TokenAccount>().Where(x => x.UserName == userName).First();
|
||||
if (user == null) return;
|
||||
var rows = db.Select<UserToken>().Where(x => x.UserName == user.UserName && !x.Revoked).ToList();
|
||||
if (sessionId != null) rows = rows.Where(x => x.Id.ToString() == sessionId).ToList();
|
||||
var ids = rows.Select(x => x.Id).ToArray();
|
||||
if (ids.Length == 0) return;
|
||||
db.Update<UserToken>().Set(x => x.Revoked, true).Where(x => ids.Contains(x.Id)).ExecuteAffrows();
|
||||
foreach (var row in rows) cache.Remove(Key(row.TokenHash));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
namespace MAX.Framework.Security;
|
||||
|
||||
[Table(Name = "wxxd.user_tokens")]
|
||||
public sealed class UserToken
|
||||
{
|
||||
[Column(IsPrimary = true, IsIdentity = true)]
|
||||
public long Id { get; set; }
|
||||
[Column(StringLength = 64)]
|
||||
public string TokenHash { get; set; } = "";
|
||||
[Column(StringLength = 100)]
|
||||
public string UserName { get; set; }
|
||||
[Column(StringLength = 100)]
|
||||
public string? DeviceId { get; set; }
|
||||
[Column(StringLength = 100)]
|
||||
public string? DeviceName { get; set; }
|
||||
[Column(StringLength = 64)]
|
||||
public string? Ip { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime LastUsedAt { get; set; }
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
public bool Revoked { get; set; }
|
||||
}
|
||||
|
||||
// Read-only mapping of the existing user table; never synchronize this projection.
|
||||
[Table(Name = "wxxd.user", DisableSyncStructure = true)]
|
||||
public sealed class TokenAccount
|
||||
{
|
||||
[Column(Name = "id", IsPrimary = true)]
|
||||
public int Id { get; set; }
|
||||
[Column(Name = "user_name")]
|
||||
public string UserName { get; set; } = "";
|
||||
[Column(Name = "nick_name")]
|
||||
public string NickName { get; set; } = "";
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
-- Run once before deploying the new authentication service. No existing business tables are modified.
|
||||
CREATE TABLE IF NOT EXISTS wxxd.user_tokens (
|
||||
Id BIGINT NOT NULL AUTO_INCREMENT,
|
||||
TokenHash VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
UserId INT NOT NULL,
|
||||
DeviceId VARCHAR(100) NULL,
|
||||
DeviceName VARCHAR(100) NULL,
|
||||
Ip VARCHAR(64) NULL,
|
||||
CreatedAt DATETIME NOT NULL,
|
||||
LastUsedAt DATETIME NOT NULL,
|
||||
ExpiresAt DATETIME NOT NULL,
|
||||
Revoked TINYINT(1) NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (Id),
|
||||
UNIQUE KEY IX_UserTokens_TokenHash (TokenHash),
|
||||
KEY IX_UserTokens_UserId (UserId),
|
||||
KEY IX_UserTokens_ExpiresAt (ExpiresAt)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
@@ -1,27 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MAX.Framework.Validation;
|
||||
|
||||
/// <summary>通用请求校验入口,供各模块复用,不依赖 HTTP、数据库或具体业务。</summary>
|
||||
public static class RequestValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// 检查对象非空,并验证全部属性上的数据注解及 IValidatableObject 规则。
|
||||
/// 不递归验证子对象;对象为空抛出 ArgumentNullException,规则不满足抛出 ValidationException。
|
||||
/// </summary>
|
||||
public static void Validate(object? request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
Validator.ValidateObject(request, new ValidationContext(request), validateAllProperties: true);
|
||||
}
|
||||
|
||||
/// <summary>不抛出规则验证异常,适用于登录等需要自行处理校验结果的入口;对象为空仍视为调用错误。</summary>
|
||||
public static bool TryValidate(object? request, out IReadOnlyList<ValidationResult> errors)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var results = new List<ValidationResult>();
|
||||
bool valid = Validator.TryValidateObject(request, new ValidationContext(request), results, validateAllProperties: true);
|
||||
errors = results.AsReadOnly();
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace MAX.Plugins;
|
||||
|
||||
/// <summary>独立插件入口。实现类必须具有无参构造函数。</summary>
|
||||
public interface IPlugin
|
||||
{
|
||||
string Id { get; }
|
||||
int Priority { get; }
|
||||
void ConfigureServices(IServiceCollection services, PluginContext context);
|
||||
void Configure(IApplicationBuilder app, PluginContext context);
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -1,32 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace MAX.Plugins;
|
||||
|
||||
public abstract class PluginBase : IPlugin
|
||||
{
|
||||
public abstract string Id { get; }
|
||||
public virtual int Priority => 0;
|
||||
protected PluginContext Context { get; private set; } = null!;
|
||||
|
||||
public void ConfigureServices(IServiceCollection services, PluginContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (!string.Equals(Id, context.Id, StringComparison.Ordinal))
|
||||
throw new ArgumentException("插件上下文标识不匹配。", nameof(context));
|
||||
if (Context is not null) throw new InvalidOperationException($"插件 {Id} 已注册。");
|
||||
Context = context;
|
||||
RegisterServices(services);
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, PluginContext context)
|
||||
{
|
||||
if (!ReferenceEquals(Context, context))
|
||||
throw new InvalidOperationException($"插件 {Id} 尚未注册或上下文不匹配。");
|
||||
ConfigureApplication(app);
|
||||
}
|
||||
protected abstract void RegisterServices(IServiceCollection services);
|
||||
protected virtual void ConfigureApplication(IApplicationBuilder app) { }
|
||||
protected string RequireConfiguration(string key) => Context.RequireConfiguration(key);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace MAX.Plugins;
|
||||
|
||||
/// <summary>插件独立配置,不合并宿主或其他插件配置。</summary>
|
||||
public sealed class PluginContext : IDisposable
|
||||
{
|
||||
private int disposed;
|
||||
public string Id { get; }
|
||||
public string DirectoryPath { get; }
|
||||
public IHostEnvironment Environment { get; }
|
||||
public IConfigurationRoot Configuration { get; }
|
||||
|
||||
public PluginContext(string id, string directoryPath, IHostEnvironment environment)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
Id = id;
|
||||
DirectoryPath = Path.GetFullPath(directoryPath);
|
||||
Environment = environment;
|
||||
Configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(DirectoryPath)
|
||||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
|
||||
.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: false)
|
||||
.AddEnvironmentVariables($"Plugins__{id}__")
|
||||
.Build();
|
||||
}
|
||||
|
||||
public string RequireConfiguration(string key) =>
|
||||
!string.IsNullOrWhiteSpace(Configuration[key]) ? Configuration[key]!
|
||||
: throw new InvalidOperationException($"插件 {Id} 缺少配置 {key},请检查 {Path.Combine(DirectoryPath, "appsettings.json")}。");
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref disposed, 1) == 0)
|
||||
(Configuration as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
<!-- See https://aka.ms/dotnet/msbuild/customize for more details on customizing your build -->
|
||||
<PropertyGroup>
|
||||
<!-- API 和独立插件共用的部署目录,可通过 MSBuild 属性覆盖。 -->
|
||||
<StoreHostOutputPath Condition="'$(StoreHostOutputPath)' == ''">$(MSBuildThisFileDirectory)Bin\</StoreHostOutputPath>
|
||||
<DefaultTargetFramework>net10.0</DefaultTargetFramework>
|
||||
<TargetFramework>$(DefaultTargetFramework)</TargetFramework>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
<Project>
|
||||
<UsingTask TaskName="FindHostDuplicatePluginFiles" TaskFactory="RoslynCodeTaskFactory"
|
||||
AssemblyFile="$(MSBuildToolsPath)/Microsoft.Build.Tasks.Core.dll">
|
||||
<ParameterGroup>
|
||||
<HostDirectory ParameterType="System.String" Required="true" />
|
||||
<Duplicates ParameterType="Microsoft.Build.Framework.ITaskItem[]" Output="true" />
|
||||
</ParameterGroup>
|
||||
<Task>
|
||||
<Using Namespace="System" />
|
||||
<Using Namespace="System.IO" />
|
||||
<Using Namespace="System.Collections.Generic" />
|
||||
<Using Namespace="System.Security.Cryptography" />
|
||||
<Code Type="Fragment" Language="cs"><![CDATA[
|
||||
var host = Path.GetFullPath(HostDirectory);
|
||||
var plugins = Path.GetFullPath(Path.Combine(host, "Plugins"));
|
||||
var duplicates = new List<Microsoft.Build.Framework.ITaskItem>();
|
||||
if (Directory.Exists(plugins))
|
||||
{
|
||||
foreach (var plugin in Directory.GetDirectories(plugins))
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(plugin, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = file.Substring(plugin.TrimEnd(Path.DirectorySeparatorChar).Length + 1);
|
||||
// Plugin settings are owned by the plugin even when identical to host settings.
|
||||
if (Path.GetFileName(file).StartsWith("appsettings", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(Path.GetExtension(file), ".json", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
var shared = Path.GetFullPath(Path.Combine(host, relative));
|
||||
// Only compare files below the host, outside its plugin subtree.
|
||||
if (!shared.StartsWith(host.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
|
||||
|| shared.StartsWith(plugins + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
|
||||
|| !File.Exists(shared) || new FileInfo(file).Length != new FileInfo(shared).Length)
|
||||
continue;
|
||||
using (var hash = SHA256.Create())
|
||||
using (var source = File.OpenRead(file))
|
||||
using (var target = File.OpenRead(shared))
|
||||
{
|
||||
if (Convert.ToBase64String(hash.ComputeHash(source)) == Convert.ToBase64String(hash.ComputeHash(target)))
|
||||
duplicates.Add(new Microsoft.Build.Utilities.TaskItem(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Duplicates = duplicates.ToArray();
|
||||
]]></Code>
|
||||
</Task>
|
||||
</UsingTask>
|
||||
|
||||
<!-- Run again after the host build, so plugin-first build order is supported. -->
|
||||
<Target Name="RemoveHostDuplicatePluginFiles" AfterTargets="Build"
|
||||
Condition="'$(MSBuildProjectName)' == 'Store.Api' and '$(DesignTimeBuild)' != 'true'">
|
||||
<FindHostDuplicatePluginFiles HostDirectory="$(StoreHostOutputPath)">
|
||||
<Output TaskParameter="Duplicates" ItemName="_HostDuplicatePluginFile" />
|
||||
</FindHostDuplicatePluginFiles>
|
||||
<Delete Files="@(_HostDuplicatePluginFile)" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,123 @@
|
||||
using Hangfire;
|
||||
using Hangfire.MySql;
|
||||
using HangfireBasicAuthenticationFilter;
|
||||
using MAX.Core.Interfaces;
|
||||
using MAX.Framework.Interfaces;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Store.Modules.CloudProduct.Services;
|
||||
|
||||
namespace Store.Modules.CloudProduct
|
||||
{
|
||||
|
||||
public class CloudProductModule : IModule
|
||||
{
|
||||
/// <summary>
|
||||
/// 本模块自己的配置文件
|
||||
/// </summary>
|
||||
public const string ConfigurationFileName = "appsettings.CloudProduct.json";
|
||||
|
||||
public int Priority => IntPriority.Normal;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 服务注册阶段(builder.Build() 之前):这里只能拿到容器和配置,碰不到 app
|
||||
/// </summary>
|
||||
public void AddModule(IHostApplicationBuilder host)
|
||||
{
|
||||
IServiceCollection services = host.Services;
|
||||
IConfigurationManager configuration = host.Configuration;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(ConfigurationFileName))
|
||||
{
|
||||
string path = Path.IsPathRooted(ConfigurationFileName)? ConfigurationFileName: Path.Combine(AppContext.BaseDirectory, ConfigurationFileName);
|
||||
configuration.AddJsonFile(path, optional: false, reloadOnChange: true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//// 本模块的配置节(Search / RawData / Indexing / Delete)都在模块自己的配置文件里,
|
||||
//// 关键项缺失直接报错,避免 OpenSearch 地址为空、原始数据写到意外目录之类的隐性故障
|
||||
RequireConfiguration(configuration, "Search:Url");
|
||||
RequireConfiguration(configuration, "Search:IndexName");
|
||||
RequireConfiguration(configuration, "Search:FavoritesIndexName");
|
||||
RequireConfiguration(configuration, "RawData:Path");
|
||||
|
||||
// ===== Hangfire 后台定时任务(商品分词同步) =====
|
||||
var hangfireConnection = configuration.GetValue<string>("CloudProductConnection")
|
||||
?? throw new InvalidOperationException("缺少配置 ConnectionStrings:DefaultConnection,CloudProduct 模块的 Hangfire 无法启动。");
|
||||
|
||||
// AllowUserVariables=true:Hangfire.MySqlStorage 的建表/查询语句依赖用户变量
|
||||
var connectionStringBuilder = new MySqlConnectionStringBuilder(hangfireConnection)
|
||||
{
|
||||
AllowUserVariables = true
|
||||
};
|
||||
|
||||
services.AddHangfire(config => config
|
||||
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
|
||||
.UseSimpleAssemblyNameTypeSerializer()
|
||||
.UseRecommendedSerializerSettings()
|
||||
.UseStorage(new MySqlStorage(connectionStringBuilder.ConnectionString, new MySqlStorageOptions() { TablesPrefix = "Hangfire_" })));
|
||||
services.AddHangfireServer();
|
||||
services.AddTransient<GoodsIndexJob>();
|
||||
services.AddTransient<GoodsViolationIndexJob>();
|
||||
services.AddAuthorization(options => options.AddPolicy("CloudGoodsViolationWrite",
|
||||
policy => policy.RequireAuthenticatedUser().RequireClaim("permission", "cloudgoods:violation:write")));
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 管道装配阶段(builder.Build() 之后、app.Run() 之前):这里可以挂中间件、解析容器里的服务
|
||||
/// </summary>
|
||||
public void UseModule(IApplicationBuilder app)
|
||||
{
|
||||
try
|
||||
{
|
||||
var Configuration = app.ApplicationServices.GetService<IConfiguration>()!;
|
||||
// Hangfire 后台任务看板(默认地址 /hangfire)
|
||||
app.UseHangfireDashboard("/hangfire", new DashboardOptions
|
||||
{
|
||||
Authorization = new[]
|
||||
{
|
||||
new HangfireCustomBasicAuthenticationFilter(){
|
||||
User = Configuration.GetValue<string>("Hangfire:Dashboard:User") ?? "admin",
|
||||
Pass = Configuration.GetValue<string>("Hangfire:Dashboard:Pass") ?? "1234560"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 注册定时任务:把未同步(IndexStatus=0)的商品写入 OpenSearch 分词索引
|
||||
var cron = Configuration.GetValue<string>("Indexing:Cron") ?? "*/5 * * * *";
|
||||
|
||||
// 用容器里的 IRecurringJobManager,而不是静态 RecurringJob:
|
||||
// AddHangfire 只把 JobStorage 注册进容器(没有设置 JobStorage.Current),静态 API 在 Build() 之后调用会直接抛异常。
|
||||
app.ApplicationServices.GetRequiredService<IRecurringJobManager>().AddOrUpdate<GoodsIndexJob>(
|
||||
"goods-index-pending",
|
||||
job => job.ProcessPendingAsync(),
|
||||
cron);
|
||||
app.ApplicationServices.GetRequiredService<IRecurringJobManager>().AddOrUpdate<GoodsViolationIndexJob>(
|
||||
"goods-violation-delete-pending", job => job.ProcessPendingAsync(), "* * * * *");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 数据库不可用/表未初始化时避免阻断应用启动(看板与定时任务都会连库),恢复后重启即可重新装配
|
||||
Console.WriteLine("[Hangfire] 看板/定时任务装配失败: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验模块配置项存在(值来自模块自己的 <see cref="ConfigurationFileName"/>)
|
||||
/// </summary>
|
||||
private static void RequireConfiguration(IConfiguration configuration, string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(configuration.GetValue<string>(key)))
|
||||
{
|
||||
throw new InvalidOperationException($"缺少配置 {key},请检查模块配置文件 {ConfigurationFileName}。");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
-4
@@ -2,6 +2,7 @@ using Asp.Versioning;
|
||||
using MAX.Framework.Commons;
|
||||
using MAX.Framework.Dtos;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Store.Framework.Base;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
@@ -12,6 +13,8 @@ using System.Text.Json.Nodes;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Controllers
|
||||
{
|
||||
/// <summary>云商品管理:商品查询、导入、违规上报及搜索索引维护。</summary>
|
||||
[Tags("云商品")]
|
||||
[ApiVersionNeutral]
|
||||
[Route("api/CloudGoods/[action]")]
|
||||
public class GoodsController : AppControllerBase
|
||||
@@ -20,31 +23,62 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
private readonly IOpenSearchService _searchService;
|
||||
private readonly IRawDataStorage _rawDataStorage;
|
||||
private readonly GoodsIndexJob _goodsIndexJob;
|
||||
private readonly GoodsViolationService _violations;
|
||||
|
||||
public GoodsController(IGoodsService goodsService, IOpenSearchService searchService, IRawDataStorage rawDataStorage, GoodsIndexJob goodsIndexJob)
|
||||
public GoodsController(IGoodsService goodsService, IOpenSearchService searchService, IRawDataStorage rawDataStorage, GoodsIndexJob goodsIndexJob, GoodsViolationService violations)
|
||||
{
|
||||
_violations = violations;
|
||||
_goodsService = goodsService;
|
||||
_searchService = searchService;
|
||||
_rawDataStorage = rawDataStorage;
|
||||
_goodsIndexJob = goodsIndexJob;
|
||||
}
|
||||
|
||||
/// <summary>获取全部违规原因字典,包含未启用违规判定的原因,按ID升序返回。</summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("获取违规原因字典")]
|
||||
public Task<List<ViolationReasonDto>> GetViolationReasons()
|
||||
=> _violations.GetReasonsAsync();
|
||||
|
||||
/// <summary>批量上报违规商品;重复上报合并原因。</summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("批量上报违规商品")]
|
||||
public Task<List<ReportGoodsViolationsResult>> ReportViolations([FromBody] ReportGoodsViolationItem[] items)
|
||||
=> _violations.ReportAsync(items);
|
||||
|
||||
/// <summary>批量解除商品违规,恢复正常商品索引;失败后由后台索引任务重试。</summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("解除商品违规并恢复索引")]
|
||||
public Task<RemoveGoodsViolationsResult> RemoveViolations([FromBody] long[] ids)
|
||||
=> _violations.RemoveAsync(ids);
|
||||
|
||||
/// <summary>按商品编号批量查询是否违规。</summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("批量查询商品违规状态")]
|
||||
public Task<List<GoodsViolationStatus>> GetViolationStatus([FromBody] long[] ids)
|
||||
=> _violations.GetStatusAsync(ids);
|
||||
|
||||
/// <summary>获取服务器当前日期(长日期格式)。</summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("获取服务器当前日期")]
|
||||
public async Task<string> Time()
|
||||
{
|
||||
return DateTime.Now.ToLongDateString();
|
||||
}
|
||||
/// <summary>手动执行待处理商品的索引任务。</summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("处理待建立索引的商品")]
|
||||
public async Task Job()
|
||||
{
|
||||
await _goodsIndexJob.ProcessPendingAsync();
|
||||
}
|
||||
/// <summary>
|
||||
/// 搜索
|
||||
/// 分页搜索商品,可按标题、价格、类目、销量和平台筛选。
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
/// <param name="request">商品筛选条件及分页参数。</param>
|
||||
/// <returns>符合条件的商品列表及总数。</returns>
|
||||
[HttpPost]
|
||||
[EndpointSummary("分页搜索商品")]
|
||||
public async Task<PageData<GoodsEntity>> SearchGoods(GoodsSearchRequest request)
|
||||
{
|
||||
// 1. 参数基础校验
|
||||
@@ -145,6 +179,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[ActionName("SearchGoodsToIds")]
|
||||
[EndpointSummary("按关键词搜索商品摘要")]
|
||||
public async Task<PageData<GoodsSearchDocument>> SearchGoodsSummary(string keyword, int pageindex = 1, int pagesize = 20)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(keyword))
|
||||
@@ -172,6 +207,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 导入测试数据:读取 ImportConverters/data.txt 并走完整解析 + 入库 + 分词流程。
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("导入测试商品数据")]
|
||||
public async Task<GoodsImportResult> ImportTestData()
|
||||
{
|
||||
var filePath = GetDataFilePath();
|
||||
@@ -198,6 +234,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 导入接口:接收客户端批量上传的 JSON 文件,解析后入库并写入分词索引。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("批量导入商品 JSON 文件")]
|
||||
public async Task<GoodsImportResult> ImportFiles([FromForm] List<IFormFile> files)
|
||||
{
|
||||
if (files == null || files.Count == 0)
|
||||
@@ -247,6 +284,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 查询 OpenSearch 状态。
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("查询 OpenSearch 服务状态")]
|
||||
public async Task<OpenSearchStatusDto> GetOpenSearchStatus()
|
||||
{
|
||||
return await _searchService.GetStatusAsync();
|
||||
@@ -256,6 +294,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 检查搜索索引是否存在。
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("检查商品搜索索引是否存在")]
|
||||
public async Task<bool> IndexExists()
|
||||
{
|
||||
return await _searchService.IndexExistsAsync();
|
||||
@@ -265,6 +304,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 检查索引映射(分析器)是否符合当前服务要求。
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[EndpointSummary("检查商品索引映射是否正常")]
|
||||
public async Task<bool> IndexMappingHealthy()
|
||||
{
|
||||
return await _searchService.IsIndexMappingHealthyAsync();
|
||||
@@ -274,6 +314,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 创建搜索索引(含 IK 分词映射,已存在且映射正常时跳过)。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("创建商品搜索索引")]
|
||||
public async Task<bool> CreateIndex()
|
||||
{
|
||||
return await _searchService.CreateIndexAsync();
|
||||
@@ -283,6 +324,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 删除搜索索引。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("删除商品搜索索引")]
|
||||
public async Task DeleteIndex()
|
||||
{
|
||||
await _searchService.DeleteIndexAsync();
|
||||
@@ -292,6 +334,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 手动刷新搜索索引,使最新写入立即可搜索。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("刷新商品搜索索引")]
|
||||
public async Task RefreshIndex()
|
||||
{
|
||||
await _searchService.RefreshIndexAsync();
|
||||
@@ -301,6 +344,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 手动新增或覆盖一条搜索文档。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("新增或覆盖商品搜索文档")]
|
||||
public async Task AddSearchDocument([FromBody] GoodsSearchDocument document)
|
||||
{
|
||||
if (document == null || document.Id <= 0)
|
||||
@@ -315,27 +359,44 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 读取指定商品详情:解压缩原始数据并返回 JSON。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("查询商品详情")]
|
||||
public async Task<JsonNode> GetGoodsDetail([FromQuery] long goodsId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var raw = await GetRawDataOrThrowAsync(goodsId);
|
||||
var node = JsonNode.Parse(raw);
|
||||
return node ?? throw new AppException("商品详情解析失败", ResultCode.BusinessError);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
throw new AppException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取指定商品的原始数据(解压缩后原样返回)。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("读取商品原始数据")]
|
||||
public async Task<string> GetGoodsRawData([FromQuery] long goodsId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await GetRawDataOrThrowAsync(goodsId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new AppException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新从数据库读取指定商品,覆盖 OpenSearch 已有分词并重新分词。
|
||||
/// ids 为空时重建全部商品。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("重建商品搜索文档")]
|
||||
public async Task<long> RebuildIndex([FromBody] long[]? ids)
|
||||
{
|
||||
return await _goodsService.RebuildSearchIndexAsync(ids);
|
||||
@@ -346,6 +407,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// 软删除将 Status 置 1,硬删除物理删除记录;两种方式都会删除 OpenSearch 中对应文档。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[EndpointSummary("批量删除商品")]
|
||||
public async Task<long> DeleteGoods([FromBody] long[]? ids)
|
||||
{
|
||||
if (ids == null || ids.Length == 0)
|
||||
@@ -361,6 +423,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[ActionName("ClearSearch")]
|
||||
[EndpointSummary("清空并重建商品搜索索引")]
|
||||
public async Task<bool> ClearSearchIndex()
|
||||
{
|
||||
return await _searchService.ClearIndexAsync();
|
||||
@@ -371,6 +434,7 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[ActionName("GetSearchCount")]
|
||||
[EndpointSummary("统计商品搜索文档数量")]
|
||||
public async Task<long> GetSearchDocumentCount()
|
||||
{
|
||||
return await _searchService.CountDocumentsAsync();
|
||||
@@ -383,7 +447,10 @@ namespace Store.Modules.CloudProduct.Controllers
|
||||
|
||||
var raw = await _rawDataStorage.ReadAsync(goodsId);
|
||||
if (raw == null)
|
||||
{
|
||||
System.IO.File.WriteAllText("./NoGoods.txt", goodsId.ToString());
|
||||
throw new AppException($"商品原始数据不存在: {goodsId}", ResultCode.NotFound);
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,36 @@
|
||||
namespace Store.Modules.CloudProduct.Dtos;
|
||||
|
||||
public class ViolationReasonDto
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public bool IsViolation { get; set; }
|
||||
}
|
||||
|
||||
public class ReportGoodsViolationItem
|
||||
{
|
||||
public long GoodsId { get; set; }
|
||||
/// <summary>原因名称,例如“出售假冒商品”;新名称默认仅记录字典,不判定违规。</summary>
|
||||
public string Reasons { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class ReportGoodsViolationsResult
|
||||
{
|
||||
public long GoodsId { get; set; }
|
||||
/// <summary>存在违规记录且已完成索引下架时为 true,否则为 false。</summary>
|
||||
public bool IsOffShelf { get; set; }
|
||||
}
|
||||
|
||||
public class GoodsViolationStatus
|
||||
{
|
||||
public long GoodsId { get; set; }
|
||||
public bool IsViolation { get; set; }
|
||||
}
|
||||
|
||||
public class RemoveGoodsViolationsResult
|
||||
{
|
||||
public int RemovedCount { get; set; }
|
||||
public long[] RestoredGoodsIds { get; set; } = [];
|
||||
public long[] PendingRestoreGoodsIds { get; set; } = [];
|
||||
/// <summary>商品不存在、已删除或恢复期间再次被上报违规的编号。</summary>
|
||||
public long[] SkippedGoodsIds { get; set; } = [];
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,22 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Entities;
|
||||
|
||||
[Table(Name = "goods_violation")]
|
||||
public class GoodsViolationEntity
|
||||
{
|
||||
[Column(Name = "goods_id", IsPrimary = true)]
|
||||
public long GoodsId { get; set; }
|
||||
|
||||
[Column(Name = "reason_id", IsPrimary = true, IsNullable = false)]
|
||||
public uint ReasonId { get; set; }
|
||||
|
||||
[Column(Name = "is_index_deleted")]
|
||||
public bool IsIndexDeleted { get; set; }
|
||||
|
||||
[Column(Name = "created_time")]
|
||||
public DateTime CreatedTime { get; set; }
|
||||
|
||||
[Column(Name = "updated_time")]
|
||||
public DateTime UpdatedTime { get; set; }
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,16 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Entities;
|
||||
|
||||
[Table(Name = "violation_reason")]
|
||||
public class ViolationReasonEntity
|
||||
{
|
||||
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||
public uint Id { get; set; }
|
||||
|
||||
[Column(Name = "name", StringLength = 100, IsNullable = false)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
[Column(Name = "is_violation", IsNullable = false)]
|
||||
public bool IsViolation { get; set; }
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,118 @@
|
||||
using FreeSql;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Store.Modules.CloudProduct.Entities;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Repositorys;
|
||||
|
||||
public class GoodsViolationRepository(
|
||||
[FromKeyedServices("CloudProductConnection")] IFreeSql fsql)
|
||||
: BaseRepository<GoodsViolationEntity>(fsql), IScopedDependency
|
||||
{
|
||||
public Task<List<ViolationReasonDto>> GetReasonsAsync() => Orm.Select<ViolationReasonEntity>()
|
||||
.OrderBy(x => x.Id).ToListAsync(x => new ViolationReasonDto
|
||||
{
|
||||
Name = x.Name,
|
||||
IsViolation = x.IsViolation
|
||||
});
|
||||
|
||||
public Task<List<long>> GetViolationIdsAsync(long[] ids) => Select
|
||||
.Where(x => ids.Contains(x.GoodsId)).Distinct().ToListAsync(x => x.GoodsId);
|
||||
|
||||
public async Task<List<long>> GetOffShelfGoodsIdsAsync(long[] ids)
|
||||
{
|
||||
var records = await Select.Where(x => ids.Contains(x.GoodsId)).ToListAsync();
|
||||
return records.GroupBy(x => x.GoodsId).Where(x => x.All(row => row.IsIndexDeleted))
|
||||
.Select(x => x.Key).ToList();
|
||||
}
|
||||
|
||||
// 解除违规和设置待同步必须一起提交,进程中断后后台索引任务仍可恢复。
|
||||
public async Task<int> RemoveAndScheduleRestoreAsync(long[] ids)
|
||||
{
|
||||
using var unit = Orm.CreateUnitOfWork();
|
||||
var violations = unit.GetRepository<GoodsViolationEntity>();
|
||||
var goods = unit.GetRepository<GoodsEntity>();
|
||||
var removedIds = await violations.Select.Where(x => ids.Contains(x.GoodsId)).Distinct().ToListAsync(x => x.GoodsId);
|
||||
await violations.DeleteAsync(x => ids.Contains(x.GoodsId));
|
||||
await goods.UpdateDiy.Set(x => x.IsSegmented, (byte)0)
|
||||
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ExecuteAffrowsAsync();
|
||||
unit.Commit();
|
||||
return removedIds.Count;
|
||||
}
|
||||
|
||||
public Task<List<GoodsEntity>> GetRestorableGoodsAsync(long[] ids) => Orm.Select<GoodsEntity>()
|
||||
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ToListAsync();
|
||||
|
||||
public Task<int> MarkRestoredAsync(long[] ids) => Orm.Update<GoodsEntity>()
|
||||
.Set(x => x.IsSegmented, (byte)1)
|
||||
.Where(x => ids.Contains(x.GoodsId) && x.Status == 0).ExecuteAffrowsAsync();
|
||||
|
||||
// 调用方持有 GoodsIndexLock,事务内合并原因,避免并发覆盖。
|
||||
public async Task<long[]> MergeAsync(Dictionary<long, string[]> items)
|
||||
{
|
||||
using var unit = Orm.CreateUnitOfWork();
|
||||
var repository = unit.GetRepository<GoodsViolationEntity>();
|
||||
var reasonRepository = unit.GetRepository<ViolationReasonEntity>();
|
||||
var reasonIds = new Dictionary<string, uint>(StringComparer.Ordinal);
|
||||
foreach (var name in items.Values.SelectMany(x => x).Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
// 让数据库按字典表的排序规则匹配名称,与唯一索引保持一致。
|
||||
var reason = await reasonRepository.Select.Where(x => x.Name == name).FirstAsync();
|
||||
// 新类型只收录到字典,绝不因首次上报自动启用商品封禁。
|
||||
reason ??= await reasonRepository.InsertAsync(new ViolationReasonEntity { Name = name, IsViolation = false });
|
||||
// 数据库排序规则可能忽略部分字符差异;判定时仍要求名称完整相等。
|
||||
if (reason.IsViolation && string.Equals(reason.Name, name, StringComparison.Ordinal))
|
||||
reasonIds.Add(name, reason.Id);
|
||||
}
|
||||
var ids = items.Keys.ToArray();
|
||||
var existing = (await repository.Select.Where(x => ids.Contains(x.GoodsId))
|
||||
.ToListAsync()).ToLookup(x => x.GoodsId);
|
||||
var now = DateTime.UtcNow;
|
||||
var recordedIds = new List<long>();
|
||||
foreach (var (goodsId, reasons) in items)
|
||||
{
|
||||
var accepted = reasons.Where(reasonIds.ContainsKey).Select(x => reasonIds[x]).Distinct().ToArray();
|
||||
// 忽略原因仅记录字典,不新增或改变该商品已有的违规状态。
|
||||
if (accepted.Length == 0) continue;
|
||||
var rows = existing[goodsId].ToArray();
|
||||
var previous = rows.Select(x => x.ReasonId).ToHashSet();
|
||||
var added = accepted.Where(x => !previous.Contains(x)).ToArray();
|
||||
if (added.Length == 0 && rows.All(x => x.IsIndexDeleted)) continue;
|
||||
|
||||
// 下架是商品级操作:新增原因或存在失败记录时,整件商品重新标记待下架。
|
||||
foreach (var row in rows)
|
||||
{
|
||||
row.IsIndexDeleted = false;
|
||||
row.UpdatedTime = now;
|
||||
await repository.UpdateAsync(row);
|
||||
}
|
||||
foreach (var reasonId in added)
|
||||
{
|
||||
await repository.InsertAsync(new GoodsViolationEntity
|
||||
{
|
||||
GoodsId = goodsId, ReasonId = reasonId, IsIndexDeleted = false,
|
||||
CreatedTime = now, UpdatedTime = now
|
||||
});
|
||||
}
|
||||
recordedIds.Add(goodsId);
|
||||
}
|
||||
unit.Commit();
|
||||
return recordedIds.ToArray();
|
||||
}
|
||||
|
||||
public Task<int> MarkDeletedAsync(long[] ids) => Orm.Update<GoodsViolationEntity>()
|
||||
.Set(x => x.IsIndexDeleted, true)
|
||||
.Set(x => x.UpdatedTime, DateTime.UtcNow)
|
||||
.Where(x => ids.Contains(x.GoodsId)).ExecuteAffrowsAsync();
|
||||
|
||||
public Task<List<long>> GetBatchAsync(long afterId, int size, bool pendingOnly) => Select
|
||||
.Where(x => x.GoodsId > afterId)
|
||||
.WhereIf(pendingOnly, x => !x.IsIndexDeleted)
|
||||
.Distinct().OrderBy(x => x.GoodsId).Limit(size).ToListAsync(x => x.GoodsId);
|
||||
|
||||
public Task<List<long>> GetByReasonAsync(uint reasonId, long afterId, int size) => Select
|
||||
.Where(x => x.ReasonId == reasonId)
|
||||
.Where(x => x.GoodsId > afterId).OrderBy(x => x.GoodsId)
|
||||
.Limit(size).ToListAsync(x => x.GoodsId);
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
+3
-4
@@ -1,6 +1,5 @@
|
||||
using MAX.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services
|
||||
@@ -14,10 +13,10 @@ namespace Store.Modules.CloudProduct.Services
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<GoodsIndexJob> _logger;
|
||||
|
||||
public GoodsIndexJob(IServiceScopeFactory scopeFactory, [FromKeyedServices("CloudProduct")] PluginContext context,ILogger<GoodsIndexJob> logger)
|
||||
public GoodsIndexJob(IServiceScopeFactory scopeFactory, IConfiguration configuration,ILogger<GoodsIndexJob> logger)
|
||||
{
|
||||
_scopeFactory = scopeFactory;
|
||||
_configuration = context.Configuration;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Commons;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using MySql.Data.MySqlClient;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
/// <summary>跨实例串行化违规上报和商品索引写入,防止下架后被旧批次写回。</summary>
|
||||
public class GoodsIndexLock(IConfiguration configuration) : ISingletonDependency
|
||||
{
|
||||
public async Task<IAsyncDisposable> AcquireAsync()
|
||||
{
|
||||
// 禁用连接池:即使释放锁失败,关闭物理连接也会释放会话锁。
|
||||
var settings = new MySqlConnectionStringBuilder(configuration["CloudProductConnection"])
|
||||
{
|
||||
Pooling = false
|
||||
};
|
||||
var connection = new MySqlConnection(settings.ConnectionString);
|
||||
var name = "goods-index:" + Convert.ToHexString(SHA256.HashData(
|
||||
Encoding.UTF8.GetBytes(settings.Database)))[..40];
|
||||
try
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT GET_LOCK(@name, 30)";
|
||||
command.CommandTimeout = 35;
|
||||
command.Parameters.AddWithValue("@name", name);
|
||||
var result = await command.ExecuteScalarAsync();
|
||||
if (result == null || result == DBNull.Value || Convert.ToInt32(result) != 1)
|
||||
throw new AppException("商品索引正在处理,请稍后重试");
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await connection.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
-26
@@ -1,5 +1,3 @@
|
||||
using MAX.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
@@ -25,13 +23,15 @@ namespace Store.Modules.CloudProduct.Services
|
||||
private readonly IOpenSearchService _searchService;
|
||||
private readonly IRawDataStorage _rawDataStorage;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly GoodsViolationService _violations;
|
||||
|
||||
public GoodsService(GoodsRepository repository, IOpenSearchService searchService, IRawDataStorage rawDataStorage, [FromKeyedServices("CloudProduct")] PluginContext context)
|
||||
public GoodsService(GoodsRepository repository, IOpenSearchService searchService, IRawDataStorage rawDataStorage, IConfiguration configuration, GoodsViolationService violations)
|
||||
{
|
||||
_violations = violations;
|
||||
_repository = repository;
|
||||
_searchService = searchService;
|
||||
_rawDataStorage = rawDataStorage;
|
||||
_configuration = context.Configuration;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public async Task<(List<GoodsEntity> List, long Total)> SearchGoodsAsync(GoodsSearchRequest request)
|
||||
@@ -148,7 +148,6 @@ namespace Store.Modules.CloudProduct.Services
|
||||
|
||||
var indexImmediately = IsImmediateIndexing();
|
||||
var documents = new List<GoodsSearchDocument>();
|
||||
var indexedIds = new List<long>();
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
@@ -196,7 +195,6 @@ namespace Store.Modules.CloudProduct.Services
|
||||
MinPrice = saved.MinPrice,
|
||||
SoldQuantity = saved.SoldQuantity,
|
||||
});
|
||||
indexedIds.Add(saved.GoodsId);
|
||||
}
|
||||
|
||||
result.SuccessCount++;
|
||||
@@ -212,7 +210,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
await _searchService.BulkIndexGoodsAsync(documents);
|
||||
var indexedIds = await _searchService.BulkIndexGoodsAsync(documents);
|
||||
await MarkIndexedAsync(indexedIds);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -235,8 +233,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
if (batchSize <= 0)
|
||||
batchSize = 200;
|
||||
|
||||
var pending = await _repository.Select
|
||||
var pending = await _repository.Select.As("g")
|
||||
.Where(x => x.IsSegmented == 0 && x.Status == 0)
|
||||
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
|
||||
.OrderBy(x => x.GoodsId)
|
||||
.Limit(batchSize)
|
||||
.ToListAsync();
|
||||
@@ -260,10 +259,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
})
|
||||
.ToList();
|
||||
|
||||
await _searchService.BulkIndexGoodsAsync(documents);
|
||||
|
||||
await MarkIndexedAsync(pending.Select(x => x.GoodsId));
|
||||
return pending.Count;
|
||||
var indexedIds = await _searchService.BulkIndexGoodsAsync(documents);
|
||||
await MarkIndexedAsync(indexedIds);
|
||||
return indexedIds.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -310,22 +308,22 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// </summary>
|
||||
public async Task<long> RebuildSearchIndexAsync(IEnumerable<long>? ids = null)
|
||||
{
|
||||
List<GoodsEntity> goodsList;
|
||||
|
||||
var idList = ids?.ToList();
|
||||
if (idList == null || idList.Count == 0)
|
||||
await _violations.DeleteViolationIndexesAsync(pendingOnly: false);
|
||||
var idList = ids?.Distinct().ToArray() ?? [];
|
||||
long lastId = 0, count = 0;
|
||||
while (true)
|
||||
{
|
||||
goodsList = await _repository.Select.ToListAsync();
|
||||
var goodsList = await _repository.Select.As("g")
|
||||
.Where(x => x.Status == 0 && x.GoodsId > 0 && x.Id > lastId)
|
||||
.WhereIf(idList.Length > 0, x => idList.Contains(x.GoodsId))
|
||||
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
|
||||
.OrderBy(x => x.Id).Limit(1000).ToListAsync();
|
||||
if (goodsList.Count == 0) break;
|
||||
var indexedIds = await _searchService.RebuildIndexAsync(goodsList);
|
||||
await MarkIndexedAsync(indexedIds);
|
||||
count += indexedIds.Length;
|
||||
lastId = goodsList[^1].Id;
|
||||
}
|
||||
else
|
||||
{
|
||||
goodsList = await _repository.Select
|
||||
.Where(x => idList.Contains(x.GoodsId))
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
var count = await _searchService.RebuildIndexAsync(goodsList);
|
||||
await MarkIndexedAsync(goodsList.Where(x => x.GoodsId > 0).Select(x => x.GoodsId));
|
||||
return count;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
public class GoodsViolationIndexJob(IServiceScopeFactory scopeFactory)
|
||||
{
|
||||
public async Task ProcessPendingAsync()
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<GoodsViolationService>()
|
||||
.DeleteViolationIndexesAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Commons;
|
||||
using MAX.Framework.Dtos;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Store.Modules.CloudProduct.Dtos;
|
||||
using Store.Modules.CloudProduct.Repositorys;
|
||||
|
||||
namespace Store.Modules.CloudProduct.Services;
|
||||
|
||||
public class GoodsViolationService(
|
||||
GoodsViolationRepository repository,
|
||||
GoodsIndexLock indexLock,
|
||||
IOpenSearchService search,
|
||||
ILogger<GoodsViolationService> logger) : IScopedDependency
|
||||
{
|
||||
public Task<List<ViolationReasonDto>> GetReasonsAsync() => repository.GetReasonsAsync();
|
||||
|
||||
public static Dictionary<long, string[]> ValidateAndGroup(ReportGoodsViolationItem[]? items)
|
||||
{
|
||||
if (items == null || items.Length is < 1 or > 1000)
|
||||
throw new AppException("每次请提供1-1000条违规记录", ResultCode.ValidationError);
|
||||
for (var i = 0; i < items.Length; i++)
|
||||
{
|
||||
var item = items[i];
|
||||
if (item == null || item.GoodsId <= 0 || string.IsNullOrWhiteSpace(item.Reasons)
|
||||
|| item.Reasons.Trim().Length > 100)
|
||||
throw new AppException($"第{i + 1}条记录须提供有效商品编号和一个违规原因,原因去除首尾空白后须为1-100个字符", ResultCode.ValidationError);
|
||||
}
|
||||
return items.GroupBy(x => x.GoodsId).ToDictionary(x => x.Key,
|
||||
x => x.Select(y => y.Reasons.Trim()).Distinct(StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
|
||||
public async Task<List<ReportGoodsViolationsResult>> ReportAsync(ReportGoodsViolationItem[]? items)
|
||||
{
|
||||
var grouped = ValidateAndGroup(items);
|
||||
await using var lease = await indexLock.AcquireAsync();
|
||||
var pendingIds = await repository.MergeAsync(grouped);
|
||||
if (pendingIds.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
await search.DeleteDocumentsAsync(pendingIds);
|
||||
await repository.MarkDeletedAsync(pendingIds);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "违规记录已保存,{Count}个商品等待重试下架", pendingIds.Length);
|
||||
}
|
||||
}
|
||||
// 返回商品当前持久化状态,包括本次原因被忽略但历史已下架的商品。
|
||||
var offShelfIds = (await repository.GetOffShelfGoodsIdsAsync(grouped.Keys.ToArray())).ToHashSet();
|
||||
return grouped.Keys.Select(id => new ReportGoodsViolationsResult
|
||||
{
|
||||
GoodsId = id,
|
||||
IsOffShelf = offShelfIds.Contains(id)
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<List<GoodsViolationStatus>> GetStatusAsync(long[]? ids)
|
||||
{
|
||||
if (ids == null || ids.Length is < 1 or > 1000 || ids.Any(x => x <= 0))
|
||||
throw new AppException("请提供1-1000个正数商品编号", ResultCode.ValidationError);
|
||||
var distinct = ids.Distinct().ToArray();
|
||||
var violations = (await repository.GetViolationIdsAsync(distinct)).ToHashSet();
|
||||
return distinct.Select(x => new GoodsViolationStatus { GoodsId = x, IsViolation = violations.Contains(x) }).ToList();
|
||||
}
|
||||
|
||||
public async Task<RemoveGoodsViolationsResult> RemoveAsync(long[]? ids)
|
||||
{
|
||||
if (ids == null || ids.Length is < 1 or > 1000 || ids.Any(x => x <= 0))
|
||||
throw new AppException("请提供1-1000个正数商品编号", ResultCode.ValidationError);
|
||||
var distinct = ids.Distinct().ToArray();
|
||||
var result = new RemoveGoodsViolationsResult();
|
||||
await using (var lease = await indexLock.AcquireAsync())
|
||||
result.RemovedCount = await repository.RemoveAndScheduleRestoreAsync(distinct);
|
||||
|
||||
// 索引服务自行持锁并再次检查违规,避免与新的上报交错时重新上架违规商品。
|
||||
var goods = await repository.GetRestorableGoodsAsync(distinct);
|
||||
var candidates = goods.Select(x => x.GoodsId).Distinct().ToArray();
|
||||
result.SkippedGoodsIds = distinct.Except(candidates).ToArray();
|
||||
if (candidates.Length == 0) return result;
|
||||
try
|
||||
{
|
||||
var restored = await search.RebuildIndexAsync(goods);
|
||||
if (restored.Length > 0)
|
||||
{
|
||||
await using var lease = await indexLock.AcquireAsync();
|
||||
var blocked = await repository.GetViolationIdsAsync(restored);
|
||||
restored = restored.Except(blocked).ToArray();
|
||||
if (restored.Length > 0) await repository.MarkRestoredAsync(restored);
|
||||
}
|
||||
result.RestoredGoodsIds = restored;
|
||||
result.SkippedGoodsIds = distinct.Except(restored).ToArray();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "已解除违规,{Count}个商品等待后台任务恢复索引", candidates.Length);
|
||||
result.PendingRestoreGoodsIds = candidates;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 暂不注册 HTTP 路由。
|
||||
public Task<List<long>> GetGoodsIdsByReasonAsync(uint reasonId, long afterGoodsId = 0, int pageSize = 100)
|
||||
{
|
||||
if (reasonId == 0 || afterGoodsId < 0 || pageSize is < 1 or > 1000)
|
||||
throw new AppException("原因ID或分页参数无效", ResultCode.ValidationError);
|
||||
return repository.GetByReasonAsync(reasonId, afterGoodsId, pageSize);
|
||||
}
|
||||
|
||||
public async Task DeleteViolationIndexesAsync(bool pendingOnly = true)
|
||||
{
|
||||
long afterId = 0;
|
||||
while (true)
|
||||
{
|
||||
await using var lease = await indexLock.AcquireAsync();
|
||||
var ids = await repository.GetBatchAsync(afterId, 1000, pendingOnly);
|
||||
if (ids.Count == 0) return;
|
||||
await search.DeleteDocumentsAsync(ids);
|
||||
await repository.MarkDeletedAsync(ids.ToArray());
|
||||
afterId = ids[^1];
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-17
@@ -1,9 +1,8 @@
|
||||
using MAX.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Commons;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenSearch.Client;
|
||||
using OpenSearch.Net;
|
||||
@@ -16,7 +15,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
public interface IOpenSearchService : ISingletonDependency
|
||||
{
|
||||
Task AddDocumentAsync(GoodsSearchDocument document);
|
||||
Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
|
||||
Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
|
||||
Task<bool> ClearIndexAsync();
|
||||
Task<long> CountDocumentsAsync();
|
||||
Task<bool> CreateIndexAsync();
|
||||
@@ -26,7 +25,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
Task<bool> IndexExistsAsync();
|
||||
Task<bool> IsIndexMappingHealthyAsync();
|
||||
Task RefreshIndexAsync();
|
||||
Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
|
||||
Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
|
||||
Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request, GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance);
|
||||
}
|
||||
|
||||
@@ -41,10 +40,15 @@ namespace Store.Modules.CloudProduct.Services
|
||||
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长,可挪到配置文件)
|
||||
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
|
||||
private readonly ILogger<OpenSearchService> _logger;
|
||||
private readonly IFreeSql _database;
|
||||
private readonly GoodsIndexLock _indexLock;
|
||||
|
||||
public OpenSearchService([FromKeyedServices("CloudProduct")] PluginContext context,ILogger<OpenSearchService> logger)
|
||||
public OpenSearchService(IConfiguration configuration,ILogger<OpenSearchService> logger,
|
||||
[FromKeyedServices("CloudProductConnection")] IFreeSql database, GoodsIndexLock indexLock)
|
||||
{
|
||||
var config = context.Configuration.GetSection("Search");
|
||||
_database = database;
|
||||
_indexLock = indexLock;
|
||||
var config = configuration.GetSection("Search");
|
||||
_nodeUrl = config.GetValue<string>("Url") ?? "";
|
||||
_indexName = config.GetValue<string>("IndexName") ?? "";
|
||||
_client = CreateClient();
|
||||
@@ -206,12 +210,18 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// <summary>
|
||||
/// ============ 3.1 批量写入商品搜索文档(存在则覆盖) ============
|
||||
/// </summary>
|
||||
public async Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
|
||||
public async Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
|
||||
{
|
||||
if (documents == null) throw new ArgumentNullException(nameof(documents));
|
||||
|
||||
var list = documents.ToList();
|
||||
if (list.Count == 0) return;
|
||||
if (list.Count == 0) return [];
|
||||
await using var lease = await _indexLock.AcquireAsync();
|
||||
var ids = list.Select(x => x.Id).Distinct().ToArray();
|
||||
var blocked = (await _database.Select<GoodsViolationEntity>()
|
||||
.Where(x => ids.Contains(x.GoodsId)).ToListAsync(x => x.GoodsId)).ToHashSet();
|
||||
list = list.Where(x => !blocked.Contains(x.Id)).ToList();
|
||||
if (list.Count == 0) return [];
|
||||
|
||||
// 确保索引已按 IK 分词映射创建,否则中文分词无效
|
||||
await CreateIndexAsync();
|
||||
@@ -222,19 +232,20 @@ namespace Store.Modules.CloudProduct.Services
|
||||
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
|
||||
);
|
||||
|
||||
if (!bulkResponse.IsValid)
|
||||
if (!bulkResponse.IsValid || bulkResponse.Errors)
|
||||
{
|
||||
throw new AppException("写入 OpenSearch 失败: " + bulkResponse.DebugInformation);
|
||||
}
|
||||
|
||||
// 刷新索引,保证数据立即可搜索(仅用于演示,生产环境不建议频繁 Refresh)
|
||||
await RefreshIndexAsync();
|
||||
return list.Select(x => x.Id).Distinct().ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ============ 3.2 根据数据库商品重建搜索索引 ============
|
||||
/// </summary>
|
||||
public async Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
|
||||
public async Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
|
||||
{
|
||||
if (goodsList == null) throw new ArgumentNullException(nameof(goodsList));
|
||||
|
||||
@@ -242,6 +253,8 @@ namespace Store.Modules.CloudProduct.Services
|
||||
.Where(x => x != null && x.GoodsId > 0)
|
||||
.Select(x => new GoodsSearchDocument
|
||||
{
|
||||
Platform = x.Platform,
|
||||
ThumbUrl = x.ThumbUrl,
|
||||
Id = x.GoodsId,
|
||||
Title = x.Title ?? string.Empty,
|
||||
CatId1 = x.CatId1,
|
||||
@@ -253,10 +266,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
})
|
||||
.ToList();
|
||||
|
||||
if (documents.Count == 0) return 0;
|
||||
|
||||
await BulkIndexGoodsAsync(documents);
|
||||
return documents.Count;
|
||||
return await BulkIndexGoodsAsync(documents);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -271,7 +281,8 @@ namespace Store.Modules.CloudProduct.Services
|
||||
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||
if (!exists.Exists)
|
||||
{
|
||||
return;
|
||||
if (exists.ApiCall?.HttpStatusCode == 404) return;
|
||||
throw new AppException("检查 OpenSearch 索引失败: " + exists.DebugInformation);
|
||||
}
|
||||
|
||||
var response = await _client.BulkAsync(b =>
|
||||
@@ -284,7 +295,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
return b;
|
||||
});
|
||||
|
||||
if (!response.IsValid)
|
||||
if (response.ApiCall?.HttpStatusCode is not (>= 200 and < 300)
|
||||
|| response.Items.Count != list.Count
|
||||
|| response.Items.Any(x => x.Status != 404 && (x.Error != null || x.Status < 200 || x.Status >= 300)))
|
||||
{
|
||||
throw new AppException("删除 OpenSearch 文档失败: " + response.DebugInformation);
|
||||
}
|
||||
@@ -298,6 +311,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
public async Task AddDocumentAsync(GoodsSearchDocument document)
|
||||
{
|
||||
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||
await using var lease = await _indexLock.AcquireAsync();
|
||||
if (await _database.Select<GoodsViolationEntity>().AnyAsync(x => x.GoodsId == document.Id))
|
||||
throw new AppException("违规商品不能写入搜索索引");
|
||||
|
||||
var response = await _client.IndexAsync(document, i => i
|
||||
.Index(_indexName)
|
||||
@@ -524,6 +540,7 @@ namespace Store.Modules.CloudProduct.Services
|
||||
/// </summary>
|
||||
public async Task<bool> ClearIndexAsync()
|
||||
{
|
||||
await using var lease = await _indexLock.AcquireAsync();
|
||||
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
|
||||
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
|
||||
if (!existsResponse.Exists)
|
||||
@@ -541,7 +558,10 @@ namespace Store.Modules.CloudProduct.Services
|
||||
}
|
||||
Console.WriteLine($"索引 {_indexName} 已删除");
|
||||
|
||||
return await CreateIndexAsync();
|
||||
var created = await CreateIndexAsync();
|
||||
await _database.Update<GoodsEntity>().Set(x => x.IsSegmented, (byte)0)
|
||||
.Where(x => x.Status == 0).ExecuteAffrowsAsync();
|
||||
return created;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -1,5 +1,3 @@
|
||||
using MAX.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System.IO.Compression;
|
||||
@@ -32,13 +30,13 @@ namespace Store.Modules.CloudProduct.Services
|
||||
{
|
||||
private readonly string _rootPath;
|
||||
|
||||
public RawDataStorage([FromKeyedServices("CloudProduct")] PluginContext context)
|
||||
public RawDataStorage(IConfiguration configuration)
|
||||
{
|
||||
var configured = context.Configuration.GetValue<string>("RawData:Path");
|
||||
var configured = configuration.GetValue<string>("RawData:Path");
|
||||
if (string.IsNullOrWhiteSpace(configured))
|
||||
configured = "RawData";
|
||||
|
||||
_rootPath = Path.GetFullPath(configured, context.DirectoryPath);
|
||||
_rootPath = Path.GetFullPath(configured);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
+2
-4
@@ -1,5 +1,3 @@
|
||||
using MAX.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Framework.Commons;
|
||||
using MAX.Framework.Dtos;
|
||||
@@ -55,9 +53,9 @@ namespace Store.Modules.CloudProduct.Services
|
||||
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长)
|
||||
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
public UserFavoritesIndexService([FromKeyedServices("CloudProduct")] PluginContext context, ILogger<UserFavoritesIndexService> logger)
|
||||
public UserFavoritesIndexService(IConfiguration configuration, ILogger<UserFavoritesIndexService> logger)
|
||||
{
|
||||
var config = context.Configuration.GetSection("Search");
|
||||
var config = configuration.GetSection("Search");
|
||||
_nodeUrl = config.GetValue<string>("Url") ?? "";
|
||||
_indexName = config.GetValue<string>("FavoritesIndexName") ?? "";
|
||||
_logger = logger;
|
||||
File renamed without changes.
@@ -0,0 +1,49 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Core.Interfaces;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Store.Modules.CloudProduct.Services;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Store.Modules.CloudProduct
|
||||
{
|
||||
|
||||
public class Startup : IStartup
|
||||
{
|
||||
public int Priority => IntPriority.Normal;
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
}
|
||||
|
||||
public void Register(IServiceRegistrar registrar)
|
||||
{
|
||||
|
||||
|
||||
|
||||
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
|
||||
{
|
||||
var config = r.GetRequiredService<IConfiguration>();
|
||||
var connection = config.GetValue<string>("CloudProductConnection");
|
||||
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.MySql, connection)
|
||||
.UseAdoConnectionPool(true)
|
||||
.Build();
|
||||
return fsql;
|
||||
};
|
||||
registrar.RegisterSingleton<IFreeSql>("CloudProductConnection", (s, k) =>
|
||||
{
|
||||
return KJDFsqlFactory(s);
|
||||
});
|
||||
}
|
||||
|
||||
public async void Start(IServiceProvider serviceProvider)
|
||||
{
|
||||
var openSearchService = serviceProvider.GetRequiredService<OpenSearchService>();
|
||||
await openSearchService.GetStatusAsync();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
+8
-10
@@ -1,34 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<SatelliteResourceLanguages>zh-Hans;zh-Hant;zh;en</SatelliteResourceLanguages>
|
||||
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
|
||||
<ProjectReference Include="..\..\Core\MAX.Plugins\MAX.Plugins.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--<ItemGroup>
|
||||
--><!-- 本模块自己的配置文件:源码里叫 appsettings.json,构建后复制到宿主输出目录时改名为
|
||||
appsettings.CloudProduct.json,避免和宿主自己的 appsettings.json 互相覆盖。
|
||||
由 builder.AddStoreHub() 自动并入宿主配置树(在 appsettings*.json 之后、环境变量之前)。 --><!--
|
||||
<None Update="appsettings.json" Link="appsettings.CloudProduct.json" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>-->
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings*.json">
|
||||
<None Update="appsettings.CloudProduct.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.25" />
|
||||
<PackageReference Include="Hangfire.Dashboard.Basic.Authentication" Version="8.0.0" />
|
||||
<PackageReference Include="Hangfire.MySql" Version="1.0.0" />
|
||||
<PackageReference Include="Hangfire.MySqlStorage" Version="2.0.3" />
|
||||
<PackageReference Include="OpenSearch.Client" Version="2.1.0" />
|
||||
<!-- 覆盖 Hangfire 的旧传递依赖,修复 CVE-2024-21907。 -->
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
File renamed without changes.
+12
-5
@@ -36,14 +36,21 @@ namespace KJD_Web.Controllers
|
||||
/// 批量按 MD5 查询图片缓存。
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
public List<ImageCacheDto> GetImageCache(ImageCacheBatchQueryRequest request)
|
||||
public ApiResult<List<ImageCacheDto>> GetImageCache(ImageCacheBatchQueryRequest request)
|
||||
{
|
||||
List<ImageCacheDto> data = new List<ImageCacheDto>();
|
||||
try
|
||||
{
|
||||
if (request != null && request.Md5s != null)
|
||||
{
|
||||
data = _imageCacheService.GetByMd5s(request.Md5s, request.Platform);
|
||||
}
|
||||
return data;
|
||||
return ApiResult.Ok(data);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return ApiResult.Fail(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +63,7 @@ namespace KJD_Web.Controllers
|
||||
{
|
||||
if (requests == null || requests.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("参数不能为空");
|
||||
return ApiResult.Fail("参数不能为空");
|
||||
}
|
||||
|
||||
var failedItems = new List<string>();
|
||||
@@ -64,7 +71,7 @@ namespace KJD_Web.Controllers
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
throw new ArgumentException("图片参数不能包含空项");
|
||||
return ApiResult.Fail("图片参数不能包含空项", ResultCode.ValidationError);
|
||||
}
|
||||
try
|
||||
{
|
||||
@@ -82,7 +89,7 @@ namespace KJD_Web.Controllers
|
||||
|
||||
return failedItems.Count == 0
|
||||
? ApiResult.Ok()
|
||||
: throw new ArgumentException("部分图片失败");
|
||||
: ApiResult.Fail("部分图片失败", failedItems);
|
||||
}
|
||||
public class ImageCacheBatchQueryRequest
|
||||
{
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,47 @@
|
||||
|
||||
using MAX.Core.Interfaces;
|
||||
using MAX.Framework.Interfaces;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace Store.Modules.CloudProduct
|
||||
{
|
||||
public class Module : IModule
|
||||
{
|
||||
/// <summary>
|
||||
/// 本模块自己的配置文件
|
||||
/// </summary>
|
||||
public const string ConfigurationFileName = "appsettings.ImageCache.json";
|
||||
|
||||
public int Priority => IntPriority.Normal;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 服务注册阶段(builder.Build() 之前):这里只能拿到容器和配置,碰不到 app
|
||||
/// </summary>
|
||||
public void AddModule(IHostApplicationBuilder host)
|
||||
{
|
||||
IServiceCollection services = host.Services;
|
||||
IConfigurationManager configuration = host.Configuration;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(ConfigurationFileName))
|
||||
{
|
||||
string path = Path.IsPathRooted(ConfigurationFileName)? ConfigurationFileName: Path.Combine(AppContext.BaseDirectory, ConfigurationFileName);
|
||||
configuration.AddJsonFile(path, optional: false, reloadOnChange: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 管道装配阶段(builder.Build() 之后、app.Run() 之前):这里可以挂中间件、解析容器里的服务
|
||||
/// </summary>
|
||||
public void UseModule(IApplicationBuilder app)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,45 @@
|
||||
using MAX.Core.DependencyInjection;
|
||||
using MAX.Core.Interfaces;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace Store.Modules.CloudProduct
|
||||
{
|
||||
|
||||
public class Startup : IStartup
|
||||
{
|
||||
public int Priority => IntPriority.Normal;
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
}
|
||||
|
||||
public void Register(IServiceRegistrar registrar)
|
||||
{
|
||||
|
||||
|
||||
|
||||
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
|
||||
{
|
||||
var config = r.GetRequiredService<IConfiguration>();
|
||||
var connection = config.GetValue<string>("ImageCache:ConnectionString");
|
||||
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.MySql, connection)
|
||||
.UseAdoConnectionPool(true)
|
||||
.Build();
|
||||
return fsql;
|
||||
};
|
||||
registrar.RegisterSingleton<IFreeSql>("ImageCacheConnection", (s, k) =>
|
||||
{
|
||||
return KJDFsqlFactory(s);
|
||||
});
|
||||
}
|
||||
|
||||
public void Start(IServiceProvider serviceProvider)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -1,7 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
@@ -9,12 +8,10 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
|
||||
<ProjectReference Include="..\..\Core\MAX.Plugins\MAX.Plugins.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Update="appsettings*.json">
|
||||
<None Update="appsettings.ImageCache.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
File renamed without changes.
@@ -1,330 +0,0 @@
|
||||
using System.Text.Json;
|
||||
using MAX.Framework.Conventions;
|
||||
using MAX.Framework.Dtos;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Store.Shops.Dtos;
|
||||
using Store.Shops.Services;
|
||||
|
||||
namespace Store.Shops.Controllers;
|
||||
|
||||
/// <summary>统一店铺接口:微信、拼多多、微店及相关物流业务;使用当前认证、JSON DTO和ApiResult响应。</summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[DefaultHttpPost]
|
||||
[Route("v{version:apiVersion}/shop/[action]")]
|
||||
public sealed class ShopController(ShopService shops, ShopManagementService pddShops) : ControllerBase
|
||||
{
|
||||
/// <summary>查询本人或直属主账号分配的微信店铺。</summary>
|
||||
[EndpointSummary("查询本人或直属主账号分配的微信店铺")]
|
||||
public Task<ShopPage<ShopDetailsInfo>> GetShops(ShopQueryRequest request, CancellationToken ct)
|
||||
=> shops.Search(request, ct: ct);
|
||||
|
||||
/// <summary>查询授权店铺的ERP商户余额。</summary>
|
||||
[EndpointSummary("查询授权店铺的ERP商户余额")]
|
||||
public Task<ShopPage<ErpAccountInfo>> GetErpMerchants(ErpRequest request, CancellationToken ct)
|
||||
=> shops.ErpMerchants(request, ct);
|
||||
|
||||
/// <summary>查询登录名下的授权店铺。</summary>
|
||||
[EndpointSummary("查询登录名下的授权店铺")]
|
||||
public Task<IReadOnlyList<ShopDetailsInfo>> GetShopsByLoginName(LoginRequest request, CancellationToken ct)
|
||||
=> shops.ByLogin(request, ct);
|
||||
|
||||
/// <summary>批量读取授权店铺Cookie。</summary>
|
||||
[EndpointSummary("批量读取授权店铺Cookie")]
|
||||
public Task<IReadOnlyList<ShopCookieInfo>> GetShopCookies(ShopIdsRequest request, CancellationToken ct)
|
||||
=> shops.Cookies(request, ct);
|
||||
|
||||
/// <summary>主账号新增微信店铺,重复记录拒绝创建。</summary>
|
||||
[EndpointSummary("主账号新增微信店铺,重复记录拒绝创建")]
|
||||
public async Task<ApiResult> AddShop(ShopSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Save(request, true, false, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>删除本人所属的店铺记录。</summary>
|
||||
[EndpointSummary("删除本人所属的店铺记录")]
|
||||
public async Task<ApiResult> DeleteShop(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Delete(request, false, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>部分更新授权微信店铺。</summary>
|
||||
[EndpointSummary("部分更新授权微信店铺")]
|
||||
public async Task<ApiResult> UpdateShop(ShopSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Save(request, false, false, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>按登录名刷新授权店铺Cookie与状态。</summary>
|
||||
[EndpointSummary("按登录名刷新授权店铺Cookie与状态")]
|
||||
public async Task<ApiResult> UpdateShopLogin(CookieRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.UpdateCookies(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>管理员分页查询全部店铺。</summary>
|
||||
[EndpointSummary("管理员分页查询全部店铺")]
|
||||
public Task<ShopPage<ShopDetailsInfo>> GetAllShops(ShopQueryRequest request, CancellationToken ct)
|
||||
=> shops.Search(request, admin: true, ct: ct);
|
||||
|
||||
/// <summary>管理员按选品操作员查询店铺并刷新月度额度。</summary>
|
||||
[EndpointSummary("管理员按选品操作员查询店铺并刷新月度额度")]
|
||||
public Task<ShopPage<ShopDetailsInfo>> GetSelectionShops(ShopQueryRequest request, CancellationToken ct)
|
||||
=> shops.Search(request, selection: true, ct: ct);
|
||||
|
||||
/// <summary>管理员批量设置店铺上传剩余额度。</summary>
|
||||
[EndpointSummary("管理员批量设置店铺上传剩余额度")]
|
||||
public async Task<ApiResult> UpdateShopQuota(QuotaRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.UpdateQuota(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>管理员修改指定账号的店铺。</summary>
|
||||
[EndpointSummary("管理员修改指定账号的店铺")]
|
||||
public async Task<ApiResult> AdminUpdateShop(ShopSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Save(request, false, true, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>管理员为指定账号新增店铺。</summary>
|
||||
[EndpointSummary("管理员为指定账号新增店铺")]
|
||||
public async Task<ApiResult> AdminAddShop(ShopSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Save(request, true, true, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>管理员删除指定账号店铺。</summary>
|
||||
[EndpointSummary("管理员删除指定账号店铺")]
|
||||
public async Task<ApiResult> AdminDeleteShop(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Delete(request, true, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>管理员批量分配或解除选品操作员。</summary>
|
||||
[EndpointSummary("管理员批量分配或解除选品操作员")]
|
||||
public async Task<ApiResult> AssignShopOperator(AssignRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.Assign(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>向当前账号导入未使用运单。</summary>
|
||||
[EndpointSummary("向当前账号导入未使用运单")]
|
||||
public async Task<ApiResult> AddWaybill(WaybillAddRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.AddWaybill(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>删除本人尚未预占的运单。</summary>
|
||||
[EndpointSummary("删除本人尚未预占的运单")]
|
||||
public async Task<ApiResult> DeleteWaybills(WaybillDeleteRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.DeleteWaybills(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>分页查询本人运单。</summary>
|
||||
[EndpointSummary("分页查询本人运单")]
|
||||
public Task<ShopPage<WaybillInfo>> GetWaybills(WaybillSearchRequest request, CancellationToken ct)
|
||||
=> shops.Waybills(request, false, ct);
|
||||
|
||||
/// <summary>管理员按订单跨账号查询运单。</summary>
|
||||
[EndpointSummary("管理员按订单跨账号查询运单")]
|
||||
public Task<ShopPage<WaybillInfo>> GetAllWaybills(WaybillSearchRequest request, CancellationToken ct)
|
||||
=> shops.Waybills(request, true, ct);
|
||||
|
||||
/// <summary>在同一事务中选择并确认使用运单。</summary>
|
||||
[EndpointSummary("在同一事务中选择并确认使用运单")]
|
||||
public async Task<ApiResult> SelectAndUseWaybill(WaybillSelectRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SelectWaybill(request, true, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>为授权订单预占运单,优先匹配绑定订单。</summary>
|
||||
[EndpointSummary("为授权订单预占运单,优先匹配绑定订单")]
|
||||
public Task<WaybillInfo> ReserveWaybill(WaybillSelectRequest request, CancellationToken ct)
|
||||
=> shops.SelectWaybill(request, false, ct);
|
||||
|
||||
/// <summary>确认使用或释放本人预占运单。</summary>
|
||||
[EndpointSummary("确认使用或释放本人预占运单")]
|
||||
public async Task<ApiResult> UpdateWaybillUsage(WaybillUseRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.UseWaybill(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>保存授权订单物流优化结果。</summary>
|
||||
[EndpointSummary("保存授权订单物流优化结果")]
|
||||
public async Task<ApiResult> SaveExpressOptimizeResult(OptimizeResultRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SaveOptimizeResult(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询授权店铺物流优化结果。</summary>
|
||||
[EndpointSummary("查询授权店铺物流优化结果")]
|
||||
public Task<ShopPage<OptimizeResultInfo>> GetExpressOptimizeResults(OrderSearchRequest request, CancellationToken ct)
|
||||
=> shops.OptimizeResults(request, ct);
|
||||
|
||||
/// <summary>保存或清空授权订单物流备注。</summary>
|
||||
[EndpointSummary("保存或清空授权订单物流备注")]
|
||||
public async Task<ApiResult> SaveExpressOptimizeRemark(OptimizeRemarkRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SaveOptimizeRemark(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询授权店铺物流备注。</summary>
|
||||
[EndpointSummary("查询授权店铺物流备注")]
|
||||
public Task<ShopPage<OptimizeRemarkInfo>> GetExpressOptimizeRemarks(OrderSearchRequest request, CancellationToken ct)
|
||||
=> shops.OptimizeRemarks(request, ct);
|
||||
|
||||
/// <summary>维护本人的店铺默认售后地址。</summary>
|
||||
[EndpointSummary("维护本人的店铺默认售后地址")]
|
||||
public async Task<ApiResult> SaveShopDefaultAddress(AddressRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SaveDefaultAddress(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询本人的店铺默认地址。</summary>
|
||||
[EndpointSummary("查询本人的店铺默认地址")]
|
||||
public Task<ShopPage<DefaultAddressInfo>> GetShopDefaultAddresses(AddressSearchRequest request, CancellationToken ct)
|
||||
=> shops.DefaultAddresses(request, ct);
|
||||
|
||||
/// <summary>批量删除本人的默认地址。</summary>
|
||||
[EndpointSummary("批量删除本人的默认地址")]
|
||||
public async Task<ApiResult> DeleteShopDefaultAddresses(ShopIdsRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.DeleteDefaultAddresses(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>保存授权店铺订单解密地址。</summary>
|
||||
[EndpointSummary("保存授权店铺订单解密地址")]
|
||||
public async Task<ApiResult> SaveOrderAddress(OrderAddressRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SaveOrderAddress(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询授权店铺订单解密地址。</summary>
|
||||
[EndpointSummary("查询授权店铺订单解密地址")]
|
||||
public Task<ShopPage<OrderAddressInfo>> GetOrderAddresses(OrderSearchRequest request, CancellationToken ct)
|
||||
=> shops.OrderAddresses(request, ct);
|
||||
|
||||
/// <summary>维护当前主账号共享采购备注。</summary>
|
||||
[EndpointSummary("维护当前主账号共享采购备注")]
|
||||
public async Task<ApiResult> SaveBuyUrlNote(NoteRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SaveBuyNote(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询当前主账号共享采购备注。</summary>
|
||||
[EndpointSummary("查询当前主账号共享采购备注")]
|
||||
public Task<ShopPage<BuyUrlNoteInfo>> GetBuyUrlNotes(NoteSearchRequest request, CancellationToken ct)
|
||||
=> shops.BuyNotes(request, ct);
|
||||
|
||||
/// <summary>导入或更新微信业务下的拼多多店铺资料。</summary>
|
||||
[EndpointSummary("导入或更新微信业务下的拼多多店铺资料")]
|
||||
public async Task<ApiResult> SavePddShop(PddSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.SavePdd(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>刷新微信侧拼多多店铺Cookie与状态。</summary>
|
||||
[EndpointSummary("刷新微信侧拼多多店铺Cookie与状态")]
|
||||
public async Task<ApiResult> UpdatePddShopLogin(CookieRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.UpdatePddCookies(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>删除本人微信侧拼多多店铺。</summary>
|
||||
[EndpointSummary("删除本人微信侧拼多多店铺")]
|
||||
public async Task<ApiResult> DeletePddShop(LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
await shops.DeletePdd(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>查询授权微信侧拼多多店铺。</summary>
|
||||
[EndpointSummary("查询授权微信侧拼多多店铺")]
|
||||
public Task<ShopPage<ShopInfo>> GetPddShops(ShopSearchRequest request, CancellationToken ct)
|
||||
=> shops.PddShops(request, ct);
|
||||
|
||||
/// <summary>管理员读取共享微信令牌列表缓存。</summary>
|
||||
[EndpointSummary("管理员读取共享微信令牌列表缓存")]
|
||||
public Task<TokensInfo> GetTokens(TokenRequest request, CancellationToken ct)
|
||||
=> shops.TokenList(request, ct);
|
||||
|
||||
/// <summary>获取授权微信店铺的e57令牌。</summary>
|
||||
[EndpointSummary("获取授权微信店铺的e57令牌")]
|
||||
public Task<JsonElement> GetShopToken(ShopIdRequest request, CancellationToken ct)
|
||||
=> shops.ShopToken(request, ct);
|
||||
|
||||
/// <summary>获取部署配置中的拼多多应用信息。</summary>
|
||||
[EndpointSummary("获取部署配置中的拼多多应用信息")]
|
||||
public Task<IReadOnlyList<PddClientInfo>> GetPddClients() => pddShops.GetPddClients();
|
||||
|
||||
/// <summary>查询本人或分配店铺的拼多多授权资料,读取bxx.shop_api_auth。</summary>
|
||||
[EndpointSummary("查询本人或分配店铺的拼多多授权资料,读取bxx.shop_api_auth")]
|
||||
public Task<ShopPage<ShopClientInfo>> GetPddShopClients(ShopClientSearchRequest request, CancellationToken ct)
|
||||
=> pddShops.GetShopClientInfo(request, ct);
|
||||
|
||||
/// <summary>检查bxx.shop归属后获取拼多多商城令牌。</summary>
|
||||
[EndpointSummary("检查bxx.shop归属后获取拼多多商城令牌")]
|
||||
public Task<JsonElement> GetPddShopToken(PddTokenRequest request, CancellationToken ct)
|
||||
=> pddShops.GetPddToken(request, ct);
|
||||
|
||||
/// <summary>管理员查询bxx.shop店铺并维护共享月度额度。</summary>
|
||||
[EndpointSummary("管理员查询bxx.shop店铺并维护共享月度额度")]
|
||||
public Task<ShopPage<ShopInfo>> GetAllPddShops(ShopSearchRequest request, CancellationToken ct)
|
||||
=> pddShops.GetAdminShops(request, ct);
|
||||
|
||||
/// <summary>新增微店店铺,重复导入时更新资料。</summary>
|
||||
[EndpointSummary("新增微店店铺,重复导入时更新资料")]
|
||||
public async Task<ApiResult> AddWeidianShop(WeidianSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await pddShops.SaveWeidian(request, true, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>部分更新本人或已分配微店店铺。</summary>
|
||||
[EndpointSummary("部分更新本人或已分配微店店铺")]
|
||||
public async Task<ApiResult> UpdateWeidianShop(WeidianSaveRequest request, CancellationToken ct)
|
||||
{
|
||||
await pddShops.SaveWeidian(request, false, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>更新授权微店店铺的Cookie与登录状态。</summary>
|
||||
[EndpointSummary("更新授权微店店铺的Cookie与登录状态")]
|
||||
public async Task<ApiResult> UpdateWeidianShopLogin(WeidianCookieRequest request, CancellationToken ct)
|
||||
{
|
||||
await pddShops.UpdateWeidianCookie(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
|
||||
/// <summary>删除当前账号拥有的微店店铺。</summary>
|
||||
[EndpointSummary("删除当前账号拥有的微店店铺")]
|
||||
public async Task<ApiResult> DeleteWeidianShop(ShopIdRequest request, CancellationToken ct)
|
||||
{
|
||||
await pddShops.DeleteWeidian(request, ct);
|
||||
return ApiResult.Ok();
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
namespace Store.Shops.Dtos;
|
||||
|
||||
/// <summary>用户店铺默认售后地址的接口输出。</summary>
|
||||
public sealed class DefaultAddressInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>软件账号。</summary>
|
||||
public string UserId { get; set; } = "";
|
||||
/// <summary>店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>省份。</summary>
|
||||
public string ProvinceName { get; set; } = "";
|
||||
/// <summary>城市。</summary>
|
||||
public string CityName { get; set; } = "";
|
||||
/// <summary>区县。</summary>
|
||||
public string CountyName { get; set; } = "";
|
||||
/// <summary>详细地址。</summary>
|
||||
public string DetailInfo { get; set; } = "";
|
||||
/// <summary>收件人电话。</summary>
|
||||
public string TelNumber { get; set; } = "";
|
||||
/// <summary>收件人姓名。</summary>
|
||||
public string Receiver { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>订单解密地址的接口输出。</summary>
|
||||
public sealed class OrderAddressInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>订单ID。</summary>
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>解密后的地址内容。</summary>
|
||||
public string OrderAddress { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>主账号共享采购备注的接口输出。</summary>
|
||||
public sealed class BuyUrlNoteInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>所属主账号。</summary>
|
||||
public string UserName { get; set; } = "";
|
||||
/// <summary>商品编码。</summary>
|
||||
public string SpuCode { get; set; } = "";
|
||||
/// <summary>采购链接备注。</summary>
|
||||
public string BuyUrlNotes { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>运单库存及分配状态的接口输出。</summary>
|
||||
public sealed class WaybillInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>运单所属账号。</summary>
|
||||
public string UserName { get; set; } = "";
|
||||
/// <summary>物流公司编码。</summary>
|
||||
public string DeliveryId { get; set; } = "";
|
||||
/// <summary>物流公司名称。</summary>
|
||||
public string DeliveryName { get; set; } = "";
|
||||
/// <summary>运单号。</summary>
|
||||
public string WaybillId { get; set; } = "";
|
||||
/// <summary>预绑定订单ID。</summary>
|
||||
public string BindOrderId { get; set; } = "";
|
||||
/// <summary>分配订单ID。</summary>
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>使用店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>0未使用,1已预占,2已使用。</summary>
|
||||
public int Status { get; set; }
|
||||
/// <summary>入库时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>正式使用时间。</summary>
|
||||
public DateTime? UseTime { get; set; }
|
||||
/// <summary>揽收时间。</summary>
|
||||
public DateTime? WaybillPickupTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>订单物流优化结果的接口输出。</summary>
|
||||
public sealed class OptimizeResultInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>订单ID。</summary>
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>补发处理结果。</summary>
|
||||
public string OptimizeRst { get; set; } = "";
|
||||
/// <summary>运单号。</summary>
|
||||
public string WaybillId { get; set; } = "";
|
||||
/// <summary>物流公司名称。</summary>
|
||||
public string DeliveryName { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>订单物流优化备注的接口输出。</summary>
|
||||
public sealed class OptimizeRemarkInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>订单ID。</summary>
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>备注内容,允许清空。</summary>
|
||||
public string Remark { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>ERP商户余额的接口输出。</summary>
|
||||
public sealed class ErpAccountInfo
|
||||
{
|
||||
/// <summary>账户ID。</summary>
|
||||
public long Id { get; set; }
|
||||
/// <summary>ERP用户ID。</summary>
|
||||
public long UserId { get; set; }
|
||||
/// <summary>账户名称。</summary>
|
||||
public string AccountName { get; set; } = "";
|
||||
/// <summary>账户状态。</summary>
|
||||
public int AccountStatus { get; set; }
|
||||
/// <summary>账户类型。</summary>
|
||||
public int AccountType { get; set; }
|
||||
/// <summary>可用余额。</summary>
|
||||
public decimal Balance { get; set; }
|
||||
/// <summary>冻结金额。</summary>
|
||||
public decimal FrozenAmount { get; set; }
|
||||
/// <summary>累计充值。</summary>
|
||||
public decimal RechargeAmountTotal { get; set; }
|
||||
/// <summary>已提现金额。</summary>
|
||||
public decimal WithdrawnAmount { get; set; }
|
||||
/// <summary>提现账户图片。</summary>
|
||||
public string WithdrawAccountImageUrl { get; set; } = "";
|
||||
/// <summary>创建人。</summary>
|
||||
public long? CreateBy { get; set; }
|
||||
/// <summary>修改人。</summary>
|
||||
public long? UpdateBy { get; set; }
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime? CreateTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Store.Shops.Dtos;
|
||||
|
||||
/// <summary>分页与统计选项。</summary>
|
||||
public class PageRequest
|
||||
{
|
||||
/// <summary>页码,从1开始。</summary>
|
||||
public int Page { get; set; } = 1;
|
||||
/// <summary>每页数量,上限500。</summary>
|
||||
public int PageSize { get; set; } = 50;
|
||||
/// <summary>是否跳过总数统计,跳过时总数为-1。</summary>
|
||||
public bool NotCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>微信店铺查询。</summary>
|
||||
public class ShopQueryRequest : ShopSearchRequest
|
||||
{
|
||||
/// <summary>是否补充ERP店铺和商户编号。</summary>
|
||||
public bool IsGetErpShopId { get; set; }
|
||||
/// <summary>兼容旧调用的标志,到期信息始终返回。</summary>
|
||||
public bool IsShowExpire { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>按登录名定位店铺。</summary>
|
||||
public class LoginRequest
|
||||
{
|
||||
/// <summary>店铺登录名。</summary>
|
||||
[Required(ErrorMessage = "店铺登录名不能为空")]
|
||||
public string LoginName { get; set; } = "";
|
||||
/// <summary>可选原店铺ID。</summary>
|
||||
public string? ShopId { get; set; }
|
||||
/// <summary>管理员操作的目标账号,普通调用忽略。</summary>
|
||||
public string? ShopUserName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>微信店铺新增或部分更新;null保留,空串清空。</summary>
|
||||
public class ShopSaveRequest : LoginRequest
|
||||
{
|
||||
/// <summary>登录密码。</summary>
|
||||
public string? LoginPass { get; set; }
|
||||
/// <summary>登录Cookie。</summary>
|
||||
public string? Cookie { get; set; }
|
||||
/// <summary>第二组Cookie。</summary>
|
||||
public string? Cookie2 { get; set; }
|
||||
/// <summary>风控参数。</summary>
|
||||
public string? AntiContents { get; set; }
|
||||
/// <summary>更新后的店铺ID。</summary>
|
||||
public string? NewShopId { get; set; }
|
||||
/// <summary>店铺名称。</summary>
|
||||
public string? ShopAccount { get; set; }
|
||||
/// <summary>逗号分隔的直属子账号。</summary>
|
||||
public string? SubUserName { get; set; }
|
||||
/// <summary>店铺分组。</summary>
|
||||
public string? GroupName { get; set; }
|
||||
/// <summary>备注。</summary>
|
||||
public string? Notes { get; set; }
|
||||
/// <summary>登录状态。</summary>
|
||||
public string? LoginStatus { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>同登录名下授权店铺的登录状态更新。</summary>
|
||||
public class CookieRequest
|
||||
{
|
||||
/// <summary>店铺登录名。</summary>
|
||||
[Required(ErrorMessage = "店铺登录名不能为空")]
|
||||
public string LoginName { get; set; } = "";
|
||||
/// <summary>登录Cookie。</summary>
|
||||
public string? Cookie { get; set; }
|
||||
/// <summary>第二组Cookie。</summary>
|
||||
public string? Cookie2 { get; set; }
|
||||
/// <summary>登录状态。</summary>
|
||||
public string? LoginStatus { get; set; }
|
||||
/// <summary>第二组登录状态。</summary>
|
||||
public string? LoginStatus2 { get; set; }
|
||||
/// <summary>微信OpenId。</summary>
|
||||
public string? Openid { get; set; }
|
||||
/// <summary>拼多多用户ID。</summary>
|
||||
public string? PddId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>店铺ID批量请求。</summary>
|
||||
public class ShopIdsRequest
|
||||
{
|
||||
/// <summary>店铺ID数组。</summary>
|
||||
[Required(ErrorMessage = "店铺ID数组不能为空")]
|
||||
public string[] ShopIds { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>设置共享上传额度。</summary>
|
||||
public class QuotaRequest : ShopIdsRequest
|
||||
{
|
||||
/// <summary>剩余额度,不得小于0。</summary>
|
||||
public int RemainCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>批量分配选品操作员。</summary>
|
||||
public class AssignRequest
|
||||
{
|
||||
/// <summary>记录ID数组,优先于登录名。</summary>
|
||||
public int[]? DbIds { get; set; }
|
||||
/// <summary>店铺登录名数组。</summary>
|
||||
public string[]? ShopLoginNames { get; set; }
|
||||
/// <summary>操作员账号,空串表示解除分配。</summary>
|
||||
[Required(AllowEmptyStrings = true, ErrorMessage = "操作员账号不能为null,解除分配请传空串")]
|
||||
public string OperateSubSaName { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>查询授权店铺相关ERP商户。</summary>
|
||||
public class ErpRequest : PageRequest
|
||||
{
|
||||
/// <summary>可选店铺ID。</summary>
|
||||
public string? ShopId { get; set; }
|
||||
/// <summary>公司账号ID。</summary>
|
||||
public long? CorporateAccountUserId { get; set; }
|
||||
/// <summary>管理账号ID。</summary>
|
||||
public long? ManageUserId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>维护当前用户的店铺默认地址。</summary>
|
||||
public class AddressRequest : ShopIdRequest
|
||||
{
|
||||
/// <summary>省份。</summary>
|
||||
[Required(ErrorMessage = "省份不能为空")]
|
||||
public string ProvinceName { get; set; } = "";
|
||||
/// <summary>城市。</summary>
|
||||
[Required(ErrorMessage = "城市不能为空")]
|
||||
public string CityName { get; set; } = "";
|
||||
/// <summary>区县。</summary>
|
||||
[Required(ErrorMessage = "区县不能为空")]
|
||||
public string CountyName { get; set; } = "";
|
||||
/// <summary>详细地址。</summary>
|
||||
[Required(ErrorMessage = "详细地址不能为空")]
|
||||
public string DetailInfo { get; set; } = "";
|
||||
/// <summary>收件人电话。</summary>
|
||||
[Required(ErrorMessage = "收件人电话不能为空")]
|
||||
public string TelNumber { get; set; } = "";
|
||||
/// <summary>收件人姓名。</summary>
|
||||
[Required(ErrorMessage = "收件人姓名不能为空")]
|
||||
public string Receiver { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>查询本人默认地址。</summary>
|
||||
public class AddressSearchRequest : PageRequest
|
||||
{
|
||||
/// <summary>可选店铺ID数组。</summary>
|
||||
public string[]? ShopIds { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存订单解密地址。</summary>
|
||||
public class OrderAddressRequest : ShopIdRequest
|
||||
{
|
||||
/// <summary>订单ID。</summary>
|
||||
[Required(ErrorMessage = "订单ID不能为空")]
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>解密地址内容。</summary>
|
||||
[Required(ErrorMessage = "解密地址内容不能为空")]
|
||||
public string OrderAddress { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>按订单查询授权店铺的数据。</summary>
|
||||
public class OrderSearchRequest : PageRequest
|
||||
{
|
||||
/// <summary>订单ID数组,地址查询必填。</summary>
|
||||
public string[]? OrderIds { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>维护主账号共享采购备注。</summary>
|
||||
public class NoteRequest
|
||||
{
|
||||
/// <summary>商品编码。</summary>
|
||||
[Required(ErrorMessage = "商品编码不能为空")]
|
||||
public string SpuCode { get; set; } = "";
|
||||
/// <summary>采购备注。</summary>
|
||||
[Required(ErrorMessage = "采购备注不能为空")]
|
||||
public string BuyUrlNotes { get; set; } = "";
|
||||
/// <summary>可选目标主账号,必须匹配当前主账号。</summary>
|
||||
public string? MainUserName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>查询主账号采购备注。</summary>
|
||||
public class NoteSearchRequest : PageRequest
|
||||
{
|
||||
/// <summary>商品编码数组。</summary>
|
||||
[Required(ErrorMessage = "商品编码数组不能为空")]
|
||||
public string[] SpuCodes { get; set; } = [];
|
||||
/// <summary>可选目标主账号。</summary>
|
||||
public string? MainUserName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>微信侧拼多多店铺资料。</summary>
|
||||
public class PddSaveRequest : ShopSaveRequest
|
||||
{
|
||||
/// <summary>拼多多商城ID。</summary>
|
||||
public string? MallId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>查询运单库存。</summary>
|
||||
public class WaybillSearchRequest : OrderSearchRequest
|
||||
{
|
||||
/// <summary>状态数组:0未使用、1预占、2已使用。</summary>
|
||||
public int[]? Status { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>新增本人运单库存。</summary>
|
||||
public class WaybillAddRequest
|
||||
{
|
||||
/// <summary>物流公司编码。</summary>
|
||||
[Required(ErrorMessage = "物流公司编码不能为空")]
|
||||
public string DeliveryId { get; set; } = "";
|
||||
/// <summary>物流公司名称。</summary>
|
||||
[Required(ErrorMessage = "物流公司名称不能为空")]
|
||||
public string DeliveryName { get; set; } = "";
|
||||
/// <summary>运单号。</summary>
|
||||
[Required(ErrorMessage = "运单号不能为空")]
|
||||
public string WaybillId { get; set; } = "";
|
||||
/// <summary>预绑定订单ID。</summary>
|
||||
public string? BindOrderId { get; set; }
|
||||
/// <summary>揽收时间,与绑定订单至少填写一个。</summary>
|
||||
public DateTime? WaybillPickupTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>删除未使用运单。</summary>
|
||||
public class WaybillDeleteRequest
|
||||
{
|
||||
/// <summary>运单号数组。</summary>
|
||||
[Required(ErrorMessage = "运单号数组不能为空")]
|
||||
public string[] WaybillIds { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>为授权店铺订单分配运单。</summary>
|
||||
public class WaybillSelectRequest : ShopIdRequest
|
||||
{
|
||||
/// <summary>订单ID。</summary>
|
||||
[Required(ErrorMessage = "订单ID不能为空")]
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>订单时间,按次日揽收范围选择。</summary>
|
||||
public DateTime? OrderTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>确认使用或释放预占运单。</summary>
|
||||
public class WaybillUseRequest : WaybillSelectRequest
|
||||
{
|
||||
/// <summary>运单号。</summary>
|
||||
[Required(ErrorMessage = "运单号不能为空")]
|
||||
public string WaybillId { get; set; } = "";
|
||||
/// <summary>为true时释放,仅允许预占状态释放。</summary>
|
||||
public bool IsRollback { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存授权订单的物流优化结果。</summary>
|
||||
public class OptimizeResultRequest : ShopIdRequest
|
||||
{
|
||||
/// <summary>订单ID。</summary>
|
||||
[Required(ErrorMessage = "订单ID不能为空")]
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>补发结果。</summary>
|
||||
[Required(ErrorMessage = "补发结果不能为空")]
|
||||
public string OptimizeRst { get; set; } = "";
|
||||
/// <summary>运单号,null保留。</summary>
|
||||
public string? WaybillId { get; set; }
|
||||
/// <summary>物流公司名称,null保留。</summary>
|
||||
public string? DeliveryName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>保存订单物流备注。</summary>
|
||||
public class OptimizeRemarkRequest : ShopIdRequest
|
||||
{
|
||||
/// <summary>订单ID。</summary>
|
||||
[Required(ErrorMessage = "订单ID不能为空")]
|
||||
public string OrderId { get; set; } = "";
|
||||
/// <summary>备注内容,空串可清空,null不允许。</summary>
|
||||
[Required(AllowEmptyStrings = true, ErrorMessage = "备注不能为null,清空请传空串")]
|
||||
public string Remark { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>读取共享微信令牌缓存,仅管理员可调用。</summary>
|
||||
public class TokenRequest
|
||||
{
|
||||
/// <summary>缓存分组ID,默认1。</summary>
|
||||
public int DbId { get; set; } = 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Store.Shops.Dtos;
|
||||
|
||||
/// <summary>微信店铺业务资料;列表不输出密码与Cookie。</summary>
|
||||
public sealed class ShopDetailsInfo
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>店铺登录名。</summary>
|
||||
public string LoginName { get; set; } = "";
|
||||
/// <summary>店铺ID。</summary>
|
||||
public string ShopId { get; set; } = "";
|
||||
/// <summary>店铺名称。</summary>
|
||||
public string ShopAccount { get; set; } = "";
|
||||
/// <summary>所属账号。</summary>
|
||||
public string UserName { get; set; } = "";
|
||||
/// <summary>分配子账号。</summary>
|
||||
public string SubUserName { get; set; } = "";
|
||||
/// <summary>店铺分组。</summary>
|
||||
public string GroupName { get; set; } = "";
|
||||
/// <summary>公司名称。</summary>
|
||||
public string CompanyName { get; set; } = "";
|
||||
/// <summary>备注。</summary>
|
||||
public string Notes { get; set; } = "";
|
||||
/// <summary>登录状态。</summary>
|
||||
public string LoginStatus { get; set; } = "";
|
||||
/// <summary>第二组登录状态。</summary>
|
||||
public string LoginStatus2 { get; set; } = "";
|
||||
/// <summary>选品操作员。</summary>
|
||||
public string OperateSubSaName { get; set; } = "";
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime? AddTime { get; set; }
|
||||
/// <summary>修改时间。</summary>
|
||||
public DateTime? MdyTime { get; set; }
|
||||
/// <summary>操作员分配时间。</summary>
|
||||
public DateTime? AddSubSaTime { get; set; }
|
||||
/// <summary>微信OpenId。</summary>
|
||||
public string Openid { get; set; } = "";
|
||||
/// <summary>永久有效标志。</summary>
|
||||
public bool NeverExpires { get; set; }
|
||||
/// <summary>剩余上传额度。</summary>
|
||||
public int AddProductRemaining { get; set; }
|
||||
/// <summary>额度所属月份。</summary>
|
||||
public byte AddProductMonth { get; set; }
|
||||
/// <summary>到期Unix秒数。</summary>
|
||||
public int ExpireTime { get; set; }
|
||||
/// <summary>充值用户店铺是否已过期。</summary>
|
||||
public bool IsPointShopExpire { get; set; }
|
||||
/// <summary>ERP店铺ID。</summary>
|
||||
public long? ErpShopId { get; set; }
|
||||
/// <summary>ERP公司账号ID。</summary>
|
||||
public long? ErpCorporateAccountUserId { get; set; }
|
||||
/// <summary>ERP管理账号ID。</summary>
|
||||
public long? ErpManageUserId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>专用Cookie接口响应,仅返回已授权店铺的登录凭据。</summary>
|
||||
/// <param name="ShopId">微信店铺AppId。</param>
|
||||
/// <param name="Cookies">指定店铺的Cookie内容。</param>
|
||||
public sealed record ShopCookieInfo(string ShopId, string Cookies);
|
||||
|
||||
/// <summary>共享令牌列表和实际缓存刷新时间,仅管理员可读取。</summary>
|
||||
/// <param name="Tokens">上游返回的令牌列表JSON数组。</param>
|
||||
/// <param name="MdyTime">数据库缓存的最近刷新时间。</param>
|
||||
public sealed record TokensInfo(JsonElement Tokens, DateTime MdyTime);
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Store.Shops.Dtos;
|
||||
|
||||
public class ShopSearchRequest
|
||||
{
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 50;
|
||||
public string? SearchId { get; set; }
|
||||
public string? SearchUserName { get; set; }
|
||||
public string? SearchLoginName { get; set; }
|
||||
public string? SearchNotes { get; set; }
|
||||
public string? SearchName { get; set; }
|
||||
public string? OperateSubSaName { get; set; }
|
||||
public string[]? ShopIds { get; set; }
|
||||
public string[]? ShopNames { get; set; }
|
||||
public string[]? ShopNotes { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ShopClientSearchRequest
|
||||
{
|
||||
public int Page { get; set; } = 1;
|
||||
public int PageSize { get; set; } = 500;
|
||||
public string[]? ShopIds { get; set; }
|
||||
}
|
||||
|
||||
public class ShopIdRequest
|
||||
{
|
||||
[Required(ErrorMessage = "店铺ID不能为空")]
|
||||
public string ShopId { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed class PddTokenRequest
|
||||
{
|
||||
[Required(ErrorMessage = "拼多多商城ID不能为空")]
|
||||
public string MallId { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>更新时 null 保留原值,空串清空;归属账号只从当前身份获取。</summary>
|
||||
public sealed class WeidianSaveRequest
|
||||
{
|
||||
[Required(ErrorMessage = "店铺登录名不能为空")]
|
||||
public string LoginName { get; set; } = "";
|
||||
public string? ShopId { get; set; }
|
||||
public string? NewShopId { get; set; }
|
||||
public string? LoginPass { get; set; }
|
||||
public string? Cookie { get; set; }
|
||||
public string? Cookie2 { get; set; }
|
||||
public string? WdToken { get; set; }
|
||||
public string? MallId { get; set; }
|
||||
public string? ShopAccount { get; set; }
|
||||
public string? SubUserName { get; set; }
|
||||
public string? GroupName { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public string? LoginStatus { get; set; }
|
||||
}
|
||||
|
||||
public sealed class WeidianCookieRequest : ShopIdRequest
|
||||
{
|
||||
public string? Cookie { get; set; }
|
||||
public string? WdToken { get; set; }
|
||||
public string? LoginStatus { get; set; }
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
namespace Store.Shops.Dtos;
|
||||
|
||||
public sealed record ShopPage<T>(IReadOnlyList<T> Items, long Total);
|
||||
|
||||
/// <summary>列表只返回业务资料,登录密码、Cookie 和令牌不进入列表响应。</summary>
|
||||
public sealed class ShopInfo
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string LoginName { get; set; } = "";
|
||||
public string ShopId { get; set; } = "";
|
||||
public string MallId { get; set; } = "";
|
||||
public string PddId { get; set; } = "";
|
||||
public string ShopAccount { get; set; } = "";
|
||||
public string UserName { get; set; } = "";
|
||||
public string SubUserName { get; set; } = "";
|
||||
public string CompanyName { get; set; } = "";
|
||||
public string Notes { get; set; } = "";
|
||||
public string LoginStatus { get; set; } = "";
|
||||
public string LoginStatus2 { get; set; } = "";
|
||||
public string OperateSubSaName { get; set; } = "";
|
||||
public int AddProductRemaining { get; set; }
|
||||
public int AddProductMonth { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>专用授权接口响应,仅允许读取本人或明确分配店铺的凭据。</summary>
|
||||
public sealed class ShopClientInfo
|
||||
{
|
||||
public string ShopId { get; set; } = "";
|
||||
public string AppKey { get; set; } = "";
|
||||
public string AppSecret { get; set; } = "";
|
||||
public string AccessToken { get; set; } = "";
|
||||
public string RefreshToken { get; set; } = "";
|
||||
public string ApiAuthStatus { get; set; } = "";
|
||||
public DateTime? ExpiresTime { get; set; }
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>供授权客户端使用的拼多多应用配置,通过部署配置注入。</summary>
|
||||
public sealed class PddClientInfo
|
||||
{
|
||||
public string Describe { get; set; } = "";
|
||||
public string ClientId { get; set; } = "";
|
||||
public string ClientSecret { get; set; } = "";
|
||||
public int MarketId { get; set; }
|
||||
public string RedirectUri { get; set; } = "";
|
||||
public bool IsCurrent { get; set; }
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
|
||||
namespace Store.Shops.Entities;
|
||||
|
||||
/// <summary>主账号共享采购备注;映射旧库,不自动修改数据库结构。</summary>
|
||||
[Table(Name = "bxx.product_buy_url_notes")]
|
||||
public sealed class BuyUrlNoteEntity
|
||||
{
|
||||
/// <summary>记录ID。</summary>
|
||||
[Column(Name = "id", IsPrimary = true, IsIdentity = true)]
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>所属主账号。</summary>
|
||||
[Column(Name = "user_name")]
|
||||
public string UserName { get; set; } = "";
|
||||
|
||||
/// <summary>商品编码。</summary>
|
||||
[Column(Name = "spu_code")]
|
||||
public string SpuCode { get; set; } = "";
|
||||
|
||||
/// <summary>采购链接备注。</summary>
|
||||
[Column(Name = "buy_url_notes")]
|
||||
public string BuyUrlNotes { get; set; } = "";
|
||||
|
||||
/// <summary>创建时间。</summary>
|
||||
[Column(Name = "add_time")]
|
||||
public DateTime AddTime { get; set; }
|
||||
|
||||
/// <summary>修改时间。</summary>
|
||||
[Column(Name = "mdy_time")]
|
||||
public DateTime MdyTime { get; set; }
|
||||
}
|
||||
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user