namespace Brizco.Repository.Handlers.ShiftPlan; public class UpdateShiftPlanCommandHandler : IRequestHandler { private readonly IRepositoryWrapper _repositoryWrapper; public UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper) { _repositoryWrapper = repositoryWrapper; } public async Task Handle(UpdateShiftPlanCommand request, CancellationToken cancellationToken) { var shiftPlan = await _repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken); if (shiftPlan == null) throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound); var shift = await _repositoryWrapper.SetRepository() .TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken); if (shift == null) throw new AppException("Shift not found", ApiResultStatusCode.NotFound); var newPlan = shift.AddPlan(DateTimeExtensions.UnixTimeStampToDateTime(request.PlanDate), request.RoutineId,request.SupervisionUserId); newPlan.Id = request.Id; var shiftPlanUsers = await _repositoryWrapper.SetRepository() .TableNoTracking .Where(s => s.ShiftPlanId == newPlan.Id) .ToListAsync(cancellationToken); foreach (var shiftPlanUser in shiftPlanUsers) { if (request.UserAndPositionIds.Contains(new KeyValuePair(shiftPlanUser.PositionId,shiftPlanUser.UserId))) request.UserAndPositionIds.Remove(new KeyValuePair(shiftPlanUser.PositionId, shiftPlanUser.UserId)); else { _repositoryWrapper.SetRepository() .Delete(shiftPlanUser); await _repositoryWrapper.SaveChangesAsync(cancellationToken); } } foreach (var userId in request.UserAndPositionIds) newPlan.AddUser(userId.Key,userId.Value); _repositoryWrapper.SetRepository() .Update(newPlan); await _repositoryWrapper.SaveChangesAsync(cancellationToken); return true; } }