using F9WebAiTest.Application.Common; using F9WebAiTest.Application.Common.Exceptions; using F9WebAiTest.Application.CQRS.SYS.RBAC.Menus.Commands; using F9WebAiTest.Application.Interfaces.Repositories.SYS.RBAC.Menus; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace F9WebAiTest.Api.Controllers; /// 系统菜单管理(DDD + CQRS) [ApiController] [Route("api/sys/menu")] [Authorize] public class SysMenuController : ControllerBase { private readonly IMediator _mediator; private readonly IMenuReadRepository _menuReadRepository; public SysMenuController(IMediator mediator, IMenuReadRepository menuReadRepository) { _mediator = mediator; _menuReadRepository = menuReadRepository; } [HttpGet("tree")] public async Task GetTree() => Ok(ApiResult.Ok(await _menuReadRepository.GetTreeMenuAsync())); [HttpGet] public async Task GetAll([FromQuery] string like = "", [FromQuery] long? parentId = null) => Ok(ApiResult.Ok(await _menuReadRepository.GetAllMenuAsync(like, parentId))); [HttpGet("{id}")] public async Task GetById(long id) => Ok(ApiResult.Ok(await _menuReadRepository.GetMenuByIdForEditAsync(id))); [HttpPost] public async Task Create([FromBody] Menu_CreateCommand command) { try { return Ok(ApiResult.Ok(new { id = await _mediator.Send(command) }, "创建成功")); } catch (F9NotFoundException ex) { return NotFound(ApiResult.Fail(ex.Message, 404)); } catch (F9OperationException ex) { return BadRequest(ApiResult.Fail(ex.Message, 400)); } } [HttpPut("{id}")] public async Task Update(long id, [FromBody] Menu_UpdateCommand command) { try { return Ok(ApiResult.Ok(await _mediator.Send(command with { Id = id }), "修改成功")); } catch (F9NotFoundException ex) { return NotFound(ApiResult.Fail(ex.Message, 404)); } catch (F9OperationException ex) { return BadRequest(ApiResult.Fail(ex.Message, 400)); } } [HttpDelete("{id}")] public async Task Delete(long id) { try { return Ok(ApiResult.Ok(await _mediator.Send(new Menu_DelCommand(id)), "删除成功")); } catch (F9NotFoundException ex) { return NotFound(ApiResult.Fail(ex.Message, 404)); } catch (F9OperationException ex) { return BadRequest(ApiResult.Fail(ex.Message, 400)); } } [HttpPut("{id}/active")] public async Task ActiveOrDeactivate(long id, [FromBody] Menu_ActiveOrDeactivateCommand command) { try { return Ok(ApiResult.Ok(await _mediator.Send(command with { Id = id }), "操作成功")); } catch (F9NotFoundException ex) { return NotFound(ApiResult.Fail(ex.Message, 404)); } catch (F9OperationException ex) { return BadRequest(ApiResult.Fail(ex.Message, 400)); } } }