1 Commits

Author SHA1 Message Date
1f805fdff1 CustomMapper 2025-05-30 02:27:18 +04:00
43 changed files with 696 additions and 393 deletions

View File

@@ -1,4 +1,10 @@
namespace SPiluSZharuContracts.BindingModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
using SPiluSZharuContracts.Mapper;
using System.Text.Json;
namespace SPiluSZharuContracts.BindingModels;
public class PostBindingModel
{
@@ -10,5 +16,27 @@ public class PostBindingModel
public string? PostType { get; set; }
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public string? ConfigurationJson { get; set; }
private string ParseConfiguration(PostConfiguration model) =>
System.Text.Json.JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
private PostConfiguration? ParseJson(string json)
{
if (ConfigurationJson is null)
return null;
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(DeliveryManPostConfiguration) => JsonConvert.DeserializeObject<DeliveryManPostConfiguration>(json)!,
nameof(OperatorPostConfiguration) => JsonConvert.DeserializeObject<OperatorPostConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(json)!,
};
}
return null;
}
}

View File

@@ -6,32 +6,54 @@ using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.DataModels;
internal class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
[AlternativeName("PostId")]
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
[AlternativeName("Configuration")]
[AlternativeName("ConfigurationJson")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, null) { }
public PostDataModel(string postId, string postName) : this(postId, postName, PostType.None, new PostConfiguration() { Rate = 10 }) { }
private PostConfiguration? ParseJson(object json)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
if (json is PostConfiguration config)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(OperatorPostConfiguration) => JsonConvert.DeserializeObject<OperatorPostConfiguration>(configurationJson)!,
nameof(DeliveryManPostConfiguration) => JsonConvert.DeserializeObject<DeliveryManPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
return config;
}
if (json is string)
{
var obj = JToken.Parse((string)json);
var type = obj.Value<string>("Type");
switch (type)
{
case nameof(DeliveryManPostConfiguration):
ConfigurationModel = JsonConvert.DeserializeObject<DeliveryManPostConfiguration>((string)json);
break;
case nameof(OperatorPostConfiguration):
ConfigurationModel = JsonConvert.DeserializeObject<OperatorPostConfiguration>((string)json);
break;
default:
ConfigurationModel = JsonConvert.DeserializeObject<PostConfiguration>((string)json);
break;
}
return ConfigurationModel;
}
return null;
}
public void Validate(IStringLocalizer<Messages> localizer)

View File

