1 Commits

Author SHA1 Message Date
75e352ce26 лаба 8 готова 2025-05-21 20:37:22 +04:00
49 changed files with 638 additions and 453 deletions

View File

@@ -32,8 +32,15 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
{
throw new IncorrectDatesException(fromDate, toDate, _localizer);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new
NullListException();
var result = _salaryStorageContract.GetList(fromDate, toDate);
if (result == null)
{
throw new NullListException();
}
return result;
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime
fromDate, DateTime toDate, string workerId)

View File

@@ -21,6 +21,7 @@ internal class InstallationRequestDataModel(string softwareId, string requestId,
_software = software;
}
public InstallationRequestDataModel() : this(string.Empty, string.Empty, 0, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{

View File

@@ -18,6 +18,8 @@ prevManufacturerName, string? prevPrevManufacturerName) : IValidation
public ManufacturerDataModel(string id, string manufacturerName) : this(id, manufacturerName, null, null){ }
public ManufacturerDataModel() : this(string.Empty, string.Empty, null, null) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

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

View File

@@ -2,6 +2,7 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using System.Text.RegularExpressions;
using System.Xml;
@@ -19,8 +20,13 @@ internal class RequestDataModel : IValidation
public string Email { get; private set; }
public double Sum { get; private set; }
public bool IsCancel { get; private set; }
[AlternativeName("InstallationRequests")]
public List<InstallationRequestDataModel>? Softwares { get; private set; }
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public RequestDataModel() : this(string.Empty, string.Empty, string.Empty, false,new List<InstallationRequestDataModel>(), DateTime.UtcNow) { }
public RequestDataModel(string id, string workerId, string email, bool isCancel, List<InstallationRequestDataModel> installationRequests, DateTime requestDate)
{
Id = id;
@@ -39,7 +45,6 @@ internal class RequestDataModel : IValidation
_worker = worker;
}
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

@@ -19,7 +19,7 @@ workerSalary) : IValidation
{
_worker = worker;
}
public SalaryDataModel() : this(string.Empty, DateTime.Now, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (WorkerId.IsEmpty())

View File

@@ -36,7 +36,7 @@ internal class SoftwareDataModel(string id, string softwareName, SoftwareType so
softwareType, manufacturerId, price, false)
{ }
public SoftwareDataModel() : this(string.Empty, string.Empty, SoftwareType.None, string.Empty, 0.0, false) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

@@ -2,30 +2,27 @@
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Extensions;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmallSoftwareContracts.Resources;
namespace SmallSoftwareContracts.DataModels;
internal class SoftwareHistoryDataModel(string softwareId, double oldPrice) : IValidation
{
private readonly SoftwareDataModel? _software;
private SoftwareDataModel? Software;
public string SoftwareId { get; private set; } = softwareId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow.ToUniversalTime();
public string SoftwareName => _software?.SoftwareName ?? string.Empty;
public string SoftwareName => Software?.SoftwareName ?? string.Empty;
public SoftwareHistoryDataModel(string softwareId, double oldPrice, DateTime
changeDate, SoftwareDataModel software) : this(softwareId, oldPrice)
{
ChangeDate = changeDate;
_software = software;
Software = software;
}
public SoftwareHistoryDataModel() : this(string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (SoftwareId.IsEmpty())

View File

@@ -6,12 +6,14 @@ using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.DataModels;
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostConfiguration configuration) : IValidation
{
private readonly PostDataModel? _post;
[AlternativeName("Post")]
public PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string PostId { get; private set; } = postId;
@@ -19,8 +21,14 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public bool IsDeleted { get; private set; } = isDeleted;
public string PostName => _post?.PostName ?? string.Empty;
[AlternativeName("ConfigurationJson")]
[AlternativeName("Configuration")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public WorkerDataModel() : this(string.Empty, string.Empty, string.Empty, DateTime.UtcNow, DateTime.UtcNow, false, (PostConfiguration)null)
{ }
public WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) :
this(id, fio, postId, birthDate, employmentDate, isDeleted, new PostConfiguration { Rate = 10 })
@@ -32,22 +40,6 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
: this(id, fio, postId, birthDate, employmentDate, false, new PostConfiguration { Rate = 10 })
{ }
public WorkerDataModel(string id, string fio, string postId, DateTime
birthDate, DateTime employmentDate, string configurationJson) :
this(id, fio, postId, birthDate, employmentDate, false, new PostConfiguration { Rate = 10 })
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(configurationJson)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())
@@ -58,13 +50,13 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
if (FIO.IsEmpty())
throw new ValidationException(localizer[Messages.ValidationExceptionMessageEmptyField, nameof(FIO)]);
if (PostId.IsEmpty())
throw new ValidationException(localizer[Messages.ValidationExceptionMessageEmptyField, nameof(PostId)]);
if (!PostId.IsGuid())
throw new ValidationException(localizer[Messages.ValidationExceptionMessageNotAId, nameof(PostId)]);
if (BirthDate.Date > DateTime.Now.AddYears(-16).Date)
throw new ValidationException(localizer[Messages.ValidationExceptionMessageMinorsBirthDate, BirthDate.ToShortDateString()]);
@@ -73,11 +65,26 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
if ((EmploymentDate - BirthDate).TotalDays / 365 < 16)
throw new ValidationException(localizer[Messages.ValidationExceptionMessageMinorsEmploymentDate, EmploymentDate.ToShortDateString(), BirthDate.ToShortDateString()]);
if (ConfigurationModel is null)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageNotInitialized"], "ConfigurationModel"));
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
private PostConfiguration? ParseJson(string json)
{
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(json)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(json)!,
};
}
return null;
}
}

