|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using MediatR;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using CellularManagement.Application.Common;
|
|
|
|
using CellularManagement.Domain.Entities;
|
|
|
|
using CellularManagement.Domain.Repositories;
|
|
|
|
using CellularManagement.Domain.Common;
|
|
|
|
using System;
|
|
|
|
|
|
|
|
namespace CellularManagement.Application.Features.Permissions.Commands.CreatePermission;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 创建权限命令处理器
|
|
|
|
/// </summary>
|
|
|
|
public sealed class CreatePermissionCommandHandler : IRequestHandler<CreatePermissionCommand, OperationResult<CreatePermissionResponse>>
|
|
|
|
{
|
|
|
|
private readonly IPermissionRepository _permissionRepository;
|
|
|
|
private readonly ILogger<CreatePermissionCommandHandler> _logger;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 初始化处理器
|
|
|
|
/// </summary>
|
|
|
|
public CreatePermissionCommandHandler(
|
|
|
|
IPermissionRepository permissionRepository,
|
|
|
|
ILogger<CreatePermissionCommandHandler> logger)
|
|
|
|
{
|
|
|
|
_permissionRepository = permissionRepository;
|
|
|
|
_logger = logger;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 处理创建权限请求
|
|
|
|
/// </summary>
|
|
|
|
public async Task<OperationResult<CreatePermissionResponse>> Handle(
|
|
|
|
CreatePermissionCommand request,
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
// 检查权限是否已存在
|
|
|
|
var existingPermission = await _permissionRepository.GetByNameAsync(request.Name, cancellationToken);
|
|
|
|
if (existingPermission != null)
|
|
|
|
{
|
|
|
|
_logger.LogWarning("权限 {PermissionName} 已存在", request.Name);
|
|
|
|
return OperationResult<CreatePermissionResponse>.CreateFailure("权限已存在");
|
|
|
|
}
|
|
|
|
|
|
|
|
// 创建权限
|
|
|
|
var permission = Permission.Create(request.Name, request.Description);
|
|
|
|
var createdPermission = await _permissionRepository.AddAsync(permission, cancellationToken);
|
|
|
|
|
|
|
|
_logger.LogInformation("权限 {PermissionName} 创建成功", request.Name);
|
|
|
|
|
|
|
|
return OperationResult<CreatePermissionResponse>.CreateSuccess(
|
|
|
|
new CreatePermissionResponse(createdPermission.Id));
|
|
|
|
}
|
|
|
|
catch (Exception ex)
|
|
|
|
{
|
|
|
|
_logger.LogError(ex, "创建权限 {PermissionName} 失败", request.Name);
|
|
|
|
return OperationResult<CreatePermissionResponse>.CreateFailure("创建权限失败,请稍后重试");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|