@@ -3,6 +3,7 @@ using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.DataModels;
@@ -11,6 +12,7 @@ internal class ProductDataModel(string id, string productName, ProductType produ
{
private readonly RestaurantDataModel? _restaurant;
[AlternativeName("ProductId")]
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
@@ -32,6 +34,8 @@ internal class ProductDataModel(string id, string productName, ProductType produ
public ProductDataModel(string id, string productName, ProductType productType, string restaurantId, double price) : this(id, productName, productType, restaurantId, price, false) { }
public ProductDataModel() : this(string.Empty, string.Empty, ProductType.None, string.Empty, 0, false) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

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

View File

@@ -2,12 +2,14 @@
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.DataModels;
internal class RestaurantDataModel(string id, string restaurantName, string? prevRestaurantName, string? prevPrevRestaurantName) : IValidation
{
[AlternativeName("RestaurantId")]
public string Id { get; private set; } = id;
public string RestaurantName { get; private set; } = restaurantName;
@@ -18,6 +20,8 @@ internal class RestaurantDataModel(string id, string restaurantName, string? pre
public RestaurantDataModel(string id, string restaurantName) : this(id, restaurantName, null, null) { }
public RestaurantDataModel() : this(string.Empty, string.Empty, null, null) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

@@ -3,11 +3,12 @@ using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.DataModels;
internal class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
internal class SalaryDataModel(string workerId, DateTime salaryDate, double salary) : IValidation
{
private readonly WorkerDataModel? _worker;
@@ -15,7 +16,8 @@ internal class SalaryDataModel(string workerId, DateTime salaryDate, double work
public DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
public double Salary { get; private set; } = workerSalary;
[AlternativeName("WorkerSalary")]
public double Salary { get; private set; } = salary;
public string WorkerName => _worker?.FIO ?? string.Empty;
@@ -24,6 +26,8 @@ internal class SalaryDataModel(string workerId, DateTime salaryDate, double work
_worker = worker;
}
public SalaryDataModel() : this(string.Empty, DateTime.Now, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (WorkerId.IsEmpty())

View File

@@ -2,6 +2,7 @@
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.DataModels;
@@ -24,6 +25,7 @@ internal class SaleDataModel : IValidation
public bool IsCancel { get; private set; }
[AlternativeName("SaleProducts")]
public List<SaleProductDataModel>? Products { get; private set; }
public string RestaurantName => _restaurant?.RestaurantName ?? string.Empty;
@@ -49,6 +51,8 @@ internal class SaleDataModel : IValidation
public SaleDataModel(string id, string workerId, string? restaurantId, List<SaleProductDataModel> products) : this(id, workerId, restaurantId, false, products) { }
public SaleDataModel() : this(string.Empty, string.Empty, string.Empty, false, new List<SaleProductDataModel>()) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

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

View File

@@ -3,6 +3,7 @@ using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using System.Text.RegularExpressions;
@@ -12,6 +13,7 @@ internal class WorkerDataModel(string id, string fio, string postId, string phon
{
private readonly PostDataModel? _post;
[AlternativeName("WorkerId")]
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
@@ -35,6 +37,8 @@ internal class WorkerDataModel(string id, string fio, string postId, string phon
public WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, phoneNumber, birthDate, employmentDate, false) { }
public WorkerDataModel() : this(string.Empty, string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MinValue, false) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

@@ -4,7 +4,7 @@ using SPiluSZharuContracts.Resources;
namespace SPiluSZharuContracts.Exceptions;
internal class ElementNotFoundException(string value, IStringLocalizer<Messages> localizer) :
Exception(string.Format(localizer["ElementNotFoundExceptionMessage"], value))
Exception(string.Format(localizer["AdapterMessageElementNotFoundException"], value))
{
public string Value { get; private set; } = value;
}

View File

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

View File

@@ -0,0 +1,280 @@
using System.Collections;
using System.Reflection;
namespace SPiluSZharuContracts.Mapper;
internal static class CustomMapper
{
public static To MapObject<To>(object obj, To newObject)
{
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(newObject);
var typeFrom = obj.GetType();
var typeTo = newObject.GetType();
var propertiesFrom = typeFrom.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanRead)
.ToArray();
// свойств
foreach (var property in typeTo.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(x => x.CanWrite))
{
if (property.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
if (propertyFrom is null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var fromValue = propertyFrom.GetValue(obj);
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
if (postProcessingAttribute is not null)
{
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
if (value is not null)
{
property.SetValue(newObject, value);
}
continue;
}
if (propertyFrom.PropertyType.IsGenericType && propertyFrom.PropertyType.Name.StartsWith("List") && fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
if (propertyFrom.PropertyType.IsEnum && property.PropertyType == typeof(string) && fromValue != null)
{
fromValue = fromValue.ToString();
}
else if (!propertyFrom.PropertyType.IsEnum && property.PropertyType.IsEnum && fromValue is not null)
{
if (fromValue is string stringValue && !string.IsNullOrEmpty(stringValue))
fromValue = Enum.Parse(property.PropertyType, stringValue);
else
fromValue = Enum.ToObject(property.PropertyType, fromValue);
}
if (fromValue is not null)
{
if (propertyFrom.PropertyType.IsClass
&& property.PropertyType.IsClass
&& propertyFrom.PropertyType != typeof(string)
&& property.PropertyType != typeof(string)
&& !property.PropertyType.IsAssignableFrom(propertyFrom.PropertyType))
{
try
{
var nestedInstance = Activator.CreateInstance(property.PropertyType);
if (nestedInstance != null)
{
var nestedMapped = MapObject(fromValue, nestedInstance);
property.SetValue(newObject, nestedMapped);
continue;
}
}
catch
{
// ignore
}
}
property.SetValue(newObject, fromValue);
}
}
// полей
var fieldsTo = typeTo.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var fieldsFrom = typeFrom.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var field in fieldsTo)
{
if (field.Name.Contains("k__BackingField"))
continue;
if (field.GetCustomAttribute<IgnoreMappingAttribute>() is not null)
continue;
var sourceField = fieldsFrom.FirstOrDefault(f => f.Name == field.Name);
object? fromValue = null;
if (sourceField is not null)
{
fromValue = sourceField.GetValue(obj);
}
else
{
var propertyName = field.Name.Trim('_').Substring(0, 1).ToUpper() + field.Name.Substring(2);
var sourceProperty = typeFrom.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (sourceProperty is not null && sourceProperty.CanRead)
{
fromValue = sourceProperty.GetValue(obj);
}
}
if (fromValue is null)
continue;
if (field.FieldType.IsClass && field.FieldType != typeof(string))
{
try
{
var nested = Activator.CreateInstance(field.FieldType)!;
var mapped = MapObject(fromValue, nested);
RemoveReadOnly(field);
field.SetValue(newObject, mapped);
continue;
}
catch
{
// ignore
}
}
RemoveReadOnly(field);
field.SetValue(newObject, fromValue);
}
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
{
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo?.Invoke(newObject, []);
}
return newObject;
}
private static void RemoveReadOnly(FieldInfo field)
{
if (!field.IsInitOnly)
return;
var attr = typeof(FieldInfo).GetField("m_fieldAttributes", BindingFlags.Instance | BindingFlags.NonPublic);
if (attr != null)
{
var current = (FieldAttributes)attr.GetValue(field)!;
attr.SetValue(field, current & ~FieldAttributes.InitOnly);
}
}
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
{
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
.ToArray()
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
if (customAttribute is not null)
{
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
}
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
}
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
{
if (value is null || newObject is null)
{
return null;
}
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo =
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo is not null)
{
return methodInfo.Invoke(newObject, [value]);
}
}
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
{
switch (postProcessingAttribute.ActionType)
{
case PostProcessingType.ToUniversalTime:
return ToUniversalTime(value);
case PostProcessingType.ToLocalTime:
return ToLocalTime(value);
}
}
return null;
}
private static object? ToLocalTime(object? obj)
{
if (obj is DateTime date)
return date.ToLocalTime();
return obj;
}
private static object? ToUniversalTime(object? obj)
{
if (obj is DateTime date)
return date.ToUniversalTime();
return obj;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
{
var defaultValueAttribute = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttribute is null)
{
return;
}
if (defaultValueAttribute.DefaultValue is not null)
{
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
return;
}
var value = defaultValueAttribute.Func switch
{
DefaultValueFunc.UtcNow => DateTime.UtcNow,
_ => (object?)null,
};
if (value is not null)
{
property.SetValue(newObject, value);
}
}
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
{
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
var elementType = propertyTo.PropertyType.GenericTypeArguments[0];
foreach (var elem in (IEnumerable)list)
{
object? newElem;
if (elementType.IsPrimitive || elementType == typeof(string) || elementType == typeof(decimal) || elementType == typeof(DateTime))
{
newElem = elem;
}
else
{
newElem = MapObject(elem, Activator.CreateInstance(elementType)!);
}
if (newElem is not null)
{
propertyTo.PropertyType.GetMethod("Add")!.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}
enum DefaultValueFunc
{
None,
UtcNow
}

View File

@@ -0,0 +1,11 @@
namespace SPiluSZharuContracts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public string? FuncName { get; set; }
public DefaultValueFunc Func { get; set; } = DefaultValueFunc.None;
}

View File

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

View File

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

View File

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

View File

@@ -1,12 +1,27 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
using SPiluSZharuContracts.Mapper;
using System.Text.Json;
namespace SPiluSZharuContracts.ViewModels;
public class PostViewModel
{
[AlternativeName("PostId")]
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; }
private string ParseConfiguration(PostConfiguration? model)
{
if (model == null)
return string.Empty;
return JsonSerializer.Serialize(model, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
}

View File

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

View File

@@ -1,7 +1,10 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class ProductViewModel
{
[AlternativeName("ProductId")]
public required string Id { get; set; }
public required string ProductName { get; set; }

View File

@@ -1,7 +1,10 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class RestaurantViewModel
{
[AlternativeName("RestaurantId")]
public required string Id { get; set; }
public required string RestaurantName { get; set; }

View File

@@ -1,4 +1,6 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class SalaryViewModel
{
@@ -6,7 +8,9 @@ public class SalaryViewModel
public required string WorkerFIO { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime SalaryDate { get; set; }
[AlternativeName("WorkerSalary")]
public double Salary { get; set; }
}

View File

@@ -1,7 +1,10 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class SaleViewModel
{
[AlternativeName("SaleId")]
public required string Id { get; set; }
public required string WorkerId { get; set; }
@@ -12,6 +15,7 @@ public class SaleViewModel
public string? RestaurantName { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime SaleDate { get; set; }
public double Sum { get; set; }

View File

@@ -1,4 +1,6 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class WorkerSalaryByPeriodViewModel
{
@@ -6,7 +8,9 @@ public class WorkerSalaryByPeriodViewModel
public double TotalSalary { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime FromPeriod { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime ToPeriod { get; set; }
}

View File

@@ -1,7 +1,10 @@
namespace SPiluSZharuContracts.ViewModels;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuContracts.ViewModels;
public class WorkerViewModel
{
[AlternativeName("WorkerId")]
public required string Id { get; set; }
public required string FIO { get; set; }
@@ -14,7 +17,9 @@ public class WorkerViewModel
public bool IsDeleted { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime BirthDate { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime EmploymentDate { get; set; }
}

View File

@@ -1,44 +1,25 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
internal class PostStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer) : IPostStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(SPiluSZharuDbContext 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))
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SPiluSZharuDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<PostDataModel> GetList()
{
try
{
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
return [.. _dbContext.Posts.Select(x => CustomMapper.MapObject<PostDataModel>(x))];
}
catch (Exception ex)
{
@@ -51,7 +32,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => CustomMapper.MapObject<PostDataModel>(x))];
}
catch (Exception ex)
{
@@ -64,7 +45,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
@@ -77,7 +58,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
return CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
@@ -90,7 +71,11 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
var post = MapToEntity(postDataModel);
post.IsActual = true;
post.ChangeDate = DateTime.UtcNow;
_dbContext.Posts.Add(post);
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
@@ -124,7 +109,9 @@ internal class PostStorageContract : IPostStorageContract
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
var newElement = MapToEntity(postDataModel);
newElement.IsActual = true;
newElement.ChangeDate = DateTime.UtcNow;
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
@@ -186,5 +173,13 @@ internal class PostStorageContract : IPostStorageContract
}
}
private Post MapToEntity(PostDataModel model)
{
var post = CustomMapper.MapObject<Post>(model);
post.PostId = model.Id;
post.Configuration = model.ConfigurationModel;
return post;
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -1,35 +1,19 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
internal class ProductStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer) : IProductStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ProductStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Restaurant, RestaurantDataModel>();
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;
}
private readonly SPiluSZharuDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ProductDataModel> GetList(bool onlyActive = true, string? restaurantId = null)
{
@@ -44,7 +28,7 @@ internal class ProductStorageContract : IProductStorageContract
{
query = query.Where(x => x.RestaurantId == restaurantId);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<ProductDataModel>(x))];
}
catch (Exception ex)
{
@@ -57,7 +41,7 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
return [.. await _dbContext.Products.Include(x => x.Restaurant).Select(x => _mapper.Map<ProductDataModel>(x)).ToListAsync(ct)];
return [.. await _dbContext.Products.Include(x => x.Restaurant).Select(x => CustomMapper.MapObject<ProductDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
@@ -70,7 +54,7 @@ internal class ProductStorageContract : IProductStorageContract
{
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)
{
@@ -83,7 +67,7 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
return CustomMapper.MapObjectWithNull<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
@@ -96,7 +80,7 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.Include(x => x.Restaurant).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
return CustomMapper.MapObjectWithNull<ProductDataModel>(_dbContext.Products.Include(x => x.Restaurant).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
}
catch (Exception ex)
{
@@ -109,7 +93,9 @@ internal class ProductStorageContract : IProductStorageContract
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
var product = CustomMapper.MapObject<Product>(productDataModel);
product.IsDeleted = false;
_dbContext.Products.Add(product);
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
@@ -147,7 +133,9 @@ internal class ProductStorageContract : IProductStorageContract
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
var product = CustomMapper.MapObject<Product>(productDataModel, element);
product.IsDeleted = false;
_dbContext.Products.Update(product);
_dbContext.SaveChanges();
transaction.Commit();
}

View File

@@ -1,9 +1,9 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
@@ -13,17 +13,11 @@ namespace SPiluSZharuDatabase.Implementations;
internal class RestaurantStorageContract : IRestaurantStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public RestaurantStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
_localizer = localizer;
}
@@ -31,7 +25,7 @@ internal class RestaurantStorageContract : IRestaurantStorageContract
{
try
{
return [.. _dbContext.Restaurants.Select(x => _mapper.Map<RestaurantDataModel>(x))];
return [.. _dbContext.Restaurants.Select(x => CustomMapper.MapObject<RestaurantDataModel>(x))];
}
catch (Exception ex)
{
@@ -44,7 +38,7 @@ internal class RestaurantStorageContract : IRestaurantStorageContract
{
try
{
return _mapper.Map<RestaurantDataModel>(GetRestaurantById(id));
return CustomMapper.MapObjectWithNull<RestaurantDataModel>(GetRestaurantById(id));
}
catch (Exception ex)
{
@@ -57,7 +51,7 @@ internal class RestaurantStorageContract : IRestaurantStorageContract
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.RestaurantName == name));
return CustomMapper.MapObjectWithNull<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.RestaurantName == name));
}
catch (Exception ex)
{
@@ -70,7 +64,7 @@ internal class RestaurantStorageContract : IRestaurantStorageContract
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.PrevRestaurantName == name ||
return CustomMapper.MapObjectWithNull<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.PrevRestaurantName == name ||
x.PrevPrevRestaurantName == name));
}
catch (Exception ex)
@@ -84,7 +78,7 @@ internal class RestaurantStorageContract : IRestaurantStorageContract
{
try
{
_dbContext.Restaurants.Add(_mapper.Map<Restaurant>(restaurantDataModel));
_dbContext.Restaurants.Add(CustomMapper.MapObject<Restaurant>(restaurantDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")

View File

@@ -1,33 +1,18 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
internal class SalaryStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer) : ISalaryStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SPiluSZharuDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? workerId = null)
{
@@ -40,7 +25,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (workerId != null)
query = query.Where(x => x.WorkerId == workerId);
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<SalaryDataModel>(x))];
}
catch (Exception ex)
{
@@ -53,7 +38,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
{
try
{
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => CustomMapper.MapObject<SalaryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
@@ -66,7 +51,9 @@ internal class SalaryStorageContract : ISalaryStorageContract
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
var salary = MapToEntity(salaryDataModel);
_dbContext.Salaries.Add(salary);
_dbContext.SaveChanges();
}
catch (Exception ex)
@@ -75,4 +62,11 @@ internal class SalaryStorageContract : ISalaryStorageContract
throw new StorageException(ex, _localizer);
}
}
private Salary MapToEntity(SalaryDataModel dataModel)
{
var salary = CustomMapper.MapObject<Salary>(dataModel);
salary.WorkerSalary = dataModel.Salary;
return salary;
}
}

View File

@@ -1,38 +1,18 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
internal class SaleStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer) : ISaleStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SaleStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Restaurant, RestaurantDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
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;
}
private readonly SPiluSZharuDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? restaurantId = null, string? productId = null)
{
@@ -55,7 +35,7 @@ internal class SaleStorageContract : ISaleStorageContract
{
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)
{
@@ -68,7 +48,7 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
return [.. await _dbContext.Sales.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.SaleProducts)!.ThenInclude(x => x.Product).Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => CustomMapper.MapObject<SaleDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
@@ -81,7 +61,7 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
return CustomMapper.MapObjectWithNull<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
@@ -94,7 +74,9 @@ internal class SaleStorageContract : ISaleStorageContract
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
var sale = MapToEntity(saleDataModel);
_dbContext.Sales.Add(sale);
_dbContext.SaveChanges();
}
catch (Exception ex)
@@ -128,5 +110,22 @@ internal class SaleStorageContract : ISaleStorageContract
}
}
private Sale MapToEntity(SaleDataModel dataModel)
{
var sale = CustomMapper.MapObject<Sale>(dataModel);
sale.IsCancel = false;
sale.SaleProducts = dataModel.Products?
.Select(p => new SaleProduct
{
ProductId = p.ProductId,
Count = p.Count,
Price = p.Price,
SaleId = sale.Id
})
.ToList();
return sale;
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Restaurant).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}

View File

@@ -1,33 +1,19 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
internal class WorkerStorageContract(SPiluSZharuDbContext dbContext, IStringLocalizer<Messages> localizer) : IWorkerStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(SPiluSZharuDbContext 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(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SPiluSZharuDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<WorkerDataModel> 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 WorkerStorageContract : IWorkerStorageContract
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
return [.. JoinPost(query).Select(x => CustomMapper.MapObject<WorkerDataModel>(x))];
}
catch (Exception ex)
{
@@ -63,7 +49,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
return CustomMapper.MapObjectWithNull<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
@@ -76,7 +62,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
return CustomMapper.MapObjectWithNull<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -89,7 +75,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber && !x.IsDeleted)));
return CustomMapper.MapObjectWithNull<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -102,7 +88,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.Workers.Add(CustomMapper.MapObject<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
@@ -132,7 +118,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id, _localizer);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, element));
_dbContext.Workers.Update(CustomMapper.MapObject(workerDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -195,5 +181,5 @@ internal class WorkerStorageContract : IWorkerStorageContract
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker)
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
=> worker == null ? null : worker.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
}

View File

@@ -1,5 +1,6 @@
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuDatabase.Models;
@@ -13,9 +14,12 @@ internal class Post
public PostType PostType { get; set; }
[AlternativeName("ConfigurationModel")]
public required PostConfiguration Configuration { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -1,4 +1,6 @@
namespace SPiluSZharuDatabase.Models;
using SPiluSZharuContracts.Mapper;
namespace SPiluSZharuDatabase.Models;
internal class Salary
{

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace SPiluSZharuDatabase.Models;
@@ -23,6 +24,7 @@ internal class Worker
public DateTime? DateOfDelete { get; set; }
[NotMapped]
[IgnoreMapping]
public Post? Post { get; set; }
[ForeignKey("WorkerId")]

View File

@@ -227,7 +227,6 @@ internal class PostControllerTests : BaseWebApiControllerTest
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
});
}
@@ -357,7 +356,6 @@ internal class PostControllerTests : BaseWebApiControllerTest
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPostTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Type is incorrect");
Assert.That(responseWithSalaryIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Salary is incorrect");
});
}

View File

@@ -320,8 +320,7 @@ internal class ProductControllerTests : BaseWebApiControllerTest
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
});
}
@@ -412,8 +411,7 @@ internal class ProductControllerTests : BaseWebApiControllerTest
{
Assert.That(responseWithIdIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithProductTypeIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest), "Price is incorrect");
});
}

