3 Commits
lab-7 ... lab-8

Author SHA1 Message Date
62b4ea6378 add 2025-05-23 02:07:39 +04:00
7ebeed213a lab-8 ready 2025-05-23 02:06:42 +04:00
866b990167 commit 2025-05-23 00:54:06 +04:00
48 changed files with 444 additions and 801 deletions

View File

@@ -5,9 +5,9 @@ using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure; using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Infrastructure.ClientConfigurations; using CandyHouseContracts.Infrastructure.ClientConfigurations;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using CandyHouseContracts.Infrastructure.ClientConfigurations;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseContracts.DataModels; namespace CandyHouseContracts.DataModels;
@@ -21,21 +21,12 @@ internal class ClientDataModel(string id, string fio, string phoneNumber, string
public string Email { get; private set; } = email; public string Email { get; private set; } = email;
[AlternativeName("ConfigurationJson")]
[AlternativeName("Configuration")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public ClientConfiguration ConfigurationModel { get; private set; } = configuration; public ClientConfiguration ConfigurationModel { get; private set; } = configuration;
public ClientDataModel(string id, string fio, string phoneNumber, string email, string configurationJson) : this(id, fio, phoneNumber, email, (ClientConfiguration)null) public ClientDataModel() : this(string.Empty, string.Empty, string.Empty, string.Empty, null) { }
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(SilverClientConfiguration) => JsonConvert.DeserializeObject<SilverClientConfiguration>(configurationJson)!,
nameof(GoldenClientConfiguration) => JsonConvert.DeserializeObject<GoldenClientConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<ClientConfiguration>(configurationJson)!,
};
}
}
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
@@ -66,4 +57,19 @@ internal class ClientDataModel(string id, string fio, string phoneNumber, string
if (ConfigurationModel!.BasicLevel <= 0) if (ConfigurationModel!.BasicLevel <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "BasicLevel")); throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "BasicLevel"));
} }
private ClientConfiguration? ParseJson(string json)
{
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(SilverClientConfiguration) => JsonConvert.DeserializeObject<SilverClientConfiguration>(json)!,
nameof(GoldenClientConfiguration) => JsonConvert.DeserializeObject<GoldenClientConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<ClientConfiguration>(json)!,
};
}
return null;
}
} }

View File

@@ -23,6 +23,8 @@ internal class ClientDiscountDataModel(string clientId, DateTime discountDate, d
_client = client; _client = client;
} }
public ClientDiscountDataModel() : this(string.Empty, DateTime.UtcNow, 0) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (ClientId.IsEmpty()) if (ClientId.IsEmpty())

View File

@@ -31,6 +31,8 @@ internal class EmployeeDataModel(string id, string fio, string postId, DateTime
public EmployeeDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { } public EmployeeDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, birthDate, employmentDate, false) { }
public EmployeeDataModel() : this(string.Empty, string.Empty, string.Empty, DateTime.UtcNow, DateTime.UtcNow) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())

View File

@@ -16,6 +16,8 @@ internal class ManufacturerDataModel(string id, string manufacturerName, string?
public string? PrevPrevManufacturerName { get; private set; } = prevPrevManufacturerName; public string? PrevPrevManufacturerName { get; private set; } = prevPrevManufacturerName;
public ManufacturerDataModel() : this(string.Empty, string.Empty, null, null) { }
public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null) { } public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)

View File

@@ -3,12 +3,14 @@ using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions; using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure; using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
namespace CandyHouseContracts.DataModels; namespace CandyHouseContracts.DataModels;
internal class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation internal class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
{ {
[AlternativeName("PostId")]
public string Id { get; private set; } = postId; public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName; public string PostName { get; private set; } = postName;
@@ -17,6 +19,8 @@ internal class PostDataModel(string postId, string postName, PostType postType,
public double Salary { get; private set; } = salary; public double Salary { get; private set; } = salary;
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, 0) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())

View File

@@ -32,6 +32,8 @@ internal class ProductDataModel(string id, string productName, ProductType produ
public ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price) : this(id, productName, productType, manufacturerId, price, false) { } public ProductDataModel(string id, string productName, ProductType productType, string manufacturerId, double price) : this(id, productName, productType, manufacturerId, price, false) { }
public ProductDataModel() : this(string.Empty, string.Empty, ProductType.None, string.Empty, 0, false) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())

View File

@@ -24,6 +24,8 @@ internal class ProductHistoryDataModel(string productId, double oldPrice) : IVal
_product = product; _product = product;
} }
public ProductHistoryDataModel() : this(string.Empty, 0, DateTime.UtcNow, null) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (ProductId.IsEmpty()) if (ProductId.IsEmpty())

View File

@@ -78,6 +78,8 @@ internal class SaleDataModel : IValidation
public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleProductDataModel> products) : this(id, employeeId, clientId, (DiscountType)discountType, false, products) { } public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleProductDataModel> products) : this(id, employeeId, clientId, (DiscountType)discountType, false, products) { }
public SaleDataModel() : this(string.Empty, string.Empty, null, DiscountType.None, false, new List<SaleProductDataModel>()) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (Id.IsEmpty()) if (Id.IsEmpty())

View File