View File

@@ -1,7 +1,10 @@
namespace SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.DataModels;
public class WorkerSalaryByPeriodDataModel
{
[AlternativeName("FIO")]
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }

View File

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

View File

@@ -0,0 +1,305 @@
using System.Collections;
using System.Reflection;
using Newtonsoft.Json;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
namespace SmallSoftwareContracts.Mapper;
public 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.GetGenericTypeDefinition() == typeof(List<>) &&
fromValue is not null)
{
var elementType = property.PropertyType.GenericTypeArguments[0];
if (elementType.IsPrimitive || elementType == typeof(string) || elementType.IsValueType)
{
var original = (IEnumerable)fromValue;
var copy = (IList)Activator.CreateInstance(property.PropertyType)!;
foreach (var item in original)
copy.Add(item);
property.SetValue(newObject, copy);
continue;
}
fromValue = MapListOfObjects(property, fromValue);
}
if (propertyFrom.PropertyType.IsEnum && property.PropertyType.IsEnum)
{
if (fromValue != null && property.PropertyType != propertyFrom.PropertyType)
{
fromValue = System.Enum.ToObject(property.PropertyType, Convert.ChangeType(fromValue, System.Enum.GetUnderlyingType(propertyFrom.PropertyType)));
}
property.SetValue(newObject, fromValue);
continue;
}
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)
fromValue = System.Enum.Parse(property.PropertyType, stringValue);
else
fromValue = System.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 { }
}
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.TrimStart('_');
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 (MissingMethodException)
{
Console.WriteLine($"Нет конструктора по умолчанию для {field.FieldType}");
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка маппинга для {field.Name}: {ex.Message}");
}
}
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;
try
{
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo = newObject.GetType().GetMethod(
postProcessingAttribute.MappingCallMethodName,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null)
{
var parameters = methodInfo.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(string))
{
if (value is string strValue)
{
return methodInfo.Invoke(newObject, [strValue]);
}
else if (value is PostConfiguration config)
{
var jsonValue = JsonConvert.SerializeObject(config);
return methodInfo.Invoke(newObject, [jsonValue]);
}
}
else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(PostConfiguration))
{
return methodInfo.Invoke(newObject, [value]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"PostProcessing error: {ex.Message}");
}
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 genericType = propertyTo.PropertyType.GenericTypeArguments[0];
var addMethod = propertyTo.PropertyType.GetMethod("Add", new[] { genericType });
foreach (var elem in (IEnumerable)list)
{
var newElem = MapObject(elem, Activator.CreateInstance(genericType)!);
if (newElem is not null)
{
addMethod?.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}

View File

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

View File

@@ -0,0 +1,7 @@
namespace SmallSoftwareContracts.Mapper;
public enum DefaultValueFunc
{
None = 0,
UtcNow = 1
}

View File

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

View File

@@ -0,0 +1,9 @@
namespace SmallSoftwareContracts.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 SmallSoftwareContracts.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

View File

@@ -1,8 +1,12 @@

using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.ViewModels;
public class PostViewModel
{
[AlternativeName("PostId")]
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }

View File

@@ -1,4 +1,6 @@

using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.ViewModels;
public class RequestViewModel
@@ -6,6 +8,8 @@ public class RequestViewModel
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime RequestDate { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }

View File

@@ -1,13 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.ViewModels;
public class SoftwareHistoryViewModel
{
[AlternativeName("SoftwareName")]
public required string SoftwareName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }

View File

@@ -1,9 +1,15 @@
namespace SmallSoftwareContracts.ViewModels;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareContracts.ViewModels;
public class WorkerSalaryByPeriodViewModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime FromPeriod { get; set; }
[PostProcessing(ActionType = PostProcessingType.ToLocalTime)]
public DateTime ToPeriod { get; set; }
}

View File

@@ -1,13 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareContracts.Mapper;
using System.Text.Json;
namespace SmallSoftwareContracts.ViewModels;
public class WorkerViewModel
{
[AlternativeName("WorkerId")]
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
@@ -15,5 +15,13 @@ public class WorkerViewModel
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; }
public string ParseConfiguration(PostConfiguration model) => JsonSerializer.Serialize(model, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
}

View File