View File

@@ -301,32 +301,6 @@ internal class SaleControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_ShouldSuccess_Test()
{
//Arrange
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, null, products: [(_productId, 5, 1.1)]);
var saleModel = CreateModel(_workerId, _restaurantId, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(SPiluSZharuDbContext.GetSalesByRestaurantId(_restaurantId)[0], saleModel);
}
[Test]
public async Task Post_WhenNoRestaurant_ShouldSuccess_Test()
{
//Arrange
SPiluSZharuDbContext.InsertSaleToDatabaseAndReturn(_workerId, _restaurantId, products: [(_productId, 5, 1.1)]);
var saleModel = CreateModel(_workerId, null, _productId);
//Act
var response = await HttpClient.PostAsync($"/api/sales/sale", MakeContent(saleModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
AssertElement(SPiluSZharuDbContext.GetSalesByRestaurantId(null)[0], saleModel);
}
[Test]
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{

View File

@@ -1,49 +1,32 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Moq;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
using System.Text.Json;
namespace SPiluSZharuWebApi.Adapters;
internal class PostAdapter : IPostAdapter
internal class PostAdapter(IPostBuisnessLogicContract postBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger) : IPostAdapter
{
private readonly IPostBuisnessLogicContract _postBuisnessLogicContract;
private readonly IPostBuisnessLogicContract _postBuisnessLogicContract = postBuisnessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly ILogger _logger = logger;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public PostAdapter(IPostBuisnessLogicContract postBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger)
{
_postBuisnessLogicContract = postBuisnessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public PostOperationResponse GetList()
{
try
{
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllPosts().Select(CustomMapper.MapObject<PostViewModel>)]);
}
catch (StorageException ex)
{
@@ -61,7 +44,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([.. _postBuisnessLogicContract.GetAllDataOfPost(id).Select(CustomMapper.MapObject<PostViewModel>)]);
}
catch (ArgumentNullException ex)
{
@@ -89,7 +72,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBuisnessLogicContract.GetPostByData(data)));
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBuisnessLogicContract.GetPostByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -122,7 +105,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
_postBuisnessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
_postBuisnessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -156,7 +139,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
_postBuisnessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
_postBuisnessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,47 +1,29 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using SPiluSZharuBuisnessLogic.Implementations;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuWebApi.Adapters;
internal class ProductAdapter : IProductAdapter
internal class ProductAdapter(IProductBuisnessLogicContract productBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger) : IProductAdapter
{
private readonly IProductBuisnessLogicContract _productBuisnessLogicContract;
private readonly IProductBuisnessLogicContract _productBuisnessLogicContract = productBuisnessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public ProductAdapter(IProductBuisnessLogicContract productBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger)
{
_productBuisnessLogicContract = productBuisnessLogicContract;
_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;
}
private readonly ILogger _logger = logger;
public ProductOperationResponse GetList(bool includeDeleted)
{
try
{
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetAllProducts(!includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetAllProducts(!includeDeleted).Select(CustomMapper.MapObject<ProductViewModel>)]);
}
catch (StorageException ex)
{
@@ -59,7 +41,7 @@ internal class ProductAdapter : IProductAdapter
{
try
{
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetAllProductsByRestaurant(id, !includeDeleted).Select(x => _mapper.Map<ProductViewModel>(x))]);
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetAllProductsByRestaurant(id, !includeDeleted).Select(CustomMapper.MapObject<ProductViewModel>)]);
}
catch (ValidationException ex)
{
@@ -82,7 +64,7 @@ internal class ProductAdapter : IProductAdapter
{
try
{
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetProductHistoryByProduct(id).Select(x => _mapper.Map<ProductHistoryViewModel>(x))]);
return ProductOperationResponse.OK([.. _productBuisnessLogicContract.GetProductHistoryByProduct(id).Select(CustomMapper.MapObject<ProductHistoryViewModel>)]);
}
catch (ValidationException ex)
{
@@ -105,7 +87,7 @@ internal class ProductAdapter : IProductAdapter
{
try
{
return ProductOperationResponse.OK(_mapper.Map<ProductViewModel>(_productBuisnessLogicContract.GetProductByData(data)));
return ProductOperationResponse.OK(CustomMapper.MapObject<ProductViewModel>(_productBuisnessLogicContract.GetProductByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -138,7 +120,7 @@ internal class ProductAdapter : IProductAdapter
{
try
{
_productBuisnessLogicContract.InsertProduct(_mapper.Map<ProductDataModel>(productModel));
_productBuisnessLogicContract.InsertProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -172,7 +154,7 @@ internal class ProductAdapter : IProductAdapter
{
try
{
_productBuisnessLogicContract.UpdateProduct(_mapper.Map<ProductDataModel>(productModel));
_productBuisnessLogicContract.UpdateProduct(CustomMapper.MapObject<ProductDataModel>(productModel));
return ProductOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -5,35 +5,19 @@ using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuWebApi.Adapters;
internal class ReportAdapter : IReportAdapter
internal class ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> 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 Mapper _mapper;
public ReportAdapter(IReportContract reportContract, IStringLocalizer<Messages> localizer, ILogger<ProductAdapter> logger)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RestaurantProductDataModel, RestaurantProductViewModel>();
cfg.CreateMap<SaleDataModel, SaleViewModel>();
cfg.CreateMap<SaleProductDataModel, SaleProductViewModel>();
cfg.CreateMap<WorkerSalaryByPeriodDataModel, WorkerSalaryByPeriodViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly ILogger _logger = logger;
public async Task<ReportOperationResponse> CreateDocumentProductsByRestaurantAsync(CancellationToken ct)
{
@@ -118,7 +102,7 @@ internal class ReportAdapter : IReportAdapter
{
try
{
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductsByRestaurantAsync(ct)).Select(x => _mapper.Map<RestaurantProductViewModel>(x))]);
return ReportOperationResponse.OK([.. (await _reportContract.GetDataProductsByRestaurantAsync(ct)).Select(CustomMapper.MapObject<RestaurantProductViewModel>)]);
}
catch (InvalidOperationException ex)
{
@@ -141,7 +125,7 @@ internal class ReportAdapter : IReportAdapter
{
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(CustomMapper.MapObject<SaleViewModel>).ToList());
}
catch (IncorrectDatesException ex)
{
@@ -169,7 +153,7 @@ internal class ReportAdapter : IReportAdapter
{
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x => _mapper.Map<WorkerSalaryByPeriodViewModel>(x)).ToList());
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(CustomMapper.MapObject<WorkerSalaryByPeriodViewModel>).ToList());
}
catch (IncorrectDatesException ex)
{

View File

@@ -1,45 +1,29 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
using SPiluSZharuDatabase;
namespace SPiluSZharuWebApi.Adapters;
internal class RestaurantAdapter : IRestaurantAdapter
internal class RestaurantAdapter(IRestaurantBuisnessLogicContract restaurantBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<RestaurantAdapter> logger) : IRestaurantAdapter
{
private readonly IRestaurantBuisnessLogicContract _restaurantBuisnessLogicContract;
private readonly IRestaurantBuisnessLogicContract _restaurantBuisnessLogicContract = restaurantBuisnessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public RestaurantAdapter(IRestaurantBuisnessLogicContract restaurantBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<RestaurantAdapter> logger)
{
_restaurantBuisnessLogicContract = restaurantBuisnessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RestaurantBindingModel, RestaurantDataModel>();
cfg.CreateMap<RestaurantDataModel, RestaurantViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly ILogger _logger = logger;
public RestaurantOperationResponse GetList()
{
try
{
return RestaurantOperationResponse.OK([.. _restaurantBuisnessLogicContract.GetAllRestaurants().Select(x => _mapper.Map<RestaurantViewModel>(x))]);
return RestaurantOperationResponse.OK([.. _restaurantBuisnessLogicContract.GetAllRestaurants().Select(CustomMapper.MapObject<RestaurantViewModel>)]);
}
catch (StorageException ex)
{
@@ -57,7 +41,7 @@ internal class RestaurantAdapter : IRestaurantAdapter
{
try
{
return RestaurantOperationResponse.OK(_mapper.Map<RestaurantViewModel>(_restaurantBuisnessLogicContract.GetRestaurantByData(data)));
return RestaurantOperationResponse.OK(CustomMapper.MapObject<RestaurantViewModel>(_restaurantBuisnessLogicContract.GetRestaurantByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -85,7 +69,7 @@ internal class RestaurantAdapter : IRestaurantAdapter
{
try
{
_restaurantBuisnessLogicContract.InsertRestaurant(_mapper.Map<RestaurantDataModel>(restaurantModel));
_restaurantBuisnessLogicContract.InsertRestaurant(CustomMapper.MapObject<RestaurantDataModel>(restaurantModel));
return RestaurantOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -119,7 +103,7 @@ internal class RestaurantAdapter : IRestaurantAdapter
{
try
{
_restaurantBuisnessLogicContract.UpdateRestaurant(_mapper.Map<RestaurantDataModel>(restaurantModel));
_restaurantBuisnessLogicContract.UpdateRestaurant(CustomMapper.MapObject<RestaurantDataModel>(restaurantModel));
return RestaurantOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,42 +1,31 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuWebApi.Adapters;
internal class SalaryAdapter : ISalaryAdapter
internal class SalaryAdapter(ISalaryBuisnessLogicContract salaryBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SalaryAdapter> logger) : ISalaryAdapter
{
private readonly ISalaryBuisnessLogicContract _salaryBuisnessLogicContract;
private readonly ISalaryBuisnessLogicContract _salaryBuisnessLogicContract = salaryBuisnessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public SalaryAdapter(ISalaryBuisnessLogicContract salaryBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SalaryAdapter> logger)
{
_salaryBuisnessLogicContract = salaryBuisnessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly ILogger _logger = logger;
public SalaryOperationResponse GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
try
{
return SalaryOperationResponse.OK([.. _salaryBuisnessLogicContract.GetAllSalariesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SalaryViewModel>(x))]);
var data = _salaryBuisnessLogicContract.GetAllSalariesByPeriod(
fromDate.ToUniversalTime(),
toDate.ToUniversalTime());
return SalaryOperationResponse.OK([.. data.Select(CustomMapper.MapObject<SalaryViewModel>)]);
}
catch (ValidationException ex)
{
@@ -64,7 +53,12 @@ internal class SalaryAdapter : ISalaryAdapter
{
try
{
return SalaryOperationResponse.OK([.. _salaryBuisnessLogicContract.GetAllSalariesByPeriodByWorker(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), workerId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
var data = _salaryBuisnessLogicContract.GetAllSalariesByPeriodByWorker(
fromDate.ToUniversalTime(),
toDate.ToUniversalTime(),
workerId);
return SalaryOperationResponse.OK(data.Select(CustomMapper.MapObject<SalaryViewModel>).ToList());
}
catch (ArgumentNullException ex)
{

View File

@@ -1,47 +1,35 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuWebApi.Adapters;
internal class SaleAdapter : ISaleAdapter
internal class SaleAdapter(ISaleBuisnessLogicContract saleBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger) : ISaleAdapter
{
private readonly ISaleBuisnessLogicContract _saleBuisnessLogicContract;
private readonly ISaleBuisnessLogicContract _saleBuisnessLogicContract = saleBuisnessLogicContract;
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(ISaleBuisnessLogicContract saleBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SaleAdapter> logger)
{
_saleBuisnessLogicContract = saleBuisnessLogicContract;
_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;
}
private SaleViewModel MapSaleViewModel(SaleDataModel source) => CustomMapper.MapObject<SaleViewModel>(source);
public SaleOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
var data = _saleBuisnessLogicContract.GetAllSalesByPeriod(
fromDate.ToUniversalTime(),
toDate.ToUniversalTime());
return SaleOperationResponse.OK([.. data.Select(MapSaleViewModel)]);
}
catch (IncorrectDatesException ex)
{
@@ -64,7 +52,12 @@ internal class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
var data = _saleBuisnessLogicContract.GetAllSalesByWorkerByPeriod(
id,
fromDate.ToUniversalTime(),
toDate.ToUniversalTime());
return SaleOperationResponse.OK(data.Select(MapSaleViewModel).ToList());
}
catch (IncorrectDatesException ex)
{
@@ -92,7 +85,12 @@ internal class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByRestaurantByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
var data = _saleBuisnessLogicContract.GetAllSalesByRestaurantByPeriod(
id,
fromDate.ToUniversalTime(),
toDate.ToUniversalTime());
return SaleOperationResponse.OK([.. data.Select(MapSaleViewModel)]);
}
catch (IncorrectDatesException ex)
{
@@ -120,7 +118,12 @@ internal class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK([.. _saleBuisnessLogicContract.GetAllSalesByProductByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SaleViewModel>(x))]);
var data = _saleBuisnessLogicContract.GetAllSalesByProductByPeriod(
id,
fromDate.ToUniversalTime(),
toDate.ToUniversalTime());
return SaleOperationResponse.OK([.. data.Select(MapSaleViewModel)]);
}
catch (IncorrectDatesException ex)
{
@@ -148,7 +151,8 @@ internal class SaleAdapter : ISaleAdapter
{
try
{
return SaleOperationResponse.OK(_mapper.Map<SaleViewModel>(_saleBuisnessLogicContract.GetSaleByData(id)));
var data = _saleBuisnessLogicContract.GetSaleByData(id);
return SaleOperationResponse.OK(MapSaleViewModel(data));
}
catch (ArgumentNullException ex)
{
@@ -181,8 +185,8 @@ internal class SaleAdapter : ISaleAdapter
{
try
{
var data = _mapper.Map<SaleDataModel>(saleModel);
_saleBuisnessLogicContract.InsertSale(_mapper.Map<SaleDataModel>(saleModel));
var dataModel = CustomMapper.MapObject<SaleDataModel>(saleModel);
_saleBuisnessLogicContract.InsertSale(dataModel);
return SaleOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,46 +1,32 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SPiluSZharuContracts.AdapterContracts;
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Mapper;
using SPiluSZharuContracts.Resources;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuWebApi.Adapters;
internal class WorkerAdapter : IWorkerAdapter
internal class WorkerAdapter(IWorkerBuisnessLogicContract workerBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<WorkerAdapter> logger) : IWorkerAdapter
{
private readonly IWorkerBuisnessLogicContract _workerBuisnessLogicContract;
private readonly IWorkerBuisnessLogicContract _workerBuisnessLogicContract = workerBuisnessLogicContract;
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 WorkerAdapter(IWorkerBuisnessLogicContract workerBuisnessLogicContract, IStringLocalizer<Messages> localizer, ILogger<WorkerAdapter> logger)
{
_workerBuisnessLogicContract = workerBuisnessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, WorkerViewModel>()
.ForMember(x => x.BirthDate, x => x.MapFrom(src => src.BirthDate.ToLocalTime()))
.ForMember(x => x.EmploymentDate, x => x.MapFrom(src => src.EmploymentDate.ToLocalTime()));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private WorkerViewModel MapWorkerViewModel(WorkerDataModel source) => CustomMapper.MapObject<WorkerViewModel>(source);
public WorkerOperationResponse GetList(bool includeDeleted)
{
try
{
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkers(!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var data = _workerBuisnessLogicContract.GetAllWorkers(!includeDeleted);
return WorkerOperationResponse.OK(data.Select(MapWorkerViewModel).ToList());
}
catch (StorageException ex)
{
@@ -58,7 +44,8 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var data = _workerBuisnessLogicContract.GetAllWorkersByPost(id, !includeDeleted);
return WorkerOperationResponse.OK(data.Select(MapWorkerViewModel).ToList());
}
catch (ValidationException ex)
{
@@ -81,7 +68,12 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var data = _workerBuisnessLogicContract.GetAllWorkersByBirthDate(
fromDate.ToUniversalTime(),
toDate.ToUniversalTime(),
!includeDeleted);
return WorkerOperationResponse.OK(data.Select(MapWorkerViewModel).ToList());
}
catch (IncorrectDatesException ex)
{
@@ -104,7 +96,12 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK([.. _workerBuisnessLogicContract.GetAllWorkersByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
var data = _workerBuisnessLogicContract.GetAllWorkersByEmploymentDate(
fromDate.ToUniversalTime(),
toDate.ToUniversalTime(),
!includeDeleted);
return WorkerOperationResponse.OK(data.Select(MapWorkerViewModel).ToList());
}
catch (IncorrectDatesException ex)
{
@@ -127,7 +124,8 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
return WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_workerBuisnessLogicContract.GetWorkerByData(data)));
var worker = _workerBuisnessLogicContract.GetWorkerByData(data);
return WorkerOperationResponse.OK(MapWorkerViewModel(worker));
}
catch (ArgumentNullException ex)
{
@@ -160,7 +158,8 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
_workerBuisnessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
var dataModel = CustomMapper.MapObject<WorkerDataModel>(workerModel);
_workerBuisnessLogicContract.InsertWorker(dataModel);
return WorkerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -194,7 +193,8 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
_workerBuisnessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
var dataModel = CustomMapper.MapObject<WorkerDataModel>(workerModel);
_workerBuisnessLogicContract.UpdateWorker(dataModel);
return WorkerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)