namespace Brizco.Repository.Handlers.ShiftPlans; public class CreateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) : IRequestHandler { private readonly ICurrentUserService _currentUserService = currentUserService; public async Task Handle(CreateShiftPlanCommand request, CancellationToken cancellationToken) { 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 planDate = DateTimeExtensions.UnixTimeStampToDateTime(request.PlanDate); var planFor = new DateTime(planDate.Year, planDate.Month, planDate.Day, shift.StartAt.Hours, shift.StartAt.Minutes, shift.StartAt.Seconds); var existedShiftPlan = await repositoryWrapper.SetRepository() .TableNoTracking .FirstOrDefaultAsync(s => s.ShiftId == request.ShiftId && s.PlanFor.Date == planFor.Date, cancellationToken); if (existedShiftPlan != null) throw new AppException("Shift plan is exist for this date , you can update existed shift plan", ApiResultStatusCode.BadRequest); try { await repositoryWrapper.BeginTransaction(cancellationToken); var shiftPlan = shift.AddPlan(planFor, request.RoutineId, request.SupervisionUserId); if (request.UserAndPositionIds.Count == 0) throw new AppException("شیفت بندی مورد نظر باید حداقل متشکل از یک فرد باشد", ApiResultStatusCode.BadRequest); foreach (var userAndPositionId in request.UserAndPositionIds) { shiftPlan.AddUser(userAndPositionId.Key, userAndPositionId.Value); } repositoryWrapper.SetRepository().Add(shiftPlan); await repositoryWrapper.SaveChangesAsync(cancellationToken); await repositoryWrapper.CommitAsync(cancellationToken); return shiftPlan.AdaptToLDto(); } catch (Exception ) { await repositoryWrapper.RollBackAsync(cancellationToken); throw; } } }