Api/Brizco.Repository/Handlers/ShiftPlans/UpdateShiftPlanCommandHandl...

52 lines
2.1 KiB
C#

namespace Brizco.Repository.Handlers.ShiftPlans;
public class UpdateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<UpdateShiftPlanCommand, bool>
{
public async Task<bool> Handle(UpdateShiftPlanCommand request, CancellationToken cancellationToken)
{
var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
.TableNoTracking.FirstOrDefaultAsync(s => s.Id == request.Id,cancellationToken);
if (shiftPlan == null)
throw new AppException("ShiftPlan not found", ApiResultStatusCode.NotFound);
var shift = await repositoryWrapper.SetRepository<Shift>()
.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<ShiftPlanUser>()
.TableNoTracking
.Where(s => s.ShiftPlanId == newPlan.Id)
.ToListAsync(cancellationToken);
foreach (var shiftPlanUser in shiftPlanUsers)
{
if (request.UserAndPositionIds.Contains(new KeyValuePair<Guid, Guid>(shiftPlanUser.PositionId,shiftPlanUser.UserId)))
request.UserAndPositionIds.Remove(new KeyValuePair<Guid, Guid>(shiftPlanUser.PositionId, shiftPlanUser.UserId));
else
{
repositoryWrapper.SetRepository<ShiftPlanUser>()
.Delete(shiftPlanUser);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
}
foreach (var userId in request.UserAndPositionIds)
newPlan.AddUser(userId.Key,userId.Value);
repositoryWrapper.SetRepository<ShiftPlan>()
.Update(newPlan);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}