Merge branch 'chore/comment-fix' into dev
This commit is contained in:
13
.editorconfig
Normal file
13
.editorconfig
Normal file
@@ -0,0 +1,13 @@
|
||||
# EditorConfig
|
||||
root = true
|
||||
|
||||
[*.cs]
|
||||
dotnet_diagnostic.SA1600.severity = error
|
||||
dotnet_diagnostic.SA1601.severity = error
|
||||
dotnet_diagnostic.SA1615.severity = error
|
||||
dotnet_diagnostic.SA1629.severity = none
|
||||
dotnet_diagnostic.SA1202.severity = none
|
||||
dotnet_diagnostic.SA1200.severity = none
|
||||
dotnet_diagnostic.SA1623.severity = none
|
||||
dotnet_diagnostic.SA1111.severity = none
|
||||
dotnet_diagnostic.SA1101.severity = none
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -3,3 +3,4 @@ bin/
|
||||
obj/
|
||||
**/bin/
|
||||
**/obj/
|
||||
.claude/
|
||||
|
||||
@@ -6,5 +6,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Identity.Abstractions;
|
||||
using TakeoutSaaS.Application.Identity.Contracts;
|
||||
@@ -13,24 +9,22 @@ using TakeoutSaaS.Shared.Web.Api;
|
||||
using TakeoutSaaS.Shared.Web.Security;
|
||||
|
||||
namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// 管理后台认证接口
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
///
|
||||
/// </remarks>
|
||||
/// <param name="authService"></param>
|
||||
/// <remarks>提供登录、刷新 Token 以及用户权限查询能力。</remarks>
|
||||
/// <param name="authService">认证服务</param>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/auth")]
|
||||
public sealed class AuthController(IAdminAuthService authService) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 登录获取 Token
|
||||
/// </summary>
|
||||
/// <param name="request">登录请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>包含访问令牌与刷新令牌的响应。</returns>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
|
||||
@@ -43,6 +37,9 @@ public sealed class AuthController(IAdminAuthService authService) : BaseApiContr
|
||||
/// <summary>
|
||||
/// 刷新 Token
|
||||
/// </summary>
|
||||
/// <param name="request">刷新令牌请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>新的访问令牌与刷新令牌。</returns>
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
|
||||
@@ -78,18 +75,22 @@ public sealed class AuthController(IAdminAuthService authService) : BaseApiContr
|
||||
/// }
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>当前用户档案信息。</returns>
|
||||
[HttpGet("profile")]
|
||||
[PermissionAuthorize("identity:profile:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<ApiResponse<CurrentUserProfile>> GetProfile(CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 从 JWT 中获取当前用户标识
|
||||
var userId = User.GetUserId();
|
||||
if (userId == 0)
|
||||
{
|
||||
return ApiResponse<CurrentUserProfile>.Error(ErrorCodes.Unauthorized, "Token 缺少有效的用户标识");
|
||||
}
|
||||
|
||||
// 2. 读取用户档案并返回
|
||||
var profile = await authService.GetProfileAsync(userId, cancellationToken);
|
||||
return ApiResponse<CurrentUserProfile>.Ok(profile);
|
||||
}
|
||||
@@ -119,6 +120,9 @@ public sealed class AuthController(IAdminAuthService authService) : BaseApiContr
|
||||
/// }
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
/// <param name="userId">目标用户 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>用户权限概览,未找到则返回 404。</returns>
|
||||
[HttpGet("permissions/{userId:long}")]
|
||||
[PermissionAuthorize("identity:permission:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<UserPermissionDto>), StatusCodes.Status200OK)]
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Deliveries.Commands;
|
||||
using TakeoutSaaS.Application.App.Deliveries.Dto;
|
||||
@@ -16,31 +15,40 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 配送单管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/deliveries")]
|
||||
public sealed class DeliveriesController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建配送单。
|
||||
/// </summary>
|
||||
/// <param name="command">创建命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建后的配送单。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("delivery:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<DeliveryOrderDto>> Create([FromBody] CreateDeliveryOrderCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建配送单
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<DeliveryOrderDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询配送单列表。
|
||||
/// </summary>
|
||||
/// <param name="orderId">订单 ID。</param>
|
||||
/// <param name="status">配送状态。</param>
|
||||
/// <param name="page">页码。</param>
|
||||
/// <param name="pageSize">每页大小。</param>
|
||||
/// <param name="sortBy">排序字段。</param>
|
||||
/// <param name="sortDesc">是否倒序。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>配送单分页列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("delivery:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<DeliveryOrderDto>>), StatusCodes.Status200OK)]
|
||||
@@ -53,6 +61,7 @@ public sealed class DeliveriesController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数
|
||||
var result = await mediator.Send(new SearchDeliveryOrdersQuery
|
||||
{
|
||||
OrderId = orderId,
|
||||
@@ -63,19 +72,26 @@ public sealed class DeliveriesController(IMediator mediator) : BaseApiController
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<DeliveryOrderDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取配送单详情。
|
||||
/// </summary>
|
||||
/// <param name="deliveryOrderId">配送单 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>配送单详情或未找到。</returns>
|
||||
[HttpGet("{deliveryOrderId:long}")]
|
||||
[PermissionAuthorize("delivery:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<DeliveryOrderDto>> Detail(long deliveryOrderId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询配送单详情
|
||||
var result = await mediator.Send(new GetDeliveryOrderByIdQuery { DeliveryOrderId = deliveryOrderId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<DeliveryOrderDto>.Error(ErrorCodes.NotFound, "配送单不存在")
|
||||
: ApiResponse<DeliveryOrderDto>.Ok(result);
|
||||
@@ -84,17 +100,26 @@ public sealed class DeliveriesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 更新配送单。
|
||||
/// </summary>
|
||||
/// <param name="deliveryOrderId">配送单 ID。</param>
|
||||
/// <param name="command">更新命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的配送单或未找到。</returns>
|
||||
[HttpPut("{deliveryOrderId:long}")]
|
||||
[PermissionAuthorize("delivery:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<DeliveryOrderDto>> Update(long deliveryOrderId, [FromBody] UpdateDeliveryOrderCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令携带配送单标识
|
||||
if (command.DeliveryOrderId == 0)
|
||||
{
|
||||
command = command with { DeliveryOrderId = deliveryOrderId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<DeliveryOrderDto>.Error(ErrorCodes.NotFound, "配送单不存在")
|
||||
: ApiResponse<DeliveryOrderDto>.Ok(result);
|
||||
@@ -103,13 +128,19 @@ public sealed class DeliveriesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除配送单。
|
||||
/// </summary>
|
||||
/// <param name="deliveryOrderId">配送单 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>删除结果,未找到则返回错误。</returns>
|
||||
[HttpDelete("{deliveryOrderId:long}")]
|
||||
[PermissionAuthorize("delivery:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long deliveryOrderId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteDeliveryOrderCommand { DeliveryOrderId = deliveryOrderId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "配送单不存在");
|
||||
|
||||
@@ -12,74 +12,101 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 参数字典管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化字典控制器。
|
||||
/// </remarks>
|
||||
/// <param name="dictionaryAppService">字典服务</param>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/dictionaries")]
|
||||
public sealed class DictionaryController(IDictionaryAppService dictionaryAppService) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 查询字典分组。
|
||||
/// </summary>
|
||||
/// <param name="query">分组查询条件。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>分组列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("dictionary:group:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<DictionaryGroupDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<DictionaryGroupDto>>> GetGroups([FromQuery] DictionaryGroupQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询字典分组
|
||||
var groups = await dictionaryAppService.SearchGroupsAsync(query, cancellationToken);
|
||||
|
||||
// 2. 返回分组列表
|
||||
return ApiResponse<IReadOnlyList<DictionaryGroupDto>>.Ok(groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建字典分组。
|
||||
/// </summary>
|
||||
/// <param name="request">创建分组请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建后的分组。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("dictionary:group:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DictionaryGroupDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<DictionaryGroupDto>> CreateGroup([FromBody] CreateDictionaryGroupRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建字典分组
|
||||
var group = await dictionaryAppService.CreateGroupAsync(request, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<DictionaryGroupDto>.Ok(group);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新字典分组。
|
||||
/// </summary>
|
||||
/// <param name="groupId">分组 ID。</param>
|
||||
/// <param name="request">更新请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的分组。</returns>
|
||||
[HttpPut("{groupId:long}")]
|
||||
[PermissionAuthorize("dictionary:group:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DictionaryGroupDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<DictionaryGroupDto>> UpdateGroup(long groupId, [FromBody] UpdateDictionaryGroupRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 更新字典分组
|
||||
var group = await dictionaryAppService.UpdateGroupAsync(groupId, request, cancellationToken);
|
||||
|
||||
// 2. 返回更新结果
|
||||
return ApiResponse<DictionaryGroupDto>.Ok(group);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除字典分组。
|
||||
/// </summary>
|
||||
/// <param name="groupId">分组 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>操作结果。</returns>
|
||||
[HttpDelete("{groupId:long}")]
|
||||
[PermissionAuthorize("dictionary:group:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<object>> DeleteGroup(long groupId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除字典分组
|
||||
await dictionaryAppService.DeleteGroupAsync(groupId, cancellationToken);
|
||||
|
||||
// 2. 返回成功响应
|
||||
return ApiResponse.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建字典项。
|
||||
/// </summary>
|
||||
/// <param name="groupId">分组 ID。</param>
|
||||
/// <param name="request">创建请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建的字典项。</returns>
|
||||
[HttpPost("{groupId:long}/items")]
|
||||
[PermissionAuthorize("dictionary:item:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DictionaryItemDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<DictionaryItemDto>> CreateItem(long groupId, [FromBody] CreateDictionaryItemRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定分组标识
|
||||
request.GroupId = groupId;
|
||||
|
||||
// 2. 创建字典项
|
||||
var item = await dictionaryAppService.CreateItemAsync(request, cancellationToken);
|
||||
return ApiResponse<DictionaryItemDto>.Ok(item);
|
||||
}
|
||||
@@ -87,35 +114,54 @@ public sealed class DictionaryController(IDictionaryAppService dictionaryAppServ
|
||||
/// <summary>
|
||||
/// 更新字典项。
|
||||
/// </summary>
|
||||
/// <param name="itemId">字典项 ID。</param>
|
||||
/// <param name="request">更新请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的字典项。</returns>
|
||||
[HttpPut("items/{itemId:long}")]
|
||||
[PermissionAuthorize("dictionary:item:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<DictionaryItemDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<DictionaryItemDto>> UpdateItem(long itemId, [FromBody] UpdateDictionaryItemRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 更新字典项
|
||||
var item = await dictionaryAppService.UpdateItemAsync(itemId, request, cancellationToken);
|
||||
|
||||
// 2. 返回更新结果
|
||||
return ApiResponse<DictionaryItemDto>.Ok(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除字典项。
|
||||
/// </summary>
|
||||
/// <param name="itemId">字典项 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>操作结果。</returns>
|
||||
[HttpDelete("items/{itemId:long}")]
|
||||
[PermissionAuthorize("dictionary:item:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<object>> DeleteItem(long itemId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除字典项
|
||||
await dictionaryAppService.DeleteItemAsync(itemId, cancellationToken);
|
||||
|
||||
// 2. 返回成功响应
|
||||
return ApiResponse.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量获取字典项(命中缓存)。
|
||||
/// </summary>
|
||||
/// <param name="request">批量查询请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>分组编码到字典项列表的映射。</returns>
|
||||
[HttpPost("batch")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyDictionary<string, IReadOnlyList<DictionaryItemDto>>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyDictionary<string, IReadOnlyList<DictionaryItemDto>>>> BatchGet([FromBody] DictionaryBatchQueryRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 批量读取并命中缓存
|
||||
var dictionaries = await dictionaryAppService.GetCachedItemsAsync(request, cancellationToken);
|
||||
|
||||
// 2. 返回批量结果
|
||||
return ApiResponse<IReadOnlyDictionary<string, IReadOnlyList<DictionaryItemDto>>>.Ok(dictionaries);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Storage.Abstractions;
|
||||
using TakeoutSaaS.Application.Storage.Contracts;
|
||||
@@ -19,34 +17,38 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
[Route("api/admin/v{version:apiVersion}/files")]
|
||||
public sealed class FilesController(IFileStorageService fileStorageService) : BaseApiController
|
||||
{
|
||||
private readonly IFileStorageService _fileStorageService = fileStorageService;
|
||||
|
||||
/// <summary>
|
||||
/// 上传图片或文件。
|
||||
/// </summary>
|
||||
/// <returns>文件上传响应信息。</returns>
|
||||
[HttpPost("upload")]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = 30 * 1024 * 1024)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status400BadRequest)]
|
||||
public async Task<ApiResponse<FileUploadResponse>> Upload([FromForm] IFormFile? file, [FromForm] string? type, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验文件有效性
|
||||
if (file == null || file.Length == 0)
|
||||
{
|
||||
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "文件不能为空");
|
||||
}
|
||||
|
||||
// 2. 解析上传类型
|
||||
if (!UploadFileTypeParser.TryParse(type, out var uploadType))
|
||||
{
|
||||
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "上传类型不合法");
|
||||
}
|
||||
|
||||
// 3. 提取请求来源
|
||||
var origin = Request.Headers["Origin"].FirstOrDefault() ?? Request.Headers["Referer"].FirstOrDefault();
|
||||
await using var stream = file.OpenReadStream();
|
||||
|
||||
var result = await _fileStorageService.UploadAsync(
|
||||
// 4. 调用存储服务执行上传
|
||||
var result = await fileStorageService.UploadAsync(
|
||||
new UploadFileRequest(uploadType, stream, file.FileName, file.ContentType ?? string.Empty, file.Length, origin),
|
||||
cancellationToken);
|
||||
|
||||
// 5. 返回上传结果
|
||||
return ApiResponse<FileUploadResponse>.Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
@@ -23,7 +21,10 @@ public class HealthController : BaseApiController
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public ApiResponse<object> Get()
|
||||
{
|
||||
// 1. 构造健康状态
|
||||
var payload = new { status = "OK", service = "AdminApi", time = DateTime.UtcNow };
|
||||
|
||||
// 2. 返回健康响应
|
||||
return ApiResponse<object>.Ok(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
@@ -24,37 +22,54 @@ public sealed class MerchantCategoriesController(IMediator mediator) : BaseApiCo
|
||||
/// <summary>
|
||||
/// 列出所有类目。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>类目列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("merchant_category:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantCategoryDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<MerchantCategoryDto>>> List(CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询所有类目
|
||||
var result = await mediator.Send(new ListMerchantCategoriesQuery(), cancellationToken);
|
||||
|
||||
// 2. 返回类目列表
|
||||
return ApiResponse<IReadOnlyList<MerchantCategoryDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增类目。
|
||||
/// </summary>
|
||||
/// <param name="command">创建命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建的类目。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("merchant_category:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantCategoryDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<MerchantCategoryDto>> Create([FromBody] CreateMerchantCategoryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建类目
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<MerchantCategoryDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除类目。
|
||||
/// </summary>
|
||||
/// <param name="categoryId">类目 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>删除结果,未找到则返回错误。</returns>
|
||||
[HttpDelete("{categoryId:long}")]
|
||||
[PermissionAuthorize("merchant_category:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long categoryId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteMerchantCategoryCommand(categoryId), cancellationToken);
|
||||
|
||||
// 2. 返回删除结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "类目不存在");
|
||||
@@ -63,12 +78,18 @@ public sealed class MerchantCategoriesController(IMediator mediator) : BaseApiCo
|
||||
/// <summary>
|
||||
/// 批量调整类目排序。
|
||||
/// </summary>
|
||||
/// <param name="command">排序命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>执行结果。</returns>
|
||||
[HttpPost("reorder")]
|
||||
[PermissionAuthorize("merchant_category:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<object>> Reorder([FromBody] ReorderMerchantCategoriesCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行排序调整
|
||||
await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回成功结果
|
||||
return ApiResponse<object>.Ok(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
@@ -16,31 +15,39 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 商户管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/merchants")]
|
||||
public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建商户。
|
||||
/// </summary>
|
||||
/// <param name="command">创建命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建后的商户。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("merchant:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<MerchantDto>> Create([FromBody] CreateMerchantCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建商户
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<MerchantDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询商户列表。
|
||||
/// </summary>
|
||||
/// <param name="status">状态筛选。</param>
|
||||
/// <param name="page">页码。</param>
|
||||
/// <param name="pageSize">每页大小。</param>
|
||||
/// <param name="sortBy">排序字段。</param>
|
||||
/// <param name="sortDesc">是否倒序。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>商户分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantDto>>), StatusCodes.Status200OK)]
|
||||
@@ -52,6 +59,7 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数并执行查询
|
||||
var result = await mediator.Send(new SearchMerchantsQuery
|
||||
{
|
||||
Status = status,
|
||||
@@ -60,24 +68,34 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
SortBy = sortBy,
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<MerchantDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新商户。
|
||||
/// </summary>
|
||||
/// <param name="merchantId">商户 ID。</param>
|
||||
/// <param name="command">更新命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的商户或未找到。</returns>
|
||||
[HttpPut("{merchantId:long}")]
|
||||
[PermissionAuthorize("merchant:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<MerchantDto>> Update(long merchantId, [FromBody] UpdateMerchantCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户标识
|
||||
if (command.MerchantId == 0)
|
||||
{
|
||||
command = command with { MerchantId = merchantId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<MerchantDto>.Error(ErrorCodes.NotFound, "商户不存在")
|
||||
: ApiResponse<MerchantDto>.Ok(result);
|
||||
@@ -86,13 +104,19 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除商户。
|
||||
/// </summary>
|
||||
/// <param name="merchantId">商户 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{merchantId:long}")]
|
||||
[PermissionAuthorize("merchant:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long merchantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteMerchantCommand { MerchantId = merchantId }, cancellationToken);
|
||||
|
||||
// 2. 返回删除结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "商户不存在");
|
||||
@@ -101,13 +125,19 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 获取商户概览。
|
||||
/// </summary>
|
||||
/// <param name="merchantId">商户 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>商户概览或未找到。</returns>
|
||||
[HttpGet("{merchantId:long}")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<MerchantDto>> Detail(long merchantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询商户概览
|
||||
var result = await mediator.Send(new GetMerchantByIdQuery { MerchantId = merchantId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return result == null
|
||||
? ApiResponse<MerchantDto>.Error(ErrorCodes.NotFound, "商户不存在")
|
||||
: ApiResponse<MerchantDto>.Ok(result);
|
||||
@@ -116,18 +146,23 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 获取商户详细资料(含证照、合同)。
|
||||
/// </summary>
|
||||
/// <returns>创建的证照信息。</returns>
|
||||
[HttpGet("{merchantId:long}/detail")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDetailDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<MerchantDetailDto>> FullDetail(long merchantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询商户详细资料
|
||||
var result = await mediator.Send(new GetMerchantDetailQuery(merchantId), cancellationToken);
|
||||
|
||||
// 2. 返回详情
|
||||
return ApiResponse<MerchantDetailDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传商户证照信息(先通过文件上传接口获取 COS 地址)。
|
||||
/// </summary>
|
||||
/// <returns>创建的证照信息。</returns>
|
||||
[HttpPost("{merchantId:long}/documents")]
|
||||
[PermissionAuthorize("merchant:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDocumentDto>), StatusCodes.Status200OK)]
|
||||
@@ -136,7 +171,10 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] AddMerchantDocumentCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户标识
|
||||
var command = body with { MerchantId = merchantId };
|
||||
|
||||
// 2. 创建证照记录
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<MerchantDocumentDto>.Ok(result);
|
||||
}
|
||||
@@ -144,18 +182,23 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 商户证照列表。
|
||||
/// </summary>
|
||||
/// <returns>商户证照列表。</returns>
|
||||
[HttpGet("{merchantId:long}/documents")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantDocumentDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<MerchantDocumentDto>>> Documents(long merchantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询证照列表
|
||||
var result = await mediator.Send(new GetMerchantDocumentsQuery(merchantId), cancellationToken);
|
||||
|
||||
// 2. 返回证照集合
|
||||
return ApiResponse<IReadOnlyList<MerchantDocumentDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审核指定证照。
|
||||
/// </summary>
|
||||
/// <returns>审核后的证照信息。</returns>
|
||||
[HttpPost("{merchantId:long}/documents/{documentId:long}/review")]
|
||||
[PermissionAuthorize("merchant:review")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDocumentDto>), StatusCodes.Status200OK)]
|
||||
@@ -165,7 +208,10 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] ReviewMerchantDocumentCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户与证照标识
|
||||
var command = body with { MerchantId = merchantId, DocumentId = documentId };
|
||||
|
||||
// 2. 执行审核
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<MerchantDocumentDto>.Ok(result);
|
||||
}
|
||||
@@ -173,6 +219,7 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 新增商户合同。
|
||||
/// </summary>
|
||||
/// <returns>创建的合同信息。</returns>
|
||||
[HttpPost("{merchantId:long}/contracts")]
|
||||
[PermissionAuthorize("merchant:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantContractDto>), StatusCodes.Status200OK)]
|
||||
@@ -181,7 +228,10 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] CreateMerchantContractCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户标识
|
||||
var command = body with { MerchantId = merchantId };
|
||||
|
||||
// 2. 创建合同
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<MerchantContractDto>.Ok(result);
|
||||
}
|
||||
@@ -189,18 +239,23 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 合同列表。
|
||||
/// </summary>
|
||||
/// <returns>商户合同列表。</returns>
|
||||
[HttpGet("{merchantId:long}/contracts")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<MerchantContractDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<MerchantContractDto>>> Contracts(long merchantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询合同列表
|
||||
var result = await mediator.Send(new GetMerchantContractsQuery(merchantId), cancellationToken);
|
||||
|
||||
// 2. 返回合同集合
|
||||
return ApiResponse<IReadOnlyList<MerchantContractDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新合同状态(生效/终止等)。
|
||||
/// </summary>
|
||||
/// <returns>更新后的合同信息。</returns>
|
||||
[HttpPut("{merchantId:long}/contracts/{contractId:long}/status")]
|
||||
[PermissionAuthorize("merchant:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantContractDto>), StatusCodes.Status200OK)]
|
||||
@@ -210,7 +265,10 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] UpdateMerchantContractStatusCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户与合同标识
|
||||
var command = body with { MerchantId = merchantId, ContractId = contractId };
|
||||
|
||||
// 2. 更新合同状态
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<MerchantContractDto>.Ok(result);
|
||||
}
|
||||
@@ -218,12 +276,16 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 审核商户(通过/驳回)。
|
||||
/// </summary>
|
||||
/// <returns>审核后的商户信息。</returns>
|
||||
[HttpPost("{merchantId:long}/review")]
|
||||
[PermissionAuthorize("merchant:review")]
|
||||
[ProducesResponseType(typeof(ApiResponse<MerchantDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<MerchantDto>> Review(long merchantId, [FromBody] ReviewMerchantCommand body, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定商户标识
|
||||
var command = body with { MerchantId = merchantId };
|
||||
|
||||
// 2. 执行审核
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<MerchantDto>.Ok(result);
|
||||
}
|
||||
@@ -231,6 +293,7 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 审核日志。
|
||||
/// </summary>
|
||||
/// <returns>商户审核日志分页结果。</returns>
|
||||
[HttpGet("{merchantId:long}/audits")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<MerchantAuditLogDto>>), StatusCodes.Status200OK)]
|
||||
@@ -240,19 +303,26 @@ public sealed class MerchantsController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] int pageSize = 20,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 查询审核日志
|
||||
var result = await mediator.Send(new GetMerchantAuditLogsQuery(merchantId, page, pageSize), cancellationToken);
|
||||
|
||||
// 2. 返回日志分页
|
||||
return ApiResponse<PagedResult<MerchantAuditLogDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 可选商户类目列表。
|
||||
/// </summary>
|
||||
/// <returns>可选的商户类目列表。</returns>
|
||||
[HttpGet("categories")]
|
||||
[PermissionAuthorize("merchant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<string>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<string>>> Categories(CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询可选类目
|
||||
var result = await mediator.Send(new GetMerchantCategoriesQuery(), cancellationToken);
|
||||
|
||||
// 2. 返回类目列表
|
||||
return ApiResponse<IReadOnlyList<string>>.Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Orders.Commands;
|
||||
using TakeoutSaaS.Application.App.Orders.Dto;
|
||||
@@ -17,31 +16,31 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 订单管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/orders")]
|
||||
public sealed class OrdersController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建订单。
|
||||
/// </summary>
|
||||
/// <returns>创建的订单信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("order:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<OrderDto>> Create([FromBody] CreateOrderCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建订单
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<OrderDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询订单列表。
|
||||
/// </summary>
|
||||
/// <returns>订单分页列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("order:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<OrderDto>>), StatusCodes.Status200OK)]
|
||||
@@ -56,6 +55,7 @@ public sealed class OrdersController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数并执行查询
|
||||
var result = await mediator.Send(new SearchOrdersQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
@@ -68,19 +68,24 @@ public sealed class OrdersController(IMediator mediator) : BaseApiController
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<OrderDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取订单详情。
|
||||
/// </summary>
|
||||
/// <returns>订单详情。</returns>
|
||||
[HttpGet("{orderId:long}")]
|
||||
[PermissionAuthorize("order:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<OrderDto>> Detail(long orderId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询订单详情
|
||||
var result = await mediator.Send(new GetOrderByIdQuery { OrderId = orderId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<OrderDto>.Error(ErrorCodes.NotFound, "订单不存在")
|
||||
: ApiResponse<OrderDto>.Ok(result);
|
||||
@@ -89,17 +94,23 @@ public sealed class OrdersController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 更新订单。
|
||||
/// </summary>
|
||||
/// <returns>更新后的订单信息。</returns>
|
||||
[HttpPut("{orderId:long}")]
|
||||
[PermissionAuthorize("order:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<OrderDto>> Update(long orderId, [FromBody] UpdateOrderCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令包含订单标识
|
||||
if (command.OrderId == 0)
|
||||
{
|
||||
command = command with { OrderId = orderId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<OrderDto>.Error(ErrorCodes.NotFound, "订单不存在")
|
||||
: ApiResponse<OrderDto>.Ok(result);
|
||||
@@ -108,13 +119,17 @@ public sealed class OrdersController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除订单。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{orderId:long}")]
|
||||
[PermissionAuthorize("order:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long orderId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteOrderCommand { OrderId = orderId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "订单不存在");
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Payments.Commands;
|
||||
using TakeoutSaaS.Application.App.Payments.Dto;
|
||||
@@ -16,31 +15,31 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 支付记录管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/payments")]
|
||||
public sealed class PaymentsController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建支付记录。
|
||||
/// </summary>
|
||||
/// <returns>创建的支付记录信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("payment:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PaymentDto>> Create([FromBody] CreatePaymentCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建支付记录
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<PaymentDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询支付记录列表。
|
||||
/// </summary>
|
||||
/// <returns>支付记录分页列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("payment:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<PaymentDto>>), StatusCodes.Status200OK)]
|
||||
@@ -53,6 +52,7 @@ public sealed class PaymentsController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数并执行查询
|
||||
var result = await mediator.Send(new SearchPaymentsQuery
|
||||
{
|
||||
OrderId = orderId,
|
||||
@@ -63,19 +63,24 @@ public sealed class PaymentsController(IMediator mediator) : BaseApiController
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<PaymentDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取支付记录详情。
|
||||
/// </summary>
|
||||
/// <returns>支付记录详情。</returns>
|
||||
[HttpGet("{paymentId:long}")]
|
||||
[PermissionAuthorize("payment:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<PaymentDto>> Detail(long paymentId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询支付记录详情
|
||||
var result = await mediator.Send(new GetPaymentByIdQuery { PaymentId = paymentId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<PaymentDto>.Error(ErrorCodes.NotFound, "支付记录不存在")
|
||||
: ApiResponse<PaymentDto>.Ok(result);
|
||||
@@ -84,17 +89,23 @@ public sealed class PaymentsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 更新支付记录。
|
||||
/// </summary>
|
||||
/// <returns>更新后的支付记录信息。</returns>
|
||||
[HttpPut("{paymentId:long}")]
|
||||
[PermissionAuthorize("payment:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<PaymentDto>> Update(long paymentId, [FromBody] UpdatePaymentCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令包含支付记录标识
|
||||
if (command.PaymentId == 0)
|
||||
{
|
||||
command = command with { PaymentId = paymentId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<PaymentDto>.Error(ErrorCodes.NotFound, "支付记录不存在")
|
||||
: ApiResponse<PaymentDto>.Ok(result);
|
||||
@@ -103,13 +114,17 @@ public sealed class PaymentsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除支付记录。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{paymentId:long}")]
|
||||
[PermissionAuthorize("payment:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long paymentId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeletePaymentCommand { PaymentId = paymentId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "支付记录不存在");
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Identity.Commands;
|
||||
using TakeoutSaaS.Application.Identity.Contracts;
|
||||
@@ -26,6 +25,9 @@ public sealed class PermissionsController(IMediator mediator) : BaseApiControlle
|
||||
/// <remarks>
|
||||
/// 示例:GET /api/admin/v1/permissions?keyword=order&page=1&pageSize=20
|
||||
/// </remarks>
|
||||
/// <param name="query">查询条件。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>权限的分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("identity:permission:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<PermissionDto>>), StatusCodes.Status200OK)]
|
||||
@@ -38,6 +40,9 @@ public sealed class PermissionsController(IMediator mediator) : BaseApiControlle
|
||||
/// <summary>
|
||||
/// 创建权限。
|
||||
/// </summary>
|
||||
/// <param name="command">创建命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建的权限。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("identity:permission:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PermissionDto>), StatusCodes.Status200OK)]
|
||||
@@ -50,6 +55,10 @@ public sealed class PermissionsController(IMediator mediator) : BaseApiControlle
|
||||
/// <summary>
|
||||
/// 更新权限。
|
||||
/// </summary>
|
||||
/// <param name="permissionId">权限 ID。</param>
|
||||
/// <param name="command">更新命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的权限,未找到时返回 404。</returns>
|
||||
[HttpPut("{permissionId:long}")]
|
||||
[PermissionAuthorize("identity:permission:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PermissionDto>), StatusCodes.Status200OK)]
|
||||
@@ -66,6 +75,9 @@ public sealed class PermissionsController(IMediator mediator) : BaseApiControlle
|
||||
/// <summary>
|
||||
/// 删除权限。
|
||||
/// </summary>
|
||||
/// <param name="permissionId">权限 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{permissionId:long}")]
|
||||
[PermissionAuthorize("identity:permission:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Products.Commands;
|
||||
using TakeoutSaaS.Application.App.Products.Dto;
|
||||
@@ -16,31 +15,31 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 商品管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/products")]
|
||||
public sealed class ProductsController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建商品。
|
||||
/// </summary>
|
||||
/// <returns>创建的商品信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("product:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<ProductDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<ProductDto>> Create([FromBody] CreateProductCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建商品
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<ProductDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询商品列表。
|
||||
/// </summary>
|
||||
/// <returns>商品分页列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("product:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<ProductDto>>), StatusCodes.Status200OK)]
|
||||
@@ -54,6 +53,7 @@ public sealed class ProductsController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数并执行查询
|
||||
var result = await mediator.Send(new SearchProductsQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
@@ -65,19 +65,24 @@ public sealed class ProductsController(IMediator mediator) : BaseApiController
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<ProductDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取商品详情。
|
||||
/// </summary>
|
||||
/// <returns>商品详情。</returns>
|
||||
[HttpGet("{productId:long}")]
|
||||
[PermissionAuthorize("product:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<ProductDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<ProductDto>> Detail(long productId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询商品详情
|
||||
var result = await mediator.Send(new GetProductByIdQuery { ProductId = productId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<ProductDto>.Error(ErrorCodes.NotFound, "商品不存在")
|
||||
: ApiResponse<ProductDto>.Ok(result);
|
||||
@@ -86,17 +91,23 @@ public sealed class ProductsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 更新商品。
|
||||
/// </summary>
|
||||
/// <returns>更新后的商品信息。</returns>
|
||||
[HttpPut("{productId:long}")]
|
||||
[PermissionAuthorize("product:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<ProductDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<ProductDto>> Update(long productId, [FromBody] UpdateProductCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令包含商品标识
|
||||
if (command.ProductId == 0)
|
||||
{
|
||||
command = command with { ProductId = productId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<ProductDto>.Error(ErrorCodes.NotFound, "商品不存在")
|
||||
: ApiResponse<ProductDto>.Ok(result);
|
||||
@@ -105,13 +116,17 @@ public sealed class ProductsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除商品。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{productId:long}")]
|
||||
[PermissionAuthorize("product:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long productId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteProductCommand { ProductId = productId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "商品不存在");
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.Identity.Commands;
|
||||
using TakeoutSaaS.Application.Identity.Contracts;
|
||||
using TakeoutSaaS.Application.Identity.Queries;
|
||||
@@ -27,12 +25,16 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <remarks>
|
||||
/// 示例:GET /api/admin/v1/roles/templates
|
||||
/// </remarks>
|
||||
/// <returns>角色模板列表。</returns>
|
||||
[HttpGet("templates")]
|
||||
[PermissionAuthorize("identity:role:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<RoleTemplateDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<IReadOnlyList<RoleTemplateDto>>> ListTemplates([FromQuery] bool? isActive, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询模板列表
|
||||
var result = await mediator.Send(new ListRoleTemplatesQuery { IsActive = isActive }, cancellationToken);
|
||||
|
||||
// 2. 返回模板集合
|
||||
return ApiResponse<IReadOnlyList<RoleTemplateDto>>.Ok(result);
|
||||
}
|
||||
|
||||
@@ -42,13 +44,17 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <remarks>
|
||||
/// 示例:GET /api/admin/v1/roles/templates/tenant-admin
|
||||
/// </remarks>
|
||||
/// <returns>角色模板详情。</returns>
|
||||
[HttpGet("templates/{templateCode}")]
|
||||
[PermissionAuthorize("identity:role:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleTemplateDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleTemplateDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<RoleTemplateDto>> GetTemplate(string templateCode, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询指定模板
|
||||
var result = await mediator.Send(new GetRoleTemplateQuery { TemplateCode = templateCode }, cancellationToken);
|
||||
|
||||
// 2. 返回模板或 404
|
||||
return result is null
|
||||
? ApiResponse<RoleTemplateDto>.Error(StatusCodes.Status404NotFound, "角色模板不存在")
|
||||
: ApiResponse<RoleTemplateDto>.Ok(result);
|
||||
@@ -57,18 +63,23 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 创建角色模板。
|
||||
/// </summary>
|
||||
/// <returns>创建的角色模板信息。</returns>
|
||||
[HttpPost("templates")]
|
||||
[PermissionAuthorize("role-template:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleTemplateDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<RoleTemplateDto>> CreateTemplate([FromBody, Required] CreateRoleTemplateCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建模板
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<RoleTemplateDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新角色模板。
|
||||
/// </summary>
|
||||
/// <returns>更新后的角色模板信息。</returns>
|
||||
[HttpPut("templates/{templateCode}")]
|
||||
[PermissionAuthorize("role-template:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleTemplateDto>), StatusCodes.Status200OK)]
|
||||
@@ -78,8 +89,13 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
[FromBody, Required] UpdateRoleTemplateCommand command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定模板编码
|
||||
command = command with { TemplateCode = templateCode };
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result is null
|
||||
? ApiResponse<RoleTemplateDto>.Error(StatusCodes.Status404NotFound, "角色模板不存在")
|
||||
: ApiResponse<RoleTemplateDto>.Ok(result);
|
||||
@@ -88,12 +104,16 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除角色模板。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("templates/{templateCode}")]
|
||||
[PermissionAuthorize("role-template:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<bool>> DeleteTemplate(string templateCode, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除模板
|
||||
var result = await mediator.Send(new DeleteRoleTemplateCommand { TemplateCode = templateCode }, cancellationToken);
|
||||
|
||||
// 2. 返回执行结果
|
||||
return ApiResponse<bool>.Ok(result);
|
||||
}
|
||||
|
||||
@@ -104,6 +124,7 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// 示例:POST /api/admin/v1/roles/templates/store-manager/copy
|
||||
/// Body: { "roleName": "新区店长" }
|
||||
/// </remarks>
|
||||
/// <returns>创建的角色信息。</returns>
|
||||
[HttpPost("templates/{templateCode}/copy")]
|
||||
[PermissionAuthorize("identity:role:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
|
||||
@@ -112,7 +133,10 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
[FromBody, Required] CopyRoleTemplateCommand command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定模板编码
|
||||
command = command with { TemplateCode = templateCode };
|
||||
|
||||
// 2. 复制模板并返回角色
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<RoleDto>.Ok(result);
|
||||
}
|
||||
@@ -124,6 +148,7 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// 示例:POST /api/admin/v1/roles/templates/init
|
||||
/// Body: { "templateCodes": ["tenant-admin","store-manager","store-staff"] }
|
||||
/// </remarks>
|
||||
/// <returns>创建的角色列表。</returns>
|
||||
[HttpPost("templates/init")]
|
||||
[PermissionAuthorize("identity:role:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<RoleDto>>), StatusCodes.Status200OK)]
|
||||
@@ -131,7 +156,10 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
[FromBody] InitializeRoleTemplatesCommand? command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令实例存在
|
||||
command ??= new InitializeRoleTemplatesCommand();
|
||||
|
||||
// 2. 执行初始化
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<IReadOnlyList<RoleDto>>.Ok(result);
|
||||
}
|
||||
@@ -144,38 +172,52 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// GET /api/admin/v1/roles?keyword=ops&page=1&pageSize=20
|
||||
/// Header: Authorization: Bearer <JWT> + X-Tenant-Id
|
||||
/// </remarks>
|
||||
/// <returns>角色分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("identity:role:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<RoleDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<RoleDto>>> Search([FromQuery] SearchRolesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询角色分页
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 2. 返回分页数据
|
||||
return ApiResponse<PagedResult<RoleDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建角色。
|
||||
/// </summary>
|
||||
/// <returns>创建的角色信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("identity:role:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<RoleDto>> Create([FromBody, Required] CreateRoleCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建角色
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<RoleDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新角色。
|
||||
/// </summary>
|
||||
/// <returns>更新后的角色信息。</returns>
|
||||
[HttpPut("{roleId:long}")]
|
||||
[PermissionAuthorize("identity:role:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<RoleDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<RoleDto>> Update(long roleId, [FromBody, Required] UpdateRoleCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定角色标识
|
||||
command = command with { RoleId = roleId };
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result is null
|
||||
? ApiResponse<RoleDto>.Error(StatusCodes.Status404NotFound, "角色不存在")
|
||||
: ApiResponse<RoleDto>.Ok(result);
|
||||
@@ -184,12 +226,16 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除角色。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{roleId:long}")]
|
||||
[PermissionAuthorize("identity:role:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<bool>> Delete(long roleId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 构建删除命令
|
||||
var command = new DeleteRoleCommand { RoleId = roleId };
|
||||
|
||||
// 2. 执行删除
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<bool>.Ok(result);
|
||||
}
|
||||
@@ -197,12 +243,16 @@ public sealed class RolesController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 绑定角色权限(覆盖式)。
|
||||
/// </summary>
|
||||
/// <returns>是否绑定成功。</returns>
|
||||
[HttpPut("{roleId:long}/permissions")]
|
||||
[PermissionAuthorize("identity:role:bind-permission")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<bool>> BindPermissions(long roleId, [FromBody, Required] BindRolePermissionsCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定角色标识
|
||||
command = command with { RoleId = roleId };
|
||||
|
||||
// 2. 执行覆盖式授权
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<bool>.Ok(result);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Stores.Commands;
|
||||
using TakeoutSaaS.Application.App.Stores.Dto;
|
||||
@@ -17,31 +16,31 @@ namespace TakeoutSaaS.AdminApi.Controllers;
|
||||
/// <summary>
|
||||
/// 门店管理。
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 初始化控制器。
|
||||
/// </remarks>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/admin/v{version:apiVersion}/stores")]
|
||||
public sealed class StoresController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 创建门店。
|
||||
/// </summary>
|
||||
/// <returns>创建的门店信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("store:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<StoreDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<StoreDto>> Create([FromBody] CreateStoreCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建门店
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<StoreDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询门店列表。
|
||||
/// </summary>
|
||||
/// <returns>门店分页列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("store:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<StoreDto>>), StatusCodes.Status200OK)]
|
||||
@@ -54,6 +53,7 @@ public sealed class StoresController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组装查询参数并执行查询
|
||||
var result = await mediator.Send(new SearchStoresQuery
|
||||
{
|
||||
MerchantId = merchantId,
|
||||
@@ -64,19 +64,24 @@ public sealed class StoresController(IMediator mediator) : BaseApiController
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<StoreDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取门店详情。
|
||||
/// </summary>
|
||||
/// <returns>门店详情。</returns>
|
||||
[HttpGet("{storeId:long}")]
|
||||
[PermissionAuthorize("store:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<StoreDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<StoreDto>> Detail(long storeId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询门店详情
|
||||
var result = await mediator.Send(new GetStoreByIdQuery { StoreId = storeId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<StoreDto>.Error(ErrorCodes.NotFound, "门店不存在")
|
||||
: ApiResponse<StoreDto>.Ok(result);
|
||||
@@ -85,17 +90,23 @@ public sealed class StoresController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 更新门店。
|
||||
/// </summary>
|
||||
/// <returns>更新后的门店信息。</returns>
|
||||
[HttpPut("{storeId:long}")]
|
||||
[PermissionAuthorize("store:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<StoreDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<StoreDto>> Update(long storeId, [FromBody] UpdateStoreCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令包含门店标识
|
||||
if (command.StoreId == 0)
|
||||
{
|
||||
command = command with { StoreId = storeId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result == null
|
||||
? ApiResponse<StoreDto>.Error(ErrorCodes.NotFound, "门店不存在")
|
||||
: ApiResponse<StoreDto>.Ok(result);
|
||||
@@ -104,13 +115,17 @@ public sealed class StoresController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 删除门店。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{storeId:long}")]
|
||||
[PermissionAuthorize("store:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long storeId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteStoreCommand { StoreId = storeId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return success
|
||||
? ApiResponse<object>.Ok(null)
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "门店不存在");
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.SystemParameters.Commands;
|
||||
using TakeoutSaaS.Application.App.SystemParameters.Dto;
|
||||
@@ -26,18 +25,23 @@ public sealed class SystemParametersController(IMediator mediator) : BaseApiCont
|
||||
/// <summary>
|
||||
/// 创建系统参数。
|
||||
/// </summary>
|
||||
/// <returns>创建的系统参数信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("system-parameter:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<SystemParameterDto>> Create([FromBody] CreateSystemParameterCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 创建系统参数
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<SystemParameterDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询系统参数列表。
|
||||
/// </summary>
|
||||
/// <returns>分页的系统参数列表。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("system-parameter:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<SystemParameterDto>>), StatusCodes.Status200OK)]
|
||||
@@ -50,6 +54,7 @@ public sealed class SystemParametersController(IMediator mediator) : BaseApiCont
|
||||
[FromQuery] bool sortDesc = true,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 组合查询参数
|
||||
var result = await mediator.Send(new SearchSystemParametersQuery
|
||||
{
|
||||
Keyword = keyword,
|
||||
@@ -60,19 +65,24 @@ public sealed class SystemParametersController(IMediator mediator) : BaseApiCont
|
||||
SortDescending = sortDesc
|
||||
}, cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<SystemParameterDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取系统参数详情。
|
||||
/// </summary>
|
||||
/// <returns>系统参数详情。</returns>
|
||||
[HttpGet("{parameterId:long}")]
|
||||
[PermissionAuthorize("system-parameter:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<SystemParameterDto>> Detail(long parameterId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询参数详情
|
||||
var result = await mediator.Send(new GetSystemParameterByIdQuery(parameterId), cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result == null
|
||||
? ApiResponse<SystemParameterDto>.Error(ErrorCodes.NotFound, "系统参数不存在")
|
||||
: ApiResponse<SystemParameterDto>.Ok(result);
|
||||
@@ -81,18 +91,23 @@ public sealed class SystemParametersController(IMediator mediator) : BaseApiCont
|
||||
/// <summary>
|
||||
/// 更新系统参数。
|
||||
/// </summary>
|
||||
/// <returns>更新后的系统参数信息。</returns>
|
||||
[HttpPut("{parameterId:long}")]
|
||||
[PermissionAuthorize("system-parameter:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<SystemParameterDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<SystemParameterDto>> Update(long parameterId, [FromBody] UpdateSystemParameterCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 确保命令包含参数标识
|
||||
if (command.ParameterId == 0)
|
||||
{
|
||||
command = command with { ParameterId = parameterId };
|
||||
}
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回结果或 404
|
||||
return result == null
|
||||
? ApiResponse<SystemParameterDto>.Error(ErrorCodes.NotFound, "系统参数不存在")
|
||||
: ApiResponse<SystemParameterDto>.Ok(result);
|
||||
@@ -101,13 +116,17 @@ public sealed class SystemParametersController(IMediator mediator) : BaseApiCont
|
||||
/// <summary>
|
||||
/// 删除系统参数。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{parameterId:long}")]
|
||||
[PermissionAuthorize("system-parameter:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<object>> Delete(long parameterId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行删除
|
||||
var success = await mediator.Send(new DeleteSystemParameterCommand { ParameterId = parameterId }, cancellationToken);
|
||||
|
||||
// 2. 返回成功或 404
|
||||
return success
|
||||
? ApiResponse.Success()
|
||||
: ApiResponse<object>.Error(ErrorCodes.NotFound, "系统参数不存在");
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -23,26 +22,36 @@ public sealed class TenantAnnouncementsController(IMediator mediator) : BaseApiC
|
||||
/// <summary>
|
||||
/// 分页查询公告。
|
||||
/// </summary>
|
||||
/// <returns>租户公告分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("tenant-announcement:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantAnnouncementDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<TenantAnnouncementDto>>> Search(long tenantId, [FromQuery] SearchTenantAnnouncementsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
query = query with { TenantId = tenantId };
|
||||
|
||||
// 2. 查询公告列表
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 3. 返回分页结果
|
||||
return ApiResponse<PagedResult<TenantAnnouncementDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 公告详情。
|
||||
/// </summary>
|
||||
/// <returns>租户公告详情。</returns>
|
||||
[HttpGet("{announcementId:long}")]
|
||||
[PermissionAuthorize("tenant-announcement:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantAnnouncementDto>> Detail(long tenantId, long announcementId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询指定公告
|
||||
var result = await mediator.Send(new GetTenantAnnouncementQuery { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantAnnouncementDto>.Error(StatusCodes.Status404NotFound, "公告不存在")
|
||||
: ApiResponse<TenantAnnouncementDto>.Ok(result);
|
||||
@@ -51,12 +60,16 @@ public sealed class TenantAnnouncementsController(IMediator mediator) : BaseApiC
|
||||
/// <summary>
|
||||
/// 创建公告。
|
||||
/// </summary>
|
||||
/// <returns>创建的公告信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("tenant-announcement:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantAnnouncementDto>> Create(long tenantId, [FromBody, Required] CreateTenantAnnouncementCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
command = command with { TenantId = tenantId };
|
||||
|
||||
// 2. 创建公告并返回
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<TenantAnnouncementDto>.Ok(result);
|
||||
}
|
||||
@@ -64,14 +77,20 @@ public sealed class TenantAnnouncementsController(IMediator mediator) : BaseApiC
|
||||
/// <summary>
|
||||
/// 更新公告。
|
||||
/// </summary>
|
||||
/// <returns>更新后的公告信息。</returns>
|
||||
[HttpPut("{announcementId:long}")]
|
||||
[PermissionAuthorize("tenant-announcement:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantAnnouncementDto>> Update(long tenantId, long announcementId, [FromBody, Required] UpdateTenantAnnouncementCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户与公告标识
|
||||
command = command with { TenantId = tenantId, AnnouncementId = announcementId };
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantAnnouncementDto>.Error(StatusCodes.Status404NotFound, "公告不存在")
|
||||
: ApiResponse<TenantAnnouncementDto>.Ok(result);
|
||||
@@ -80,25 +99,33 @@ public sealed class TenantAnnouncementsController(IMediator mediator) : BaseApiC
|
||||
/// <summary>
|
||||
/// 删除公告。
|
||||
/// </summary>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{announcementId:long}")]
|
||||
[PermissionAuthorize("tenant-announcement:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<bool>> Delete(long tenantId, long announcementId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除公告
|
||||
var result = await mediator.Send(new DeleteTenantAnnouncementCommand { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);
|
||||
|
||||
// 2. 返回执行结果
|
||||
return ApiResponse<bool>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记公告已读。
|
||||
/// </summary>
|
||||
/// <returns>标记已读后的公告信息。</returns>
|
||||
[HttpPost("{announcementId:long}/read")]
|
||||
[PermissionAuthorize("tenant-announcement:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantAnnouncementDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantAnnouncementDto>> MarkRead(long tenantId, long announcementId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 标记公告已读
|
||||
var result = await mediator.Send(new MarkTenantAnnouncementReadCommand { TenantId = tenantId, AnnouncementId = announcementId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantAnnouncementDto>.Error(StatusCodes.Status404NotFound, "公告不存在")
|
||||
: ApiResponse<TenantAnnouncementDto>.Ok(result);
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -23,26 +22,36 @@ public sealed class TenantBillingsController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 分页查询账单。
|
||||
/// </summary>
|
||||
/// <returns>租户账单分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("tenant-bill:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantBillingDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<TenantBillingDto>>> Search(long tenantId, [FromQuery] SearchTenantBillsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
query = query with { TenantId = tenantId };
|
||||
|
||||
// 2. 查询账单列表
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 3. 返回分页结果
|
||||
return ApiResponse<PagedResult<TenantBillingDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 账单详情。
|
||||
/// </summary>
|
||||
/// <returns>租户账单详情。</returns>
|
||||
[HttpGet("{billingId:long}")]
|
||||
[PermissionAuthorize("tenant-bill:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantBillingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantBillingDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantBillingDto>> Detail(long tenantId, long billingId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询账单详情
|
||||
var result = await mediator.Send(new GetTenantBillQuery { TenantId = tenantId, BillingId = billingId }, cancellationToken);
|
||||
|
||||
// 2. 返回详情或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantBillingDto>.Error(StatusCodes.Status404NotFound, "账单不存在")
|
||||
: ApiResponse<TenantBillingDto>.Ok(result);
|
||||
@@ -51,12 +60,16 @@ public sealed class TenantBillingsController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 创建账单。
|
||||
/// </summary>
|
||||
/// <returns>创建的账单信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("tenant-bill:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantBillingDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantBillingDto>> Create(long tenantId, [FromBody, Required] CreateTenantBillingCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
command = command with { TenantId = tenantId };
|
||||
|
||||
// 2. 创建账单
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<TenantBillingDto>.Ok(result);
|
||||
}
|
||||
@@ -64,14 +77,20 @@ public sealed class TenantBillingsController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 标记账单已支付。
|
||||
/// </summary>
|
||||
/// <returns>标记支付后的账单信息。</returns>
|
||||
[HttpPost("{billingId:long}/pay")]
|
||||
[PermissionAuthorize("tenant-bill:pay")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantBillingDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantBillingDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantBillingDto>> MarkPaid(long tenantId, long billingId, [FromBody, Required] MarkTenantBillingPaidCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户与账单标识
|
||||
command = command with { TenantId = tenantId, BillingId = billingId };
|
||||
|
||||
// 2. 标记支付状态
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantBillingDto>.Error(StatusCodes.Status404NotFound, "账单不存在")
|
||||
: ApiResponse<TenantBillingDto>.Ok(result);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
@@ -22,26 +21,36 @@ public sealed class TenantNotificationsController(IMediator mediator) : BaseApiC
|
||||
/// <summary>
|
||||
/// 分页查询通知。
|
||||
/// </summary>
|
||||
/// <returns>租户通知分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("tenant-notification:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantNotificationDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<TenantNotificationDto>>> Search(long tenantId, [FromQuery] SearchTenantNotificationsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
query = query with { TenantId = tenantId };
|
||||
|
||||
// 2. 查询通知列表
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 3. 返回分页结果
|
||||
return ApiResponse<PagedResult<TenantNotificationDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记通知已读。
|
||||
/// </summary>
|
||||
/// <returns>标记已读后的通知信息。</returns>
|
||||
[HttpPost("{notificationId:long}/read")]
|
||||
[PermissionAuthorize("tenant-notification:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantNotificationDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantNotificationDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantNotificationDto>> MarkRead(long tenantId, long notificationId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 标记通知为已读
|
||||
var result = await mediator.Send(new MarkTenantNotificationReadCommand { TenantId = tenantId, NotificationId = notificationId }, cancellationToken);
|
||||
|
||||
// 2. 返回结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantNotificationDto>.Error(StatusCodes.Status404NotFound, "通知不存在")
|
||||
: ApiResponse<TenantNotificationDto>.Ok(result);
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -23,25 +22,37 @@ public sealed class TenantPackagesController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 分页查询租户套餐。
|
||||
/// </summary>
|
||||
/// <param name="query">查询条件。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>租户套餐分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("tenant-package:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantPackageDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<TenantPackageDto>>> Search([FromQuery] SearchTenantPackagesQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询租户套餐分页
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 2. 返回结果
|
||||
return ApiResponse<PagedResult<TenantPackageDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查看套餐详情。
|
||||
/// </summary>
|
||||
/// <param name="tenantPackageId">套餐 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>套餐详情或未找到。</returns>
|
||||
[HttpGet("{tenantPackageId:long}")]
|
||||
[PermissionAuthorize("tenant-package:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantPackageDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantPackageDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantPackageDto>> Detail(long tenantPackageId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询套餐详情
|
||||
var result = await mediator.Send(new GetTenantPackageByIdQuery { TenantPackageId = tenantPackageId }, cancellationToken);
|
||||
|
||||
// 2. 返回查询结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantPackageDto>.Error(StatusCodes.Status404NotFound, "套餐不存在")
|
||||
: ApiResponse<TenantPackageDto>.Ok(result);
|
||||
@@ -50,26 +61,41 @@ public sealed class TenantPackagesController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 创建套餐。
|
||||
/// </summary>
|
||||
/// <param name="command">创建命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>创建后的套餐。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("tenant-package:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantPackageDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantPackageDto>> Create([FromBody, Required] CreateTenantPackageCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 执行创建
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回创建结果
|
||||
return ApiResponse<TenantPackageDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新套餐。
|
||||
/// </summary>
|
||||
/// <param name="tenantPackageId">套餐 ID。</param>
|
||||
/// <param name="command">更新命令。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>更新后的套餐或未找到。</returns>
|
||||
[HttpPut("{tenantPackageId:long}")]
|
||||
[PermissionAuthorize("tenant-package:update")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantPackageDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantPackageDto>), StatusCodes.Status404NotFound)]
|
||||
public async Task<ApiResponse<TenantPackageDto>> Update(long tenantPackageId, [FromBody, Required] UpdateTenantPackageCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定路由 ID
|
||||
command = command with { TenantPackageId = tenantPackageId };
|
||||
|
||||
// 2. 执行更新
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回更新结果或 404
|
||||
return result is null
|
||||
? ApiResponse<TenantPackageDto>.Error(StatusCodes.Status404NotFound, "套餐不存在")
|
||||
: ApiResponse<TenantPackageDto>.Ok(result);
|
||||
@@ -78,12 +104,18 @@ public sealed class TenantPackagesController(IMediator mediator) : BaseApiContro
|
||||
/// <summary>
|
||||
/// 删除套餐。
|
||||
/// </summary>
|
||||
/// <param name="tenantPackageId">套餐 ID。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>删除结果。</returns>
|
||||
[HttpDelete("{tenantPackageId:long}")]
|
||||
[PermissionAuthorize("tenant-package:delete")]
|
||||
[ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<bool>> Delete(long tenantPackageId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 构建删除命令
|
||||
var command = new DeleteTenantPackageCommand { TenantPackageId = tenantPackageId };
|
||||
|
||||
// 2. 执行删除并返回
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<bool>.Ok(result);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
using TakeoutSaaS.Module.Authorization.Attributes;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
|
||||
@@ -24,42 +22,55 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 注册租户并初始化套餐。
|
||||
/// </summary>
|
||||
/// <returns>注册的租户信息。</returns>
|
||||
[HttpPost]
|
||||
[PermissionAuthorize("tenant:create")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantDto>> Register([FromBody] RegisterTenantCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 注册租户并初始化套餐
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 2. 返回注册结果
|
||||
return ApiResponse<TenantDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询租户。
|
||||
/// </summary>
|
||||
/// <returns>租户分页结果。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("tenant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantDto>>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<PagedResult<TenantDto>>> Search([FromQuery] SearchTenantsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询租户分页
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
|
||||
// 2. 返回分页数据
|
||||
return ApiResponse<PagedResult<TenantDto>>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查看租户详情。
|
||||
/// </summary>
|
||||
/// <returns>租户详情。</returns>
|
||||
[HttpGet("{tenantId:long}")]
|
||||
[PermissionAuthorize("tenant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantDetailDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantDetailDto>> Detail(long tenantId, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询租户详情
|
||||
var result = await mediator.Send(new GetTenantByIdQuery(tenantId), cancellationToken);
|
||||
|
||||
// 2. 返回租户信息
|
||||
return ApiResponse<TenantDetailDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 提交或更新实名认证资料。
|
||||
/// </summary>
|
||||
/// <returns>提交的实名认证信息。</returns>
|
||||
[HttpPost("{tenantId:long}/verification")]
|
||||
[PermissionAuthorize("tenant:review")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantVerificationDto>), StatusCodes.Status200OK)]
|
||||
@@ -68,27 +79,39 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] SubmitTenantVerificationCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 合并路由中的租户标识
|
||||
var command = body with { TenantId = tenantId };
|
||||
|
||||
// 2. 提交或更新认证资料
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回认证结果
|
||||
return ApiResponse<TenantVerificationDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审核租户。
|
||||
/// </summary>
|
||||
/// <returns>审核后的租户信息。</returns>
|
||||
[HttpPost("{tenantId:long}/review")]
|
||||
[PermissionAuthorize("tenant:review")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantDto>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TenantDto>> Review(long tenantId, [FromBody] ReviewTenantCommand body, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
var command = body with { TenantId = tenantId };
|
||||
|
||||
// 2. 执行审核
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回审核结果
|
||||
return ApiResponse<TenantDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建或续费租户订阅。
|
||||
/// </summary>
|
||||
/// <returns>创建或续费的订阅信息。</returns>
|
||||
[HttpPost("{tenantId:long}/subscriptions")]
|
||||
[PermissionAuthorize("tenant:subscription")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status200OK)]
|
||||
@@ -97,7 +120,10 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] CreateTenantSubscriptionCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户并创建或续费订阅
|
||||
var command = body with { TenantId = tenantId };
|
||||
|
||||
// 2. 返回订阅结果
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<TenantSubscriptionDto>.Ok(result);
|
||||
}
|
||||
@@ -105,6 +131,7 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
/// <summary>
|
||||
/// 套餐升降配。
|
||||
/// </summary>
|
||||
/// <returns>更新后的订阅信息。</returns>
|
||||
[HttpPut("{tenantId:long}/subscriptions/{subscriptionId:long}/plan")]
|
||||
[PermissionAuthorize("tenant:subscription")]
|
||||
[ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status200OK)]
|
||||
@@ -114,14 +141,20 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody] ChangeTenantSubscriptionPlanCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户与订阅标识
|
||||
var command = body with { TenantId = tenantId, TenantSubscriptionId = subscriptionId };
|
||||
|
||||
// 2. 执行升降配
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
|
||||
// 3. 返回调整后的订阅
|
||||
return ApiResponse<TenantSubscriptionDto>.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询审核日志。
|
||||
/// </summary>
|
||||
/// <returns>租户审核日志分页结果。</returns>
|
||||
[HttpGet("{tenantId:long}/audits")]
|
||||
[PermissionAuthorize("tenant:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<TenantAuditLogDto>>), StatusCodes.Status200OK)]
|
||||
@@ -131,7 +164,10 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
[FromQuery] int pageSize = 20,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 1. 构造审核日志查询
|
||||
var query = new GetTenantAuditLogsQuery(tenantId, page, pageSize);
|
||||
|
||||
// 2. 查询并返回分页结果
|
||||
var result = await mediator.Send(query, cancellationToken);
|
||||
return ApiResponse<PagedResult<TenantAuditLogDto>>.Ok(result);
|
||||
}
|
||||
@@ -140,6 +176,7 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
/// 配额校验并占用额度(门店/账号/短信/配送)。
|
||||
/// </summary>
|
||||
/// <remarks>需在请求头携带 X-Tenant-Id 对应的租户。</remarks>
|
||||
/// <returns>配额校验结果。</returns>
|
||||
[HttpPost("{tenantId:long}/quotas/check")]
|
||||
[PermissionAuthorize("tenant:quota:check")]
|
||||
[ProducesResponseType(typeof(ApiResponse<QuotaCheckResultDto>), StatusCodes.Status200OK)]
|
||||
@@ -148,7 +185,10 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
|
||||
[FromBody, Required] CheckTenantQuotaCommand body,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 绑定租户标识
|
||||
var command = body with { TenantId = tenantId };
|
||||
|
||||
// 2. 校验并占用配额
|
||||
var result = await mediator.Send(command, cancellationToken);
|
||||
return ApiResponse<QuotaCheckResultDto>.Ok(result);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Identity.Abstractions;
|
||||
using TakeoutSaaS.Application.Identity.Contracts;
|
||||
@@ -51,6 +50,9 @@ public sealed class UserPermissionsController(IAdminAuthService authService) : B
|
||||
/// }
|
||||
/// </code>
|
||||
/// </remarks>
|
||||
/// <param name="query">搜索条件。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>分页的用户权限概览。</returns>
|
||||
[HttpGet]
|
||||
[PermissionAuthorize("identity:permission:read")]
|
||||
[ProducesResponseType(typeof(ApiResponse<PagedResult<UserPermissionDto>>), StatusCodes.Status200OK)]
|
||||
@@ -58,6 +60,7 @@ public sealed class UserPermissionsController(IAdminAuthService authService) : B
|
||||
[FromQuery] SearchUserPermissionsQuery query,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询当前租户的用户权限概览
|
||||
var result = await authService.SearchUserPermissionsAsync(
|
||||
query.Keyword,
|
||||
query.Page,
|
||||
@@ -66,6 +69,7 @@ public sealed class UserPermissionsController(IAdminAuthService authService) : B
|
||||
query.SortDescending,
|
||||
cancellationToken);
|
||||
|
||||
// 2. 返回分页结果
|
||||
return ApiResponse<PagedResult<UserPermissionDto>>.Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Cors.Infrastructure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
@@ -26,13 +20,16 @@ using TakeoutSaaS.Module.Tenancy.Extensions;
|
||||
using TakeoutSaaS.Shared.Web.Extensions;
|
||||
using TakeoutSaaS.Shared.Web.Swagger;
|
||||
|
||||
// 1. 创建构建器与日志模板
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
const string logTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] [TraceId:{TraceId}] [SpanId:{SpanId}] [Service:{Service}] {SourceContext} {Message:lj}{NewLine}{Exception}";
|
||||
|
||||
// 2. 加载种子配置文件
|
||||
builder.Configuration
|
||||
.AddJsonFile("appsettings.Seed.json", optional: true, reloadOnChange: true)
|
||||
.AddJsonFile($"appsettings.Seed.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
|
||||
|
||||
// 3. 配置 Serilog 输出
|
||||
builder.Host.UseSerilog((context, _, configuration) =>
|
||||
{
|
||||
configuration
|
||||
@@ -47,6 +44,7 @@ builder.Host.UseSerilog((context, _, configuration) =>
|
||||
outputTemplate: logTemplate);
|
||||
});
|
||||
|
||||
// 4. 注册通用 Web 能力与 Swagger
|
||||
builder.Services.AddSharedWebCore();
|
||||
builder.Services.AddSharedSwagger(options =>
|
||||
{
|
||||
@@ -54,6 +52,8 @@ builder.Services.AddSharedSwagger(options =>
|
||||
options.Description = "管理后台 API 文档";
|
||||
options.EnableAuthorization = true;
|
||||
});
|
||||
|
||||
// 5. 注册领域与基础设施模块
|
||||
builder.Services.AddIdentityApplication();
|
||||
builder.Services.AddIdentityInfrastructure(builder.Configuration, enableAdminSeed: true);
|
||||
builder.Services.AddAppInfrastructure(builder.Configuration);
|
||||
@@ -71,6 +71,8 @@ builder.Services.AddMessagingModule(builder.Configuration);
|
||||
builder.Services.AddMessagingApplication();
|
||||
builder.Services.AddSchedulerModule(builder.Configuration);
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
// 6. 配置 OpenTelemetry 采集
|
||||
var otelSection = builder.Configuration.GetSection("Otel");
|
||||
var otelEndpoint = otelSection.GetValue<string>("Endpoint");
|
||||
var useConsoleExporter = otelSection.GetValue<bool?>("UseConsoleExporter") ?? builder.Environment.IsDevelopment();
|
||||
@@ -86,7 +88,6 @@ builder.Services.AddOpenTelemetry()
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddEntityFrameworkCoreInstrumentation();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(otelEndpoint))
|
||||
{
|
||||
tracing.AddOtlpExporter(exporter =>
|
||||
@@ -107,7 +108,6 @@ builder.Services.AddOpenTelemetry()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddRuntimeInstrumentation()
|
||||
.AddPrometheusExporter();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(otelEndpoint))
|
||||
{
|
||||
metrics.AddOtlpExporter(exporter =>
|
||||
@@ -122,6 +122,7 @@ builder.Services.AddOpenTelemetry()
|
||||
}
|
||||
});
|
||||
|
||||
// 7. 解析并配置 CORS
|
||||
var adminOrigins = ResolveCorsOrigins(builder.Configuration, "Cors:Admin");
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
@@ -131,8 +132,8 @@ builder.Services.AddCors(options =>
|
||||
});
|
||||
});
|
||||
|
||||
// 8. 构建应用并配置中间件管道
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseCors("AdminApiCors");
|
||||
app.UseTenantResolution();
|
||||
app.UseSharedWebCore();
|
||||
@@ -140,12 +141,12 @@ app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseSharedSwagger();
|
||||
app.UseSchedulerDashboard(builder.Configuration);
|
||||
|
||||
app.MapHealthChecks("/healthz");
|
||||
app.MapPrometheusScrapingEndpoint();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
|
||||
// 9. 解析配置中的 CORS 域名
|
||||
static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionKey)
|
||||
{
|
||||
var origins = configuration.GetSection(sectionKey).Get<string[]>();
|
||||
@@ -155,6 +156,7 @@ static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionK
|
||||
.ToArray() ?? [];
|
||||
}
|
||||
|
||||
// 10. 构建 CORS 策略
|
||||
static void ConfigureCorsPolicy(CorsPolicyBuilder policy, string[] origins)
|
||||
{
|
||||
if (origins.Length == 0)
|
||||
|
||||
@@ -10,38 +10,46 @@ namespace TakeoutSaaS.MiniApi.Controllers;
|
||||
/// <summary>
|
||||
/// 小程序登录认证
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 小程序登录认证
|
||||
/// </remarks>
|
||||
/// <param name="authService"></param>
|
||||
/// <remarks>提供小程序端的微信登录与 Token 刷新能力。</remarks>
|
||||
/// <param name="authService">小程序认证服务</param>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/mini/v{version:apiVersion}/auth")]
|
||||
public sealed class AuthController(IMiniAuthService authService) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 微信登录
|
||||
/// </summary>
|
||||
/// <param name="request">微信登录请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>包含访问令牌与刷新令牌的响应。</returns>
|
||||
[HttpPost("wechat/login")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TokenResponse>> LoginWithWeChat([FromBody] WeChatLoginRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 调用认证服务完成微信登录
|
||||
var response = await authService.LoginWithWeChatAsync(request, cancellationToken);
|
||||
|
||||
// 2. 返回访问与刷新令牌
|
||||
return ApiResponse<TokenResponse>.Ok(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 刷新 Token
|
||||
/// </summary>
|
||||
/// <param name="request">刷新令牌请求。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>新的访问令牌与刷新令牌。</returns>
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(ApiResponse<TokenResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<TokenResponse>> RefreshToken([FromBody] RefreshTokenRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 调用认证服务刷新 Token
|
||||
var response = await authService.RefreshTokenAsync(request, cancellationToken);
|
||||
|
||||
// 2. 返回新的令牌
|
||||
return ApiResponse<TokenResponse>.Ok(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Storage.Abstractions;
|
||||
using TakeoutSaaS.Application.Storage.Contracts;
|
||||
@@ -19,34 +17,41 @@ namespace TakeoutSaaS.MiniApi.Controllers;
|
||||
[Route("api/mini/v{version:apiVersion}/files")]
|
||||
public sealed class FilesController(IFileStorageService fileStorageService) : BaseApiController
|
||||
{
|
||||
private readonly IFileStorageService _fileStorageService = fileStorageService;
|
||||
|
||||
/// <summary>
|
||||
/// 上传图片或文件。
|
||||
/// </summary>
|
||||
/// <param name="file">上传文件。</param>
|
||||
/// <param name="type">上传类型。</param>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>上传结果,包含访问链接等信息。</returns>
|
||||
[HttpPost("upload")]
|
||||
[RequestFormLimits(MultipartBodyLengthLimit = 30 * 1024 * 1024)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FileUploadResponse>), StatusCodes.Status400BadRequest)]
|
||||
public async Task<ApiResponse<FileUploadResponse>> Upload([FromForm] IFormFile? file, [FromForm] string? type, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验文件有效性
|
||||
if (file == null || file.Length == 0)
|
||||
{
|
||||
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "文件不能为空");
|
||||
}
|
||||
|
||||
// 2. 解析上传类型
|
||||
if (!UploadFileTypeParser.TryParse(type, out var uploadType))
|
||||
{
|
||||
return ApiResponse<FileUploadResponse>.Error(ErrorCodes.BadRequest, "上传类型不合法");
|
||||
}
|
||||
|
||||
// 3. 提取请求来源
|
||||
var origin = Request.Headers["Origin"].FirstOrDefault() ?? Request.Headers["Referer"].FirstOrDefault();
|
||||
await using var stream = file.OpenReadStream();
|
||||
|
||||
var result = await _fileStorageService.UploadAsync(
|
||||
// 4. 调用存储服务执行上传
|
||||
var result = await fileStorageService.UploadAsync(
|
||||
new UploadFileRequest(uploadType, stream, file.FileName, file.ContentType ?? string.Empty, file.Length, origin),
|
||||
cancellationToken);
|
||||
|
||||
// 5. 返回上传结果
|
||||
return ApiResponse<FileUploadResponse>.Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
@@ -23,7 +21,10 @@ public class HealthController : BaseApiController
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public ApiResponse<object> Get()
|
||||
{
|
||||
// 1. 构造健康状态
|
||||
var payload = new { status = "OK", service = "MiniApi", time = DateTime.UtcNow };
|
||||
|
||||
// 2. 返回健康响应
|
||||
return ApiResponse<object>.Ok(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.Identity.Abstractions;
|
||||
using TakeoutSaaS.Application.Identity.Contracts;
|
||||
@@ -16,31 +12,31 @@ namespace TakeoutSaaS.MiniApi.Controllers;
|
||||
/// <summary>
|
||||
/// 当前用户信息
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
///
|
||||
/// </remarks>
|
||||
/// <param name="authService"></param>
|
||||
/// <remarks>提供小程序端当前用户档案查询。</remarks>
|
||||
/// <param name="authService">小程序认证服务</param>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/mini/v{version:apiVersion}/me")]
|
||||
public sealed class MeController(IMiniAuthService authService) : BaseApiController
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户档案
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">取消标记。</param>
|
||||
/// <returns>当前用户档案信息。</returns>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(ApiResponse<CurrentUserProfile>), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<ApiResponse<CurrentUserProfile>> Get(CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 从 JWT 中解析用户标识
|
||||
var userId = User.GetUserId();
|
||||
if (userId == 0)
|
||||
{
|
||||
return ApiResponse<CurrentUserProfile>.Error(ErrorCodes.Unauthorized, "Token 缺少有效的用户标识");
|
||||
}
|
||||
|
||||
// 2. 查询用户档案并返回
|
||||
var profile = await authService.GetProfileAsync(userId, cancellationToken);
|
||||
return ApiResponse<CurrentUserProfile>.Ok(profile);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Cors.Infrastructure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
@@ -18,9 +15,11 @@ using TakeoutSaaS.Shared.Kernel.Ids;
|
||||
using TakeoutSaaS.Shared.Web.Extensions;
|
||||
using TakeoutSaaS.Shared.Web.Swagger;
|
||||
|
||||
// 1. 创建构建器与日志模板
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
const string logTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] [TraceId:{TraceId}] [SpanId:{SpanId}] [Service:{Service}] {SourceContext} {Message:lj}{NewLine}{Exception}";
|
||||
|
||||
// 2. 注册雪花 ID 生成器与 Serilog
|
||||
builder.Services.AddSingleton<IIdGenerator>(_ => new SnowflakeIdGenerator());
|
||||
builder.Host.UseSerilog((_, _, configuration) =>
|
||||
{
|
||||
@@ -36,6 +35,7 @@ builder.Host.UseSerilog((_, _, configuration) =>
|
||||
outputTemplate: logTemplate);
|
||||
});
|
||||
|
||||
// 3. 注册通用 Web 能力与 Swagger
|
||||
builder.Services.AddSharedWebCore();
|
||||
builder.Services.AddSharedSwagger(options =>
|
||||
{
|
||||
@@ -43,6 +43,8 @@ builder.Services.AddSharedSwagger(options =>
|
||||
options.Description = "小程序 API 文档";
|
||||
options.EnableAuthorization = true;
|
||||
});
|
||||
|
||||
// 4. 注册多租户与业务模块
|
||||
builder.Services.AddTenantResolution(builder.Configuration);
|
||||
builder.Services.AddStorageModule(builder.Configuration);
|
||||
builder.Services.AddStorageApplication();
|
||||
@@ -51,6 +53,8 @@ builder.Services.AddSmsApplication(builder.Configuration);
|
||||
builder.Services.AddMessagingModule(builder.Configuration);
|
||||
builder.Services.AddMessagingApplication();
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
// 5. 配置 OpenTelemetry 采集
|
||||
var otelSection = builder.Configuration.GetSection("Otel");
|
||||
var otelEndpoint = otelSection.GetValue<string>("Endpoint");
|
||||
var useConsoleExporter = otelSection.GetValue<bool?>("UseConsoleExporter") ?? builder.Environment.IsDevelopment();
|
||||
@@ -102,6 +106,7 @@ builder.Services.AddOpenTelemetry()
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 配置 CORS
|
||||
var miniOrigins = ResolveCorsOrigins(builder.Configuration, "Cors:Mini");
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
@@ -111,6 +116,7 @@ builder.Services.AddCors(options =>
|
||||
});
|
||||
});
|
||||
|
||||
// 7. 构建应用并配置中间件管道
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseCors("MiniApiCors");
|
||||
@@ -123,6 +129,7 @@ app.MapPrometheusScrapingEndpoint();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
|
||||
// 8. 解析配置中的 CORS 域名
|
||||
static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionKey)
|
||||
{
|
||||
var origins = configuration.GetSection(sectionKey).Get<string[]>();
|
||||
@@ -132,6 +139,7 @@ static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionK
|
||||
.ToArray() ?? [];
|
||||
}
|
||||
|
||||
// 9. 构建 CORS 策略
|
||||
static void ConfigureCorsPolicy(CorsPolicyBuilder policy, string[] origins)
|
||||
{
|
||||
if (origins.Length == 0)
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
@@ -23,7 +21,10 @@ public class HealthController : BaseApiController
|
||||
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
|
||||
public ApiResponse<object> Get()
|
||||
{
|
||||
// 1. 构造健康状态
|
||||
var payload = new { status = "OK", service = "UserApi", time = DateTime.UtcNow };
|
||||
|
||||
// 2. 返回健康响应
|
||||
return ApiResponse<object>.Ok(payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Cors.Infrastructure;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
@@ -12,9 +9,11 @@ using TakeoutSaaS.Shared.Kernel.Ids;
|
||||
using TakeoutSaaS.Shared.Web.Extensions;
|
||||
using TakeoutSaaS.Shared.Web.Swagger;
|
||||
|
||||
// 1. 创建构建器与日志模板
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
const string logTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] [TraceId:{TraceId}] [SpanId:{SpanId}] [Service:{Service}] {SourceContext} {Message:lj}{NewLine}{Exception}";
|
||||
|
||||
// 2. 注册雪花 ID 生成器与 Serilog
|
||||
builder.Services.AddSingleton<IIdGenerator>(_ => new SnowflakeIdGenerator());
|
||||
builder.Host.UseSerilog((_, _, configuration) =>
|
||||
{
|
||||
@@ -30,6 +29,7 @@ builder.Host.UseSerilog((_, _, configuration) =>
|
||||
outputTemplate: logTemplate);
|
||||
});
|
||||
|
||||
// 3. 注册通用 Web 能力与 Swagger
|
||||
builder.Services.AddSharedWebCore();
|
||||
builder.Services.AddSharedSwagger(options =>
|
||||
{
|
||||
@@ -37,8 +37,12 @@ builder.Services.AddSharedSwagger(options =>
|
||||
options.Description = "C 端用户 API 文档";
|
||||
options.EnableAuthorization = true;
|
||||
});
|
||||
|
||||
// 4. 注册多租户与健康检查
|
||||
builder.Services.AddTenantResolution(builder.Configuration);
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
// 5. 配置 OpenTelemetry 采集
|
||||
var otelSection = builder.Configuration.GetSection("Otel");
|
||||
var otelEndpoint = otelSection.GetValue<string>("Endpoint");
|
||||
var useConsoleExporter = otelSection.GetValue<bool?>("UseConsoleExporter") ?? builder.Environment.IsDevelopment();
|
||||
@@ -90,6 +94,7 @@ builder.Services.AddOpenTelemetry()
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 配置 CORS
|
||||
var userOrigins = ResolveCorsOrigins(builder.Configuration, "Cors:User");
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
@@ -99,6 +104,7 @@ builder.Services.AddCors(options =>
|
||||
});
|
||||
});
|
||||
|
||||
// 7. 构建应用并配置中间件管道
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseCors("UserApiCors");
|
||||
@@ -111,6 +117,7 @@ app.MapPrometheusScrapingEndpoint();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
|
||||
// 8. 解析配置中的 CORS 域名
|
||||
static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionKey)
|
||||
{
|
||||
var origins = configuration.GetSection(sectionKey).Get<string[]>();
|
||||
@@ -120,6 +127,7 @@ static string[] ResolveCorsOrigins(IConfiguration configuration, string sectionK
|
||||
.ToArray() ?? [];
|
||||
}
|
||||
|
||||
// 9. 构建 CORS 策略
|
||||
static void ConfigureCorsPolicy(CorsPolicyBuilder policy, string[] origins)
|
||||
{
|
||||
if (origins.Length == 0)
|
||||
|
||||
@@ -13,12 +13,10 @@ namespace TakeoutSaaS.Application.App.Deliveries.Handlers;
|
||||
public sealed class CreateDeliveryOrderCommandHandler(IDeliveryRepository deliveryRepository, ILogger<CreateDeliveryOrderCommandHandler> logger)
|
||||
: IRequestHandler<CreateDeliveryOrderCommand, DeliveryOrderDto>
|
||||
{
|
||||
private readonly IDeliveryRepository _deliveryRepository = deliveryRepository;
|
||||
private readonly ILogger<CreateDeliveryOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DeliveryOrderDto> Handle(CreateDeliveryOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 构建配送单实体
|
||||
var deliveryOrder = new DeliveryOrder
|
||||
{
|
||||
OrderId = request.OrderId,
|
||||
@@ -34,10 +32,14 @@ public sealed class CreateDeliveryOrderCommandHandler(IDeliveryRepository delive
|
||||
FailureReason = request.FailureReason?.Trim()
|
||||
};
|
||||
|
||||
await _deliveryRepository.AddDeliveryOrderAsync(deliveryOrder, cancellationToken);
|
||||
await _deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("创建配送单 {DeliveryOrderId} 对应订单 {OrderId}", deliveryOrder.Id, deliveryOrder.OrderId);
|
||||
// 2. 持久化配送单
|
||||
await deliveryRepository.AddDeliveryOrderAsync(deliveryOrder, cancellationToken);
|
||||
await deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 3. 记录日志
|
||||
logger.LogInformation("创建配送单 {DeliveryOrderId} 对应订单 {OrderId}", deliveryOrder.Id, deliveryOrder.OrderId);
|
||||
|
||||
// 4. 映射 DTO 返回
|
||||
return MapToDto(deliveryOrder, []);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,23 +15,23 @@ public sealed class DeleteDeliveryOrderCommandHandler(
|
||||
ILogger<DeleteDeliveryOrderCommandHandler> logger)
|
||||
: IRequestHandler<DeleteDeliveryOrderCommand, bool>
|
||||
{
|
||||
private readonly IDeliveryRepository _deliveryRepository = deliveryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<DeleteDeliveryOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> Handle(DeleteDeliveryOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
// 1. 获取租户并定位配送单
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _deliveryRepository.DeleteDeliveryOrderAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
await _deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("删除配送单 {DeliveryOrderId}", request.DeliveryOrderId);
|
||||
// 2. 删除并保存
|
||||
await deliveryRepository.DeleteDeliveryOrderAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
await deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 3. 记录删除日志
|
||||
logger.LogInformation("删除配送单 {DeliveryOrderId}", request.DeliveryOrderId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -15,20 +15,23 @@ public sealed class GetDeliveryOrderByIdQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetDeliveryOrderByIdQuery, DeliveryOrderDto?>
|
||||
{
|
||||
private readonly IDeliveryRepository _deliveryRepository = deliveryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DeliveryOrderDto?> Handle(GetDeliveryOrderByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var order = await _deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
// 1. 读取当前租户标识
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
|
||||
// 2. 查询配送单主体
|
||||
var order = await deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
if (order == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var events = await _deliveryRepository.GetEventsAsync(order.Id, tenantId, cancellationToken);
|
||||
// 3. 查询配送事件明细
|
||||
var events = await deliveryRepository.GetEventsAsync(order.Id, tenantId, cancellationToken);
|
||||
|
||||
// 4. 映射为 DTO 返回
|
||||
return MapToDto(order, events);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,21 +15,25 @@ public sealed class SearchDeliveryOrdersQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SearchDeliveryOrdersQuery, PagedResult<DeliveryOrderDto>>
|
||||
{
|
||||
private readonly IDeliveryRepository _deliveryRepository = deliveryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<DeliveryOrderDto>> Handle(SearchDeliveryOrdersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var orders = await _deliveryRepository.SearchAsync(tenantId, request.Status, request.OrderId, cancellationToken);
|
||||
// 1. 获取当前租户标识
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
|
||||
// 2. 查询配送单列表(租户隔离)
|
||||
var orders = await deliveryRepository.SearchAsync(tenantId, request.Status, request.OrderId, cancellationToken);
|
||||
|
||||
// 3. 本地排序
|
||||
var sorted = ApplySorting(orders, request.SortBy, request.SortDescending);
|
||||
|
||||
// 4. 本地分页
|
||||
var paged = sorted
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
// 5. 映射 DTO
|
||||
var items = paged.Select(order => new DeliveryOrderDto
|
||||
{
|
||||
Id = order.Id,
|
||||
@@ -48,6 +52,7 @@ public sealed class SearchDeliveryOrdersQueryHandler(
|
||||
CreatedAt = order.CreatedAt
|
||||
}).ToList();
|
||||
|
||||
// 6. 返回分页结果
|
||||
return new PagedResult<DeliveryOrderDto>(items, request.Page, request.PageSize, orders.Count);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,20 +17,20 @@ public sealed class UpdateDeliveryOrderCommandHandler(
|
||||
ILogger<UpdateDeliveryOrderCommandHandler> logger)
|
||||
: IRequestHandler<UpdateDeliveryOrderCommand, DeliveryOrderDto?>
|
||||
{
|
||||
private readonly IDeliveryRepository _deliveryRepository = deliveryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<UpdateDeliveryOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DeliveryOrderDto?> Handle(UpdateDeliveryOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
// 1. 获取当前租户标识
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
|
||||
// 2. 查询目标配送单
|
||||
var existing = await deliveryRepository.FindByIdAsync(request.DeliveryOrderId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 3. 更新字段
|
||||
existing.OrderId = request.OrderId;
|
||||
existing.Provider = request.Provider;
|
||||
existing.ProviderOrderId = request.ProviderOrderId?.Trim();
|
||||
@@ -43,11 +43,15 @@ public sealed class UpdateDeliveryOrderCommandHandler(
|
||||
existing.DeliveredAt = request.DeliveredAt;
|
||||
existing.FailureReason = request.FailureReason?.Trim();
|
||||
|
||||
await _deliveryRepository.UpdateDeliveryOrderAsync(existing, cancellationToken);
|
||||
await _deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("更新配送单 {DeliveryOrderId}", existing.Id);
|
||||
// 4. 持久化变更
|
||||
await deliveryRepository.UpdateDeliveryOrderAsync(existing, cancellationToken);
|
||||
await deliveryRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var events = await _deliveryRepository.GetEventsAsync(existing.Id, tenantId, cancellationToken);
|
||||
// 5. 记录更新日志
|
||||
logger.LogInformation("更新配送单 {DeliveryOrderId}", existing.Id);
|
||||
|
||||
// 6. 查询事件并返回映射结果
|
||||
var events = await deliveryRepository.GetEventsAsync(existing.Id, tenantId, cancellationToken);
|
||||
return MapToDto(existing, events);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Reflection;
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Reflection;
|
||||
using TakeoutSaaS.Application.App.Common.Behaviors;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Extensions;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Domain.Merchants.Enums;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using MediatR;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Domain.Merchants.Enums;
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -22,20 +22,17 @@ public sealed class AddMerchantDocumentCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<AddMerchantDocumentCommand, MerchantDocumentDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
public async Task<MerchantDocumentDto> Handle(AddMerchantDocumentCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 1. 获取租户并查询商户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
// 2. 构建证照记录
|
||||
var document = new MerchantDocument
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
MerchantId = merchant.Id,
|
||||
DocumentType = request.DocumentType,
|
||||
Status = MerchantDocumentStatus.Pending,
|
||||
@@ -45,8 +42,9 @@ public sealed class AddMerchantDocumentCommandHandler(
|
||||
ExpiresAt = request.ExpiresAt
|
||||
};
|
||||
|
||||
await _merchantRepository.AddDocumentAsync(document, cancellationToken);
|
||||
await _merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
// 3. 持久化与审计
|
||||
await merchantRepository.AddDocumentAsync(document, cancellationToken);
|
||||
await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
{
|
||||
TenantId = tenantId,
|
||||
MerchantId = merchant.Id,
|
||||
@@ -57,20 +55,21 @@ public sealed class AddMerchantDocumentCommandHandler(
|
||||
OperatorName = ResolveOperatorName()
|
||||
}, cancellationToken);
|
||||
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 4. 返回 DTO
|
||||
return MerchantMapping.ToDto(document);
|
||||
}
|
||||
|
||||
private long? ResolveOperatorId()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? null : id;
|
||||
}
|
||||
|
||||
private string ResolveOperatorName()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? "system" : $"user:{id}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
@@ -18,22 +17,23 @@ public sealed class CreateMerchantCategoryCommandHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<CreateMerchantCategoryCommand, MerchantCategoryDto>
|
||||
{
|
||||
private readonly IMerchantCategoryRepository _categoryRepository = categoryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<MerchantCategoryDto> Handle(CreateMerchantCategoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
// 1. 获取租户上下文
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var normalizedName = request.Name.Trim();
|
||||
|
||||
if (await _categoryRepository.ExistsAsync(normalizedName, tenantId, cancellationToken))
|
||||
// 2. 检查重名
|
||||
if (await categoryRepository.ExistsAsync(normalizedName, tenantId, cancellationToken))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.Conflict, $"类目“{normalizedName}”已存在");
|
||||
}
|
||||
|
||||
var categories = await _categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
// 3. 计算排序
|
||||
var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
var targetOrder = request.DisplayOrder ?? (categories.Count == 0 ? 1 : categories.Max(x => x.DisplayOrder) + 1);
|
||||
|
||||
// 4. 构建实体
|
||||
var entity = new MerchantCategory
|
||||
{
|
||||
Name = normalizedName,
|
||||
@@ -41,8 +41,9 @@ public sealed class CreateMerchantCategoryCommandHandler(
|
||||
IsActive = request.IsActive
|
||||
};
|
||||
|
||||
await _categoryRepository.AddAsync(entity, cancellationToken);
|
||||
await _categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
// 5. 持久化并返回
|
||||
await categoryRepository.AddAsync(entity, cancellationToken);
|
||||
await categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return MerchantMapping.ToDto(entity);
|
||||
}
|
||||
|
||||
@@ -13,12 +13,10 @@ namespace TakeoutSaaS.Application.App.Merchants.Handlers;
|
||||
public sealed class CreateMerchantCommandHandler(IMerchantRepository merchantRepository, ILogger<CreateMerchantCommandHandler> logger)
|
||||
: IRequestHandler<CreateMerchantCommand, MerchantDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ILogger<CreateMerchantCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MerchantDto> Handle(CreateMerchantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 构建商户实体
|
||||
var merchant = new Merchant
|
||||
{
|
||||
BrandName = request.BrandName.Trim(),
|
||||
@@ -31,10 +29,12 @@ public sealed class CreateMerchantCommandHandler(IMerchantRepository merchantRep
|
||||
JoinedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _merchantRepository.AddMerchantAsync(merchant, cancellationToken);
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
// 2. 持久化
|
||||
await merchantRepository.AddMerchantAsync(merchant, cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("创建商户 {MerchantId} - {BrandName}", merchant.Id, merchant.BrandName);
|
||||
// 3. 记录日志
|
||||
logger.LogInformation("创建商户 {MerchantId} - {BrandName}", merchant.Id, merchant.BrandName);
|
||||
return MapToDto(merchant);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,25 +22,23 @@ public sealed class CreateMerchantContractCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<CreateMerchantContractCommand, MerchantContractDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
public async Task<MerchantContractDto> Handle(CreateMerchantContractCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验时间
|
||||
if (request.EndDate <= request.StartDate)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "合同结束时间必须晚于开始时间");
|
||||
}
|
||||
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 2. 查询商户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
// 3. 构建合同
|
||||
var contract = new MerchantContract
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
MerchantId = merchant.Id,
|
||||
ContractNumber = request.ContractNumber.Trim(),
|
||||
StartDate = request.StartDate,
|
||||
@@ -48,8 +46,9 @@ public sealed class CreateMerchantContractCommandHandler(
|
||||
FileUrl = request.FileUrl.Trim()
|
||||
};
|
||||
|
||||
await _merchantRepository.AddContractAsync(contract, cancellationToken);
|
||||
await _merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
// 4. 持久化与审计
|
||||
await merchantRepository.AddContractAsync(contract, cancellationToken);
|
||||
await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
{
|
||||
TenantId = tenantId,
|
||||
MerchantId = merchant.Id,
|
||||
@@ -60,19 +59,21 @@ public sealed class CreateMerchantContractCommandHandler(
|
||||
OperatorName = ResolveOperatorName()
|
||||
}, cancellationToken);
|
||||
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 5. 返回 DTO
|
||||
return MerchantMapping.ToDto(contract);
|
||||
}
|
||||
|
||||
private long? ResolveOperatorId()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? null : id;
|
||||
}
|
||||
|
||||
private string ResolveOperatorName()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? "system" : $"user:{id}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,21 +13,20 @@ public sealed class DeleteMerchantCategoryCommandHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<DeleteMerchantCategoryCommand, bool>
|
||||
{
|
||||
private readonly IMerchantCategoryRepository _categoryRepository = categoryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<bool> Handle(DeleteMerchantCategoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _categoryRepository.FindByIdAsync(request.CategoryId, tenantId, cancellationToken);
|
||||
// 1. 获取租户上下文
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await categoryRepository.FindByIdAsync(request.CategoryId, tenantId, cancellationToken);
|
||||
|
||||
if (existing == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _categoryRepository.RemoveAsync(existing, cancellationToken);
|
||||
await _categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
// 2. 删除并保存
|
||||
await categoryRepository.RemoveAsync(existing, cancellationToken);
|
||||
await categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,25 +15,21 @@ public sealed class DeleteMerchantCommandHandler(
|
||||
ILogger<DeleteMerchantCommandHandler> logger)
|
||||
: IRequestHandler<DeleteMerchantCommand, bool>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<DeleteMerchantCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> Handle(DeleteMerchantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验存在性
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. 删除
|
||||
await _merchantRepository.DeleteMerchantAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("删除商户 {MerchantId}", request.MerchantId);
|
||||
await merchantRepository.DeleteMerchantAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
logger.LogInformation("删除商户 {MerchantId}", request.MerchantId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
@@ -16,20 +15,21 @@ public sealed class GetMerchantAuditLogsQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantAuditLogsQuery, PagedResult<MerchantAuditLogDto>>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<PagedResult<MerchantAuditLogDto>> Handle(GetMerchantAuditLogsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var logs = await _merchantRepository.GetAuditLogsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
// 1. 获取租户上下文并查询日志
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var logs = await merchantRepository.GetAuditLogsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
var total = logs.Count;
|
||||
|
||||
// 2. 分页映射
|
||||
var paged = logs
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(MerchantMapping.ToDto)
|
||||
.ToList();
|
||||
|
||||
// 3. 返回结果
|
||||
return new PagedResult<MerchantAuditLogDto>(paged, request.Page, request.PageSize, total);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,19 +12,18 @@ namespace TakeoutSaaS.Application.App.Merchants.Handlers;
|
||||
public sealed class GetMerchantByIdQueryHandler(IMerchantRepository merchantRepository, ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantByIdQuery, MerchantDto?>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MerchantDto?> Handle(GetMerchantByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
// 1. 获取租户上下文
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
if (merchant == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 返回 DTO
|
||||
return new MerchantDto
|
||||
{
|
||||
Id = merchant.Id,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
using TakeoutSaaS.Domain.Merchants.Repositories;
|
||||
@@ -15,14 +13,13 @@ public sealed class GetMerchantCategoriesQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantCategoriesQuery, IReadOnlyList<string>>
|
||||
{
|
||||
private readonly IMerchantCategoryRepository _categoryRepository = categoryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<IReadOnlyList<string>> Handle(GetMerchantCategoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var categories = await _categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
// 1. 获取租户上下文并读取类目
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
|
||||
// 2. 过滤启用类目并去重
|
||||
return categories
|
||||
.Where(x => x.IsActive)
|
||||
.Select(x => x.Name.Trim())
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
@@ -17,16 +16,15 @@ public sealed class GetMerchantContractsQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantContractsQuery, IReadOnlyList<MerchantContractDto>>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<IReadOnlyList<MerchantContractDto>> Handle(GetMerchantContractsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
_ = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 1. 获取租户上下文并校验商户存在
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
_ = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
var contracts = await _merchantRepository.GetContractsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
// 2. 查询合同列表
|
||||
var contracts = await merchantRepository.GetContractsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
return MerchantMapping.ToContractDtos(contracts);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,18 +16,18 @@ public sealed class GetMerchantDetailQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantDetailQuery, MerchantDetailDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<MerchantDetailDto> Handle(GetMerchantDetailQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 1. 获取租户上下文并查询商户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
var documents = await _merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
var contracts = await _merchantRepository.GetContractsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
// 2. 查询证照与合同
|
||||
var documents = await merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
var contracts = await merchantRepository.GetContractsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
|
||||
// 3. 返回明细 DTO
|
||||
return new MerchantDetailDto
|
||||
{
|
||||
Merchant = MerchantMapping.ToDto(merchant),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
@@ -17,16 +16,15 @@ public sealed class GetMerchantDocumentsQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetMerchantDocumentsQuery, IReadOnlyList<MerchantDocumentDto>>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<IReadOnlyList<MerchantDocumentDto>> Handle(GetMerchantDocumentsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
_ = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 1. 获取租户上下文并校验商户存在
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
_ = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
var documents = await _merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
// 2. 查询证照列表
|
||||
var documents = await merchantRepository.GetDocumentsAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
return MerchantMapping.ToDocumentDtos(documents);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
@@ -15,13 +14,13 @@ public sealed class ListMerchantCategoriesQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ListMerchantCategoriesQuery, IReadOnlyList<MerchantCategoryDto>>
|
||||
{
|
||||
private readonly IMerchantCategoryRepository _categoryRepository = categoryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<IReadOnlyList<MerchantCategoryDto>> Handle(ListMerchantCategoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var categories = await _categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
// 1. 获取租户上下文
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
|
||||
// 2. 映射 DTO
|
||||
return MerchantMapping.ToCategoryDtos(categories);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
using TakeoutSaaS.Domain.Merchants.Repositories;
|
||||
@@ -16,15 +15,14 @@ public sealed class ReorderMerchantCategoriesCommandHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ReorderMerchantCategoriesCommand, bool>
|
||||
{
|
||||
private readonly IMerchantCategoryRepository _categoryRepository = categoryRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
public async Task<bool> Handle(ReorderMerchantCategoriesCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var categories = await _categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
// 1. 获取租户并查询类目
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var categories = await categoryRepository.ListAsync(tenantId, cancellationToken);
|
||||
var map = categories.ToDictionary(x => x.Id);
|
||||
|
||||
// 2. 更新排序
|
||||
foreach (var item in request.Items)
|
||||
{
|
||||
if (!map.TryGetValue(item.CategoryId, out var category))
|
||||
@@ -35,8 +33,9 @@ public sealed class ReorderMerchantCategoriesCommandHandler(
|
||||
category.DisplayOrder = item.DisplayOrder;
|
||||
}
|
||||
|
||||
await _categoryRepository.UpdateRangeAsync(map.Values, cancellationToken);
|
||||
await _categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
// 3. 持久化
|
||||
await categoryRepository.UpdateRangeAsync(map.Values, cancellationToken);
|
||||
await categoryRepository.SaveChangesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,21 +20,20 @@ public sealed class ReviewMerchantCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<ReviewMerchantCommand, MerchantDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
public async Task<MerchantDto> Handle(ReviewMerchantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
// 1. 读取商户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchant = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "商户不存在");
|
||||
|
||||
// 2. 已审核通过则直接返回
|
||||
if (request.Approve && merchant.Status == MerchantStatus.Approved)
|
||||
{
|
||||
return MerchantMapping.ToDto(merchant);
|
||||
}
|
||||
|
||||
// 3. 更新审核状态
|
||||
var previousStatus = merchant.Status;
|
||||
merchant.Status = request.Approve ? MerchantStatus.Approved : MerchantStatus.Rejected;
|
||||
merchant.ReviewRemarks = request.Remarks;
|
||||
@@ -44,8 +43,9 @@ public sealed class ReviewMerchantCommandHandler(
|
||||
merchant.JoinedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
await _merchantRepository.UpdateMerchantAsync(merchant, cancellationToken);
|
||||
await _merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
// 4. 持久化与审计
|
||||
await merchantRepository.UpdateMerchantAsync(merchant, cancellationToken);
|
||||
await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
{
|
||||
TenantId = tenantId,
|
||||
MerchantId = merchant.Id,
|
||||
@@ -55,20 +55,21 @@ public sealed class ReviewMerchantCommandHandler(
|
||||
OperatorId = ResolveOperatorId(),
|
||||
OperatorName = ResolveOperatorName()
|
||||
}, cancellationToken);
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 5. 返回 DTO
|
||||
return MerchantMapping.ToDto(merchant);
|
||||
}
|
||||
|
||||
private long? ResolveOperatorId()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? null : id;
|
||||
}
|
||||
|
||||
private string ResolveOperatorName()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? "system" : $"user:{id}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Commands;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Domain.Merchants.Enums;
|
||||
using TakeoutSaaS.Domain.Merchants.Entities;
|
||||
using TakeoutSaaS.Domain.Merchants.Enums;
|
||||
using TakeoutSaaS.Domain.Merchants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
@@ -20,27 +20,27 @@ public sealed class ReviewMerchantDocumentCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<ReviewMerchantDocumentCommand, MerchantDocumentDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
public async Task<MerchantDocumentDto> Handle(ReviewMerchantDocumentCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var document = await _merchantRepository.FindDocumentByIdAsync(request.MerchantId, tenantId, request.DocumentId, cancellationToken)
|
||||
// 1. 读取证照
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var document = await merchantRepository.FindDocumentByIdAsync(request.MerchantId, tenantId, request.DocumentId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "证照不存在");
|
||||
|
||||
// 2. 若状态无变化且备注相同,直接返回
|
||||
var targetStatus = request.Approve ? MerchantDocumentStatus.Approved : MerchantDocumentStatus.Rejected;
|
||||
if (document.Status == targetStatus && document.Remarks == request.Remarks)
|
||||
{
|
||||
return MerchantMapping.ToDto(document);
|
||||
}
|
||||
|
||||
// 3. 更新状态
|
||||
document.Status = targetStatus;
|
||||
document.Remarks = request.Remarks;
|
||||
|
||||
await _merchantRepository.UpdateDocumentAsync(document, cancellationToken);
|
||||
await _merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
// 4. 持久化与审计
|
||||
await merchantRepository.UpdateDocumentAsync(document, cancellationToken);
|
||||
await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
{
|
||||
TenantId = tenantId,
|
||||
MerchantId = document.MerchantId,
|
||||
@@ -50,20 +50,21 @@ public sealed class ReviewMerchantDocumentCommandHandler(
|
||||
OperatorId = ResolveOperatorId(),
|
||||
OperatorName = ResolveOperatorName()
|
||||
}, cancellationToken);
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 5. 返回 DTO
|
||||
return MerchantMapping.ToDto(document);
|
||||
}
|
||||
|
||||
private long? ResolveOperatorId()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? null : id;
|
||||
}
|
||||
|
||||
private string ResolveOperatorName()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? "system" : $"user:{id}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,21 +15,21 @@ public sealed class SearchMerchantsQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SearchMerchantsQuery, PagedResult<MerchantDto>>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<MerchantDto>> Handle(SearchMerchantsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var merchants = await _merchantRepository.SearchAsync(tenantId, request.Status, cancellationToken);
|
||||
// 1. 获取租户并查询商户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var merchants = await merchantRepository.SearchAsync(tenantId, request.Status, cancellationToken);
|
||||
|
||||
// 2. 排序与分页
|
||||
var sorted = ApplySorting(merchants, request.SortBy, request.SortDescending);
|
||||
var paged = sorted
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
// 3. 映射 DTO
|
||||
var items = paged.Select(merchant => new MerchantDto
|
||||
{
|
||||
Id = merchant.Id,
|
||||
@@ -45,6 +45,7 @@ public sealed class SearchMerchantsQueryHandler(
|
||||
CreatedAt = merchant.CreatedAt
|
||||
}).ToList();
|
||||
|
||||
// 4. 返回分页结果
|
||||
return new PagedResult<MerchantDto>(items, request.Page, request.PageSize, merchants.Count);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,16 +16,12 @@ public sealed class UpdateMerchantCommandHandler(
|
||||
ILogger<UpdateMerchantCommandHandler> logger)
|
||||
: IRequestHandler<UpdateMerchantCommand, MerchantDto?>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<UpdateMerchantCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<MerchantDto?> Handle(UpdateMerchantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取现有商户
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await merchantRepository.FindByIdAsync(request.MerchantId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return null;
|
||||
@@ -41,9 +37,9 @@ public sealed class UpdateMerchantCommandHandler(
|
||||
existing.Status = request.Status;
|
||||
|
||||
// 3. 持久化
|
||||
await _merchantRepository.UpdateMerchantAsync(existing, cancellationToken);
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("更新商户 {MerchantId} - {BrandName}", existing.Id, existing.BrandName);
|
||||
await merchantRepository.UpdateMerchantAsync(existing, cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
logger.LogInformation("更新商户 {MerchantId} - {BrandName}", existing.Id, existing.BrandName);
|
||||
|
||||
// 4. 返回 DTO
|
||||
return MapToDto(existing);
|
||||
|
||||
@@ -20,16 +20,14 @@ public sealed class UpdateMerchantContractStatusCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<UpdateMerchantContractStatusCommand, MerchantContractDto>
|
||||
{
|
||||
private readonly IMerchantRepository _merchantRepository = merchantRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
public async Task<MerchantContractDto> Handle(UpdateMerchantContractStatusCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var contract = await _merchantRepository.FindContractByIdAsync(request.MerchantId, tenantId, request.ContractId, cancellationToken)
|
||||
// 1. 查询合同
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var contract = await merchantRepository.FindContractByIdAsync(request.MerchantId, tenantId, request.ContractId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "合同不存在");
|
||||
|
||||
// 2. 更新状态
|
||||
if (request.Status == ContractStatus.Active)
|
||||
{
|
||||
contract.Status = ContractStatus.Active;
|
||||
@@ -46,8 +44,9 @@ public sealed class UpdateMerchantContractStatusCommandHandler(
|
||||
contract.Status = request.Status;
|
||||
}
|
||||
|
||||
await _merchantRepository.UpdateContractAsync(contract, cancellationToken);
|
||||
await _merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
// 3. 持久化与审计
|
||||
await merchantRepository.UpdateContractAsync(contract, cancellationToken);
|
||||
await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
|
||||
{
|
||||
TenantId = tenantId,
|
||||
MerchantId = contract.MerchantId,
|
||||
@@ -58,19 +57,21 @@ public sealed class UpdateMerchantContractStatusCommandHandler(
|
||||
OperatorName = ResolveOperatorName()
|
||||
}, cancellationToken);
|
||||
|
||||
await _merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
await merchantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 4. 返回 DTO
|
||||
return MerchantMapping.ToDto(contract);
|
||||
}
|
||||
|
||||
private long? ResolveOperatorId()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? null : id;
|
||||
}
|
||||
|
||||
private string ResolveOperatorName()
|
||||
{
|
||||
var id = _currentUserAccessor.UserId;
|
||||
var id = currentUserAccessor.UserId;
|
||||
return id == 0 ? "system" : $"user:{id}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
using TakeoutSaaS.Domain.Merchants.Entities;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Merchants.Queries;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Merchants.Dto;
|
||||
|
||||
|
||||
@@ -17,17 +17,13 @@ public sealed class CreateOrderCommandHandler(
|
||||
ILogger<CreateOrderCommandHandler> logger)
|
||||
: IRequestHandler<CreateOrderCommand, OrderDto>
|
||||
{
|
||||
private readonly IOrderRepository _orderRepository = orderRepository;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
private readonly ILogger<CreateOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<OrderDto> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 构建订单
|
||||
var order = new Order
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
OrderNo = request.OrderNo.Trim(),
|
||||
StoreId = request.StoreId,
|
||||
Channel = request.Channel,
|
||||
@@ -77,15 +73,18 @@ public sealed class CreateOrderCommandHandler(
|
||||
}
|
||||
|
||||
// 4. 持久化
|
||||
await _orderRepository.AddOrderAsync(order, cancellationToken);
|
||||
await orderRepository.AddOrderAsync(order, cancellationToken);
|
||||
if (items.Count > 0)
|
||||
{
|
||||
await _orderRepository.AddItemsAsync(items, cancellationToken);
|
||||
await orderRepository.AddItemsAsync(items, cancellationToken);
|
||||
}
|
||||
await _orderRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("创建订单 {OrderNo} ({OrderId})", order.OrderNo, order.Id);
|
||||
|
||||
// 5. 返回 DTO
|
||||
await orderRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 5. 记录日志
|
||||
logger.LogInformation("创建订单 {OrderNo} ({OrderId})", order.OrderNo, order.Id);
|
||||
|
||||
// 6. 返回 DTO
|
||||
return MapToDto(order, items, [], []);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,26 +15,25 @@ public sealed class DeleteOrderCommandHandler(
|
||||
ILogger<DeleteOrderCommandHandler> logger)
|
||||
: IRequestHandler<DeleteOrderCommand, bool>
|
||||
{
|
||||
private readonly IOrderRepository _orderRepository = orderRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<DeleteOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验存在性
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. 删除
|
||||
await _orderRepository.DeleteOrderAsync(request.OrderId, tenantId, cancellationToken);
|
||||
await _orderRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("删除订单 {OrderId}", request.OrderId);
|
||||
await orderRepository.DeleteOrderAsync(request.OrderId, tenantId, cancellationToken);
|
||||
await orderRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 3. 记录日志
|
||||
logger.LogInformation("删除订单 {OrderId}", request.OrderId);
|
||||
|
||||
// 4. 返回执行结果
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,23 +15,25 @@ public sealed class GetOrderByIdQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetOrderByIdQuery, OrderDto?>
|
||||
{
|
||||
private readonly IOrderRepository _orderRepository = orderRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<OrderDto?> Handle(GetOrderByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var order = await _orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
// 1. 获取当前租户
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
|
||||
// 2. 查询订单主体
|
||||
var order = await orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
if (order == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var items = await _orderRepository.GetItemsAsync(order.Id, tenantId, cancellationToken);
|
||||
var histories = await _orderRepository.GetStatusHistoryAsync(order.Id, tenantId, cancellationToken);
|
||||
var refunds = await _orderRepository.GetRefundsAsync(order.Id, tenantId, cancellationToken);
|
||||
// 3. 查询关联明细
|
||||
var items = await orderRepository.GetItemsAsync(order.Id, tenantId, cancellationToken);
|
||||
var histories = await orderRepository.GetStatusHistoryAsync(order.Id, tenantId, cancellationToken);
|
||||
var refunds = await orderRepository.GetRefundsAsync(order.Id, tenantId, cancellationToken);
|
||||
|
||||
// 4. 映射并返回
|
||||
return MapToDto(order, items, histories, refunds);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,20 +15,20 @@ public sealed class SearchOrdersQueryHandler(
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SearchOrdersQuery, PagedResult<OrderDto>>
|
||||
{
|
||||
private readonly IOrderRepository _orderRepository = orderRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<OrderDto>> Handle(SearchOrdersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var orders = await _orderRepository.SearchAsync(tenantId, request.Status, request.PaymentStatus, cancellationToken);
|
||||
// 1. 获取当前租户并查询订单
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var orders = await orderRepository.SearchAsync(tenantId, request.Status, request.PaymentStatus, cancellationToken);
|
||||
|
||||
// 2. 可选过滤:门店
|
||||
if (request.StoreId.HasValue)
|
||||
{
|
||||
orders = orders.Where(x => x.StoreId == request.StoreId.Value).ToList();
|
||||
}
|
||||
|
||||
// 3. 可选过滤:订单号模糊
|
||||
if (!string.IsNullOrWhiteSpace(request.OrderNo))
|
||||
{
|
||||
var orderNo = request.OrderNo.Trim();
|
||||
@@ -37,12 +37,14 @@ public sealed class SearchOrdersQueryHandler(
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// 4. 排序与分页
|
||||
var sorted = ApplySorting(orders, request.SortBy, request.SortDescending);
|
||||
var paged = sorted
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
// 5. 映射 DTO
|
||||
var items = paged.Select(order => new OrderDto
|
||||
{
|
||||
Id = order.Id,
|
||||
@@ -70,6 +72,7 @@ public sealed class SearchOrdersQueryHandler(
|
||||
CreatedAt = order.CreatedAt
|
||||
}).ToList();
|
||||
|
||||
// 6. 返回分页结果
|
||||
return new PagedResult<OrderDto>(items, request.Page, request.PageSize, orders.Count);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,16 +17,12 @@ public sealed class UpdateOrderCommandHandler(
|
||||
ILogger<UpdateOrderCommandHandler> logger)
|
||||
: IRequestHandler<UpdateOrderCommand, OrderDto?>
|
||||
{
|
||||
private readonly IOrderRepository _orderRepository = orderRepository;
|
||||
private readonly ITenantProvider _tenantProvider = tenantProvider;
|
||||
private readonly ILogger<UpdateOrderCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<OrderDto?> Handle(UpdateOrderCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取订单
|
||||
var tenantId = _tenantProvider.GetCurrentTenantId();
|
||||
var existing = await _orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var existing = await orderRepository.FindByIdAsync(request.OrderId, tenantId, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
return null;
|
||||
@@ -55,14 +51,16 @@ public sealed class UpdateOrderCommandHandler(
|
||||
existing.Remark = request.Remark?.Trim();
|
||||
|
||||
// 3. 持久化
|
||||
await _orderRepository.UpdateOrderAsync(existing, cancellationToken);
|
||||
await _orderRepository.SaveChangesAsync(cancellationToken);
|
||||
_logger.LogInformation("更新订单 {OrderNo} ({OrderId})", existing.OrderNo, existing.Id);
|
||||
await orderRepository.UpdateOrderAsync(existing, cancellationToken);
|
||||
await orderRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 4. 读取关联数据并返回
|
||||
var items = await _orderRepository.GetItemsAsync(existing.Id, tenantId, cancellationToken);
|
||||
var histories = await _orderRepository.GetStatusHistoryAsync(existing.Id, tenantId, cancellationToken);
|
||||
var refunds = await _orderRepository.GetRefundsAsync(existing.Id, tenantId, cancellationToken);
|
||||
// 4. 记录更新日志
|
||||
logger.LogInformation("更新订单 {OrderNo} ({OrderId})", existing.OrderNo, existing.Id);
|
||||
|
||||
// 5. 读取关联数据并返回
|
||||
var items = await orderRepository.GetItemsAsync(existing.Id, tenantId, cancellationToken);
|
||||
var histories = await orderRepository.GetStatusHistoryAsync(existing.Id, tenantId, cancellationToken);
|
||||
var refunds = await orderRepository.GetRefundsAsync(existing.Id, tenantId, cancellationToken);
|
||||
|
||||
return MapToDto(existing, items, histories, refunds);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Payments.Dto;
|
||||
using TakeoutSaaS.Application.App.Payments.Queries;
|
||||
using TakeoutSaaS.Domain.Payments.Entities;
|
||||
using TakeoutSaaS.Domain.Payments.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
@@ -18,20 +18,19 @@ public sealed class ChangeTenantSubscriptionPlanCommandHandler(
|
||||
IIdGenerator idGenerator)
|
||||
: IRequestHandler<ChangeTenantSubscriptionPlanCommand, TenantSubscriptionDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantSubscriptionDto> Handle(ChangeTenantSubscriptionPlanCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
_ = await _tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
// 1. 校验租户与订阅存在性
|
||||
_ = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
|
||||
|
||||
var subscription = await _tenantRepository.FindSubscriptionByIdAsync(request.TenantId, request.TenantSubscriptionId, cancellationToken)
|
||||
var subscription = await tenantRepository.FindSubscriptionByIdAsync(request.TenantId, request.TenantSubscriptionId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "订阅不存在");
|
||||
|
||||
var previousPackage = subscription.TenantPackageId;
|
||||
|
||||
// 2. 根据立即生效或排期设置目标套餐
|
||||
if (request.Immediate)
|
||||
{
|
||||
subscription.TenantPackageId = request.TargetPackageId;
|
||||
@@ -42,10 +41,11 @@ public sealed class ChangeTenantSubscriptionPlanCommandHandler(
|
||||
subscription.ScheduledPackageId = request.TargetPackageId;
|
||||
}
|
||||
|
||||
await _tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
|
||||
await _tenantRepository.AddSubscriptionHistoryAsync(new TenantSubscriptionHistory
|
||||
// 3. 更新订阅并记录变更历史
|
||||
await tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
|
||||
await tenantRepository.AddSubscriptionHistoryAsync(new TenantSubscriptionHistory
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
TenantId = subscription.TenantId,
|
||||
TenantSubscriptionId = subscription.Id,
|
||||
FromPackageId = previousPackage,
|
||||
@@ -56,7 +56,8 @@ public sealed class ChangeTenantSubscriptionPlanCommandHandler(
|
||||
Notes = request.Notes
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
// 4. 记录审计日志
|
||||
await tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
{
|
||||
TenantId = subscription.TenantId,
|
||||
Action = TenantAuditAction.SubscriptionPlanChanged,
|
||||
@@ -66,7 +67,8 @@ public sealed class ChangeTenantSubscriptionPlanCommandHandler(
|
||||
CurrentStatus = null
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
// 5. 保存并返回 DTO
|
||||
await tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return subscription.ToSubscriptionDto()
|
||||
?? throw new BusinessException(ErrorCodes.InternalServerError, "订阅更新失败");
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
@@ -24,18 +23,20 @@ public sealed class CheckTenantQuotaCommandHandler(
|
||||
/// <inheritdoc />
|
||||
public async Task<QuotaCheckResultDto> Handle(CheckTenantQuotaCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验请求参数
|
||||
if (request.Delta <= 0)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "配额消耗量必须大于 0");
|
||||
}
|
||||
|
||||
// 2. 校验租户上下文
|
||||
var currentTenantId = tenantProvider.GetCurrentTenantId();
|
||||
if (currentTenantId == 0 || currentTenantId != request.TenantId)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.Forbidden, "租户上下文不匹配,请在请求头 X-Tenant-Id 指定目标租户");
|
||||
}
|
||||
|
||||
// 1. 获取租户与当前订阅。
|
||||
// 3. 获取租户与当前订阅
|
||||
_ = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
|
||||
|
||||
@@ -50,7 +51,7 @@ public sealed class CheckTenantQuotaCommandHandler(
|
||||
|
||||
var limit = ResolveLimit(package, request.QuotaType);
|
||||
|
||||
// 2. 加载配额使用记录并计算。
|
||||
// 4. 加载配额使用记录并计算
|
||||
var usage = await quotaUsageRepository.FindAsync(request.TenantId, request.QuotaType, cancellationToken)
|
||||
?? new TenantQuotaUsage
|
||||
{
|
||||
@@ -69,12 +70,14 @@ public sealed class CheckTenantQuotaCommandHandler(
|
||||
throw new BusinessException(ErrorCodes.Conflict, $"{request.QuotaType} 配额不足");
|
||||
}
|
||||
|
||||
// 5. 更新使用并保存
|
||||
usage.LimitValue = limit ?? usage.LimitValue;
|
||||
usage.UsedValue = usedAfter;
|
||||
usage.ResetCycle ??= ResolveResetCycle(request.QuotaType);
|
||||
|
||||
await PersistUsageAsync(usage, quotaUsageRepository, cancellationToken);
|
||||
|
||||
// 6. 返回结果
|
||||
return new QuotaCheckResultDto
|
||||
{
|
||||
QuotaType = request.QuotaType,
|
||||
|
||||
@@ -16,11 +16,13 @@ public sealed class CreateTenantAnnouncementCommandHandler(ITenantAnnouncementRe
|
||||
{
|
||||
public async Task<TenantAnnouncementDto> Handle(CreateTenantAnnouncementCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验标题与内容
|
||||
if (string.IsNullOrWhiteSpace(request.Title) || string.IsNullOrWhiteSpace(request.Content))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "公告标题和内容不能为空");
|
||||
}
|
||||
|
||||
// 2. 构建公告实体
|
||||
var announcement = new TenantAnnouncement
|
||||
{
|
||||
TenantId = request.TenantId,
|
||||
@@ -33,6 +35,7 @@ public sealed class CreateTenantAnnouncementCommandHandler(ITenantAnnouncementRe
|
||||
IsActive = request.IsActive
|
||||
};
|
||||
|
||||
// 3. 持久化并返回 DTO
|
||||
await announcementRepository.AddAsync(announcement, cancellationToken);
|
||||
await announcementRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
|
||||
@@ -16,11 +16,13 @@ public sealed class CreateTenantBillingCommandHandler(ITenantBillingRepository b
|
||||
{
|
||||
public async Task<TenantBillingDto> Handle(CreateTenantBillingCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验账单编号
|
||||
if (string.IsNullOrWhiteSpace(request.StatementNo))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "账单编号不能为空");
|
||||
}
|
||||
|
||||
// 2. 构建账单实体
|
||||
var bill = new TenantBillingStatement
|
||||
{
|
||||
TenantId = request.TenantId,
|
||||
@@ -34,9 +36,11 @@ public sealed class CreateTenantBillingCommandHandler(ITenantBillingRepository b
|
||||
LineItemsJson = request.LineItemsJson
|
||||
};
|
||||
|
||||
// 3. 持久化账单
|
||||
await billingRepository.AddAsync(bill, cancellationToken);
|
||||
await billingRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 4. 返回 DTO
|
||||
return bill.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,13 @@ public sealed class CreateTenantPackageCommandHandler(ITenantPackageRepository p
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantPackageDto> Handle(CreateTenantPackageCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验套餐名称
|
||||
if (string.IsNullOrWhiteSpace(request.Name))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "套餐名称不能为空");
|
||||
}
|
||||
|
||||
// 2. 构建套餐实体
|
||||
var package = new TenantPackage
|
||||
{
|
||||
Name = request.Name.Trim(),
|
||||
@@ -38,6 +40,7 @@ public sealed class CreateTenantPackageCommandHandler(ITenantPackageRepository p
|
||||
IsActive = request.IsActive
|
||||
};
|
||||
|
||||
// 3. 持久化并返回
|
||||
await packageRepository.AddAsync(package, cancellationToken);
|
||||
await packageRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
|
||||
@@ -18,28 +18,28 @@ public sealed class CreateTenantSubscriptionCommandHandler(
|
||||
IIdGenerator idGenerator)
|
||||
: IRequestHandler<CreateTenantSubscriptionCommand, TenantSubscriptionDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantSubscriptionDto> Handle(CreateTenantSubscriptionCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验订阅时长
|
||||
if (request.DurationMonths <= 0)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "订阅时长必须大于 0");
|
||||
}
|
||||
|
||||
var tenant = await _tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
// 2. 获取租户与当前订阅
|
||||
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
|
||||
|
||||
var current = await _tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
var current = await tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
var from = current?.EffectiveTo ?? tenant.EffectiveTo ?? DateTime.UtcNow;
|
||||
var effectiveFrom = from > DateTime.UtcNow ? from : DateTime.UtcNow;
|
||||
var effectiveTo = effectiveFrom.AddMonths(request.DurationMonths);
|
||||
|
||||
// 3. 创建订阅实体
|
||||
var subscription = new TenantSubscription
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
TenantId = tenant.Id,
|
||||
TenantPackageId = request.TenantPackageId,
|
||||
EffectiveFrom = effectiveFrom,
|
||||
@@ -50,10 +50,11 @@ public sealed class CreateTenantSubscriptionCommandHandler(
|
||||
Notes = request.Notes
|
||||
};
|
||||
|
||||
await _tenantRepository.AddSubscriptionAsync(subscription, cancellationToken);
|
||||
await _tenantRepository.AddSubscriptionHistoryAsync(new TenantSubscriptionHistory
|
||||
// 4. 记录订阅与历史
|
||||
await tenantRepository.AddSubscriptionAsync(subscription, cancellationToken);
|
||||
await tenantRepository.AddSubscriptionHistoryAsync(new TenantSubscriptionHistory
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
TenantId = tenant.Id,
|
||||
TenantSubscriptionId = subscription.Id,
|
||||
FromPackageId = current?.TenantPackageId ?? request.TenantPackageId,
|
||||
@@ -66,7 +67,8 @@ public sealed class CreateTenantSubscriptionCommandHandler(
|
||||
Notes = request.Notes
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
// 5. 记录审计
|
||||
await tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
{
|
||||
TenantId = tenant.Id,
|
||||
Action = TenantAuditAction.SubscriptionUpdated,
|
||||
@@ -74,8 +76,10 @@ public sealed class CreateTenantSubscriptionCommandHandler(
|
||||
Description = $"套餐 {request.TenantPackageId} 时长 {request.DurationMonths} 月"
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
// 6. 保存变更
|
||||
await tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 7. 返回 DTO
|
||||
return subscription.ToSubscriptionDto()
|
||||
?? throw new BusinessException(ErrorCodes.InternalServerError, "订阅生成失败");
|
||||
}
|
||||
|
||||
@@ -12,8 +12,11 @@ public sealed class DeleteTenantAnnouncementCommandHandler(ITenantAnnouncementRe
|
||||
{
|
||||
public async Task<bool> Handle(DeleteTenantAnnouncementCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除公告
|
||||
await announcementRepository.DeleteAsync(request.TenantId, request.AnnouncementId, cancellationToken);
|
||||
await announcementRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 2. 返回执行结果
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,11 @@ public sealed class DeleteTenantPackageCommandHandler(ITenantPackageRepository p
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> Handle(DeleteTenantPackageCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 删除套餐
|
||||
await packageRepository.DeleteAsync(request.TenantPackageId, cancellationToken);
|
||||
await packageRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 2. 返回执行结果
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,12 +17,14 @@ public sealed class GetTenantAnnouncementQueryHandler(
|
||||
{
|
||||
public async Task<TenantAnnouncementDto?> Handle(GetTenantAnnouncementQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询公告主体
|
||||
var announcement = await announcementRepository.FindByIdAsync(request.TenantId, request.AnnouncementId, cancellationToken);
|
||||
if (announcement == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 优先查用户级已读
|
||||
var userId = currentUserAccessor?.UserId ?? 0;
|
||||
var reads = await readRepository.GetByAnnouncementAsync(
|
||||
request.TenantId,
|
||||
@@ -37,6 +39,7 @@ public sealed class GetTenantAnnouncementQueryHandler(
|
||||
reads = tenantReads;
|
||||
}
|
||||
|
||||
// 3. 返回 DTO 并附带已读状态
|
||||
var readRecord = reads.FirstOrDefault();
|
||||
return announcement.ToDto(readRecord != null, readRecord?.ReadAt);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -13,20 +12,21 @@ namespace TakeoutSaaS.Application.App.Tenants.Handlers;
|
||||
public sealed class GetTenantAuditLogsQueryHandler(ITenantRepository tenantRepository)
|
||||
: IRequestHandler<GetTenantAuditLogsQuery, PagedResult<TenantAuditLogDto>>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<TenantAuditLogDto>> Handle(GetTenantAuditLogsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var logs = await _tenantRepository.GetAuditLogsAsync(request.TenantId, cancellationToken);
|
||||
// 1. 查询审核日志
|
||||
var logs = await tenantRepository.GetAuditLogsAsync(request.TenantId, cancellationToken);
|
||||
var total = logs.Count;
|
||||
|
||||
// 2. 分页映射
|
||||
var paged = logs
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(TenantMapping.ToDto)
|
||||
.ToList();
|
||||
|
||||
// 3. 返回分页结果
|
||||
return new PagedResult<TenantAuditLogDto>(paged, request.Page, request.PageSize, total);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,10 @@ public sealed class GetTenantBillQueryHandler(ITenantBillingRepository billingRe
|
||||
{
|
||||
public async Task<TenantBillingDto?> Handle(GetTenantBillQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询账单
|
||||
var bill = await billingRepository.FindByIdAsync(request.TenantId, request.BillingId, cancellationToken);
|
||||
|
||||
// 2. 返回 DTO 或 null
|
||||
return bill?.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,17 +13,18 @@ namespace TakeoutSaaS.Application.App.Tenants.Handlers;
|
||||
public sealed class GetTenantByIdQueryHandler(ITenantRepository tenantRepository)
|
||||
: IRequestHandler<GetTenantByIdQuery, TenantDetailDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantDetailDto> Handle(GetTenantByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenant = await _tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
// 1. 查询租户
|
||||
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
|
||||
|
||||
var subscription = await _tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
var verification = await _tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken);
|
||||
// 2. 查询订阅与认证
|
||||
var subscription = await tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken);
|
||||
|
||||
// 3. 组装返回
|
||||
return new TenantDetailDto
|
||||
{
|
||||
Tenant = TenantMapping.ToDto(tenant, subscription, verification),
|
||||
|
||||
@@ -14,7 +14,10 @@ public sealed class GetTenantPackageByIdQueryHandler(ITenantPackageRepository pa
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantPackageDto?> Handle(GetTenantPackageByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询套餐
|
||||
var package = await packageRepository.FindByIdAsync(request.TenantPackageId, cancellationToken);
|
||||
|
||||
// 2. 返回 DTO 或 null
|
||||
return package?.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ using TakeoutSaaS.Application.App.Tenants.Commands;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Security;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Tenants.Handlers;
|
||||
@@ -20,15 +18,18 @@ public sealed class MarkTenantAnnouncementReadCommandHandler(
|
||||
{
|
||||
public async Task<TenantAnnouncementDto?> Handle(MarkTenantAnnouncementReadCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询公告
|
||||
var announcement = await announcementRepository.FindByIdAsync(request.TenantId, request.AnnouncementId, cancellationToken);
|
||||
if (announcement == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 确定用户标识
|
||||
var userId = currentUserAccessor?.UserId ?? 0;
|
||||
var existing = await readRepository.FindAsync(request.TenantId, request.AnnouncementId, userId == 0 ? null : userId, cancellationToken);
|
||||
|
||||
// 3. 如未读则写入已读记录
|
||||
if (existing == null)
|
||||
{
|
||||
var record = new TenantAnnouncementRead
|
||||
@@ -44,6 +45,7 @@ public sealed class MarkTenantAnnouncementReadCommandHandler(
|
||||
existing = record;
|
||||
}
|
||||
|
||||
// 4. 返回带已读时间的公告 DTO
|
||||
return announcement.ToDto(true, existing.ReadAt);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,19 +14,23 @@ public sealed class MarkTenantBillingPaidCommandHandler(ITenantBillingRepository
|
||||
{
|
||||
public async Task<TenantBillingDto?> Handle(MarkTenantBillingPaidCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询账单
|
||||
var bill = await billingRepository.FindByIdAsync(request.TenantId, request.BillingId, cancellationToken);
|
||||
if (bill == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 更新支付状态
|
||||
bill.AmountPaid = request.AmountPaid;
|
||||
bill.Status = TenantBillingStatus.Paid;
|
||||
bill.DueDate = bill.DueDate;
|
||||
|
||||
// 3. 持久化变更
|
||||
await billingRepository.UpdateAsync(bill, cancellationToken);
|
||||
await billingRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// 4. 返回 DTO
|
||||
return bill.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,14 @@ public sealed class MarkTenantNotificationReadCommandHandler(ITenantNotification
|
||||
{
|
||||
public async Task<TenantNotificationDto?> Handle(MarkTenantNotificationReadCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询通知
|
||||
var notification = await notificationRepository.FindByIdAsync(request.TenantId, request.NotificationId, cancellationToken);
|
||||
if (notification == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 若未读则标记已读
|
||||
if (notification.ReadAt == null)
|
||||
{
|
||||
notification.ReadAt = DateTime.UtcNow;
|
||||
@@ -26,6 +28,7 @@ public sealed class MarkTenantNotificationReadCommandHandler(ITenantNotification
|
||||
await notificationRepository.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
// 3. 返回 DTO
|
||||
return notification.ToDto();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,30 +20,30 @@ public sealed class RegisterTenantCommandHandler(
|
||||
ILogger<RegisterTenantCommandHandler> logger)
|
||||
: IRequestHandler<RegisterTenantCommand, TenantDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
private readonly IIdGenerator _idGenerator = idGenerator;
|
||||
private readonly ILogger<RegisterTenantCommandHandler> _logger = logger;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantDto> Handle(RegisterTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验订阅时长
|
||||
if (request.DurationMonths <= 0)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "订阅时长必须大于 0");
|
||||
}
|
||||
|
||||
if (await _tenantRepository.ExistsByCodeAsync(request.Code, cancellationToken))
|
||||
// 2. 检查租户编码唯一性
|
||||
if (await tenantRepository.ExistsByCodeAsync(request.Code, cancellationToken))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.Conflict, $"租户编码 {request.Code} 已存在");
|
||||
}
|
||||
|
||||
// 3. 计算生效时间
|
||||
var now = DateTime.UtcNow;
|
||||
var effectiveFrom = request.EffectiveFrom ?? now;
|
||||
var effectiveTo = effectiveFrom.AddMonths(request.DurationMonths);
|
||||
|
||||
// 4. 构建租户实体
|
||||
var tenant = new Tenant
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
Code = request.Code.Trim(),
|
||||
Name = request.Name,
|
||||
ShortName = request.ShortName,
|
||||
@@ -56,9 +56,10 @@ public sealed class RegisterTenantCommandHandler(
|
||||
EffectiveTo = effectiveTo
|
||||
};
|
||||
|
||||
// 5. 构建订阅实体
|
||||
var subscription = new TenantSubscription
|
||||
{
|
||||
Id = _idGenerator.NextId(),
|
||||
Id = idGenerator.NextId(),
|
||||
TenantId = tenant.Id,
|
||||
TenantPackageId = request.TenantPackageId,
|
||||
EffectiveFrom = effectiveFrom,
|
||||
@@ -69,9 +70,10 @@ public sealed class RegisterTenantCommandHandler(
|
||||
Notes = "Init subscription"
|
||||
};
|
||||
|
||||
await _tenantRepository.AddTenantAsync(tenant, cancellationToken);
|
||||
await _tenantRepository.AddSubscriptionAsync(subscription, cancellationToken);
|
||||
await _tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
// 6. 持久化租户、订阅和审计日志
|
||||
await tenantRepository.AddTenantAsync(tenant, cancellationToken);
|
||||
await tenantRepository.AddSubscriptionAsync(subscription, cancellationToken);
|
||||
await tenantRepository.AddAuditLogAsync(new TenantAuditLog
|
||||
{
|
||||
TenantId = tenant.Id,
|
||||
Action = TenantAuditAction.RegistrationSubmitted,
|
||||
@@ -79,10 +81,12 @@ public sealed class RegisterTenantCommandHandler(
|
||||
Description = $"提交套餐 {request.TenantPackageId},时长 {request.DurationMonths} 月"
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
await tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("已注册租户 {TenantCode}", tenant.Code);
|
||||
// 7. 记录日志
|
||||
logger.LogInformation("已注册租户 {TenantCode}", tenant.Code);
|
||||
|
||||
// 8. 返回 DTO
|
||||
return TenantMapping.ToDto(tenant, subscription, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,31 +17,32 @@ public sealed class ReviewTenantCommandHandler(
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<ReviewTenantCommand, TenantDto>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
private readonly ICurrentUserAccessor _currentUserAccessor = currentUserAccessor;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantDto> Handle(ReviewTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenant = await _tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
// 1. 获取租户与认证资料
|
||||
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
|
||||
|
||||
var verification = await _tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken)
|
||||
var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, "请先提交实名认证资料");
|
||||
|
||||
var subscription = await _tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
var subscription = await tenantRepository.GetActiveSubscriptionAsync(request.TenantId, cancellationToken);
|
||||
|
||||
var actorName = _currentUserAccessor.IsAuthenticated
|
||||
? $"user:{_currentUserAccessor.UserId}"
|
||||
// 2. 记录审核人
|
||||
var actorName = currentUserAccessor.IsAuthenticated
|
||||
? $"user:{currentUserAccessor.UserId}"
|
||||
: "system";
|
||||
|
||||
// 3. 写入审核信息
|
||||
verification.ReviewedAt = DateTime.UtcNow;
|
||||
verification.ReviewedBy = _currentUserAccessor.UserId == 0 ? null : _currentUserAccessor.UserId;
|
||||
verification.ReviewedBy = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId;
|
||||
verification.ReviewedByName = actorName;
|
||||
verification.ReviewRemarks = request.Reason;
|
||||
|
||||
var previousStatus = tenant.Status;
|
||||
|
||||
// 4. 更新租户与订阅状态
|
||||
if (request.Approve)
|
||||
{
|
||||
verification.Status = TenantVerificationStatus.Approved;
|
||||
@@ -61,26 +62,29 @@ public sealed class ReviewTenantCommandHandler(
|
||||
}
|
||||
}
|
||||
|
||||
await _tenantRepository.UpdateTenantAsync(tenant, cancellationToken);
|
||||
await _tenantRepository.UpsertVerificationProfileAsync(verification, cancellationToken);
|
||||
// 5. 持久化租户与认证资料
|
||||
await tenantRepository.UpdateTenantAsync(tenant, cancellationToken);
|
||||
await tenantRepository.UpsertVerificationProfileAsync(verification, cancellationToken);
|
||||
if (subscription != null)
|
||||
{
|
||||
await _tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
|
||||
await tenantRepository.UpdateSubscriptionAsync(subscription, cancellationToken);
|
||||
}
|
||||
|
||||
await _tenantRepository.AddAuditLogAsync(new Domain.Tenants.Entities.TenantAuditLog
|
||||
// 6. 记录审核日志
|
||||
await tenantRepository.AddAuditLogAsync(new Domain.Tenants.Entities.TenantAuditLog
|
||||
{
|
||||
TenantId = tenant.Id,
|
||||
Action = request.Approve ? TenantAuditAction.VerificationApproved : TenantAuditAction.VerificationRejected,
|
||||
Title = request.Approve ? "审核通过" : "审核驳回",
|
||||
Description = request.Reason,
|
||||
OperatorId = _currentUserAccessor.UserId == 0 ? null : _currentUserAccessor.UserId,
|
||||
OperatorId = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId,
|
||||
OperatorName = actorName,
|
||||
PreviousStatus = previousStatus,
|
||||
CurrentStatus = tenant.Status
|
||||
}, cancellationToken);
|
||||
|
||||
await _tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
// 7. 保存并返回 DTO
|
||||
await tenantRepository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return TenantMapping.ToDto(tenant, subscription, verification);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -20,22 +18,27 @@ public sealed class SearchTenantAnnouncementsQueryHandler(
|
||||
{
|
||||
public async Task<PagedResult<TenantAnnouncementDto>> Handle(SearchTenantAnnouncementsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 过滤有效期条件
|
||||
var effectiveAt = request.OnlyEffective == true ? DateTime.UtcNow : (DateTime?)null;
|
||||
var announcements = await announcementRepository.SearchAsync(request.TenantId, request.AnnouncementType, request.IsActive, effectiveAt, cancellationToken);
|
||||
|
||||
// 2. 排序(优先级/时间)
|
||||
var ordered = announcements
|
||||
.OrderByDescending(x => x.Priority)
|
||||
.ThenByDescending(x => x.CreatedAt)
|
||||
.ToList();
|
||||
|
||||
// 3. 计算分页参数
|
||||
var page = request.Page <= 0 ? 1 : request.Page;
|
||||
var size = request.PageSize <= 0 ? 20 : request.PageSize;
|
||||
|
||||
// 4. 分页
|
||||
var pageItems = ordered
|
||||
.Skip((page - 1) * size)
|
||||
.Take(size)
|
||||
.ToList();
|
||||
|
||||
// 5. 构建已读映射
|
||||
var announcementIds = pageItems.Select(x => x.Id).ToArray();
|
||||
var userId = currentUserAccessor?.UserId ?? 0;
|
||||
|
||||
@@ -65,6 +68,7 @@ public sealed class SearchTenantAnnouncementsQueryHandler(
|
||||
}
|
||||
}
|
||||
|
||||
// 6. 映射 DTO 并带上已读状态
|
||||
var items = pageItems
|
||||
.Select(a =>
|
||||
{
|
||||
@@ -73,6 +77,7 @@ public sealed class SearchTenantAnnouncementsQueryHandler(
|
||||
})
|
||||
.ToList();
|
||||
|
||||
// 7. 返回分页结果
|
||||
return new PagedResult<TenantAnnouncementDto>(items, page, size, ordered.Count);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -15,13 +14,16 @@ public sealed class SearchTenantBillsQueryHandler(ITenantBillingRepository billi
|
||||
{
|
||||
public async Task<PagedResult<TenantBillingDto>> Handle(SearchTenantBillsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询账单
|
||||
var bills = await billingRepository.SearchAsync(request.TenantId, request.Status, request.From, request.To, cancellationToken);
|
||||
|
||||
// 2. 排序与分页
|
||||
var ordered = bills.OrderByDescending(x => x.PeriodEnd).ToList();
|
||||
var page = request.Page <= 0 ? 1 : request.Page;
|
||||
var size = request.PageSize <= 0 ? 20 : request.PageSize;
|
||||
var items = ordered.Skip((page - 1) * size).Take(size).Select(x => x.ToDto()).ToList();
|
||||
|
||||
// 3. 返回分页结果
|
||||
return new PagedResult<TenantBillingDto>(items, page, size, ordered.Count);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -15,6 +14,7 @@ public sealed class SearchTenantNotificationsQueryHandler(ITenantNotificationRep
|
||||
{
|
||||
public async Task<PagedResult<TenantNotificationDto>> Handle(SearchTenantNotificationsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询通知
|
||||
var notifications = await notificationRepository.SearchAsync(
|
||||
request.TenantId,
|
||||
request.Severity,
|
||||
@@ -23,11 +23,13 @@ public sealed class SearchTenantNotificationsQueryHandler(ITenantNotificationRep
|
||||
null,
|
||||
cancellationToken);
|
||||
|
||||
// 2. 排序与分页
|
||||
var ordered = notifications.OrderByDescending(x => x.SentAt).ToList();
|
||||
var page = request.Page <= 0 ? 1 : request.Page;
|
||||
var size = request.PageSize <= 0 ? 20 : request.PageSize;
|
||||
var items = ordered.Skip((page - 1) * size).Take(size).Select(x => x.ToDto()).ToList();
|
||||
|
||||
// 3. 返回分页结果
|
||||
return new PagedResult<TenantNotificationDto>(items, page, size, ordered.Count);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -16,8 +15,10 @@ public sealed class SearchTenantPackagesQueryHandler(ITenantPackageRepository pa
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<TenantPackageDto>> Handle(SearchTenantPackagesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 查询套餐
|
||||
var packages = await packageRepository.SearchAsync(request.Keyword, request.IsActive, cancellationToken);
|
||||
|
||||
// 2. 排序与分页
|
||||
var ordered = packages.OrderByDescending(x => x.CreatedAt).ToList();
|
||||
var pageIndex = request.Page <= 0 ? 1 : request.Page;
|
||||
var size = request.PageSize <= 0 ? 20 : request.PageSize;
|
||||
@@ -28,6 +29,7 @@ public sealed class SearchTenantPackagesQueryHandler(ITenantPackageRepository pa
|
||||
.Select(x => x.ToDto())
|
||||
.ToList();
|
||||
|
||||
// 3. 返回分页结果
|
||||
return new PagedResult<TenantPackageDto>(pagedItems, pageIndex, size, ordered.Count);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Linq;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Tenants.Dto;
|
||||
using TakeoutSaaS.Application.App.Tenants.Queries;
|
||||
@@ -13,27 +12,29 @@ namespace TakeoutSaaS.Application.App.Tenants.Handlers;
|
||||
public sealed class SearchTenantsQueryHandler(ITenantRepository tenantRepository)
|
||||
: IRequestHandler<SearchTenantsQuery, PagedResult<TenantDto>>
|
||||
{
|
||||
private readonly ITenantRepository _tenantRepository = tenantRepository;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<TenantDto>> Handle(SearchTenantsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenants = await _tenantRepository.SearchAsync(request.Status, request.Keyword, cancellationToken);
|
||||
// 1. 查询租户列表
|
||||
var tenants = await tenantRepository.SearchAsync(request.Status, request.Keyword, cancellationToken);
|
||||
var total = tenants.Count;
|
||||
|
||||
// 2. 分页
|
||||
var paged = tenants
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.ToList();
|
||||
|
||||
// 3. 映射 DTO(带订阅与认证)
|
||||
var result = new List<TenantDto>(paged.Count);
|
||||
foreach (var tenant in paged)
|
||||
{
|
||||
var subscription = await _tenantRepository.GetActiveSubscriptionAsync(tenant.Id, cancellationToken);
|
||||
var verification = await _tenantRepository.GetVerificationProfileAsync(tenant.Id, cancellationToken);
|
||||
var subscription = await tenantRepository.GetActiveSubscriptionAsync(tenant.Id, cancellationToken);
|
||||
var verification = await tenantRepository.GetVerificationProfileAsync(tenant.Id, cancellationToken);
|
||||
result.Add(TenantMapping.ToDto(tenant, subscription, verification));
|
||||
}
|
||||
|
||||
// 4. 返回分页结果
|
||||
return new PagedResult<TenantDto>(result, request.Page, request.PageSize, total);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user