Compare commits
1 Commits
Task_7_Loc
...
Task_8_Map
| Author | SHA1 | Date | |
|---|---|---|---|
| d1f7e5ccf8 |
@@ -8,7 +8,6 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.4">
|
||||
|
||||
@@ -1,41 +1,30 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Npgsql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public BuyerStorageContract(AndDietCokeDbContext andDietCokeDbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = andDietCokeDbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(AndDietCokeDbContext).Assembly);
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<BuyerDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Buyers.Select(x => _mapper.Map<BuyerDataModel>(x))];
|
||||
return [.. _dbContext.Buyers.Select(x => CustomMapper.MapObject<BuyerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -48,7 +37,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
|
||||
return CustomMapper.MapObjectWithNull<BuyerDataModel>(GetBuyerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -61,7 +50,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
|
||||
return CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -74,7 +63,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
|
||||
return CustomMapper.MapObjectWithNull<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -87,7 +76,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
|
||||
_dbContext.Buyers.Add(CustomMapper.MapObject<Buyer>(buyerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
@@ -118,7 +107,7 @@ internal class BuyerStorageContract : IBuyerStorageContract
|
||||
try
|
||||
{
|
||||
var element = GetBuyerById(buyerDataModel.Id) ?? throw new ElementNotFoundException(buyerDataModel.Id, _localizer);
|
||||
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel, element));
|
||||
_dbContext.Buyers.Update(CustomMapper.MapObject(buyerDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Npgsql;
|
||||
@@ -18,20 +18,11 @@ namespace AndDietCokeDatabase.Implementations;
|
||||
internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public DishStorageContract(AndDietCokeDbContext dbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Dish, DishDataModel>();
|
||||
cfg.CreateMap<DishDataModel, Dish>()
|
||||
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
|
||||
cfg.CreateMap<DishHistory, DishHistoryDataModel>();
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<DishDataModel> GetList(bool onlyActive = true)
|
||||
@@ -43,7 +34,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
query = query.Where(x => !x.IsDeleted);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<DishDataModel>(x))];
|
||||
return [.. query.Select(x => CustomMapper.MapObject<DishDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -56,7 +47,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.DishHistories.Include(x => x.Dish).Where(x => x.DishId == dishId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<DishHistoryDataModel>(x))];
|
||||
return [.. _dbContext.DishHistories.Include(x => x.Dish).Where(x => x.DishId == dishId).OrderByDescending(x => x.ChangeDate).Select(x => CustomMapper.MapObject<DishHistoryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -69,7 +60,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<DishDataModel>(GetDishById(id));
|
||||
return CustomMapper.MapObjectWithNull<DishDataModel>(GetDishById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -82,7 +73,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<DishDataModel>(_dbContext.Dishes.FirstOrDefault(x => x.DishName == name && !x.IsDeleted));
|
||||
return CustomMapper.MapObjectWithNull<DishDataModel>(_dbContext.Dishes.FirstOrDefault(x => x.DishName == name && !x.IsDeleted));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -95,7 +86,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Dishes.Add(_mapper.Map<Dish>(dishDataModel));
|
||||
_dbContext.Dishes.Add(CustomMapper.MapObject<Dish>(dishDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
@@ -134,7 +125,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
_dbContext.DishHistories.Add(new DishHistory() { DishId = element.Id, OldPrice = element.Price });
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
_dbContext.Dishes.Update(_mapper.Map(dishDataModel, element));
|
||||
_dbContext.Dishes.Update(CustomMapper.MapObject(dishDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
@@ -191,7 +182,7 @@ internal class DishStorageContract : IDishStorageContract
|
||||
.Include(x => x.Dish)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return entities.Select(x => _mapper.Map<DishHistoryDataModel>(x)).ToList();
|
||||
return entities.Select(x => CustomMapper.MapObject<DishHistoryDataModel>(x)).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,41 +1,22 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Npgsql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public PostStorageContract(AndDietCokeDbContext dbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, opt => opt.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<PostDataModel, Post>()
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
|
||||
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
|
||||
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
|
||||
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<PostDataModel> GetList(bool onlyActual = true)
|
||||
@@ -43,7 +24,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Posts.AsQueryable();
|
||||
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
return [.. query.Select(x => CustomMapper.MapObject<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -56,7 +37,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
|
||||
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => CustomMapper.MapObject<PostDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -69,7 +50,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
|
||||
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -82,7 +63,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
|
||||
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -95,7 +76,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
|
||||
_dbContext.Posts.Add(CustomMapper.MapObject<Post>(postDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
|
||||
@@ -129,7 +110,7 @@ internal class PostStorageContract : IPostStorageContract
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
var newElement = _mapper.Map<Post>(postDataModel);
|
||||
var newElement = CustomMapper.MapObject<Post>(postDataModel);
|
||||
_dbContext.Posts.Add(newElement);
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
@@ -13,21 +13,11 @@ namespace AndDietCokeDatabase.Implementations;
|
||||
internal class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public SalaryStorageContract(AndDietCokeDbContext dbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, Worker>();
|
||||
cfg.CreateMap<Salary, SalaryDataModel>();
|
||||
cfg.CreateMap<SalaryDataModel, Salary>()
|
||||
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
|
||||
@@ -39,7 +29,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
query = query.Where(x => x.WorkerId == workerId);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
|
||||
return [.. query.Select(x => CustomMapper.MapObject<SalaryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -52,7 +42,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
|
||||
_dbContext.Salaries.Add(CustomMapper.MapObject<Salary>(salaryDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -66,7 +56,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync()];
|
||||
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => CustomMapper.MapObject<SalaryDataModel>(x)).ToListAsync()];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -2,40 +2,21 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public SaleStorageContract(AndDietCokeDbContext dbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Buyer, BuyerDataModel>();
|
||||
cfg.CreateMap<Dish, DishDataModel>();
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<OrderDish, OrderDishDataModel>();
|
||||
cfg.CreateMap<Sale, SaleDataModel>();
|
||||
cfg.CreateMap<OrderDishDataModel, OrderDish>();
|
||||
cfg.CreateMap<SaleDataModel, Sale>()
|
||||
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
|
||||
.ForMember(x => x.OrderDishes, x => x.MapFrom(src => src.Dishes));
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? buyerId = null, string? dishId = null)
|
||||
@@ -59,7 +40,7 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
query = query.Where(x => x.OrderDishes!.Any(y => y.DishId == dishId));
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
|
||||
return [.. query.Select(x => CustomMapper.MapObject<SaleDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -72,7 +53,7 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<SaleDataModel>(GetSaleById(id));
|
||||
return CustomMapper.MapObjectWithNull<SaleDataModel>(GetSaleById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -85,7 +66,7 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
|
||||
_dbContext.Sales.Add(CustomMapper.MapObject<Sale>(saleDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -127,7 +108,7 @@ internal class SaleStorageContract : ISaleStorageContract
|
||||
{
|
||||
var query = _dbContext.Sales.Include(x => x.Buyer).Include(x => x.Worker).Include(x => x.OrderDishes)!.ThenInclude(x => x.Dish).AsQueryable();
|
||||
query = query.Where(x => x.SaleDate.Date >= startDate.Date && x.SaleDate.Date < endDate.Date);
|
||||
return Task.FromResult(query.Select(x => _mapper.Map<SaleDataModel>(x)).ToList());
|
||||
return Task.FromResult(query.Select(x => CustomMapper.MapObject<SaleDataModel>(x)).ToList());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,38 +1,24 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Npgsql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public WorkerStorageContract(AndDietCokeDbContext dbContext, IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Post, PostDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
|
||||
cfg.CreateMap<Worker, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, Worker>();
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
|
||||
@@ -56,7 +42,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
|
||||
}
|
||||
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
|
||||
return [.. JoinPost(query).Select(x => CustomMapper.MapObject<WorkerDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -69,7 +55,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
|
||||
return CustomMapper.MapObjectWithNull<WorkerDataModel>(GetWorkerById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -82,7 +68,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
return CustomMapper.MapObjectWithNull<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -95,7 +81,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
|
||||
_dbContext.Workers.Add(CustomMapper.MapObject<Worker>(workerDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
@@ -135,7 +121,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
|
||||
try
|
||||
{
|
||||
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id, _localizer);
|
||||
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
|
||||
_dbContext.Workers.Update(CustomMapper.MapObject(workerDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AutoMapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@@ -9,7 +8,6 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
|
||||
public class Buyer
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@@ -18,7 +19,7 @@ public class Dish
|
||||
public DishType DishType { get; set; }
|
||||
|
||||
public double Price { get; set; }
|
||||
|
||||
[IgnoreValue]
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
[ForeignKey("DishId")]
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
@@ -13,7 +14,7 @@ public class DishHistory
|
||||
public required string DishId { get; set; }
|
||||
|
||||
public double OldPrice { get; set; }
|
||||
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime ChangeDate { get; set; }
|
||||
|
||||
public Dish? Dish { get; set; }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -10,15 +11,18 @@ namespace AndDietCokeDatabase.Models;
|
||||
|
||||
public class Post
|
||||
{
|
||||
[IgnoreValue]
|
||||
public required string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
[AlternativeName("Id")]
|
||||
public required string PostId { get; set; }
|
||||
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public PostType PostType { get; set; }
|
||||
|
||||
[AlternativeName("ConfigurationModel")]
|
||||
public required PostConfiguration Configuration { get; set; }
|
||||
[CustomDefault(DefaultValue = true)]
|
||||
public bool IsActual { get; set; }
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
@@ -11,9 +12,9 @@ public class Salary
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime SalaryDate { get; set; }
|
||||
|
||||
[AlternativeName("Salary")]
|
||||
public double WorkerSalary { get; set; }
|
||||
|
||||
public Worker? Worker { get; set; }
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
@@ -14,13 +16,14 @@ public class Sale
|
||||
public required string WorkerId { get; set; }
|
||||
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
public bool IsConstantClient { get; set; }
|
||||
|
||||
[IgnoreValue]
|
||||
[CustomDefault(DefaultValue = false)]
|
||||
public bool IsCancel { get; set; }
|
||||
|
||||
public Worker? Worker { get; set; }
|
||||
@@ -28,5 +31,6 @@ public class Sale
|
||||
public Buyer? Buyer { get; set; }
|
||||
|
||||
[ForeignKey("SaleId")]
|
||||
[AlternativeName("Dishes")]
|
||||
public List<OrderDish>? OrderDishes { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AutoMapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
|
||||
public class Worker
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
@@ -17,12 +11,14 @@ public class Worker
|
||||
public required string FIO { get; set; }
|
||||
|
||||
public required string PostId { get; set; }
|
||||
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
[CustomDefault(FuncName = DefaultValuesFunc.UtcNow)]
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
[CustomDefault(DefaultValue = false)]
|
||||
public bool IsDeleted { get; set; }
|
||||
public DateTime? DateOfDelete { get; set; }
|
||||
[IgnoreValue]
|
||||
[NotMapped]
|
||||
public Post? Post { get; set; }
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
|
||||
@@ -21,6 +21,8 @@ internal class BuyerDataModel(string id, string fio, string phoneNumber, double
|
||||
public string FIO { get; private set; } = fio;
|
||||
public string PhoneNumber { get; private set; } = phoneNumber;
|
||||
public double DiscountSize { get; private set; } = discountSize;
|
||||
public BuyerDataModel() : this("","","",0)
|
||||
{ }
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
@@ -22,7 +23,10 @@ internal class DishDataModel(string id, string dishName, DishType dishType, doub
|
||||
public bool IsDeleted { get; private set; } = isDeleted;
|
||||
|
||||
public DishDataModel(string id, string dishName, int dishType, double price) : this(id, dishName, (DishType)dishType, price, false) { }
|
||||
public DishDataModel() : this("", "", DishType.None, 0, false)
|
||||
{
|
||||
|
||||
}
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -8,11 +8,13 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
internal class DishHistoryDataModel(string dishId, double oldPrice) : IValidation
|
||||
{
|
||||
[SourceFromMember(SourcePropertyName = "Dish")]
|
||||
private readonly DishDataModel? _dish;
|
||||
public string DishId { get; private set; } = dishId;
|
||||
public double OldPrice { get; private set; } = oldPrice;
|
||||
@@ -24,7 +26,10 @@ internal class DishHistoryDataModel(string dishId, double oldPrice) : IValidatio
|
||||
ChangeDate = changeDate.ToUniversalTime();
|
||||
_dish = dish;
|
||||
}
|
||||
public DishHistoryDataModel() : this ("", 0)
|
||||
{
|
||||
|
||||
}
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (DishId.IsEmpty())
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using System;
|
||||
@@ -14,13 +15,14 @@ namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
internal class OrderDishDataModel(string orderId, string dishId, int count, double price) : IValidation
|
||||
{
|
||||
[SourceFromMember(SourcePropertyName ="Dish")]
|
||||
private readonly DishDataModel? _dish;
|
||||
public string OrderId { get; private set; } = orderId;
|
||||
public string DishId { get; private set; } = dishId;
|
||||
public int Count { get; private set; } = count;
|
||||
public double Price { get; private set; } = price;
|
||||
public string DishName => _dish?.DishName ?? string.Empty;
|
||||
|
||||
public OrderDishDataModel() : this ("","",0,0) { }
|
||||
public OrderDishDataModel(string saleId, string dishId, int count, double price, DishDataModel dish) : this(saleId, dishId, count, price)
|
||||
{
|
||||
_dish = dish;
|
||||
|
||||
@@ -13,28 +13,21 @@ using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
internal class PostDataModel(string postid, string postName, PostType postType, PostConfiguration configuration) : IValidation
|
||||
{
|
||||
[AlternativeName("PostId")]
|
||||
public string Id { get; private set; } = postid;
|
||||
public string PostName { get; private set; } = postName;
|
||||
public PostType PostType { get; private set; } = postType;
|
||||
[AlternativeName("Configuration")]
|
||||
[AlternativeName("ConfigurationJson")]
|
||||
[PostProcessing(MappingCallMethodName = "ParseJson")]
|
||||
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
|
||||
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
|
||||
{
|
||||
var obj = JToken.Parse(configurationJson);
|
||||
if (obj is not null)
|
||||
{
|
||||
ConfigurationModel = obj.Value<string>("Type") switch
|
||||
{
|
||||
nameof(WaiterPostConfiguration) => JsonConvert.DeserializeObject<WaiterPostConfiguration>(configurationJson)!,
|
||||
nameof(ChefPostConfiguration) => JsonConvert.DeserializeObject<ChefPostConfiguration>(configurationJson)!,
|
||||
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
|
||||
};
|
||||
}
|
||||
}
|
||||
public PostDataModel() : this("","",PostType.None, null) { }
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
@@ -50,5 +43,33 @@ internal class PostDataModel(string postid, string postName, PostType postType,
|
||||
if (ConfigurationModel!.Rate <= 0)
|
||||
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
|
||||
}
|
||||
private PostConfiguration? ParseJson(object json)
|
||||
{
|
||||
if (json is PostConfiguration config)
|
||||
{
|
||||
return config;
|
||||
}
|
||||
if (json is string)
|
||||
{
|
||||
|
||||
var obj = JToken.Parse((string)json);
|
||||
var type = obj.Value<string>("Type");
|
||||
switch (type)
|
||||
{
|
||||
case nameof(ChefPostConfiguration):
|
||||
ConfigurationModel = JsonConvert.DeserializeObject<ChefPostConfiguration>((string)json);
|
||||
break;
|
||||
case nameof(WaiterPostConfiguration):
|
||||
ConfigurationModel = JsonConvert.DeserializeObject<WaiterPostConfiguration>((string)json);
|
||||
break;
|
||||
default:
|
||||
ConfigurationModel = JsonConvert.DeserializeObject<PostConfiguration>((string)json);
|
||||
break;
|
||||
}
|
||||
return ConfigurationModel;
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using System;
|
||||
@@ -14,13 +15,18 @@ namespace AndDietCokeContracts.DataModels;
|
||||
internal class SalaryDataModel(string id, string workerId, DateTime salaryDate, double
|
||||
workerSalary) : IValidation
|
||||
{
|
||||
[SourceFromMember(SourcePropertyName ="Worker")]
|
||||
private readonly WorkerDataModel? _worker;
|
||||
public string Id { get; private set; } = id;
|
||||
public string WorkerId { get; private set; } = workerId;
|
||||
public DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
|
||||
[AlternativeName("WorkerSalary")]
|
||||
public double Salary { get; private set; } = workerSalary;
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
public SalaryDataModel() : this("", "", DateTime.UtcNow, 0)
|
||||
{
|
||||
|
||||
}
|
||||
public SalaryDataModel(string id, string workerId, DateTime salaryDate, double workersalary, WorkerDataModel worker) : this(id, workerId, salaryDate, workersalary)
|
||||
{
|
||||
_worker = worker;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using System;
|
||||
@@ -12,11 +13,11 @@ using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
internal class SaleDataModel : IValidation
|
||||
{
|
||||
[SourceFromMember(SourcePropertyName ="Buyer")]
|
||||
private readonly BuyerDataModel? _buyer;
|
||||
|
||||
[SourceFromMember(SourcePropertyName = "Worker")]
|
||||
private readonly WorkerDataModel? _worker;
|
||||
|
||||
public string Id { get; private set; }
|
||||
@@ -25,7 +26,8 @@ internal class SaleDataModel : IValidation
|
||||
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
|
||||
public double Sum { get; private set; }
|
||||
public bool IsConstantClient { get; private set; }
|
||||
public bool IsCancel { get; private set; }
|
||||
public bool IsCancel { get; private set; }
|
||||
[AlternativeName("OrderDishes")]
|
||||
public List<OrderDishDataModel>? Dishes { get; private set; }
|
||||
public string BuyerFIO => _buyer?.FIO ?? string.Empty;
|
||||
public string WorkerFIO => _worker?.FIO ?? string.Empty;
|
||||
@@ -47,9 +49,9 @@ internal class SaleDataModel : IValidation
|
||||
_worker = worker;
|
||||
_buyer = buyer;
|
||||
}
|
||||
|
||||
public SaleDataModel() : this("","","",new List<OrderDishDataModel>()) { }
|
||||
public SaleDataModel(string id, string workerId, string? buyerId, List<OrderDishDataModel> dishes) : this(id, workerId, buyerId, true, false, dishes) { }
|
||||
|
||||
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastrusture;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Localization;
|
||||
@@ -17,6 +18,7 @@ namespace AndDietCokeContracts.DataModels;
|
||||
internal class WorkerDataModel(string id, string fio, string postId, DateTime
|
||||
birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
{
|
||||
[SourceFromMember(SourcePropertyName = "Post")]
|
||||
private readonly PostDataModel? _post;
|
||||
public string Id { get; private set; } = id;
|
||||
public string FIO { get; private set; } = fio;
|
||||
@@ -31,7 +33,7 @@ birthDate, DateTime employmentDate, bool isDeleted) : IValidation
|
||||
_post = post;
|
||||
}
|
||||
public WorkerDataModel(string id, string fio,string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
|
||||
|
||||
public WorkerDataModel() : this("","","",DateTime.UtcNow,DateTime.UtcNow) { }
|
||||
public void Validate(IStringLocalizer<Messages> localizer)
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace AndDietCokeContracts.Mapper;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
|
||||
class AlternativeNameAttribute(string alternativeName) : Attribute
|
||||
{
|
||||
public string AlternativeName { get; set; } = alternativeName;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace AndDietCokeContracts.Mapper;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
|
||||
class CustomDefaultAttribute : Attribute
|
||||
{
|
||||
public object? DefaultValue { get; set; }
|
||||
|
||||
public DefaultValuesFunc FuncName { get; set; }
|
||||
}
|
||||
216
AndDietCokeProject/AndDietCokeProject/Mapper/CustomMapper.cs
Normal file
216
AndDietCokeProject/AndDietCokeProject/Mapper/CustomMapper.cs
Normal file
@@ -0,0 +1,216 @@
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
|
||||
namespace AndDietCokeContracts.Mapper;
|
||||
|
||||
internal static class CustomMapper
|
||||
{
|
||||
public static To MapObject<To>(object obj, To newObject)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(obj);
|
||||
ArgumentNullException.ThrowIfNull(newObject);
|
||||
var typeFrom = obj.GetType();
|
||||
var typeTo = newObject.GetType();
|
||||
var propertiesFrom = typeFrom.GetProperties().Where(x => x.CanRead).ToArray();
|
||||
foreach (var property in typeTo.GetProperties().Where(x => x.CanWrite))
|
||||
{
|
||||
//ignore
|
||||
if(property.GetCustomAttribute(typeof(IgnoreValueAttribute)) != null)
|
||||
{
|
||||
FindAndMapDefaultValue(property, newObject);
|
||||
continue;
|
||||
}
|
||||
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
|
||||
if (propertyFrom is null)
|
||||
{
|
||||
FindAndMapDefaultValue(property, newObject);
|
||||
continue;
|
||||
}
|
||||
|
||||
var fromValue = propertyFrom.GetValue(obj);
|
||||
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
|
||||
if ((postProcessingAttribute is not null))
|
||||
{
|
||||
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
|
||||
if (value is not null)
|
||||
{
|
||||
property.SetValue(newObject, value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (propertyFrom.PropertyType.IsGenericType && propertyFrom.PropertyType.Name.StartsWith("List") && fromValue is not null)
|
||||
{
|
||||
fromValue = MapListOfObjects(property, fromValue);
|
||||
}
|
||||
if (fromValue is not null)
|
||||
{
|
||||
object? finalValue = null;
|
||||
bool successConversion = false;
|
||||
|
||||
var targetType = property.PropertyType;
|
||||
|
||||
if (propertyFrom.PropertyType.IsEnum && !targetType.IsEnum)
|
||||
{
|
||||
finalValue = fromValue.ToString();
|
||||
successConversion = true;
|
||||
}
|
||||
else if (targetType.IsEnum)
|
||||
{
|
||||
successConversion = Enum.TryParse(targetType, fromValue.ToString(), ignoreCase: true, out object? parsedEnum);
|
||||
if (successConversion)
|
||||
{
|
||||
finalValue = parsedEnum;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
finalValue = fromValue;
|
||||
successConversion = true;
|
||||
|
||||
}
|
||||
|
||||
if (successConversion)
|
||||
{
|
||||
property.SetValue(newObject, finalValue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
// fields
|
||||
var fieldsTo = typeTo.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
foreach (var field in fieldsTo)
|
||||
{
|
||||
var mapFromAttr = field.GetCustomAttribute<SourceFromMemberAttribute>();
|
||||
if (mapFromAttr is null)
|
||||
continue;
|
||||
|
||||
var sourceProp = typeFrom.GetProperty(mapFromAttr.SourcePropertyName);
|
||||
if (sourceProp is null || !sourceProp.CanRead)
|
||||
continue;
|
||||
|
||||
var sourceValue = sourceProp.GetValue(obj);
|
||||
if (sourceValue is null)
|
||||
continue;
|
||||
|
||||
var targetFieldType = field.FieldType;
|
||||
var mappedValue = typeof(CustomMapper)
|
||||
.GetMethod(nameof(MapObject), new[] { typeof(object) })!
|
||||
.MakeGenericMethod(targetFieldType)
|
||||
.Invoke(null, new[] { sourceValue });
|
||||
|
||||
if (mappedValue is not null)
|
||||
{
|
||||
field.SetValue(newObject, mappedValue);
|
||||
}
|
||||
}
|
||||
|
||||
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
|
||||
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
|
||||
{
|
||||
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
methodInfo?.Invoke(newObject, []);
|
||||
}
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
|
||||
|
||||
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
|
||||
|
||||
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
|
||||
{
|
||||
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
|
||||
.ToArray()
|
||||
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
|
||||
if (customAttribute is not null)
|
||||
{
|
||||
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
|
||||
}
|
||||
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
|
||||
}
|
||||
|
||||
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
|
||||
{
|
||||
|
||||
if (value is null || newObject is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
|
||||
{
|
||||
var methodInfo =
|
||||
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
if (methodInfo is not null)
|
||||
{
|
||||
return methodInfo.Invoke(newObject, [value]);
|
||||
}
|
||||
}
|
||||
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
|
||||
{
|
||||
switch (postProcessingAttribute.ActionType)
|
||||
{
|
||||
case PostProcessingType.ToUniversalTime:
|
||||
return ToUniversalTime(value);
|
||||
case PostProcessingType.ToLocalTime:
|
||||
return ToLocalTime(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static object? ToLocalTime(object? obj)
|
||||
{
|
||||
if (obj is DateTime date)
|
||||
return date.ToLocalTime();
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static object? ToUniversalTime(object? obj)
|
||||
{
|
||||
if (obj is DateTime date)
|
||||
return date.ToUniversalTime();
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
|
||||
{
|
||||
var defaultValueAttribute = property.GetCustomAttribute<CustomDefaultAttribute>();
|
||||
if (defaultValueAttribute is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (defaultValueAttribute.DefaultValue is not null)
|
||||
{
|
||||
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
|
||||
return;
|
||||
}
|
||||
|
||||
var value = defaultValueAttribute.FuncName switch
|
||||
{
|
||||
DefaultValuesFunc.UtcNow => DateTime.UtcNow,
|
||||
DefaultValuesFunc.Null => (object?)null,
|
||||
};
|
||||
if (value is not null)
|
||||
{
|
||||
property.SetValue(newObject, value);
|
||||
}
|
||||
}
|
||||
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
|
||||
{
|
||||
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
|
||||
foreach (var elem in (IEnumerable)list)
|
||||
{
|
||||
var newElem = MapObject(elem, Activator.CreateInstance(propertyTo.PropertyType.GenericTypeArguments[0])!);
|
||||
if (newElem is not null)
|
||||
{
|
||||
propertyTo.PropertyType.GetMethod("Add")!.Invoke(listResult, [newElem]);
|
||||
}
|
||||
}
|
||||
|
||||
return listResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
|
||||
namespace AndDietCokeContracts.Mapper
|
||||
{
|
||||
enum DefaultValuesFunc
|
||||
{
|
||||
Null,
|
||||
UtcNow
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
namespace AndDietCokeContracts.Mapper
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
class IgnoreValueAttribute : Attribute
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
namespace AndDietCokeContracts.Mapper
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
|
||||
class PostProcessingAttribute : Attribute
|
||||
{
|
||||
public string? MappingCallMethodName { get; set; }
|
||||
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
namespace AndDietCokeContracts.Mapper
|
||||
{
|
||||
enum PostProcessingType
|
||||
{
|
||||
None = -1,
|
||||
ToUniversalTime = 1,
|
||||
ToLocalTime = 2,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
|
||||
namespace AndDietCokeContracts.Mapper
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
class SourceFromMemberAttribute : Attribute
|
||||
{
|
||||
public string? SourcePropertyName { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// Этот код создан программой.
|
||||
// Исполняемая версия:4.0.30319.42000
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
|
||||
// повторной генерации кода.
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
@@ -13,12 +13,12 @@ namespace AndDietCokeContracts.Resources {
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
|
||||
// с помощью такого средства, как ResGen или Visual Studio.
|
||||
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
|
||||
// с параметром /str или перестройте свой проект VS.
|
||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
@@ -33,7 +33,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
@@ -47,8 +47,8 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
|
||||
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
@@ -61,7 +61,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Элемент по данным: {0} был удален.
|
||||
/// Looks up a localized string similar to Элемент по данным: {0} был удален.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageElementDeletedException {
|
||||
get {
|
||||
@@ -70,7 +70,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Не найден элемент по данным: {0}.
|
||||
/// Looks up a localized string similar to Не найден элемент по данным: {0}.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageElementNotFoundException {
|
||||
get {
|
||||
@@ -79,7 +79,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Данные пусты.
|
||||
/// Looks up a localized string similar to Данные пусты.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageEmptyData {
|
||||
get {
|
||||
@@ -88,7 +88,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Неправильные даты: {0}.
|
||||
/// Looks up a localized string similar to Неправильные даты: {0}.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageIncorrectDatesException {
|
||||
get {
|
||||
@@ -97,7 +97,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Ошибка при обработке данных: {0}.
|
||||
/// Looks up a localized string similar to Ошибка при обработке данных: {0}.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageInvalidOperationException {
|
||||
get {
|
||||
@@ -106,7 +106,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Ошибка при работе с хранилищем данных: {0}.
|
||||
/// Looks up a localized string similar to Ошибка при работе с хранилищем данных: {0}.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageStorageException {
|
||||
get {
|
||||
@@ -115,7 +115,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Переданы неверные данные: {0}.
|
||||
/// Looks up a localized string similar to Переданы неверные данные: {0}.
|
||||
/// </summary>
|
||||
internal static string AdapterMessageValidationException {
|
||||
get {
|
||||
@@ -124,7 +124,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Дата изменения.
|
||||
/// Looks up a localized string similar to Дата изменения.
|
||||
/// </summary>
|
||||
internal static string DocumentDocCaptionDate {
|
||||
get {
|
||||
@@ -133,7 +133,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Блюдо.
|
||||
/// Looks up a localized string similar to Блюдо.
|
||||
/// </summary>
|
||||
internal static string DocumentDocCaptionDish {
|
||||
get {
|
||||
@@ -142,7 +142,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на История изменения.
|
||||
/// Looks up a localized string similar to История изменения.
|
||||
/// </summary>
|
||||
internal static string DocumentDocCaptionPriceHistories {
|
||||
get {
|
||||
@@ -151,7 +151,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на История цен блюд.
|
||||
/// Looks up a localized string similar to История цен блюд.
|
||||
/// </summary>
|
||||
internal static string DocumentDocHeader {
|
||||
get {
|
||||
@@ -160,7 +160,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Сформировано на дату {0}.
|
||||
/// Looks up a localized string similar to Сформировано на дату {0}.
|
||||
/// </summary>
|
||||
internal static string DocumentDocSubHeader {
|
||||
get {
|
||||
@@ -169,7 +169,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Кол-во.
|
||||
/// Looks up a localized string similar to Кол-во.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionCount {
|
||||
get {
|
||||
@@ -178,7 +178,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Дата.
|
||||
/// Looks up a localized string similar to Дата.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionDate {
|
||||
get {
|
||||
@@ -187,7 +187,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Скидка.
|
||||
/// Looks up a localized string similar to Скидка.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionDiscount {
|
||||
get {
|
||||
@@ -196,7 +196,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Блюдо.
|
||||
/// Looks up a localized string similar to Блюдо.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionDish {
|
||||
get {
|
||||
@@ -205,7 +205,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Сумма.
|
||||
/// Looks up a localized string similar to Сумма.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionSum {
|
||||
get {
|
||||
@@ -214,7 +214,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Всего.
|
||||
/// Looks up a localized string similar to Всего.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionTotal {
|
||||
get {
|
||||
@@ -223,7 +223,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Имя работника.
|
||||
/// Looks up a localized string similar to Имя работника.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelCaptionWorkerName {
|
||||
get {
|
||||
@@ -232,7 +232,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Продажи за период.
|
||||
/// Looks up a localized string similar to Продажи за период.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelHeader {
|
||||
get {
|
||||
@@ -241,7 +241,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на c {0} по {1}.
|
||||
/// Looks up a localized string similar to c {0} по {1}.
|
||||
/// </summary>
|
||||
internal static string DocumentExcelSubHeader {
|
||||
get {
|
||||
@@ -250,7 +250,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Начисления.
|
||||
/// Looks up a localized string similar to Начисления.
|
||||
/// </summary>
|
||||
internal static string DocumentPdfDiagramCaption {
|
||||
get {
|
||||
@@ -259,7 +259,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Зарплатная ведомость.
|
||||
/// Looks up a localized string similar to Зарплатная ведомость.
|
||||
/// </summary>
|
||||
internal static string DocumentPdfHeader {
|
||||
get {
|
||||
@@ -268,7 +268,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на за период с {0} по {1}.
|
||||
/// Looks up a localized string similar to за период с {0} по {1}.
|
||||
/// </summary>
|
||||
internal static string DocumentPdfSubHeader {
|
||||
get {
|
||||
@@ -277,7 +277,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Всего начислено {0}.
|
||||
/// Looks up a localized string similar to Всего начислено {0}.
|
||||
/// </summary>
|
||||
internal static string DocumentPdfTotalSalary {
|
||||
get {
|
||||
@@ -286,7 +286,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Нельзя изменить удаленный элемент (идентификатор: {0}).
|
||||
/// Looks up a localized string similar to Нельзя изменить удаленный элемент (идентификатор: {0}).
|
||||
/// </summary>
|
||||
internal static string ElementDeletedExceptionMessage {
|
||||
get {
|
||||
@@ -295,7 +295,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Уже существует элемент со значением {0} параметра {1}.
|
||||
/// Looks up a localized string similar to Уже существует элемент со значением {0} параметра {1}.
|
||||
/// </summary>
|
||||
internal static string ElementExistsExceptionMessage {
|
||||
get {
|
||||
@@ -304,7 +304,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Элемент не найден по значению = {0}.
|
||||
/// Looks up a localized string similar to Элемент не найден по значению = {0}.
|
||||
/// </summary>
|
||||
internal static string ElementNotFoundExceptionMessage {
|
||||
get {
|
||||
@@ -313,7 +313,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Дата окончания должна быть позже даты начала. Дата начала: {0}. Дата окончания: {1}.
|
||||
/// Looks up a localized string similar to Дата окончания должна быть позже даты начала. Дата начала: {0}. Дата окончания: {1}.
|
||||
/// </summary>
|
||||
internal static string IncorrectDatesExceptionMessage {
|
||||
get {
|
||||
@@ -322,7 +322,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Недостаточно данных для обработки: {0}.
|
||||
/// Looks up a localized string similar to Недостаточно данных для обработки: {0}.
|
||||
/// </summary>
|
||||
internal static string NotEnoughDataToProcessExceptionMessage {
|
||||
get {
|
||||
@@ -331,7 +331,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Не найдены данные.
|
||||
/// Looks up a localized string similar to Не найдены данные.
|
||||
/// </summary>
|
||||
internal static string NotFoundDataMessage {
|
||||
get {
|
||||
@@ -340,7 +340,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Ошибка при работе в хранилище: {0}.
|
||||
/// Looks up a localized string similar to Ошибка при работе в хранилище: {0}.
|
||||
/// </summary>
|
||||
internal static string StorageExceptionMessage {
|
||||
get {
|
||||
@@ -349,7 +349,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
|
||||
/// Looks up a localized string similar to Дата трудоустройства не может быть раньше даты рождения ({0}, {1}).
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageEmploymentDateAndBirthDate {
|
||||
get {
|
||||
@@ -358,7 +358,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Значение в поле {0} пусто.
|
||||
/// Looks up a localized string similar to Значение в поле {0} пусто.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageEmptyField {
|
||||
get {
|
||||
@@ -367,7 +367,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Значение в поле Телефонный номер не является телефонным номером.
|
||||
/// Looks up a localized string similar to Значение в поле Телефонный номер не является телефонным номером.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageIncorrectPhoneNumber {
|
||||
get {
|
||||
@@ -376,7 +376,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Значение в поле {0} меньше или равно 0.
|
||||
/// Looks up a localized string similar to Значение в поле {0} меньше или равно 0.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageLessOrEqualZero {
|
||||
get {
|
||||
@@ -385,7 +385,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
|
||||
/// Looks up a localized string similar to Несовершеннолетние не могут быть приняты на работу (Дата рождения: {0}).
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageMinorsBirthDate {
|
||||
get {
|
||||
@@ -394,7 +394,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства {0}, Дата рождения: {1}).
|
||||
/// Looks up a localized string similar to Несовершеннолетние не могут быть приняты на работу (Дата трудоустройства {0}, Дата рождения: {1}).
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageMinorsEmploymentDate {
|
||||
get {
|
||||
@@ -403,7 +403,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на В продаже должен быть хотя бы одно блюдо.
|
||||
/// Looks up a localized string similar to В продаже должен быть хотя бы одно блюдо.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageNoDishesInSale {
|
||||
get {
|
||||
@@ -412,7 +412,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Значение в поле {0} не является типом уникального идентификатора.
|
||||
/// Looks up a localized string similar to Значение в поле {0} не является типом уникального идентификатора.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageNotAId {
|
||||
get {
|
||||
@@ -421,7 +421,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Значение в поле {0} не проиницализировано.
|
||||
/// Looks up a localized string similar to Значение в поле {0} не проиницализировано.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageNotInitialized {
|
||||
get {
|
||||
@@ -430,7 +430,7 @@ namespace AndDietCokeContracts.Resources {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ищет локализованную строку, похожую на Имя фамилия и отчество были введены неправильно.
|
||||
/// Looks up a localized string similar to Имя фамилия и отчество были введены неправильно.
|
||||
/// </summary>
|
||||
internal static string ValidationExceptionMessageWrongFIO {
|
||||
get {
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Infrastrusture.PostConfiguration;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
@@ -14,5 +17,11 @@ public class PostViewModel
|
||||
|
||||
public required string PostType { get; set; }
|
||||
|
||||
|
||||
|
||||
[AlternativeName("ConfigurationModel")]
|
||||
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
|
||||
public required string Configuration { get; set; }
|
||||
private string ParseConfiguration(PostConfiguration model) =>
|
||||
JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
@@ -10,6 +11,7 @@ public class SalaryViewModel
|
||||
{
|
||||
public required string WorkerId { get; set; }
|
||||
public required string WorkerFIO { get; set; }
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
public DateTime SalaryDate { get; set; }
|
||||
public double Salary { get; set; }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
@@ -17,7 +18,7 @@ public class SaleViewModel
|
||||
public string? BuyerId { get; set; }
|
||||
|
||||
public string? BuyerFIO { get; set; }
|
||||
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
public DateTime SaleDate { get; set; }
|
||||
|
||||
public double Sum { get; set; }
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels
|
||||
{
|
||||
@@ -10,7 +11,9 @@ namespace AndDietCokeContracts.ViewModels
|
||||
{
|
||||
public required string WorkerFIO { get; set; }
|
||||
public double TotalSalary { get; set; }
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
public DateTime FromPeriod { get; set; }
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeContracts.ViewModels;
|
||||
|
||||
@@ -17,8 +18,9 @@ public class WorkerViewModel
|
||||
public required string PostName { get; set; }
|
||||
|
||||
public bool IsDeleted { get; set; }
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
|
||||
public DateTime BirthDate { get; set; }
|
||||
|
||||
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="EntityFramework" Version="6.5.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.4" />
|
||||
|
||||
@@ -187,7 +187,7 @@ namespace AndDietCokeTests.LocalizationTests
|
||||
[TestCase("dishes/delete")]
|
||||
[TestCase("sales/cancel")]
|
||||
[TestCase("workers/delete")]
|
||||
public async Task Api_DeleteElement_NotFound_Test(string path) //Проверка локализуемости метода удаления (ElementNotFound)
|
||||
public async Task Api_DeleteElement_NotFound_Test(string path)
|
||||
{
|
||||
var currentLocale = GetLocale();
|
||||
//Act
|
||||
@@ -259,7 +259,7 @@ namespace AndDietCokeTests.LocalizationTests
|
||||
}
|
||||
protected abstract string MessageElementWrongId();
|
||||
[TestCaseSource(nameof(TestDataElementWrongIds))]
|
||||
public async Task Api_Put_WhenWrongData_ShouldBadRequest(Func<object> createModel, string path)//Проверка локализуемости метода редактирования (ошибка валидации)
|
||||
public async Task Api_Put_WhenWrongData_ShouldBadRequest(Func<object> createModel, string path)
|
||||
{
|
||||
//Arrange
|
||||
var model = createModel();
|
||||
|
||||
@@ -5,9 +5,9 @@ using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
@@ -16,27 +16,19 @@ internal class BuyerAdapter : IBuyerAdapter
|
||||
private readonly IBuyerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public BuyerAdapter(IBuyerBusinessLogicContract buyerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<BuyerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = buyerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<BuyerBindingModel, BuyerDataModel>();
|
||||
cfg.CreateMap<BuyerDataModel, BuyerViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public BuyerOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return BuyerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllBuyers().Select(x => _mapper.Map<BuyerViewModel>(x))]);
|
||||
return BuyerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllBuyers().Select(x => CustomMapper.MapObject<BuyerViewModel>(x))]);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
@@ -54,7 +46,7 @@ internal class BuyerAdapter : IBuyerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return BuyerOperationResponse.OK(_mapper.Map<BuyerViewModel>(_buyerBusinessLogicContract.GetBuyerByData(data)));
|
||||
return BuyerOperationResponse.OK(CustomMapper.MapObject<BuyerViewModel>(_buyerBusinessLogicContract.GetBuyerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -82,7 +74,7 @@ internal class BuyerAdapter : IBuyerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.InsertBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
|
||||
_buyerBusinessLogicContract.InsertBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
|
||||
return BuyerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
@@ -116,7 +108,7 @@ internal class BuyerAdapter : IBuyerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.UpdateBuyer(_mapper.Map<BuyerDataModel>(buyerModel));
|
||||
_buyerBusinessLogicContract.UpdateBuyer(CustomMapper.MapObject<BuyerDataModel>(buyerModel));
|
||||
return BuyerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
|
||||
@@ -4,10 +4,9 @@ using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using DocumentFormat.OpenXml.Office2010.Excel;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
@@ -17,28 +16,19 @@ internal class DishAdapter : IDishAdapter
|
||||
private readonly IDishBusinessLogicContract _dishBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public DishAdapter(IDishBusinessLogicContract dishBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<DishAdapter> logger)
|
||||
{
|
||||
_dishBusinessLogicContract = dishBusinessLogicContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<DishBindingModel, DishDataModel>();
|
||||
cfg.CreateMap<DishDataModel, DishViewModel>();
|
||||
cfg.CreateMap<DishHistoryDataModel, DishHistoryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public DishOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetAllDishes(!includeDeleted).Select(x => _mapper.Map<DishViewModel>(x))]);
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetAllDishes(!includeDeleted).Select(x => CustomMapper.MapObject<DishViewModel>(x))]);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
@@ -56,7 +46,7 @@ internal class DishAdapter : IDishAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetDishHistoryByDish(id).Select(x => _mapper.Map<DishHistoryViewModel>(x))]);
|
||||
return DishOperationResponse.OK([.. _dishBusinessLogicContract.GetDishHistoryByDish(id).Select(x => CustomMapper.MapObject<DishHistoryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
@@ -79,7 +69,7 @@ internal class DishAdapter : IDishAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return DishOperationResponse.OK(_mapper.Map<DishViewModel>(_dishBusinessLogicContract.GetDishByData(data)));
|
||||
return DishOperationResponse.OK(CustomMapper.MapObject<DishViewModel>(_dishBusinessLogicContract.GetDishByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -112,7 +102,7 @@ internal class DishAdapter : IDishAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_dishBusinessLogicContract.InsertDish(_mapper.Map<DishDataModel>(dishModel));
|
||||
_dishBusinessLogicContract.InsertDish(CustomMapper.MapObject<DishDataModel>(dishModel));
|
||||
return DishOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
@@ -146,7 +136,7 @@ internal class DishAdapter : IDishAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_dishBusinessLogicContract.UpdateDish(_mapper.Map<DishDataModel>(dishModel));
|
||||
_dishBusinessLogicContract.UpdateDish(CustomMapper.MapObject<DishDataModel>(dishModel));
|
||||
return DishOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
|
||||
@@ -5,10 +5,10 @@ using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
@@ -18,7 +18,6 @@ internal class PostAdapter : IPostAdapter
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger)
|
||||
@@ -26,19 +25,13 @@ internal class PostAdapter : IPostAdapter
|
||||
_postBusinessLogicContract = postBusinessLogicContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PostBindingModel, PostDataModel>();
|
||||
cfg.CreateMap<PostDataModel, PostViewModel>().ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PostOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts(true).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts(true).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
@@ -56,7 +49,7 @@ internal class PostAdapter : IPostAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
|
||||
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -84,7 +77,7 @@ internal class PostAdapter : IPostAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
|
||||
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -117,7 +110,7 @@ internal class PostAdapter : IPostAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
|
||||
_postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
@@ -151,7 +144,7 @@ internal class PostAdapter : IPostAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
|
||||
_postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
|
||||
return PostOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
|
||||
@@ -3,9 +3,9 @@ using AndDietCokeContracts.AdapterContracts;
|
||||
using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters
|
||||
@@ -15,8 +15,6 @@ namespace AndDietCokeWebApi.Adapters
|
||||
private readonly IReportContract _reportContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
|
||||
public ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger logger)
|
||||
@@ -24,14 +22,6 @@ namespace AndDietCokeWebApi.Adapters
|
||||
_reportContract = reportContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<DishPriceReportDataModel, DishPriceReportViewModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>();
|
||||
cfg.CreateMap<OrderDishDataModel,OrderDishViewModel>();
|
||||
cfg.CreateMap<WorkerSalaryDataModel, WorkerSalaryViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentDishPricesByDishAsync(CancellationToken cancellationToken)
|
||||
@@ -61,7 +51,7 @@ namespace AndDietCokeWebApi.Adapters
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSalesByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), cancellationToken)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList());
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSalesByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), cancellationToken)).Select(x => CustomMapper.MapObject<SaleViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -88,7 +78,7 @@ namespace AndDietCokeWebApi.Adapters
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([..( await _reportContract.GetDataDishPricesAsync(cancellationToken)).Select(x=>_mapper.Map<DishPriceReportViewModel>(x))]);
|
||||
return ReportOperationResponse.OK([..( await _reportContract.GetDataDishPricesAsync(cancellationToken)).Select(x=> CustomMapper.MapObject<DishPriceReportViewModel>(x))]);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
@@ -138,7 +128,7 @@ namespace AndDietCokeWebApi.Adapters
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), cancellationToken)).Select(x => _mapper.Map<WorkerSalaryViewModel>(x)).ToList());
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), cancellationToken)).Select(x => CustomMapper.MapObject<WorkerSalaryViewModel>(x)).ToList());
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
|
||||
@@ -3,9 +3,9 @@ using AndDietCokeContracts.AdapterContracts.OperationResponses;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
@@ -13,29 +13,20 @@ namespace AndDietCokeWebApi.Adapters;
|
||||
internal class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SalaryAdapter> logger)
|
||||
{
|
||||
_salaryBusinessLogicContract = salaryBusinessLogicContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SalaryDataModel, SalaryViewModel>()
|
||||
.ForMember(x => x.SalaryDate, x => x.MapFrom(src => src.SalaryDate.ToLocalTime()));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
@@ -63,7 +54,7 @@ internal class SalaryAdapter : ISalaryAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), workerId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
|
||||
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), workerId).Select(x => CustomMapper.MapObject<SalaryViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
|
||||
@@ -4,9 +4,9 @@ using AndDietCokeContracts.BindingModels;
|
||||
using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Localization;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
@@ -17,29 +17,19 @@ internal class SaleAdapter : ISaleAdapter
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger)
|
||||
{
|
||||
_saleBusinessLogicContract = saleBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<SaleBindingModel, SaleDataModel>();
|
||||
cfg.CreateMap<SaleDataModel, SaleViewModel>()
|
||||
.ForMember(x => x.SaleDate, x => x.MapFrom(src => src.SaleDate.ToLocalTime()));
|
||||
cfg.CreateMap<OrderDishBindingModel, OrderDishDataModel>();
|
||||
cfg.CreateMap<OrderDishDataModel, OrderDishViewModel>();
|
||||
});
|
||||
_localizer = localizer;
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -62,7 +52,7 @@ internal class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -90,7 +80,7 @@ internal class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByBuyerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -118,7 +108,7 @@ internal class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByDishByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
|
||||
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByDishByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -146,7 +136,7 @@ internal class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
|
||||
return SaleOperationResponse.OK(CustomMapper.MapObject<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -179,8 +169,8 @@ internal class SaleAdapter : ISaleAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
var data = _mapper.Map<SaleDataModel>(saleModel);
|
||||
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
|
||||
var data = CustomMapper.MapObject<SaleDataModel>(saleModel);
|
||||
_saleBusinessLogicContract.InsertSale(CustomMapper.MapObject<SaleDataModel>(saleModel));
|
||||
return SaleOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
|
||||
@@ -5,40 +5,29 @@ using AndDietCokeContracts.BisnessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.ViewModels;
|
||||
using AutoMapper;
|
||||
using AndDietCokeContracts.Resources;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using AndDietCokeContracts.Mapper;
|
||||
|
||||
namespace AndDietCokeWebApi.Adapters;
|
||||
|
||||
internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
private readonly IWorkerBusinessLogicContract _buyerBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
private readonly IStringLocalizer<Messages> _localizer;
|
||||
public WorkerAdapter(IWorkerBusinessLogicContract workerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<WorkerAdapter> logger)
|
||||
{
|
||||
_buyerBusinessLogicContract = workerBusinessLogicContract;
|
||||
_logger = logger;
|
||||
_localizer = localizer;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
|
||||
cfg.CreateMap<WorkerDataModel, WorkerViewModel>()
|
||||
.ForMember(x => x.BirthDate, x => x.MapFrom(src => src.BirthDate.ToLocalTime()))
|
||||
.ForMember(x => x.EmploymentDate, x => x.MapFrom(src => src.EmploymentDate.ToLocalTime()));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public WorkerOperationResponse GetList(bool includeDeleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkers(!includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
@@ -56,7 +45,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
@@ -79,7 +68,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -102,7 +91,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
|
||||
return WorkerOperationResponse.OK([.. _buyerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -125,7 +114,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
return WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
|
||||
return WorkerOperationResponse.OK(CustomMapper.MapObject<WorkerViewModel>(_buyerBusinessLogicContract.GetWorkerByData(data)));
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
@@ -158,7 +147,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
_buyerBusinessLogicContract.InsertWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
@@ -192,7 +181,7 @@ internal class WorkerAdapter : IWorkerAdapter
|
||||
{
|
||||
try
|
||||
{
|
||||
_buyerBusinessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
|
||||
_buyerBusinessLogicContract.UpdateWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
|
||||
return WorkerOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
|
||||
Reference in New Issue
Block a user