Files
blazor-cms/Features/Organization/EmployeeGroup/Cqrs/UpdateEmployeeGroupHandler.cs
T
2026-07-21 13:52:43 +07:00

61 lines
2.0 KiB
C#

using Indotalent.ConfigBackEnd.Exceptions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Indotalent.Features.Organization.EmployeeGroup.Cqrs;
public class UpdateEmployeeGroupRequest
{
public string? Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public DateTimeOffset? CreatedAt { get; set; }
public string? CreatedBy { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public string? UpdatedBy { get; set; }
}
public class UpdateEmployeeGroupResponse
{
public string? Id { get; set; }
public bool Success { get; set; }
}
public record UpdateEmployeeGroupCommand(UpdateEmployeeGroupRequest Data) : IRequest<UpdateEmployeeGroupResponse>;
public class UpdateEmployeeGroupHandler : IRequestHandler<UpdateEmployeeGroupCommand, UpdateEmployeeGroupResponse>
{
private readonly AppDbContext _context;
public UpdateEmployeeGroupHandler(AppDbContext context) => _context = context;
public async Task<UpdateEmployeeGroupResponse> Handle(UpdateEmployeeGroupCommand request, CancellationToken cancellationToken)
{
var isExists = await _context.EmployeeGroup
.AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);
if (isExists)
{
throw new AlreadyExistsException("Employee Group", request.Data.Name ?? string.Empty);
}
var entity = await _context.EmployeeGroup
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
if (entity == null)
{
return new UpdateEmployeeGroupResponse { Id = request.Data.Id, Success = false };
}
entity.Name = request.Data.Name;
entity.Description = request.Data.Description;
await _context.SaveChangesAsync(cancellationToken);
return new UpdateEmployeeGroupResponse
{
Id = entity.Id,
Success = true
};
}
}