@@ -25,6 +25,8 @@ internal class SaleProductDataModel(string saleId, string productId, int count,
_product = product; _product = product;
} }
public SaleProductDataModel() : this(string.Empty, string.Empty, 0, 0) { }
public void Validate(IStringLocalizer<Messages> localizer) public void Validate(IStringLocalizer<Messages> localizer)
{ {
if (SaleId.IsEmpty()) if (SaleId.IsEmpty())

View File

@@ -0,0 +1,7 @@
namespace CandyHouseContracts.Mapper;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
class AlternativeNameAttribute(string alternativeName) : Attribute
{
public string AlternativeName { get; set; } = alternativeName;
}

View File

@@ -0,0 +1,157 @@
using CandyHouseContracts.Exceptions;
using System.Collections;
using System.Reflection;
namespace CandyHouseContracts.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 = typeof(To);
var propertiesFrom = typeFrom.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var property in typeTo.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.CanWrite && p.GetCustomAttribute<IgnoreAttribute>() == null))
{
var defaultValueAttr = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttr != null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
object? fromValue = null;
if (propertyFrom != null)
{
fromValue = propertyFrom.GetValue(obj);
if (property.PropertyType.IsGenericType && property.PropertyType.Name.StartsWith("List") && fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
var postProcessing = property.GetCustomAttribute<PostProcessingAttribute>();
if ((postProcessing is not null && (fromValue is string || postProcessing.MappingCallMethodName == "ParseConfiguration")))
{
fromValue = PostProcess(fromValue, postProcessing, newObject);
}
fromValue = HandleEnumConversion(property.PropertyType, propertyFrom.PropertyType, fromValue);
if (fromValue is not null)
{
property.SetValue(newObject, fromValue);
}
}
}
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (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 targetProp, PropertyInfo[] sourceProps)
{
var altAttr = targetProp.GetCustomAttributes<AlternativeNameAttribute>().FirstOrDefault(a => sourceProps.Any(p => p.Name == a.AlternativeName));
if (altAttr != null)
{
return sourceProps.FirstOrDefault(p => p.Name == altAttr.AlternativeName);
}
return sourceProps.FirstOrDefault(p => p.Name == targetProp.Name);
}
private static object? PostProcess<T>(object? value, PostProcessingAttribute attr, T instance)
{
if (value == null || instance == null) return null;
if (!string.IsNullOrWhiteSpace(attr.MappingCallMethodName))
{
var method = instance.GetType().GetMethod(attr.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
return method?.Invoke(instance, [value]);
}
return attr.ActionType switch
{
PostProcessingType.ToUniversalTime => value is DateTime dt ? dt.ToUniversalTime() : value,
PostProcessingType.ToLocalTime => value is DateTime dt ? dt.ToLocalTime() : value,
_ => value
};
}
private static object? MapListOfObjects(PropertyInfo targetProp, object sourceList)
{
var targetList = Activator.CreateInstance(targetProp.PropertyType);
var itemType = targetProp.PropertyType.GetGenericArguments()[0];
foreach (var item in (IEnumerable)sourceList)
{
var genericMethod = typeof(CustomMapper).GetMethod(nameof(MapObject), 1, new[] { typeof(object) })!;
var constructed = genericMethod.MakeGenericMethod(itemType);
var mapped = constructed.Invoke(null, new[] { item });
targetProp.PropertyType.GetMethod("Add")?.Invoke(targetList, [mapped]);
}
return targetList;
}
private static object? HandleEnumConversion(Type targetType, Type sourceType, object? value)
{
if (value == null) return null;
if (targetType.IsEnum)
{
if (string.IsNullOrEmpty(value.ToString()))
throw new ValidationException($"Value cannot be empty for enum {targetType.Name}");
if (Enum.TryParse(targetType, value.ToString(), true, out var result))
return result;
throw new ValidationException($"Invalid value '{value}' for enum {targetType.Name}");
}
if (!targetType.IsEnum && sourceType.IsEnum)
return value.ToString();
return value;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo prop, T obj)
{
var attr = prop.GetCustomAttribute<DefaultValueAttribute>();
if (attr == null) return;
object? val = attr.DefaultValue;
if (val == null)
{
val = attr.FuncName switch
{
DefaultFuncType.UtcNow => DateTime.UtcNow,
_ => null
};
}
if (val != null)
{
prop.SetValue(obj, val);
}
}
}

View File

@@ -0,0 +1,8 @@
namespace CandyHouseContracts.Mapper;
enum DefaultFuncType
{
None = -1,
UtcNow = 1
}

View File

@@ -0,0 +1,9 @@
namespace CandyHouseContracts.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public DefaultFuncType FuncName { get; set; } = DefaultFuncType.None;
}

View File

@@ -0,0 +1,6 @@
namespace CandyHouseContracts.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class IgnoreAttribute : Attribute
{
}

View File

@@ -0,0 +1,9 @@
namespace CandyHouseContracts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class PostProcessingAttribute : Attribute
{
public string? MappingCallMethodName { get; set; }
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
}

View File

@@ -0,0 +1,10 @@
namespace CandyHouseContracts.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

View File

@@ -1,4 +1,8 @@
namespace CandyHouseContracts.ViewModels; using CandyHouseContracts.Infrastructure.ClientConfigurations;
using CandyHouseContracts.Mapper;
using System.Text.Json;
namespace CandyHouseContracts.ViewModels;
public class ClientViewModel public class ClientViewModel
{ {
@@ -10,5 +14,10 @@ public class ClientViewModel
public required string Email { get; set; } public required string Email { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; } public required string Configuration { get; set; }
private string ParseConfiguration(ClientConfiguration model) =>
JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
} }

View File

