using AutoMapper; using Microsoft.EntityFrameworkCore; using SmallSoftwareContracts.DataModels; using SmallSoftwareContracts.Exceptions; using SmallSoftwareContracts.StoragesContracts; using SmallSoftwareDatabase.Models; namespace SmallSoftwareDatabase.Implementations; internal class RequestStorageContract : IRequestStorageContract { private readonly SmallSoftwareDbContext _dbContext; private readonly Mapper _mapper; public RequestStorageContract(SmallSoftwareDbContext dbContext) { _dbContext = dbContext; var config = new MapperConfiguration(cfg => { cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap() .ForMember(x => x.SoftwareId, x => x.MapFrom(src => src.SoftwareId)); cfg.CreateMap(); cfg.CreateMap() .ForMember(x => x.IsCancel, x => x.MapFrom(src => false)) .ForMember(x => x.InstallationRequests, x => x.MapFrom(src => src.Softwares)) .ForMember(x => x.Worker, x => x.Ignore()) .ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate)) .ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate)); }); _mapper = new Mapper(config); } public List GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? softwareId = null) { try { var query = _dbContext.Requests.Include(x => x.Worker).Include(x => x.InstallationRequests).AsQueryable(); if (workerId is not null) { query = query.Where(x => x.WorkerId == workerId); } if (softwareId is not null) { query = query.Where(x => x.InstallationRequests!.Any(y => y.SoftwareId == softwareId)); } return [.. query.Select(x => _mapper.Map(x))]; } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public RequestDataModel? GetElementById(string id) { try { return _mapper.Map(GetRequestById(id)); } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public void AddElement(RequestDataModel requestDataModel) { try { _dbContext.Requests.Add(_mapper.Map(requestDataModel)); _dbContext.SaveChanges(); } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public void DelElement(string id) { try { var element = GetRequestById(id) ?? throw new ElementNotFoundException(id); if (element.IsCancel) { throw new ElementDeletedException(id); } element.IsCancel = true; _dbContext.SaveChanges(); } catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException) { _dbContext.ChangeTracker.Clear(); throw; } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } private Request? GetRequestById(string id) => _dbContext.Requests .Include(x => x.Worker) .Include(x => x.InstallationRequests)! .ThenInclude(x => x.Software) .FirstOrDefault(x => x.Id == id); }