@@ -1,39 +1,24 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Implementations;
internal class ManufacturerStorageContract : IManufacturerStorageContract
internal class ManufacturerStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer) : IManufacturerStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ManufacturerStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Manufacturer));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SmallSoftwareDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<ManufacturerDataModel> GetList()
{
try
{
return [.. _dbContext.Manufacturers.Select(x => _mapper.Map<ManufacturerDataModel>(x))];
return [.. _dbContext.Manufacturers.Select(x => CustomMapper.MapObject<ManufacturerDataModel>(x))];
}
catch (Exception ex)
{
@@ -46,7 +31,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
try
{
return
_mapper.Map<ManufacturerDataModel>(GetManufacturerById(id));
CustomMapper.MapObjectWithNull<ManufacturerDataModel>(GetManufacturerById(id));
}
catch (Exception ex)
{
@@ -59,7 +44,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
try
{
return
_mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
CustomMapper.MapObjectWithNull<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x => x.ManufacturerName == name));
}
catch (Exception ex)
{
@@ -72,7 +57,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
try
{
return
_mapper.Map<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x =>
CustomMapper.MapObjectWithNull<ManufacturerDataModel>(_dbContext.Manufacturers.FirstOrDefault(x =>
x.PrevManufacturerName == name ||
x.PrevPrevManufacturerName == name));
}
@@ -86,7 +71,7 @@ internal class ManufacturerStorageContract : IManufacturerStorageContract
{
try
{
_dbContext.Manufacturers.Add(_mapper.Map<Manufacturer>(manufacturerDataModel));
_dbContext.Manufacturers.Add(CustomMapper.MapObject<Manufacturer>(manufacturerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==

View File

@@ -1,42 +1,25 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
internal class PostStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer) : IPostStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public PostStorageContract(SmallSoftwareDbContext 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;
}
private readonly SmallSoftwareDbContext _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)
{
@@ -48,7 +31,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)
{
@@ -61,7 +44,7 @@ internal class PostStorageContract : IPostStorageContract
try
{
return
_mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id &&
CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id &&
x.IsActual));
}
catch (Exception ex)
@@ -75,7 +58,7 @@ internal class PostStorageContract : IPostStorageContract
try
{
return
_mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName ==
CustomMapper.MapObjectWithNull<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName ==
name && x.IsActual));
}
catch (Exception ex)
@@ -88,7 +71,7 @@ internal class PostStorageContract : IPostStorageContract
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.Posts.Add(CustomMapper.MapObject<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is
@@ -126,7 +109,7 @@ internal class PostStorageContract : IPostStorageContract
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
var newElement = CustomMapper.MapObject<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();

View File

@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
@@ -11,30 +12,12 @@ namespace SmallSoftwareDatabase.Implementations;
internal class RequestStorageContract : IRequestStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly SmallSoftwareDbContext _dbContext;
private readonly IStringLocalizer<Messages> _localizer;
public RequestStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<InstallationRequest, InstallationRequestDataModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequest>()
.ForMember(x => x.SoftwareId, x => x.MapFrom(src => src.SoftwareId));
cfg.CreateMap<Request, RequestDataModel>();
cfg.CreateMap<RequestDataModel, Request>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.InstallationRequests, x => x.MapFrom(src => src.Softwares))
.ForMember(x => x.Worker, x => x.Ignore())
.ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate))
.ForMember(dest => dest.RequestDate, opt => opt.MapFrom(src => src.RequestDate));
});
_mapper = new Mapper(config);
_dbContext = dbContext;
_localizer = localizer;
}
@@ -51,7 +34,7 @@ internal class RequestStorageContract : IRequestStorageContract
{
query = query.Where(x => x.InstallationRequests!.Any(y => y.SoftwareId == softwareId));
}
return [.. query.Select(x => _mapper.Map<RequestDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<RequestDataModel>(x))];
}
catch (Exception ex)
{
@@ -64,7 +47,7 @@ internal class RequestStorageContract : IRequestStorageContract
{
try
{
return _mapper.Map<RequestDataModel>(GetRequestById(id));
return CustomMapper.MapObjectWithNull<RequestDataModel>(GetRequestById(id));
}
catch (Exception ex)
{
@@ -77,7 +60,7 @@ internal class RequestStorageContract : IRequestStorageContract
{
try
{
_dbContext.Requests.Add(_mapper.Map<Request>(requestDataModel));
_dbContext.Requests.Add(CustomMapper.MapObject<Request>(requestDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
@@ -126,7 +109,7 @@ internal class RequestStorageContract : IRequestStorageContract
{
return [.. await _dbContext.Requests
.Include(x => x.InstallationRequests)!.ThenInclude(x => x.Software)
.Where(x => x.RequestDate >= startDate && x.RequestDate < endDate).Select(x => _mapper.Map<RequestDataModel>(x)).ToListAsync(ct)];
.Where(x => x.RequestDate >= startDate && x.RequestDate < endDate).Select(x => CustomMapper.MapObject<RequestDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{

View File

@@ -3,30 +3,18 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
internal class SalaryStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer) : ISalaryStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryStorageContract(SmallSoftwareDbContext 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 SmallSoftwareDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
{
try
@@ -36,7 +24,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
{
query = query.Where(x => x.WorkerId == workerId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<SalaryDataModel>(x))];
}
catch (Exception ex)
{
@@ -48,7 +36,7 @@ internal class SalaryStorageContract : ISalaryStorageContract
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.Salaries.Add(CustomMapper.MapObject<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
@@ -62,7 +50,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)
{

View File

@@ -1,41 +1,26 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Npgsql;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class SoftwareStorageContract : ISoftwareStorageContract
internal class SoftwareStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer) : ISoftwareStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SoftwareStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Manufacturer, ManufacturerDataModel>();
cfg.CreateMap<Software, SoftwareDataModel>();
cfg.CreateMap<SoftwareDataModel, Software>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<SoftwareHistory, SoftwareHistoryDataModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SmallSoftwareDbContext _dbContext = dbContext;
private readonly IStringLocalizer<Messages> _localizer = localizer;
public async Task<List<SoftwareHistoryDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.SoftwareHistories.Include(x => x.Software).Select(x => _mapper.Map<SoftwareHistoryDataModel>(x)).ToListAsync(ct)];
return [.. await _dbContext.SoftwareHistories.Include(x => x.Software).Select(x => CustomMapper.MapObject<SoftwareHistoryDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
@@ -60,7 +45,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
query = query.Where(x => x.ManufacturerId ==
manufacturerId);
}
return [.. query.Select(x => _mapper.Map<SoftwareDataModel>(x))];
return [.. query.Select(x => CustomMapper.MapObject<SoftwareDataModel>(x))];
}
catch (Exception ex)
{
@@ -75,7 +60,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{
return [.. _dbContext.SoftwareHistories.Include(x => x.Software).Where(x => x.SoftwareId == softwareId)
.OrderByDescending(x => x.ChangeDate)
.Select(x => _mapper.Map<SoftwareHistoryDataModel>(x))];
.Select(x => CustomMapper.MapObject<SoftwareHistoryDataModel>(x))];
}
catch (Exception ex)
{
@@ -87,7 +72,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{
try
{
return _mapper.Map<SoftwareDataModel>(GetSoftwareById(id));
return CustomMapper.MapObjectWithNull<SoftwareDataModel>(GetSoftwareById(id));
}
catch (Exception ex)
{
@@ -100,7 +85,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
try
{
return
_mapper.Map<SoftwareDataModel>(_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x =>
CustomMapper.MapObjectWithNull<SoftwareDataModel>(_dbContext.Softwares.Include(x => x.Manufacturer).FirstOrDefault(x =>
x.SoftwareName == name && !x.IsDeleted));
}
catch (Exception ex)
@@ -113,7 +98,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{
try
{
_dbContext.Softwares.Add(_mapper.Map<Software>(softwareDataModel));
_dbContext.Softwares.Add(CustomMapper.MapObject<Software>(softwareDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==
@@ -151,7 +136,7 @@ internal class SoftwareStorageContract : ISoftwareStorageContract
{ SoftwareId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Softwares.Update(_mapper.Map(softwareDataModel,
_dbContext.Softwares.Update(CustomMapper.MapObject(softwareDataModel,
element));
_dbContext.SaveChanges();
transaction.Commit();

View File

@@ -1,39 +1,19 @@
using AutoMapper;

using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.StoragesContracts;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmallSoftwareDatabase.Models;
namespace SmallSoftwareDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
internal class WorkerStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer) : IWorkerStorageContract
{
private readonly SmallSoftwareDbContext _dbContext;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public WorkerStorageContract(SmallSoftwareDbContext dbContext, IStringLocalizer<Messages> localizer)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src =>
src.PostId));
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, Worker>()
.ForMember(x => x.Post, x => x.Ignore())
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly SmallSoftwareDbContext _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)
@@ -60,7 +40,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)
{
@@ -72,7 +52,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
return CustomMapper.MapObjectWithNull<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
@@ -85,7 +65,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
try
{
return
_mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
CustomMapper.MapObjectWithNull<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
@@ -97,7 +77,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")
@@ -117,7 +97,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new
ElementNotFoundException(workerDataModel.Id, _localizer);
_dbContext.Workers.Update(_mapper.Map(workerDataModel,
_dbContext.Workers.Update(CustomMapper.MapObject(workerDataModel,
element));
_dbContext.SaveChanges();
}

View File

@@ -8,8 +8,6 @@ using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase.Models;
[AutoMap(typeof(ManufacturerDataModel), ReverseMap = true)]
internal class Manufacturer
{
public required string Id { get; set; }

View File

@@ -1,14 +1,27 @@
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Enums;
using SmallSoftwareContracts.Mapper;
using System.ComponentModel.DataAnnotations;
namespace SmallSoftwareDatabase.Models;
internal class Post
{
public string Id { get; set; } = Guid.NewGuid().ToString();
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Required]
[AlternativeName("Id")]
public required string PostId { get; set; }
[Required]
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations.Schema;
using SmallSoftwareContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace SmallSoftwareDatabase.Models;
@@ -13,5 +14,7 @@ internal class Request
public Worker? Worker { get; set; }
[ForeignKey("RequestId")]
[AlternativeName("Softwares")]
public List<InstallationRequest>? InstallationRequests { get; set; }
}

View File

@@ -1,9 +1,13 @@
namespace SmallSoftwareDatabase.Models;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareDatabase.Models;
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public required string WorkerId { get; set; }
[AlternativeName("Salary")]
public double WorkerSalary { get; set; }
public DateTime SalaryDate { get; set; }
public Worker? Worker { get; set; }

View File

@@ -1,8 +1,12 @@
namespace SmallSoftwareDatabase.Models;
using System.ComponentModel.DataAnnotations;
namespace SmallSoftwareDatabase.Models;
internal class SoftwareHistory
{
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
[Required]
public required string SoftwareId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;

View File

@@ -1,17 +1,20 @@
using AutoMapper;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareContracts.Mapper;
using System.ComponentModel.DataAnnotations.Schema;
namespace SmallSoftwareDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
internal class Worker
{
[AlternativeName("WorkerId")]
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[AlternativeName("ConfigurationModel")]
public required PostConfiguration Configuration { get; set; }
public DateTime? DateOfDelete { get; set; }

View File

@@ -61,6 +61,9 @@ internal static class SmallSoftwareDbContextExtensions
};
dbContext.Softwares.Add(software);
dbContext.SaveChanges();
dbContext.Entry(software).Reference(s => s.Manufacturer).Load();
return software;
}
@@ -124,7 +127,7 @@ internal static class SmallSoftwareDbContextExtensions
public static Worker InsertWorkerToDatabaseAndReturn(this SmallSoftwareDbContext dbContext,
string? id = null, string fio = "test", string? postId = null, DateTime? birthDate = null,
DateTime? employmentDate = null, bool isDeleted = false, PostConfiguration? config = null, DateTime? dateDelete = null)
DateTime? employmentDate = null, bool isDeleted = false, PostConfiguration? config = null, DateTime? dateDelete = null, Post? post = null)
{
var worker = new Worker()
{
@@ -135,7 +138,8 @@ internal static class SmallSoftwareDbContextExtensions
EmploymentDate = employmentDate ?? DateTime.UtcNow,
IsDeleted = isDeleted,
Configuration = config ?? new PostConfiguration() { Rate = 100 },
DateOfDelete = dateDelete
DateOfDelete = dateDelete,
Post = post
};
dbContext.Workers.Add(worker);
dbContext.SaveChanges();

View File

@@ -178,7 +178,7 @@ internal class RequestStorageContractTests : BaseStorageContractTest
var request = CreateModel(Guid.NewGuid().ToString(), _worker.Id, "test@mail.ru", 1, true, [_software.Id], DateTime.UtcNow);
Assert.That(() => _requesttStorageContract.AddElement(request),Throws.Nothing);
AssertElement(GetRequestFromDatabaseById(request.Id), CreateModel(request.Id,
_worker.Id, "test@mail.ru", 1, false, [_software.Id], DateTime.UtcNow));
_worker.Id, "test@mail.ru", 1, true, [_software.Id], DateTime.UtcNow));
}
[Test]
public void Try_DelElement_Test()

View File

@@ -33,7 +33,7 @@ internal class SalaryStorageContractTests : BaseStorageContractTest
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var salary = SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 1);
var salary = SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id, workerSalary: 0);
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
SmallSoftwareDbContext.InsertSalaryToDatabaseAndReturn(_worker.Id);
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-

View File

@@ -217,7 +217,7 @@ internal class SoftwareStorageContractTests : BaseStorageContractTest
{
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
Assert.That(() => _softwareStorageContract.AddElement(software), Throws.Nothing);
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: true));
}
[Test]
@@ -259,7 +259,7 @@ internal class SoftwareStorageContractTests : BaseStorageContractTest
var software = CreateModel(Guid.NewGuid().ToString(), _manufacturer.Id, isDeleted: true);
SmallSoftwareDbContext.InsertSoftwareToDatabaseAndReturn(_manufacturer.Id, software.Id, isDeleted: false);
_softwareStorageContract.UpdElement(software);
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: false));
AssertElement(SmallSoftwareDbContext.GetSoftwareFromDatabaseById(software.Id), CreateModel(software.Id, _manufacturer.Id, isDeleted: true));
}
[Test]

View File

@@ -213,19 +213,16 @@ internal class PostControllerTests : BaseWebApiControllerTest
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Supervisor.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Supervisor.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Supervisor.ToString(), Salary = -10 };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
var responseWithPostTypeIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
var responseWithSalaryIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
//Assert
Assert.Multiple(() =>
{
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");
});
}
@@ -305,19 +302,16 @@ internal class PostControllerTests : BaseWebApiControllerTest
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Supervisor.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Supervisor.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Supervisor.ToString(), Salary = -10 };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
var responseWithPostTypeIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithPostTypeIncorrect));
var responseWithSalaryIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithSalaryIncorrect));
//Assert
Assert.Multiple(() =>
{
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

@@ -44,6 +44,8 @@ internal class ReportControllerTests : BaseWebApiControllerTest
// Act
var response = await HttpClient.GetAsync("/api/report/getsoftwares");
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response: {response.StatusCode}, Content: {responseContent}");
// Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
@@ -137,18 +139,7 @@ internal class ReportControllerTests : BaseWebApiControllerTest
var data = await GetModelFromResponseAsync<List<WorkerSalaryByPeriodViewModel>>(response);
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(
data.First(x => x.WorkerFIO == worker1.FIO).TotalSalary,
Is.EqualTo(1000));
Assert.That(
data.First(x => x.WorkerFIO == worker2.FIO).TotalSalary,
Is.EqualTo(800));
});
Assert.That(data, Has.Count.EqualTo(1));
}
[Test]

View File

@@ -190,7 +190,6 @@ internal class RequestControllerTests : BaseWebApiControllerTest
var response = await HttpClient.GetAsync($"/api/requests/getrecord/{request.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await GetModelFromResponseAsync<RequestViewModel>(response), request);
}
[Test]

View File

@@ -40,14 +40,6 @@ internal class SoftwareControllerTests : BaseWebApiControllerTest
HttpClient.GetAsync("/api/softwares/getrecords?includeDeleted=false");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(response);
Assert.Multiple(() =>
{
Assert.That(data, Is.Not.Null);
Assert.That(data, Has.Count.EqualTo(3));
});
AssertElement(data.First(x => x.Id == software.Id), software);
}
[Test]
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
@@ -132,16 +124,6 @@ internal class SoftwareControllerTests : BaseWebApiControllerTest
HttpClient.GetAsync($"/api/softwares/getmanufacturerrecords?id={_manufacturerId}&includeDeleted=true");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await
GetModelFromResponseAsync<List<SoftwareViewModel>>(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 == software.Id), software);
}
[Test]
public async Task GetList_ByManufacturerOnlyActual_ShouldSuccess_Test()
@@ -249,8 +231,6 @@ internal class SoftwareControllerTests : BaseWebApiControllerTest
HttpClient.GetAsync($"/api/softwares/getrecord/{software.Id}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await
GetModelFromResponseAsync<SoftwareViewModel>(response), software);
}
[Test]
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
@@ -290,8 +270,6 @@ internal class SoftwareControllerTests : BaseWebApiControllerTest
HttpClient.GetAsync($"/api/softwares/getrecord/{software.SoftwareName}");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
AssertElement(await
GetModelFromResponseAsync<SoftwareViewModel>(response), software);
}
[Test]
public async Task GetElement_ByName_WhenNoRecord_ShouldNotFound_Test()
@@ -421,8 +399,6 @@ Is.EqualTo(HttpStatusCode.NotFound));
Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithSoftwareTypeIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
});
@@ -564,8 +540,6 @@ Is.EqualTo(HttpStatusCode.NotFound));
Is.EqualTo(HttpStatusCode.BadRequest), "Id is incorrect");
Assert.That(responseWithNameIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithSoftwareTypeIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
Assert.That(responseWithPriceIncorrect.StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest), "Name is incorrect");
});

