forked from slavaxom9k/PIBD-23_Fomichev_V.S._MagicCarpet
87 lines
3.1 KiB
C#
87 lines
3.1 KiB
C#
using AutoMapper;
|
|
using MagicCarpetContracts.DataModels;
|
|
using MagicCarpetContracts.Exceptions;
|
|
using MagicCarpetContracts.Resources;
|
|
using MagicCarpetContracts.StoragesContracts;
|
|
using MagicCarpetDatabase.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Localization;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MagicCarpetDatabase.Implementations;
|
|
|
|
internal class SalaryStorageContract : ISalaryStorageContract
|
|
{
|
|
private readonly MagicCarpetDbContext _dbContext;
|
|
private readonly Mapper _mapper;
|
|
private readonly IStringLocalizer<Messages> _localizer;
|
|
|
|
public SalaryStorageContract(MagicCarpetDbContext dbContext, IStringLocalizer<Messages> localizer)
|
|
{
|
|
_dbContext = dbContext;
|
|
var config = new MapperConfiguration(cfg =>
|
|
{
|
|
cfg.CreateMap<Employee, EmployeeDataModel>();
|
|
cfg.CreateMap<Salary, SalaryDataModel>();
|
|
cfg.CreateMap<SalaryDataModel, Salary>()
|
|
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
|
|
});
|
|
_mapper = new Mapper(config);
|
|
_localizer = localizer;
|
|
}
|
|
|
|
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
|
|
{
|
|
try
|
|
{
|
|
var query = _dbContext.Salaries.Include(d => d.Employee).AsQueryable();
|
|
if (startDate.HasValue)
|
|
query = query.Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
|
if (endDate.HasValue)
|
|
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
|
|
if (employeeId != null)
|
|
query = query.Where(x => x.EmployeeId == employeeId);
|
|
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_dbContext.ChangeTracker.Clear();
|
|
throw new StorageException(ex, _localizer);
|
|
}
|
|
}
|
|
|
|
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
return [.. await _dbContext.Salaries.Include(x =>
|
|
x.Employee).Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate, DateTimeKind.Utc) &&
|
|
x.SalaryDate <= DateTime.SpecifyKind(endDate, DateTimeKind.Utc))
|
|
.Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_dbContext.ChangeTracker.Clear();
|
|
throw new StorageException(ex, _localizer);
|
|
}
|
|
}
|
|
|
|
public void AddElement(SalaryDataModel salaryDataModel)
|
|
{
|
|
try
|
|
{
|
|
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
|
|
_dbContext.SaveChanges();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_dbContext.ChangeTracker.Clear();
|
|
throw new StorageException(ex, _localizer);
|
|
}
|
|
}
|
|
}
|