Api/Brizco.Repository/Handlers/Shifts/UpdateShiftCommandHandler.cs

68 lines
2.9 KiB
C#

namespace Brizco.Repository.Handlers.Shifts;
public class UpdatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
: IRequestHandler<UpdateShiftCommand, bool>
{
public async Task<bool> Handle(UpdateShiftCommand request, CancellationToken cancellationToken)
{
var shift = await repositoryWrapper.SetRepository<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 = Shift.Create(request.Title,
request.Description,
request.StartAt,
request.EndAt,
complexId);
newShift.Id = request.Id;
if (request.DayOfWeeks.Count == 0)
throw new AppException("روزهای شیفت را انتخاب کنید");
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 from dayOfWeek in request.DayOfWeeks let findDay = shiftDays.FirstOrDefault(sf => sf.DayOfWeek == dayOfWeek) where findDay == null select dayOfWeek)
{
newShift.SetDay(dayOfWeek);
}
if (request.Routines.Count == 0)
throw new AppException("روتین شیفت را انتخاب کنید");
var shiftRoutines = await repositoryWrapper.SetRepository<ShiftRoutine>()
.TableNoTracking.Where(sd => sd.ShiftId == request.Id)
.ToListAsync(cancellationToken);
foreach (var shiftRoutine in shiftRoutines.Where(shiftRoutine => !request.Routines.Contains(shiftRoutine.RoutineId)))
{
repositoryWrapper.SetRepository<ShiftRoutine>()
.Delete(shiftRoutine);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
foreach (var routine in request.Routines.Where(r=>!shiftRoutines.Exists(routine=>routine.RoutineId==r)))
{
newShift.AddRoutine(routine);
}
repositoryWrapper.SetRepository<Shift>()
.Update(newShift);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}