59 lines
2.3 KiB
C#
59 lines
2.3 KiB
C#
using Brizco.Domain.Entities.Shift;
|
|
|
|
namespace Brizco.Repository.Handlers.Shift;
|
|
|
|
public class UpdatePositionCommandHandler : IRequestHandler<UpdateShiftCommand, bool>
|
|
{
|
|
private readonly IRepositoryWrapper _repositoryWrapper;
|
|
private readonly ICurrentUserService _currentUserService;
|
|
|
|
public UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
|
|
{
|
|
_repositoryWrapper = repositoryWrapper;
|
|
_currentUserService = currentUserService;
|
|
}
|
|
|
|
public async Task<bool> Handle(UpdateShiftCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var shift = await _repositoryWrapper.SetRepository<Domain.Entities.Shift.Shift>()
|
|
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
|
|
if (shift == null)
|
|
throw new AppException("Shift not found", ApiResultStatusCode.NotFound);
|
|
|
|
if (_currentUserService.ComplexId == null)
|
|
throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
|
|
if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
|
|
throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
|
|
|
|
var newShift = Domain.Entities.Shift.Shift.Create(request.Title,
|
|
request.Description,
|
|
request.StartAt,
|
|
request.EndAt,
|
|
complexId);
|
|
newShift.Id = request.Id;
|
|
|
|
var shiftDays = await _repositoryWrapper.SetRepository<ShiftDay>()
|
|
.TableNoTracking.Where(sd => sd.ShiftId == request.Id)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
foreach (var shiftDay in shiftDays.Where(shiftDay => !request.DayOfWeeks.Contains(shiftDay.DayOfWeek)))
|
|
{
|
|
_repositoryWrapper.SetRepository<ShiftDay>()
|
|
.Delete(shiftDay);
|
|
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
|
|
}
|
|
|
|
foreach (var dayOfWeek in request.DayOfWeeks)
|
|
{
|
|
var findDay = shiftDays.FirstOrDefault(sf => sf.DayOfWeek == dayOfWeek);
|
|
if (findDay == null)
|
|
newShift.SetDay(dayOfWeek);
|
|
}
|
|
|
|
_repositoryWrapper.SetRepository<Domain.Entities.Shift.Shift>()
|
|
.Update(newShift);
|
|
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
|
|
|
|
return true;
|
|
}
|
|
} |