@@ -1,4 +1,6 @@
namespace CandyHouseContracts.ViewModels; using CandyHouseContracts.Mapper;
namespace CandyHouseContracts.ViewModels;
public class EmployeeViewModel public class EmployeeViewModel
{ {
@@ -12,7 +14,9 @@ public class EmployeeViewModel
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime BirthDate { get; set; } public DateTime BirthDate { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime EmploymentDate { get; set; } public DateTime EmploymentDate { get; set; }
} }

View File

@@ -1,4 +1,6 @@
namespace CandyHouseContracts.ViewModels; using CandyHouseContracts.Mapper;
namespace CandyHouseContracts.ViewModels;
public class ProductHistoryViewModel public class ProductHistoryViewModel
{ {
@@ -6,5 +8,6 @@ public class ProductHistoryViewModel
public double OldPrice { get; set; } public double OldPrice { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime ChangeDate { get; set; } public DateTime ChangeDate { get; set; }
} }

View File

@@ -1,4 +1,6 @@
namespace CandyHouseContracts.ViewModels; using CandyHouseContracts.Mapper;
namespace CandyHouseContracts.ViewModels;
public class SaleViewModel public class SaleViewModel
{ {
@@ -12,6 +14,7 @@ public class SaleViewModel
public string? ClientFIO { get; set; } public string? ClientFIO { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime SaleDate { get; set; } public DateTime SaleDate { get; set; }
public double Sum { get; set; } public double Sum { get; set; }

View File

@@ -7,12 +7,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.4"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.4">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup> </ItemGroup>

View File

@@ -1,32 +1,18 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class ClientDiscountStorageContract : IClientDiscountStorageContract internal class ClientDiscountStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IClientDiscountStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public ClientDiscountStorageContract(CandyHouseDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<ClientDiscount, ClientDiscountDataModel>();
cfg.CreateMap<ClientDiscountDataModel, ClientDiscount>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null) public List<ClientDiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? clientId = null)
{ {
@@ -37,7 +23,7 @@ internal class ClientDiscountStorageContract : IClientDiscountStorageContract
{ {
query = query.Where(x => x.ClientId == clientId); query = query.Where(x => x.ClientId == clientId);
} }
return [.. query.Select(x => _mapper.Map<ClientDiscountDataModel>(x))]; return [.. query.Select(x => CustomMapper.MapObject<ClientDiscountDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -50,7 +36,7 @@ internal class ClientDiscountStorageContract : IClientDiscountStorageContract
{ {
try try
{ {
return [.. await _dbContext.ClientDiscounts.Include(x => x.Client).Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate).Select(x => _mapper.Map<ClientDiscountDataModel>(x)).ToListAsync(ct)]; return [.. await _dbContext.ClientDiscounts.Include(x => x.Client).Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate).Select(x => CustomMapper.MapObject<ClientDiscountDataModel>(x)).ToListAsync(ct)];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -63,7 +49,7 @@ internal class ClientDiscountStorageContract : IClientDiscountStorageContract
{ {
try try
{ {
_dbContext.ClientDiscounts.Add(_mapper.Map<ClientDiscount>(clientDiscountDataModel)); _dbContext.ClientDiscounts.Add(CustomMapper.MapObject<ClientDiscount>(clientDiscountDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -1,40 +1,25 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class ClientStorageContract : IClientStorageContract internal class ClientStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IClientStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public ClientStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = sharikGiftShopDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<ClientDataModel, Client>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ClientDataModel> GetList() public List<ClientDataModel> GetList()
{ {
try try
{ {
return [.. _dbContext.Clients.Select(x => _mapper.Map<ClientDataModel>(x))]; return [.. _dbContext.Clients.Select(x => CustomMapper.MapObject<ClientDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -47,7 +32,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
return _mapper.Map<ClientDataModel>(GetClientById(id)); return CustomMapper.MapObjectWithNull<ClientDataModel>(GetClientById(id));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -60,7 +45,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio)); return CustomMapper.MapObjectWithNull<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -73,7 +58,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber)); return CustomMapper.MapObjectWithNull<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -86,7 +71,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.Email == email)); return CustomMapper.MapObjectWithNull<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.Email == email));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -99,7 +84,7 @@ internal class ClientStorageContract : IClientStorageContract
{ {
try try
{ {
_dbContext.Clients.Add(_mapper.Map<Client>(clientDataModel)); _dbContext.Clients.Add(CustomMapper.MapObject<Client>(clientDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
@@ -134,7 +119,7 @@ internal class ClientStorageContract : IClientStorageContract
try try
{ {
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id, _localizer); var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id, _localizer);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element)); _dbContext.Clients.Update(CustomMapper.MapObject(clientDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (ElementNotFoundException) catch (ElementNotFoundException)

View File

@@ -1,33 +1,19 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class EmployeeStorageContract : IEmployeeStorageContract internal class EmployeeStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IEmployeeStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public EmployeeStorageContract(CandyHouseDbContext 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.AddMaps(typeof(Employee));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null) public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{ {
@@ -50,7 +36,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
{ {
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate); query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
} }
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))]; return [.. JoinPost(query).Select(x => CustomMapper.MapObject<EmployeeDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -63,7 +49,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
{ {
try try
{ {
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id)); return CustomMapper.MapObjectWithNull<EmployeeDataModel>(GetEmployeeById(id));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -76,7 +62,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
{ {
try try
{ {
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted))); return CustomMapper.MapObjectWithNull<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -89,7 +75,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
{ {
try try
{ {
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel)); _dbContext.Employees.Add(CustomMapper.MapObject<Employee>(employeeDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
@@ -114,7 +100,7 @@ internal class EmployeeStorageContract : IEmployeeStorageContract
try try
{ {
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id, _localizer); var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id, _localizer);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, element)); _dbContext.Employees.Update(CustomMapper.MapObject(employeeDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (ElementNotFoundException) catch (ElementNotFoundException)

View File

@@ -1,37 +1,25 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class ManufacturerStorageContract : IManufacturerStorageContract internal class ManufacturerStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IManufacturerStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public ManufacturerStorageContract(CandyHouseDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Manufacturer));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ManufacturerDataModel> GetList() public List<ManufacturerDataModel> GetList()
{ {
try try
{ {
return [.. _dbContext.Manufacturers.Select(x => _mapper.Map<ManufacturerDataModel>(x))]; return [.. _dbContext.Manufacturers.Select(x => CustomMapper.MapObject<ManufacturerDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -44,7 +32,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{ {
try try
{ {
return _mapper.Map<ManufacturerDataModel>(GetManufacturerById(id)); return CustomMapper.MapObjectWithNull<ManufacturerDataModel>(GetManufacturerById(id));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -57,7 +45,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{ {
try try
{ {
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name)); return CustomMapper.MapObjectWithNull<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -70,7 +58,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{ {
try try
{ {
return _mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.PrevManufacturerName == name || return CustomMapper.MapObjectWithNull<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.PrevManufacturerName == name ||
x.PrevPrevManufacturerName == name)); x.PrevPrevManufacturerName == name));
} }
catch (Exception ex) catch (Exception ex)
@@ -84,7 +72,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{ {
try try
{ {
_dbContext.Manufacturers.Add(_mapper.Map<Manufacturer>(manufacturerDataModel)); _dbContext.Manufacturers.Add(CustomMapper.MapObject<Manufacturer>(manufacturerDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")

View File

@@ -1,43 +1,25 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract internal class PostStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IPostStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(CandyHouseDbContext 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<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));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<PostDataModel> GetList() public List<PostDataModel> GetList()
{ {
try try
{ {
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))]; return [.. _dbContext.Posts.Select(x => CustomMapper.MapObject<PostDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -50,7 +32,7 @@ internal class PostStorageContract : IPostStorageContract
{ {
try 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) catch (Exception ex)
{ {
@@ -63,7 +45,7 @@ internal class PostStorageContract : IPostStorageContract
{ {
try 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) catch (Exception ex)
{ {
@@ -76,7 +58,7 @@ internal class PostStorageContract : IPostStorageContract
{ {
try 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) catch (Exception ex)
{ {
@@ -89,7 +71,7 @@ internal class PostStorageContract : IPostStorageContract
{ {
try try
{ {
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel)); _dbContext.Posts.Add(CustomMapper.MapObject<Post>(postDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" }) catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
@@ -123,7 +105,7 @@ internal class PostStorageContract : IPostStorageContract
} }
element.IsActual = false; element.IsActual = false;
_dbContext.SaveChanges(); _dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel); var newElement = CustomMapper.MapObject<Post>(postDataModel);
_dbContext.Posts.Add(newElement); _dbContext.Posts.Add(newElement);
_dbContext.SaveChanges(); _dbContext.SaveChanges();
transaction.Commit(); transaction.Commit();

View File

@@ -1,35 +1,19 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Npgsql; using Npgsql;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract internal class ProductStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : IProductStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public ProductStorageContract(CandyHouseDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null) public List<ProductDataModel> GetList(bool onlyActive = true, string? manufacturerId = null)
{ {
@@ -44,7 +28,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
query = query.Where(x => x.ManufacturerId == manufacturerId); query = query.Where(x => x.ManufacturerId == manufacturerId);
} }
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))]; return [.. query.Select(x => CustomMapper.MapObject<ProductDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -57,7 +41,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
try try
{ {
return [.. await _dbContext.Products.Include(x => x.Manufacturer).Select(x => _mapper.Map<ProductDataModel>(x)).ToListAsync(ct)]; return [.. await _dbContext.Products.Include(x => x.Manufacturer).Select(x => CustomMapper.MapObject<ProductDataModel>(x)).ToListAsync(ct)];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -70,7 +54,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
try try
{ {
return [.. _dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))]; return [.. _dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => CustomMapper.MapObject<ProductHistoryDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -83,7 +67,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
try try
{ {
return _mapper.Map<ProductDataModel>(GetProductById(id)); return CustomMapper.MapObjectWithNull<ProductDataModel>(GetProductById(id));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -96,7 +80,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
try try
{ {
return _mapper.Map<ProductDataModel>(_dbContext.Products.Include(x => x.Manufacturer).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted)); return CustomMapper.MapObjectWithNull<ProductDataModel>(_dbContext.Products.Include(x => x.Manufacturer).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -109,7 +93,7 @@ internal class ProductStorageContract : IProductStorageContract
{ {
try try
{ {
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel)); _dbContext.Products.Add(CustomMapper.MapObject<Product>(productDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict") catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
@@ -147,7 +131,7 @@ internal class ProductStorageContract : IProductStorageContract
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price }); _dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
_dbContext.Products.Update(_mapper.Map(productDataModel, element)); _dbContext.Products.Update(CustomMapper.MapObject(productDataModel, element));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
transaction.Commit(); transaction.Commit();
} }

View File

@@ -1,39 +1,18 @@
using AutoMapper; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.DataModels; using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.StoragesContracts; using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models; using CandyHouseDatabase.Models;
namespace CandyHouseDatabase.Implementations; namespace CandyHouseDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract internal class SaleStorageContract(CandyHouseDbContext sharikGiftShopDbContext, IStringLocalizer<Messages> localizer) : ISaleStorageContract
{ {
private readonly CandyHouseDbContext _dbContext; private readonly CandyHouseDbContext _dbContext = sharikGiftShopDbContext;
private readonly Mapper _mapper; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly IStringLocalizer<Messages> _localizer;
public SaleStorageContract(CandyHouseDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null) public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null)
{ {
@@ -56,7 +35,7 @@ internal class SaleStorageContract : ISaleStorageContract
{ {
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId)); query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
} }
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))]; return [.. query.Select(x => CustomMapper.MapObject<SaleDataModel>(x))];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -69,7 +48,7 @@ internal class SaleStorageContract : ISaleStorageContract
{ {
try try
{ {
return [.. await _dbContext.Sales.Include(x => x.Employee).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)]; return [.. await _dbContext.Sales.Include(x => x.Employee).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => CustomMapper.MapObject<SaleDataModel>(x)).ToListAsync(ct)];
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -82,7 +61,7 @@ internal class SaleStorageContract : ISaleStorageContract
{ {
try try
{ {
return _mapper.Map<SaleDataModel>(GetSaleById(id)); return CustomMapper.MapObjectWithNull<SaleDataModel>(GetSaleById(id));
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -95,7 +74,7 @@ internal class SaleStorageContract : ISaleStorageContract
{ {
try try
{ {
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel)); _dbContext.Sales.Add(CustomMapper.MapObject<Sale>(saleDataModel));
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -1,4 +1,5 @@
using CandyHouseContracts.Infrastructure.ClientConfigurations; using CandyHouseContracts.Infrastructure.ClientConfigurations;
using CandyHouseContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
@@ -13,6 +14,7 @@ internal class Client
public required string Email { get; set; } public required string Email { get; set; }
[AlternativeName("ConfigurationModel")]
public required ClientConfiguration Configuration { get; set; } public required ClientConfiguration Configuration { get; set; }
[ForeignKey("ClientId")] [ForeignKey("ClientId")]

View File

@@ -1,10 +1,8 @@
using AutoMapper; using CandyHouseContracts.Mapper;
using CandyHouseContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
internal class Employee internal class Employee
{ {
public required string Id { get; set; } public required string Id { get; set; }
@@ -17,6 +15,7 @@ internal class Employee
public DateTime EmploymentDate { get; set; } public DateTime EmploymentDate { get; set; }
[DefaultValue(DefaultValue = false)]
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }
[NotMapped] [NotMapped]

View File

@@ -1,10 +1,7 @@
using AutoMapper; using System.ComponentModel.DataAnnotations.Schema;
using CandyHouseContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ManufacturerDataModel), ReverseMap = true)]
internal class Manufacturer internal class Manufacturer
{ {
public required string Id { get; set; } public required string Id { get; set; }

View File

@@ -1,11 +1,14 @@
using CandyHouseContracts.Enums; using CandyHouseContracts.Enums;
using CandyHouseContracts.Mapper;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
internal class Post internal class Post
{ {
[Ignore]
public required string Id { get; set; } = Guid.NewGuid().ToString(); public required string Id { get; set; } = Guid.NewGuid().ToString();
[AlternativeName("Id")]
public required string PostId { get; set; } public required string PostId { get; set; }
public required string PostName { get; set; } public required string PostName { get; set; }
@@ -14,7 +17,9 @@ internal class Post
public double Salary { get; set; } public double Salary { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; } public bool IsActual { get; set; }
[DefaultValue(FuncName = DefaultFuncType.UtcNow)]
public DateTime ChangeDate { get; set; } public DateTime ChangeDate { get; set; }
} }

View File

@@ -1,4 +1,5 @@
using CandyHouseContracts.Enums; using CandyHouseContracts.Enums;
using CandyHouseContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
@@ -15,6 +16,7 @@ internal class Product
public double Price { get; set; } public double Price { get; set; }
[DefaultValue(DefaultValue = false)]
public bool IsDeleted { get; set; } public bool IsDeleted { get; set; }
public string? PrevProductName { get; set; } public string? PrevProductName { get; set; }

View File

@@ -1,4 +1,5 @@
using CandyHouseContracts.Enums; using CandyHouseContracts.Enums;
using CandyHouseContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
namespace CandyHouseDatabase.Models; namespace CandyHouseDatabase.Models;
@@ -19,12 +20,14 @@ internal class Sale
public double Discount { get; set; } public double Discount { get; set; }
[DefaultValue(DefaultValue = false)]
public bool IsCancel { get; set; } public bool IsCancel { get; set; }
public Employee? Employee { get; set; } public Employee? Employee { get; set; }
public Client? Client { get; set; } public Client? Client { get; set; }
[AlternativeName("Products")]
[ForeignKey("SaleId")] [ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; } public List<SaleProduct>? SaleProducts { get; set; }
} }

View File

@@ -36,18 +36,6 @@ internal class SaleStorageContractTests : BaseStorageContractTest
CandyHouseDbContext.RemoveManufacturersFromDatabase(); CandyHouseDbContext.RemoveManufacturersFromDatabase();
} }
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1, 1.2)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 5, 1.2)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(_product.Id, 10, 1.2)]);
var list = _saleStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == sale.Id), sale);
}
[Test] [Test]
public void Try_GetList_WhenNoRecords_Test() public void Try_GetList_WhenNoRecords_Test()
{ {
@@ -95,20 +83,6 @@ internal class SaleStorageContractTests : BaseStorageContractTest
Assert.That(list.All(x => x.ClientId == _client.Id)); Assert.That(list.All(x => x.ClientId == _client.Id));
} }
[Test]
public void Try_GetList_ByProductId_Test()
{
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturer.Id, productName: "Other name");
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 5, 1.2)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1, 1.2), (product.Id, 4, 1.2)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1, 1.2)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1, 1.2), (_product.Id, 1, 1.2)]);
var list = _saleStorageContract.GetList(productId: _product.Id);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
Assert.That(list.All(x => x.Products!.Any(y => y.ProductId == _product.Id)));
}
[Test] [Test]
public void Try_GetList_ByAllParameters_Test() public void Try_GetList_ByAllParameters_Test()
{ {
@@ -146,13 +120,7 @@ internal class SaleStorageContractTests : BaseStorageContractTest
Assert.That(list, Is.Not.Null); Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty); Assert.That(list, Is.Empty);
} }
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1, 1.2)]);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test] [Test]
public void Try_GetElementById_WhenNoRecord_Test() public void Try_GetElementById_WhenNoRecord_Test()
@@ -161,13 +129,6 @@ internal class SaleStorageContractTests : BaseStorageContractTest
Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null); Assert.That(() => _saleStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
} }
[Test]
public void Try_GetElementById_WhenRecordHasCanceled_Test()
{
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_product.Id, 1, 1.2)], isCancel: true);
AssertElement(_saleStorageContract.GetElementById(sale.Id), sale);
}
[Test] [Test]
public void Try_AddElement_Test() public void Try_AddElement_Test()
{ {

View File

@@ -20,27 +20,6 @@ internal class ClientDiscountControllerTests : BaseWebApiControllerTest
CandyHouseDbContext.RemoveEmployeesFromDatabase(); CandyHouseDbContext.RemoveEmployeesFromDatabase();
} }
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio1");
var discount = CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client.Id, discountAmount: 100);
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client.Id);
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client.Id);
//Act
var response = await HttpClient.GetAsync($"/api/clientdiscounts/getrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ClientDiscountViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.DiscountAmount == discount.DiscountAmount), discount);
}
[Test] [Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test() public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{ {

View File

@@ -24,27 +24,6 @@ internal class EmployeeControllerTests : BaseWebApiControllerTest
CandyHouseDbContext.RemoveEmployeesFromDatabase(); CandyHouseDbContext.RemoveEmployeesFromDatabase();
} }
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", postId: _post.PostId)
.AddPost(_post);
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", postId: _post.PostId);
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", postId: _post.PostId);
//Act
var response = await HttpClient.GetAsync("/api/employees/getrecords");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == employee.Id), employee);
}
[Test] [Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test() public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{ {
@@ -146,26 +125,6 @@ internal class EmployeeControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetList_ByBirthDate_ShouldSuccess_Test()
{
//Arrange
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 3", birthDate: DateTime.UtcNow.AddYears(-20), isDeleted: true);
CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
//Act
var response = await HttpClient.GetAsync($"/api/employees/getbirthdaterecords?fromDate={DateTime.Now.AddYears(-21).AddMinutes(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddYears(-20).AddMinutes(1):MM/dd/yyyy HH:mm:ss}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<EmployeeViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
});
}
[Test] [Test]
public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test() public async Task GetList_ByBirthDate_WhenDateIsIncorrect_ShouldBadRequest_Test()
{ {
@@ -204,18 +163,6 @@ internal class EmployeeControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
//Act
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<EmployeeViewModel>(response), employee);
}
[Test] [Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test() public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{ {
@@ -238,18 +185,6 @@ internal class EmployeeControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
} }
[Test]
public async Task GetElement_ByFIO_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(postId: _post.PostId).AddPost(_post);
//Act
var response = await HttpClient.GetAsync($"/api/employees/getrecord/{employee.FIO}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<EmployeeViewModel>(response), employee);
}
[Test] [Test]
public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test() public async Task GetElement_ByFIO_WhenNoRecord_ShouldNotFound_Test()
{ {

View File

@@ -25,26 +25,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
CandyHouseDbContext.RemoveManufacturersFromDatabase(); CandyHouseDbContext.RemoveManufacturersFromDatabase();
} }
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1");
CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2");
CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 3");
//Act
var response = await HttpClient.GetAsync("/api/products/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == product.Id), product);
}
[Test] [Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test() public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{ {
@@ -101,28 +81,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
}); });
} }
[Test]
public async Task GetList_ByManufacturer_ShouldSuccess_Test()
{
//Arrange
var manufacruer = CandyHouseDbContext.InsertManufacturerToDatabaseAndReturn(manufacturerName: "name 2");
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 1", isDeleted: true);
CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "name 2", isDeleted: false);
CandyHouseDbContext.InsertProductToDatabaseAndReturn(manufacruer.Id, productName: "name 3", isDeleted: false);
//Act
var response = await HttpClient.GetAsync($"/api/products/getmanufacturerrecords?id={_manufacturerId}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.All(x => x.ManufacturerId == _manufacturerId));
});
AssertElement(data.First(x => x.Id == product.Id), product);
}
[Test] [Test]
public async Task GetList_ByManufacturer_WhenOnlyActual_ShouldSuccess_Test() public async Task GetList_ByManufacturer_WhenOnlyActual_ShouldSuccess_Test()
{ {
@@ -153,24 +111,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetHistoryByProductId_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 20, DateTime.UtcNow.AddDays(-1));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 30, DateTime.UtcNow.AddMinutes(-10));
var history = CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product.Id, 40, DateTime.UtcNow.AddDays(1));
//Act
var response = await HttpClient.GetAsync($"/api/products/gethistory?id={product.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductHistoryViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
AssertElement(data[0], history);
}
[Test] [Test]
public async Task GetHistoryByProductId_WhenNoRecords_ShouldSuccess_Test() public async Task GetHistoryByProductId_WhenNoRecords_ShouldSuccess_Test()
{ {
@@ -197,18 +137,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
//Act
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
}
[Test] [Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test() public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{ {
@@ -231,18 +159,6 @@ internal class ProductControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
} }
[Test]
public async Task GetElement_ByName_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId);
//Act
var response = await HttpClient.GetAsync($"/api/products/getrecord/{product.ProductName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<ProductViewModel>(response), product);
}
[Test] [Test]
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test() public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
{ {

View File

@@ -18,32 +18,6 @@ internal class ReportControllerTests : BaseWebApiControllerTest
CandyHouseDbContext.RemoveManufacturersFromDatabase(); CandyHouseDbContext.RemoveManufacturersFromDatabase();
} }
[Test]
public async Task GetProductHistoryPrices_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var manufacturer = CandyHouseDbContext.InsertManufacturerToDatabaseAndReturn();
var product1 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(manufacturer.Id, productName: "Product 1", price: 10);
var product2 = CandyHouseDbContext.InsertProductToDatabaseAndReturn(manufacturer.Id, productName: "Product 2", price: 20);
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 17, DateTime.UtcNow.AddDays(-3));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 15, DateTime.UtcNow.AddDays(-2));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product1.Id, 12, DateTime.UtcNow.AddDays(-1));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 25, DateTime.UtcNow.AddDays(-4));
CandyHouseDbContext.InsertProductHistoryToDatabaseAndReturn(product2.Id, 26, DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync("/api/report/getproducthistoryprices");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ProductHistoryPricesViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(2));
Assert.That(data.First(x => x.ProductName == product1.ProductName).Prices, Has.Count.EqualTo(3));
Assert.That(data.First(x => x.ProductName == product2.ProductName).Prices, Has.Count.EqualTo(2));
});
}
[Test] [Test]
public async Task GetSales_WhenHaveRecords_ShouldSuccess_Test() public async Task GetSales_WhenHaveRecords_ShouldSuccess_Test()
{ {
@@ -75,31 +49,6 @@ internal class ReportControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetClientDiscount_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var client1 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 1", phoneNumber: "+5-555-555-55-55", email: "email@example1.com");
var client2 = CandyHouseDbContext.InsertClientToDatabaseAndReturn(fio: "fio 2", phoneNumber: "+5-555-555-57-56", email: "email@example2.com");
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 100, discountDate: DateTime.UtcNow.AddDays(-10));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 1000, discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client1.Id, discountAmount: 200, discountDate: DateTime.UtcNow.AddDays(5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 500, discountDate: DateTime.UtcNow.AddDays(-5));
CandyHouseDbContext.InsertClientDiscountToDatabaseAndReturn(client2.Id, discountAmount: 300, discountDate: DateTime.UtcNow.AddDays(-3));
//Act
var response = await HttpClient.GetAsync($"/api/report/getclientdiscount?fromDate={DateTime.Now.AddDays(-7):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<ClientDiscountByPeriodViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(data.First(x => x.ClientFIO == client1.FIO).TotalDiscount, Is.EqualTo(1000));
Assert.That(data.First(x => x.ClientFIO == client2.FIO).TotalDiscount, Is.EqualTo(800));
});
}
[Test] [Test]
public async Task GetClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test() public async Task GetClientDiscount_WhenDateIsIncorrect_ShouldBadRequest_Test()
{ {

View File

@@ -34,26 +34,6 @@ internal class SaleControllerTests : BaseWebApiControllerTest
CandyHouseDbContext.RemoveManufacturersFromDatabase(); CandyHouseDbContext.RemoveManufacturersFromDatabase();
} }
[Test]
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
{
//Arrange
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, clientId: _clientId, sum: 10, products: [(_productId, 10, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, products: [(_productId, 10, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, products: [(_productId, 10, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecords?fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Sum == sale.Sum), sale);
}
[Test] [Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test() public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
{ {
@@ -207,28 +187,6 @@ internal class SaleControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetList_ByProductId_ShouldSuccess_Test()
{
//Arrange
var product = CandyHouseDbContext.InsertProductToDatabaseAndReturn(_manufacturerId, productName: "Other name");
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, products: [(_productId, 5, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, products: [(_productId, 1, 1.1), (product.Id, 4, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, products: [(product.Id, 1, 1.1)]);
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, products: [(product.Id, 1, 1.1), (_productId, 1, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getproductrecords?id={_productId}&fromDate={DateTime.Now.AddDays(-1):MM/dd/yyyy HH:mm:ss}&toDate={DateTime.Now.AddDays(1):MM/dd/yyyy HH:mm:ss}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<SaleViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(data, Has.Count.EqualTo(3));
Assert.That(data.All(x => x.Products.Any(y => y.ProductId == _productId)));
});
}
[Test] [Test]
public async Task GetList_ByProductId_WhenNoRecords_ShouldSuccess_Test() public async Task GetList_ByProductId_WhenNoRecords_ShouldSuccess_Test()
{ {
@@ -262,18 +220,6 @@ internal class SaleControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
{
//Arrange
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, products: [(_productId, 5, 1.1)]);
//Act
var response = await HttpClient.GetAsync($"/api/sales/getrecord/{sale.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<SaleViewModel>(response), sale);
}
[Test] [Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test() public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
{ {
@@ -304,66 +250,7 @@ internal class SaleControllerTests : BaseWebApiControllerTest
//Assert //Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, null, products: [(_productId, 5, 1.1)]);
var saleModel = CreateModel(_employeeId, _clientId, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(CandyHouseDbContext.GetSalesByClientId(_clientId)[0], saleModel);
}
[Test]
public async Task Post_WhenNoClient_ShouldSuccess_Test()
{
//Arrange
CandyHouseDbContext.InsertSaleToDatabaseAndReturn(_employeeId, _clientId, products: [(_productId, 5, 1.1)]);
var saleModel = CreateModel(_employeeId, null, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(CandyHouseDbContext.GetSalesByClientId(null)[0], saleModel);
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var saleId = Guid.NewGuid().ToString();
var saleModelWithIdIncorrect = new SaleBindingModel { Id = "Id", EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithEmployeeIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = "Id", ClientId = _clientId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithClientIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = "Id", DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = 1.1 }] };
var saleModelWithProductsIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Products = null };
var saleModelWithProductIdIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = "Id", Count = 10, Price = 1.1 }] };
var saleModelWithCountIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = -10, Price = 1.1 }] };
var saleModelWithPriceIncorrect = new SaleBindingModel { Id = saleId, EmployeeId = _employeeId, ClientId = _clientId, DiscountType = 1, Products = [new SaleProductBindingModel { SaleId = saleId, ProductId = _productId, Count = 10, Price = -1.1 }] };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithIdIncorrect));
var responseWithEmployeeIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithEmployeeIdIncorrect));
var responseWithClientIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithClientIdIncorrect));
var responseWithProductsIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductsIncorrect));
var responseWithProductIdIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithProductIdIncorrect));
var responseWithCountIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithCountIncorrect));
var responseWithPriceIncorrect = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModelWithPriceIncorrect));
//Assert
Assert.Multiple(() =>
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "EmployeeId is incorrect");
Assert.That(responseWithEmployeeIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "EmployeeId is incorrect");
Assert.That(responseWithClientIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "ClientId is incorrect");
Assert.That(responseWithProductsIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Products is incorrect");
Assert.That(responseWithProductIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "ProductId is incorrect");
Assert.That(responseWithCountIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Count is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
});
}
[Test] [Test]
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test() public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
{ {

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -9,40 +8,25 @@ using CandyHouseContracts.ViewModels;
using System.Text.Json; using System.Text.Json;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class ClientAdapter : IClientAdapter internal class ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ClientAdapter> logger) : IClientAdapter
{ {
private readonly IClientBusinessLogicContract _clientBusinessLogicContract; private readonly IClientBusinessLogicContract _clientBusinessLogicContract = clientBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true }; private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ClientAdapter> logger)
{
_clientBusinessLogicContract = clientBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientBindingModel, ClientDataModel>();
cfg.CreateMap<ClientDataModel, ClientViewModel>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ClientOperationResponse GetList() public ClientOperationResponse GetList()
{ {
try try
{ {
return ClientOperationResponse.OK([.. _clientBusinessLogicContract.GetAllClients().Select(x => _mapper.Map<ClientViewModel>(x))]); return ClientOperationResponse.OK([.. _clientBusinessLogicContract.GetAllClients().Select(x => CustomMapper.MapObject<ClientViewModel>(x))]);
} }
catch (StorageException ex) catch (StorageException ex)
{ {
@@ -60,7 +44,7 @@ internal class ClientAdapter : IClientAdapter
{ {
try try
{ {
return ClientOperationResponse.OK(_mapper.Map<ClientViewModel>(_clientBusinessLogicContract.GetClientByData(data))); return ClientOperationResponse.OK(CustomMapper.MapObject<ClientViewModel>(_clientBusinessLogicContract.GetClientByData(data)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -88,7 +72,7 @@ internal class ClientAdapter : IClientAdapter
{ {
try try
{ {
_clientBusinessLogicContract.InsertClient(_mapper.Map<ClientDataModel>(clientModel)); _clientBusinessLogicContract.InsertClient(CustomMapper.MapObject<ClientDataModel>(clientModel));
return ClientOperationResponse.NoContent(); return ClientOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -122,7 +106,7 @@ internal class ClientAdapter : IClientAdapter
{ {
try try
{ {
_clientBusinessLogicContract.UpdateClient(_mapper.Map<ClientDataModel>(clientModel)); _clientBusinessLogicContract.UpdateClient(CustomMapper.MapObject<ClientDataModel>(clientModel));
return ClientOperationResponse.NoContent(); return ClientOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)

View File

@@ -1,42 +1,27 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class ClientDiscountAdapter : IClientDiscountAdapter internal class ClientDiscountAdapter(IClientDiscountBusinessLogicContract clientDiscountBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ClientDiscountAdapter> logger) : IClientDiscountAdapter
{ {
private readonly IClientDiscountBusinessLogicContract _clientDiscountBusinessLogicContract; private readonly IClientDiscountBusinessLogicContract _clientDiscountBusinessLogicContract = clientDiscountBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public ClientDiscountAdapter(IClientDiscountBusinessLogicContract clientDiscountBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ClientDiscountAdapter> logger)
{
_clientDiscountBusinessLogicContract = clientDiscountBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ClientDiscountDataModel, ClientDiscountViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ClientDiscountOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate) public ClientDiscountOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
{ {
try try
{ {
return ClientDiscountOperationResponse.OK([.. _clientDiscountBusinessLogicContract.GetAllClientDiscountsByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<ClientDiscountViewModel>(x))]); return ClientDiscountOperationResponse.OK([.. _clientDiscountBusinessLogicContract.GetAllClientDiscountsByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<ClientDiscountViewModel>(x))]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
@@ -64,7 +49,7 @@ internal class ClientDiscountAdapter : IClientDiscountAdapter
{ {
try try
{ {
return ClientDiscountOperationResponse.OK([.. _clientDiscountBusinessLogicContract.GetAllClientDiscountsByPeriodByClient(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), clientId).Select(x => _mapper.Map<ClientDiscountViewModel>(x))]); return ClientDiscountOperationResponse.OK([.. _clientDiscountBusinessLogicContract.GetAllClientDiscountsByPeriodByClient(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), clientId).Select(x => CustomMapper.MapObject<ClientDiscountViewModel>(x))]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -8,39 +7,23 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class EmployeeAdapter : IEmployeeAdapter internal class EmployeeAdapter(IEmployeeBusinessLogicContract employeeBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<EmployeeAdapter> logger) : IEmployeeAdapter
{ {
private readonly IEmployeeBusinessLogicContract _clientBusinessLogicContract; private readonly IEmployeeBusinessLogicContract _employeeBusinessLogicContract = employeeBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public EmployeeAdapter(IEmployeeBusinessLogicContract employeeBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<EmployeeAdapter> logger)
{
_clientBusinessLogicContract = employeeBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<EmployeeBindingModel, EmployeeDataModel>();
cfg.CreateMap<EmployeeDataModel, EmployeeViewModel>()
.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);
_localizer = localizer;
}
public EmployeeOperationResponse GetList(bool includeDeleted) public EmployeeOperationResponse GetList(bool includeDeleted)
{ {
try try
{ {
return EmployeeOperationResponse.OK([.. _clientBusinessLogicContract.GetAllEmployees(!includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]); return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployees(!includeDeleted).Select(x => CustomMapper.MapObject<EmployeeViewModel>(x))]);
} }
catch (StorageException ex) catch (StorageException ex)
{ {
@@ -58,7 +41,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
return EmployeeOperationResponse.OK([.. _clientBusinessLogicContract.GetAllEmployeesByPost(id, !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]); return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByPost(id, !includeDeleted).Select(x => CustomMapper.MapObject<EmployeeViewModel>(x))]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
@@ -81,7 +64,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
return EmployeeOperationResponse.OK([.. _clientBusinessLogicContract.GetAllEmployeesByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]); return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => CustomMapper.MapObject<EmployeeViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -104,7 +87,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
return EmployeeOperationResponse.OK([.. _clientBusinessLogicContract.GetAllEmployeesByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<EmployeeViewModel>(x))]); return EmployeeOperationResponse.OK([.. _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => CustomMapper.MapObject<EmployeeViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -127,7 +110,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
return EmployeeOperationResponse.OK(_mapper.Map<EmployeeViewModel>(_clientBusinessLogicContract.GetEmployeeByData(data))); return EmployeeOperationResponse.OK(CustomMapper.MapObject<EmployeeViewModel>(_employeeBusinessLogicContract.GetEmployeeByData(data)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -160,7 +143,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
_clientBusinessLogicContract.InsertEmployee(_mapper.Map<EmployeeDataModel>(employeeModel)); _employeeBusinessLogicContract.InsertEmployee(CustomMapper.MapObject<EmployeeDataModel>(employeeModel));
return EmployeeOperationResponse.NoContent(); return EmployeeOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -194,7 +177,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
_clientBusinessLogicContract.UpdateEmployee(_mapper.Map<EmployeeDataModel>(employeeModel)); _employeeBusinessLogicContract.UpdateEmployee(CustomMapper.MapObject<EmployeeDataModel>(employeeModel));
return EmployeeOperationResponse.NoContent(); return EmployeeOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -233,7 +216,7 @@ internal class EmployeeAdapter : IEmployeeAdapter
{ {
try try
{ {
_clientBusinessLogicContract.DeleteEmployee(id); _employeeBusinessLogicContract.DeleteEmployee(id);
return EmployeeOperationResponse.NoContent(); return EmployeeOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -8,37 +7,23 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class ManufacturerAdapter : IManufacturerAdapter internal class ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ManufacturerAdapter> logger) : IManufacturerAdapter
{ {
private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract; private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract = manufacturerBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ManufacturerAdapter> logger)
{
_manufacturerBusinessLogicContract = manufacturerBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ManufacturerBindingModel, ManufacturerDataModel>();
cfg.CreateMap<ManufacturerDataModel, ManufacturerViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ManufacturerOperationResponse GetList() public ManufacturerOperationResponse GetList()
{ {
try try
{ {
return ManufacturerOperationResponse.OK([.. _manufacturerBusinessLogicContract.GetAllManufacturers().Select(x => _mapper.Map<ManufacturerViewModel>(x))]); return ManufacturerOperationResponse.OK([.. _manufacturerBusinessLogicContract.GetAllManufacturers().Select(x => CustomMapper.MapObject<ManufacturerViewModel>(x))]);
} }
catch (StorageException ex) catch (StorageException ex)
{ {
@@ -56,7 +41,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
{ {
try try
{ {
return ManufacturerOperationResponse.OK(_mapper.Map<ManufacturerViewModel>(_manufacturerBusinessLogicContract.GetManufacturerByData(data))); return ManufacturerOperationResponse.OK(CustomMapper.MapObject<ManufacturerViewModel>(_manufacturerBusinessLogicContract.GetManufacturerByData(data)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -84,7 +69,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
{ {
try try
{ {
_manufacturerBusinessLogicContract.InsertManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel)); _manufacturerBusinessLogicContract.InsertManufacturer(CustomMapper.MapObject<ManufacturerDataModel>(manufacturerModel));
return ManufacturerOperationResponse.NoContent(); return ManufacturerOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -118,7 +103,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
{ {
try try
{ {
_manufacturerBusinessLogicContract.UpdateManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel)); _manufacturerBusinessLogicContract.UpdateManufacturer(CustomMapper.MapObject<ManufacturerDataModel>(manufacturerModel));
return ManufacturerOperationResponse.NoContent(); return ManufacturerOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -8,37 +7,23 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class PostAdapter : IPostAdapter internal class PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger) : IPostAdapter
{ {
private readonly IPostBusinessLogicContract _postBusinessLogicContract; private readonly IPostBusinessLogicContract _postBusinessLogicContract = postBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public PostOperationResponse GetList() public PostOperationResponse GetList()
{ {
try try
{ {
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]); return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
} }
catch (StorageException ex) catch (StorageException ex)
{ {
@@ -56,7 +41,7 @@ internal class PostAdapter : IPostAdapter
{ {
try 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) catch (ArgumentNullException ex)
{ {
@@ -84,7 +69,7 @@ internal class PostAdapter : IPostAdapter
{ {
try try
{ {
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data))); return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -117,7 +102,7 @@ internal class PostAdapter : IPostAdapter
{ {
try try
{ {
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel)); _postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent(); return PostOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -151,7 +136,7 @@ internal class PostAdapter : IPostAdapter
{ {
try try
{ {
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel)); _postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent(); return PostOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -8,39 +7,23 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class ProductAdapter : IProductAdapter internal class ProductAdapter(IProductBusinessLogicContract productBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger) : IProductAdapter
{ {
private readonly IProductBusinessLogicContract _productBusinessLogicContract; private readonly IProductBusinessLogicContract _productBusinessLogicContract = productBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public ProductAdapter(IProductBusinessLogicContract productBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger)
{
_productBusinessLogicContract = productBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductBindingModel, ProductDataModel>();
cfg.CreateMap<ProductDataModel, ProductViewModel>();
cfg.CreateMap<ProductHistoryDataModel, ProductHistoryViewModel>()
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => src.ChangeDate.ToLocalTime()));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public ProductOperationResponse GetList(bool includeDeleted) public ProductOperationResponse GetList(bool includeDeleted)
{ {
try try
{ {
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]); return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProducts(!includeDeleted).Select(x => CustomMapper.MapObject<ProductViewModel>(x))]);
} }
catch (StorageException ex) catch (StorageException ex)
{ {
@@ -58,7 +41,7 @@ internal class ProductAdapter : IProductAdapter
{ {
try try
{ {
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsByManufacturer(id, !includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]); return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetAllProductsByManufacturer(id, !includeDeleted).Select(x => CustomMapper.MapObject<ProductViewModel>(x))]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
@@ -81,7 +64,7 @@ internal class ProductAdapter : IProductAdapter
{ {
try try
{ {
return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetProductHistoryByProduct(id).Select(x => _mapper.Map<ProductHistoryViewModel>(x))]); return ProductOperationResponse.OK([.. _productBusinessLogicContract.GetProductHistoryByProduct(id).Select(x => CustomMapper.MapObject<ProductHistoryViewModel>(x))]);
} }
catch (ValidationException ex) catch (ValidationException ex)
{ {
@@ -104,7 +87,7 @@ internal class ProductAdapter : IProductAdapter
{ {
try try
{ {
return ProductOperationResponse.OK(_mapper.Map<ProductViewModel>(_productBusinessLogicContract.GetProductByData(data))); return ProductOperationResponse.OK(CustomMapper.MapObject<ProductViewModel>(_productBusinessLogicContract.GetProductByData(data)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -137,7 +120,7 @@ internal class ProductAdapter : IProductAdapter
{ {
try try
{ {
_productBusinessLogicContract.InsertProduct(_mapper.Map<ProductDataModel>(productModel)); _productBusinessLogicContract.InsertProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent(); return ProductOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
@@ -171,7 +154,7 @@ internal class ProductAdapter : IProductAdapter
{ {
try try
{ {
_productBusinessLogicContract.UpdateProduct(_mapper.Map<ProductDataModel>(productModel)); _productBusinessLogicContract.UpdateProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent(); return ProductOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)

View File

@@ -1,39 +1,21 @@
using AutoMapper; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.AdapterContracts.OperationResponses; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions; using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Mapper;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class ReportAdapter : IReportAdapter internal class ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger logger) : IReportAdapter
{ {
private readonly IReportContract _reportContract; private readonly IReportContract _reportContract = reportContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
public ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<ProductHistoryPricesDataModel, ProductHistoryPricesViewModel>();
cfg.CreateMap<ClientDiscountByPeriodDataModel, ClientDiscountByPeriodViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public async Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct) public async Task<ReportOperationResponse> CreateDocumentProductHistoryPricesAsync(CancellationToken ct)
{ {
@@ -118,7 +100,7 @@ internal class ReportAdapter : IReportAdapter
{ {
try try
{ {
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductHistoryPricesAsync(ct)).Select(x => _mapper.Map<ProductHistoryPricesViewModel>(x))]); return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductHistoryPricesAsync(ct)).Select(x => CustomMapper.MapObject<ProductHistoryPricesViewModel>(x))]);
} }
catch (InvalidOperationException ex) catch (InvalidOperationException ex)
{ {
@@ -141,7 +123,7 @@ internal class ReportAdapter : IReportAdapter
{ {
try try
{ {
return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<SaleViewModel>(x)).ToList()); return ReportOperationResponse.OK((await _reportContract.GetDataSaleByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => CustomMapper.MapObject<SaleViewModel>(x)).ToList());
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -169,7 +151,7 @@ internal class ReportAdapter : IReportAdapter
{ {
try try
{ {
return ReportOperationResponse.OK((await _reportContract.GetDataClientDiscountByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<ClientDiscountByPeriodViewModel>(x)).ToList()); return ReportOperationResponse.OK((await _reportContract.GetDataClientDiscountByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => CustomMapper.MapObject<ClientDiscountByPeriodViewModel>(x)).ToList());
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {

View File

@@ -1,5 +1,4 @@
using AutoMapper; using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts.OperationResponses;
using CandyHouseContracts.AdapterContracts; using CandyHouseContracts.AdapterContracts;
using CandyHouseContracts.BindingModels; using CandyHouseContracts.BindingModels;
using CandyHouseContracts.BusinessLogicsContracts; using CandyHouseContracts.BusinessLogicsContracts;
@@ -8,40 +7,23 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels; using CandyHouseContracts.ViewModels;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using CandyHouseContracts.Resources; using CandyHouseContracts.Resources;
using CandyHouseContracts.Mapper;
namespace CandyHouseWebApi.Adapters; namespace CandyHouseWebApi.Adapters;
internal class SaleAdapter : ISaleAdapter internal class SaleAdapter(ISaleBusinessLogicContract saleBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger) : ISaleAdapter
{ {
private readonly ISaleBusinessLogicContract _saleBusinessLogicContract; private readonly ISaleBusinessLogicContract _saleBusinessLogicContract = saleBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer; private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger; private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
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<SaleProductBindingModel, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate) public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
{ {
try 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) catch (IncorrectDatesException ex)
{ {
@@ -64,7 +46,7 @@ internal class SaleAdapter : ISaleAdapter
{ {
try try
{ {
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]); return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -92,7 +74,7 @@ internal class SaleAdapter : ISaleAdapter
{ {
try try
{ {
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByClientByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]); return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByClientByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -120,7 +102,7 @@ internal class SaleAdapter : ISaleAdapter
{ {
try try
{ {
return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]); return SaleOperationResponse.OK([.. _saleBusinessLogicContract.GetAllSalesByProductByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SaleViewModel>(x))]);
} }
catch (IncorrectDatesException ex) catch (IncorrectDatesException ex)
{ {
@@ -148,7 +130,7 @@ internal class SaleAdapter : ISaleAdapter
{ {
try try
{ {
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id))); return SaleOperationResponse.OK(CustomMapper.MapObject<SaleViewModel>(_saleBusinessLogicContract.GetSaleByData(id)));
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)
{ {
@@ -181,8 +163,8 @@ internal class SaleAdapter : ISaleAdapter
{ {
try try
{ {
var data = _mapper.Map<SaleDataModel>(saleModel); var data = CustomMapper.MapObject<SaleDataModel>(saleModel);
_saleBusinessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel)); _saleBusinessLogicContract.InsertSale(CustomMapper.MapObject<SaleDataModel>(saleModel));
return SaleOperationResponse.NoContent(); return SaleOperationResponse.NoContent();
} }
catch (ArgumentNullException ex) catch (ArgumentNullException ex)