using AutoMapper; using MagicCarpetContracts.DataModels; using MagicCarpetContracts.Exceptions; using MagicCarpetContracts.StoragesContracts; using MagicCarpetDatabase.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MagicCarpetDatabase.Implementations; internal class SaleStorageContract : ISaleStorageContract { private readonly MagicCarpetDbContext _dbContext; private readonly Mapper _mapper; public SaleStorageContract(MagicCarpetDbContext dbContext) { _dbContext = dbContext; var config = new MapperConfiguration(cfg => { cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap(); cfg.CreateMap() .ForMember(x => x.IsCancel, x => x.MapFrom(src => false)) .ForMember(x => x.SaleTours, x => x.MapFrom(src => src.Tours)); }); _mapper = new Mapper(config); } public List GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? tourId = null) { try { var query = _dbContext.Sales.Include(x => x.SaleTours).AsQueryable(); if (startDate is not null && endDate is not null) { query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate); } if (employeeId is not null) { query = query.Where(x => x.EmployeeId == employeeId); } if (clientId is not null) { query = query.Where(x => x.ClientId == clientId); } if (tourId is not null) { query = query.Where(x => x.SaleTours!.Any(y => y.TourId == tourId)); } return [.. query.Select(x => _mapper.Map(x))]; } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public SaleDataModel? GetElementById(string id) { try { return _mapper.Map(GetSaleById(id)); } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public void AddElement(SaleDataModel saleDataModel) { try { _dbContext.Sales.Add(_mapper.Map(saleDataModel)); _dbContext.SaveChanges(); } catch (Exception ex) { _dbContext.ChangeTracker.Clear(); throw new StorageException(ex); } } public void DelElement(string id) { try { var element = GetSaleById(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 Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id); }