using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using CellularManagement.Application.Features.Permissions.Commands.CreatePermission;
using CellularManagement.Application.Common;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using CellularManagement.Presentation.Abstractions;
using CellularManagement.Domain.Common;
namespace CellularManagement.Presentation.Controllers;
///
/// 权限管理控制器
/// 提供权限管理相关的 API 接口,包括创建、删除和查询权限功能
///
[Route("api/permissions")]
[ApiController]
[Authorize(Roles = "Admin")] // 只有管理员可以访问
public class PermissionsController : ApiController
{
private readonly ILogger _logger;
///
/// 初始化权限控制器
///
/// MediatR 中介者,用于处理命令和查询
/// 日志记录器
public PermissionsController(
IMediator mediator,
ILogger logger) : base(mediator)
{
_logger = logger;
}
///
/// 创建新权限
///
///
/// 示例请求:
///
/// POST /api/permissions/create
/// {
/// "name": "CreateUser",
/// "description": "创建用户的权限"
/// }
///
///
/// 创建权限命令,包含权限名称和描述
///
/// 创建结果,包含:
/// - 成功:返回权限ID
/// - 失败:返回错误信息
///
/// 创建成功,返回权限ID
/// 创建失败,返回错误信息
[HttpPost]
[ProducesResponseType(typeof(OperationResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(OperationResult), StatusCodes.Status400BadRequest)]
public async Task> CreatePermission([FromBody] CreatePermissionCommand command)
{
try
{
var result = await mediator.Send(command);
if (result.IsSuccess)
{
_logger.LogInformation("权限 {PermissionName} 创建成功", command.Name);
}
else
{
_logger.LogWarning("权限 {PermissionName} 创建失败: {Error}",
command.Name,
result.ErrorMessages?.FirstOrDefault());
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "创建权限 {PermissionName} 时发生异常", command.Name);
return OperationResult.CreateFailure("系统错误,请稍后重试");
}
}
}