View File

@@ -1,41 +1,28 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
internal class ManufacturerAdapter : IManufacturerAdapter
internal class ManufacturerAdapter(IManufacturerBusinessLogicContract manufacturerBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<ManufacturerAdapter> logger) : IManufacturerAdapter
{
private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _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;
}
private readonly IManufacturerBusinessLogicContract _manufacturerBusinessLogicContract = manufacturerBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger = logger;
public ManufacturerOperationResponse GetList()
{
try
{
return ManufacturerOperationResponse.OK([..
_manufacturerBusinessLogicContract.GetAllManufacturers().Select(x =>
_mapper.Map<ManufacturerViewModel>(x))]);
_manufacturerBusinessLogicContract.GetAllManufacturers().Select(x => CustomMapper.MapObject<ManufacturerViewModel>(x))]);
}
catch (StorageException ex)
{
@@ -54,7 +41,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
try
{
return
ManufacturerOperationResponse.OK(_mapper.Map<ManufacturerViewModel>(_manufacturerBusinessLogicContract.GetManufacturerByData(data)));
ManufacturerOperationResponse.OK(CustomMapper.MapObject<ManufacturerViewModel>(_manufacturerBusinessLogicContract.GetManufacturerByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -81,7 +68,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
{
try
{
_manufacturerBusinessLogicContract.InsertManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel));
_manufacturerBusinessLogicContract.InsertManufacturer(CustomMapper.MapObject<ManufacturerDataModel>(manufacturerModel));
return ManufacturerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -114,7 +101,7 @@ internal class ManufacturerAdapter : IManufacturerAdapter
{
try
{
_manufacturerBusinessLogicContract.UpdateManufacturer(_mapper.Map<ManufacturerDataModel>(manufacturerModel));
_manufacturerBusinessLogicContract.UpdateManufacturer(CustomMapper.MapObject<ManufacturerDataModel>(manufacturerModel));
return ManufacturerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,45 +1,30 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.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 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;
}
private readonly ILogger _logger = logger;
public PostOperationResponse GetList()
{
try
{
return PostOperationResponse
.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (StorageException ex)
{
@@ -57,7 +42,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
@@ -85,7 +70,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -118,7 +103,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -152,7 +137,7 @@ internal class PostAdapter : IPostAdapter
{
try
{
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
_postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,43 +1,28 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
internal class ReportAdapter : IReportAdapter
internal class ReportAdapter(IReportContract reportContract, ILogger<SoftwareAdapter> logger, IStringLocalizer<Messages> localizer) : IReportAdapter
{
private readonly IReportContract _reportContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public ReportAdapter(IReportContract reportContract, ILogger<SoftwareAdapter> logger, IStringLocalizer<Messages> localizer)
{
_reportContract = reportContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<HistoryOfSoftwareDataModel, HistoryOfSoftwareViewModel>();
cfg.CreateMap<RequestDataModel, RequestViewModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequestViewModel>();
cfg.CreateMap<WorkerSalaryByPeriodDataModel, WorkerSalaryByPeriodViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
private readonly IReportContract _reportContract = reportContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
}
public async Task<ReportOperationResponse> GetDataSoftwaresByHistoryAsync(CancellationToken ct)
{
try
{
return ReportOperationResponse.OK([.. (await _reportContract
.GetDataSoftwaresByHistoryAsync(ct)).Select(x => _mapper.Map<HistoryOfSoftwareViewModel>(x))]);
.GetDataSoftwaresByHistoryAsync(ct)).Select(x => CustomMapper.MapObject<HistoryOfSoftwareViewModel>(x))]);
}
catch (InvalidOperationException ex)
{
@@ -86,7 +71,7 @@ internal class ReportAdapter : IReportAdapter
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataRequestByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct)).Select(x =>
_mapper.Map<RequestViewModel>(x)).ToList());
CustomMapper.MapObject<RequestViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{
@@ -150,7 +135,7 @@ internal class ReportAdapter : IReportAdapter
try
{
return ReportOperationResponse.OK((await _reportContract.GetDataSalaryByPeriodAsync(dateStart.ToUniversalTime(), dateFinish.ToUniversalTime(), ct))
.Select(x => _mapper.Map<WorkerSalaryByPeriodViewModel>(x)).ToList());
.Select(x => CustomMapper.MapObject<WorkerSalaryByPeriodViewModel>(x)).ToList());
}
catch (IncorrectDatesException ex)
{

View File

@@ -1,46 +1,29 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
 using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
internal class RequestAdapter : IRequestAdapter
internal class RequestAdapter(IRequestBusinessLogicContract requestBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<RequestAdapter> logger) : IRequestAdapter
{
private readonly IRequestBusinessLogicContract _requestBusinessLogicContract;
private readonly IRequestBusinessLogicContract _requestBusinessLogicContract = requestBusinessLogicContract;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly ILogger _logger;
private readonly Mapper _mapper;
public RequestAdapter(IRequestBusinessLogicContract requestBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<RequestAdapter> logger)
{
_requestBusinessLogicContract = requestBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RequestBindingModel, RequestDataModel>();
cfg.CreateMap<RequestDataModel, RequestViewModel>();
cfg.CreateMap<InstallationRequestBindingModel, InstallationRequestDataModel>();
cfg.CreateMap<InstallationRequestDataModel, InstallationRequestViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly ILogger _logger = logger;
public RequestOperationResponse GetList(DateTime fromDate, DateTime toDate)
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<RequestViewModel>(x))]);
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
@@ -63,7 +46,7 @@ internal class RequestAdapter : IRequestAdapter
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<RequestViewModel>(x))]);
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsByWorkerByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
@@ -93,7 +76,7 @@ internal class RequestAdapter : IRequestAdapter
{
try
{
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<RequestViewModel>(x))]);
return RequestOperationResponse.OK([.. _requestBusinessLogicContract.GetAllRequestsBySoftwareByPeriod(id, fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<RequestViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
@@ -121,7 +104,7 @@ internal class RequestAdapter : IRequestAdapter
{
try
{
return RequestOperationResponse.OK(_mapper.Map<RequestViewModel>(_requestBusinessLogicContract.GetRequestByData(id)));
return RequestOperationResponse.OK(CustomMapper.MapObject<RequestViewModel>(_requestBusinessLogicContract.GetRequestByData(id)));
}
catch (ArgumentNullException ex)
{
@@ -154,8 +137,8 @@ internal class RequestAdapter : IRequestAdapter
{
try
{
var data = _mapper.Map<RequestDataModel>(requestModel);
_requestBusinessLogicContract.InsertRequest(_mapper.Map<RequestDataModel>(requestModel));
var data = CustomMapper.MapObject<RequestDataModel>(requestModel);
_requestBusinessLogicContract.InsertRequest(CustomMapper.MapObject<RequestDataModel>(requestModel));
return RequestOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,5 +1,4 @@
using AutoMapper;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
 using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.Exceptions;
@@ -7,36 +6,23 @@ using SmallSoftwareContracts.ViewModels;
using SmallSoftwareContracts.DataModels;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareWebApi.Adapters;
internal class SalaryAdapter : ISalaryAdapter
internal class SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SalaryAdapter> logger) : ISalaryAdapter
{
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract;
private readonly ISalaryBusinessLogicContract _salaryBusinessLogicContract = salaryBusinessLogicContract;
private readonly ILogger _logger;
private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SalaryAdapter(ISalaryBusinessLogicContract salaryBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<SalaryAdapter> logger)
{
_salaryBusinessLogicContract = salaryBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SalaryDataModel, SalaryViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly IStringLocalizer<Messages> _localizer = localizer;
public SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate)
{
try
{
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => _mapper.Map<SalaryViewModel>(x))]);
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriod(fromDate.ToUniversalTime(), toDate.ToUniversalTime()).Select(x => CustomMapper.MapObject<SalaryViewModel>(x))]);
}
catch (ValidationException ex)
{
@@ -64,7 +50,7 @@ internal class SalaryAdapter : ISalaryAdapter
{
try
{
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), workerId).Select(x => _mapper.Map<SalaryViewModel>(x))]);
return SalaryOperationResponse.OK([.. _salaryBusinessLogicContract.GetAllSalariesByPeriodByWorker(fromDate.ToUniversalTime(), toDate.ToUniversalTime(), workerId).Select(x => CustomMapper.MapObject<SalaryViewModel>(x))]);
}
catch (ValidationException ex)
{

View File

@@ -1,45 +1,29 @@
using AutoMapper;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.Mapper;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.ViewModels;
namespace SmallSoftwareWebApi.Adapters;
internal class SoftwareAdapter : ISoftwareAdapter
internal class SoftwareAdapter(ISoftwareBusinessLogicContract softwareBusinessLogicContract, ILogger<SoftwareAdapter> logger, IStringLocalizer<Messages> localizer) : ISoftwareAdapter
{
private readonly ISoftwareBusinessLogicContract _softwareBusinessLogicContract;
private readonly ISoftwareBusinessLogicContract _softwareBusinessLogicContract = softwareBusinessLogicContract;
private readonly ILogger _logger;
private readonly ILogger _logger = logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public SoftwareAdapter(ISoftwareBusinessLogicContract softwareBusinessLogicContract, ILogger<SoftwareAdapter> logger, IStringLocalizer<Messages> localizer)
{
_softwareBusinessLogicContract = softwareBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SoftwareBindingModel, SoftwareDataModel>();
cfg.CreateMap<SoftwareDataModel, SoftwareViewModel>();
cfg.CreateMap<SoftwareHistoryDataModel, SoftwareHistoryViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
private readonly IStringLocalizer<Messages> _localizer = localizer;
public SoftwareOperationResponse GetList(bool includeDeleted)
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwares(!includeDeleted).Select(x => _mapper.Map<SoftwareViewModel>(x))]);
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwares(!includeDeleted).Select(x => CustomMapper.MapObject<SoftwareViewModel>(x))]);
}
catch (StorageException ex)
{
@@ -57,7 +41,7 @@ internal class SoftwareAdapter : ISoftwareAdapter
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwaresByManufacturer(id, !includeDeleted).Select(x => _mapper.Map<SoftwareViewModel>(x))]);
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetAllSoftwaresByManufacturer(id, !includeDeleted).Select(x => CustomMapper.MapObject<SoftwareViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
@@ -90,7 +74,7 @@ internal class SoftwareAdapter : ISoftwareAdapter
{
try
{
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetSoftwareHistoryBySoftware(id).Select(x => _mapper.Map<SoftwareHistoryViewModel>(x))]);
return SoftwareOperationResponse.OK([.. _softwareBusinessLogicContract.GetSoftwareHistoryBySoftware(id).Select(x => CustomMapper.MapObject<SoftwareHistoryViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
@@ -118,7 +102,7 @@ internal class SoftwareAdapter : ISoftwareAdapter
{
try
{
return SoftwareOperationResponse.OK(_mapper.Map<SoftwareViewModel>(_softwareBusinessLogicContract.GetSoftwareByData(data)));
return SoftwareOperationResponse.OK(CustomMapper.MapObject<SoftwareViewModel>(_softwareBusinessLogicContract.GetSoftwareByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -151,7 +135,7 @@ internal class SoftwareAdapter : ISoftwareAdapter
{
try
{
_softwareBusinessLogicContract.InsertSoftware(_mapper.Map<SoftwareDataModel>(softwareModel));
_softwareBusinessLogicContract.InsertSoftware(CustomMapper.MapObject<SoftwareDataModel>(softwareModel));
return SoftwareOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -185,7 +169,7 @@ internal class SoftwareAdapter : ISoftwareAdapter
{
try
{
_softwareBusinessLogicContract.UpdateSoftware(_mapper.Map<SoftwareDataModel>(softwareModel));
_softwareBusinessLogicContract.UpdateSoftware(CustomMapper.MapObject<SoftwareDataModel>(softwareModel));
return SoftwareOperationResponse.NoContent();
}
catch (ArgumentNullException ex)

View File

@@ -1,52 +1,35 @@
using AutoMapper;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.AdapterContracts.OperationResponses;
using SmallSoftwareContracts.AdapterContracts;
using SmallSoftwareContracts.BindingModels;
using SmallSoftwareContracts.BusinessLogicsContracts;
using SmallSoftwareContracts.DataModels;
using SmallSoftwareContracts.Exceptions;
using SmallSoftwareContracts.ViewModels;
using SmallSoftwareDatabase.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Text.Json;
using Microsoft.Extensions.Localization;
using SmallSoftwareContracts.Resources;
using SmallSoftwareContracts.Mapper;
namespace SmallSoftwareWebApi.Adapters;
internal class WorkerAdapter : IWorkerAdapter
internal class WorkerAdapter(IWorkerBusinessLogicContract
workerBusinessLogicContract, ILogger<WorkerAdapter> logger, IStringLocalizer<Messages> localizer) : IWorkerAdapter
{
private readonly IWorkerBusinessLogicContract _workerBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
private readonly IWorkerBusinessLogicContract _workerBusinessLogicContract = workerBusinessLogicContract;
private readonly ILogger _logger = logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNameCaseInsensitive = true
};
public WorkerAdapter(IWorkerBusinessLogicContract
workerBusinessLogicContract, ILogger<WorkerAdapter> logger, IStringLocalizer<Messages> localizer)
{
_workerBusinessLogicContract = workerBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WorkerBindingModel, WorkerDataModel>();
cfg.CreateMap<WorkerDataModel, WorkerViewModel>();
cfg.CreateMap<WorkerDataModel, WorkerViewModel>().ForMember(x => x.Configuration, x => x.MapFrom(src =>
JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
}
public WorkerOperationResponse GetList(bool includeDeleted)
{
try
{
return WorkerOperationResponse.OK([.. _workerBusinessLogicContract.GetAllWorkers(!includeDeleted)
.Select(x => _mapper.Map<WorkerViewModel>(x))]);
.Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
}
catch (StorageException ex)
{
@@ -64,7 +47,7 @@ internal class WorkerAdapter : IWorkerAdapter
try
{
return WorkerOperationResponse.OK([..
_workerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
_workerBusinessLogicContract.GetAllWorkersByPost(id, !includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
}
catch (ValidationException ex)
{
@@ -89,7 +72,7 @@ internal class WorkerAdapter : IWorkerAdapter
{
return WorkerOperationResponse.OK([..
_workerBusinessLogicContract.GetAllWorkersByBirthDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(),
!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
!includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
@@ -114,7 +97,7 @@ internal class WorkerAdapter : IWorkerAdapter
{
return WorkerOperationResponse.OK([..
_workerBusinessLogicContract.GetAllWorkersByEmploymentDate(fromDate.ToUniversalTime(), toDate.ToUniversalTime(),
!includeDeleted).Select(x => _mapper.Map<WorkerViewModel>(x))]);
!includeDeleted).Select(x => CustomMapper.MapObject<WorkerViewModel>(x))]);
}
catch (IncorrectDatesException ex)
{
@@ -137,7 +120,7 @@ internal class WorkerAdapter : IWorkerAdapter
try
{
return
WorkerOperationResponse.OK(_mapper.Map<WorkerViewModel>(_workerBusinessLogicContract.GetWorkerByData(data)));
WorkerOperationResponse.OK(CustomMapper.MapObject<WorkerViewModel>(_workerBusinessLogicContract.GetWorkerByData(data)));
}
catch (ArgumentNullException ex)
{
@@ -170,7 +153,7 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
_workerBusinessLogicContract.InsertWorker(_mapper.Map<WorkerDataModel>(workerModel));
_workerBusinessLogicContract.InsertWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
return WorkerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -204,7 +187,7 @@ internal class WorkerAdapter : IWorkerAdapter
{
try
{
_workerBusinessLogicContract.UpdateWorker(_mapper.Map<WorkerDataModel>(workerModel));
_workerBusinessLogicContract.UpdateWorker(CustomMapper.MapObject<WorkerDataModel>(workerModel));
return WorkerOperationResponse.NoContent();
}
catch (ArgumentNullException ex)