17 Commits

Author SHA1 Message Date
3501f2a724 test fix 2025-04-15 15:51:05 +04:00
86881f7317 lab3-ready 2025-04-15 02:40:51 +04:00
d51c616862 fix 2025-04-15 01:47:02 +04:00
4518d36016 lab2-ready 2025-04-15 01:25:50 +04:00
e0f0af6754 Add mock operations 2025-03-26 21:51:51 +04:00
dbde99c7eb Wip beda 2025-03-13 15:40:49 +04:00
fa6b1b64a2 lab2 hard ready 2025-03-11 21:44:01 +04:00
bdb510f098 lab-2 merged to lab2-hard 2025-03-11 21:18:14 +04:00
75c5ceabc0 red-line 2025-03-11 21:11:14 +04:00
514f2adefb lab1-hard merged to lab2-hard-no-logic 2025-03-11 20:45:10 +04:00
6ad09c5ff2 Merge branch 'refs/heads/lab-1-hard' into lab-2-hard-no-logic
# Conflicts:
#	CandyHouseSolution/CandyHouseBase/DataModels/StorageDataModel.cs
2025-03-11 20:37:07 +04:00
807ac64a9f fix 2025-03-11 20:36:00 +04:00
ffaeb985e5 Revert "lab1-hard"
This reverts commit b4819145
2025-03-11 20:27:46 +04:00
7b71b14c71 Merge branch 'refs/heads/lab-1-hard' into lab-2-hard-no-logic
# Conflicts:
#	CandyHouseSolution/CandyHouseBase/CandyHouseBase.csproj
2025-03-11 20:26:20 +04:00
b481914563 lab1-hard 2025-02-27 12:01:44 +04:00
805a1d0322 RED LINE UPDATE 2025-02-27 02:25:39 +04:00
79cdd4b5d7 fail tests commit 2025-02-26 23:49:16 +04:00
131 changed files with 9020 additions and 1124 deletions

View File

@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"
Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"/>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CandyHouseBase</RootNamespace>
<AssemblyName>CandyHouseBase</AssemblyName>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System"/>
<Reference Include="System.Core"/>
<Reference Include="System.Data"/>
<Reference Include="System.Xml"/>
</ItemGroup>
<ItemGroup>
<Compile Include="DataModels\IngredientDataModel.cs" />
<Compile Include="DataModels\OrderDataModel.cs" />
<Compile Include="DataModels\PekarDataModel.cs" />
<Compile Include="DataModels\PekarHistoryDataModel.cs" />
<Compile Include="DataModels\PositionDataModel.cs" />
<Compile Include="DataModels\ProductDataModel.cs" />
<Compile Include="DataModels\RecipeDataModel.cs" />
<Compile Include="DataModels\SalaryDataModel.cs" />
<Compile Include="Enums\PositionType.cs" />
<Compile Include="Enums\StatusType.cs" />
<Compile Include="Exceptions\ValidationException.cs" />
<Compile Include="Extensions\StringExtensions.cs" />
<Compile Include="Infrastructure\IValidation.cs" />
<Compile Include="Program.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -1,31 +0,0 @@
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class IngredientDataModel : IValidation
{
public string Id { get; private set; }
public string Name { get; private set; }
public string Unit { get; private set; }
public decimal Cost { get; private set; }
public IngredientDataModel(string id, string name, string unit, decimal cost)
{
Id = id;
Name = name;
Unit = unit;
Cost = cost;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
if (Name.IsEmpty()) throw new ValidationException("Field Name is empty");
if (Unit.IsEmpty()) throw new ValidationException("Field Unit is empty");
if (Cost < 0) throw new ValidationException("Cost must be non-negative");
}
}
}

View File

@@ -1,46 +0,0 @@
using System;
using System.Collections.Generic;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class OrderDataModel : IValidation
{
public string Id { get; private set; }
public string CustomerName { get; private set; } // Может быть null, если клиент разовый
public DateTime OrderDate { get; private set; }
public decimal TotalAmount { get; private set; }
public decimal DiscountAmount { get; private set; }
public string OrderId { get; private set; }
public string PekarId { get; private set; }
public StatusType StatusType { get; private set; }
public OrderDataModel(string id, string customerName, DateTime orderDate, decimal totalAmount,
decimal discountAmount, string orderId, string pekarId, StatusType statusType)
{
Id = id;
CustomerName = customerName;
OrderDate = orderDate;
TotalAmount = totalAmount;
DiscountAmount = discountAmount;
OrderId = orderId;
PekarId = pekarId;
StatusType = statusType;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
if (CustomerName.IsEmpty())
throw new ValidationException("CustomerName is empty");
if (TotalAmount < 0) throw new ValidationException("TotalAmount cannot be negative");
if (DiscountAmount < 0) throw new ValidationException("DiscountAmount cannot be negative");
if (OrderId.IsEmpty()) throw new ValidationException("Field OrderId is empty");
if (!OrderId.IsGuid()) throw new ValidationException("OrderId must be a GUID");
}
}
}

View File

@@ -1,42 +0,0 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Infrastructure;
using CandyHouseBase.Extensions;
namespace CandyHouseBase.DataModels
{
public class PekarDataModel : IValidation
{
public string Id { get; private set; }
public string FIO { get; private set; }
public string Position { get; private set; }
public decimal BonusCoefficient { get; private set; }
public List<ProductDataModel> ProductsItems { get; private set; }
public PekarDataModel(string id, string fio, string position, decimal bonusCoefficient,
List<ProductDataModel> productsItems)
{
Id = id;
FIO = fio;
Position = position;
BonusCoefficient = bonusCoefficient;
ProductsItems = productsItems;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
if (FIO.IsEmpty()) throw new ValidationException("Field FIO is empty");
var fioPattern = @"^[A-Za-zА-Яа-яЁё\s\-]+$";
if (!Regex.IsMatch(FIO, fioPattern))
throw new ValidationException("FIO contains invalid characters");
if (Position.IsEmpty()) throw new ValidationException("Field Position is empty");
if (!Position.IsGuid()) throw new ValidationException("Field must be a GUID");
if (BonusCoefficient <= 0) throw new ValidationException("BonusCoefficient must be positive");
}
}
}

View File

@@ -1,35 +0,0 @@
using System;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Infrastructure;
using CandyHouseBase.Extensions;
namespace CandyHouseBase.DataModels
{
public class PekarHistoryDataModel : IValidation
{
public string PekarId { get; private set; }
public string FIO { get; private set; }
public string PositionId { get; private set; }
public DateTime Date { get; private set; }
public decimal BonusCoefficient { get; private set; }
public PekarHistoryDataModel(string peKarId, string fio, string positionId, decimal bonusCoefficient, DateTime dateTime)
{
PekarId = peKarId;
FIO = fio;
PositionId = positionId;
BonusCoefficient = bonusCoefficient;
Date = dateTime;
}
public void Validate()
{
if (PekarId.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!PekarId.IsGuid()) throw new ValidationException("Id must be a GUID");
if (FIO.IsEmpty()) throw new ValidationException("Field FIO is empty");
if (PositionId.IsEmpty()) throw new ValidationException("Field Position is empty");
if (!PositionId.IsGuid()) throw new ValidationException("Field must be a GUID");
if (BonusCoefficient <= 0) throw new ValidationException("BonusCoefficient must be positive");
}
}
}

View File

@@ -1,35 +0,0 @@
using System;
using System.Text.RegularExpressions;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class PositionDataModel : IValidation
{
public string Id { get; set; }
public PositionType Type { get; set; }
public string Title { get; set; }
public PositionDataModel(string id, PositionType type, string title)
{
Id = id;
Type = type;
Title = title;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
var titlePattern = @"^[A-Za-zА-Яа-яЁё\s\-]+$";
if (!Regex.IsMatch(Title, titlePattern))
throw new ValidationException("FIO contains invalid characters");
if (string.IsNullOrEmpty(Title)) throw new ValidationException("Field Title is empty");
if (!Enum.IsDefined(typeof(PositionType), Type)) throw new ValidationException("Invalid PositionType");
}
}
}

View File

@@ -1,58 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class ProductDataModel : IValidation
{
public string Id { get; private set; }
public string Name
{
get => name;
private set
{
if (!name.IsEmpty()) OldName = name;
name = value.Trim();
}
}
public string Description
{
get => description;
private set
{
if (!description.IsEmpty()) OldDescription = description;
description = value.Trim();
}
}
public string OldName { get; private set; }
public string OldDescription { get; private set; }
private string name;
private string description;
public List<IngredientDataModel> IngredientsItems { get; private set; }
public ProductDataModel(string id, string name, string description, List<IngredientDataModel> ingredients)
{
Id = id;
Name = name;
Description = description;
IngredientsItems = ingredients;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
if (Name.IsEmpty()) throw new ValidationException("Field Name is empty");
if (Description.IsEmpty()) throw new ValidationException("Field Description is empty");
if (IngredientsItems.Count == 0) throw new ValidationException("Field IngredientsItems is empty");
}
}
}

View File

@@ -1,27 +0,0 @@
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class RecipeDataModel : IValidation
{
public string ProductId { get; private set; }
public string IngredientId { get; private set; }
public int Quantity { get; private set; }
public RecipeDataModel(string productId, string ingredientId, int quantity)
{
ProductId = productId;
IngredientId = ingredientId;
Quantity = quantity;
}
public void Validate()
{
if (!ProductId.IsGuid()) throw new ValidationException("ProductId must be a GUID");
if (!IngredientId.IsGuid()) throw new ValidationException("IngredientId must be a GUID");
if (Quantity <= 0) throw new ValidationException("Quantity must be positive");
}
}
}

View File

@@ -1,38 +0,0 @@
using System;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class SalaryDataModel : IValidation
{
public string Id { get; private set; }
public string PekarId { get; private set; }
public DateTime Period { get; private set; }
public decimal BaseRate { get; private set; }
public decimal BonusRate { get; private set; }
public decimal TotalSalary { get; private set; }
public SalaryDataModel(string id, string pekarId, DateTime period, decimal baseRate, decimal bonusRate, decimal totalSalary)
{
Id = id;
PekarId = pekarId;
Period = period;
BaseRate = baseRate;
BonusRate = bonusRate;
TotalSalary = totalSalary;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Id must be a GUID");
if (PekarId.IsEmpty()) throw new ValidationException("Field PekarId is empty");
if (!PekarId.IsGuid()) throw new ValidationException("PekarId must be a GUID");
if (BaseRate < 0) throw new ValidationException("BaseRate cannot be negative");
if (BonusRate < 0) throw new ValidationException("BonusRate cannot be negative");
if (TotalSalary < 0) throw new ValidationException("TotalSalary cannot be negative");
}
}
}

View File

@@ -1,10 +0,0 @@
namespace CandyHouseBase.Enums
{
public enum PositionType
{
None = 1,
Small = 2,
Medium = 3,
Cool = 4,
}
}

View File

@@ -1,10 +0,0 @@
namespace CandyHouseBase.Enums
{
public enum StatusType
{
Pending,
Completed,
Cancelled,
InProgress
}
}

View File

@@ -1,9 +0,0 @@
using System;
namespace CandyHouseBase.Exceptions
{
public class ValidationException : Exception
{
public ValidationException(string message) : base(message) { }
}
}

View File

@@ -1,10 +0,0 @@
using System;
namespace CandyHouseBase.Extensions
{
public static class StringExtensions
{
public static bool IsEmpty(this string str) => string.IsNullOrWhiteSpace(str);
public static bool IsGuid(this string str) => Guid.TryParse(str, out _);
}
}

View File

@@ -1,7 +0,0 @@
namespace CandyHouseBase.Infrastructure
{
public interface IValidation
{
void Validate();
}
}

View File

@@ -1,9 +0,0 @@
namespace CandyHouseBase
{
public class Program
{
public static void Main(string[] args)
{
}
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="CandyHouseTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CandyHouseContracts\CandyHouseContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,75 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
public List<ClientDataModel> GetAllClients()
{
_logger.LogInformation("GetAllClients");
return _clientStorageContract.GetList() ?? throw new NullListException();
}
public ClientDataModel GetClientByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _clientStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
{
return _clientStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _clientStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertClient(ClientDataModel clientDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate();
_clientStorageContract.AddElement(clientDataModel);
}
public void UpdateClient(ClientDataModel clientDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(clientDataModel));
ArgumentNullException.ThrowIfNull(clientDataModel);
clientDataModel.Validate();
_clientStorageContract.UpdElement(clientDataModel);
}
public void DeleteClient(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_clientStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,109 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
public List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}", onlyActive);
return _employeeStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _employeeStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<EmployeeDataModel> GetAllEmployeesByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllEmployees params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _employeeStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public EmployeeDataModel GetEmployeeByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _employeeStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
{
return _employeeStorageContract.GetElementByEmail(data) ?? throw new ElementNotFoundException(data);
}
return _employeeStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertEmployee(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.AddElement(employeeDataModel);
}
public void UpdateEmployee(EmployeeDataModel employeeDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(employeeDataModel));
ArgumentNullException.ThrowIfNull(employeeDataModel);
employeeDataModel.Validate();
_employeeStorageContract.UpdElement(employeeDataModel);
}
public void DeleteEmployee(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_employeeStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,96 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
_logger.LogInformation("GetAllDataOfPost for {postId}", postId);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _postStorageContract.GetPostWithHistory(postId) ?? throw new NullListException();
}
public PostDataModel GetPostByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _postStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _postStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertPost(PostDataModel postDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.AddElement(postDataModel);
}
public void UpdatePost(PostDataModel postDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(postDataModel));
ArgumentNullException.ThrowIfNull(postDataModel);
postDataModel.Validate();
_postStorageContract.UpdElement(postDataModel);
}
public void DeletePost(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.DelElement(id);
}
public void RestorePost(string id)
{
_logger.LogInformation("Restore by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_postStorageContract.ResElement(id);
}
}

View File

@@ -0,0 +1,83 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class ProductBusinessLogicContract(IProductStorageContract productStorageContract, ILogger logger) : IProductBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract = productStorageContract;
public List<ProductDataModel> GetAllProducts()
{
_logger.LogInformation("GetAllProducts");
return _productStorageContract.GetList() ?? throw new NullListException();
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId)
{
_logger.LogInformation("GetProductHistoryByProduct for {productId}", productId);
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _productStorageContract.GetHistoryByProductId(productId) ?? throw new NullListException();
}
public ProductDataModel GetProductByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _productStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _productStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.AddElement(productDataModel);
}
public void UpdateProduct(ProductDataModel productDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(productDataModel));
ArgumentNullException.ThrowIfNull(productDataModel);
productDataModel.Validate();
_productStorageContract.UpdElement(productDataModel);
}
public void DeleteProduct(string id)
{
_logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_productStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,67 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,ISaleStorageContract saleStorageContract,
IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeeId));
}
if (!employeeId.IsGuid())
{
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {employeeId}", fromDate, toDate, employeeId);
return _salaryStorageContract.GetList(fromDate, toDate, employeeId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var employees = _employeeStorageContract.GetList() ?? throw new NullListException();
foreach (var employee in employees)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var post = _postStorageContract.GetElementById(employee.PostId) ??
throw new NullListException();
var salary = post.Salary + sales * 0.1;
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
}
}
}

View File

@@ -0,0 +1,125 @@
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IStorageStorageContract storageStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IStorageStorageContract _storageStorageContract = storageStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {employeeId}, {fromDate}, {toDate}", employeeId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (employeeId.IsEmpty())
{
throw new ArgumentNullException(nameof(employeeId));
}
if (!employeeId.IsGuid())
{
throw new ValidationException("The value in the field employeeId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, employeeId: employeeId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {buyerId}, {fromDate}, {toDate}", clientId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (clientId.IsEmpty())
{
throw new ArgumentNullException(nameof(clientId));
}
if (!clientId.IsGuid())
{
throw new ValidationException("The value in the field clientId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, clientId: clientId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_storageStorageContract.CheckComponents(saleDataModel))
{
throw new InsufficientException("Dont have product in storage");
}
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,74 @@
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
public class StorageBusinessLogicContract(IStorageStorageContract storageStorageContract, ILogger logger) : IStorageBusinessLogicContract
{
private readonly IStorageStorageContract _storageStorageContract = storageStorageContract;
private readonly ILogger _logger = logger;
public List<StorageDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _storageStorageContract.GetList() ?? throw new NullListException();
return [];
}
public StorageDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _storageStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", ProductType.None, 0, []);
}
public void InsertComponent(StorageDataModel storageDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(storageDataModel));
ArgumentNullException.ThrowIfNull(storageDataModel);
storageDataModel.Validate();
_storageStorageContract.AddElement(storageDataModel);
}
public void UpdateComponent(StorageDataModel storageDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(storageDataModel));
ArgumentNullException.ThrowIfNull(storageDataModel);
storageDataModel.Validate();
_storageStorageContract.UpdElement(storageDataModel);
}
public void DeleteComponent(string id)
{
logger.LogInformation("Delete by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_storageStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,61 @@
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CandyHouseBusinessLogic.Implementations;
public class SuppliesBusinessLogicContract(ISuppliesStorageContract suppliesStorageContract, ILogger logger) : ISuppliesBusinessLogicContract
{
private readonly ISuppliesStorageContract _suppliesStorageContract = suppliesStorageContract;
private readonly ILogger _logger = logger;
public List<SuppliesDataModel> GetAllComponents()
{
_logger.LogInformation("GetAllComponents");
return _suppliesStorageContract.GetList() ?? throw new NullListException();
return [];
}
public SuppliesDataModel GetComponentByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _suppliesStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
return new("", ProductType.None, DateTime.UtcNow, 0, []);
}
public void InsertComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.AddElement(suppliesDataModel);
}
public void UpdateComponent(SuppliesDataModel suppliesDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(suppliesDataModel));
ArgumentNullException.ThrowIfNull(suppliesDataModel);
suppliesDataModel.Validate();
_suppliesStorageContract.UpdElement(suppliesDataModel);
}
}

View File

@@ -0,0 +1,21 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface IClientBusinessLogicContract
{
List<ClientDataModel> GetAllClients();
ClientDataModel GetClientByData(string data);
void InsertClient(ClientDataModel clientDataModel);
void UpdateClient(ClientDataModel clientDataModel);
void DeleteClient(string id);
}

View File

@@ -0,0 +1,27 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface IEmployeeBusinessLogicContract
{
List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByPost(string employeeId, bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<EmployeeDataModel> GetAllEmployeesByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
EmployeeDataModel GetEmployeeByData(string data);
void InsertEmployee(EmployeeDataModel employeeDataModel);
void UpdateEmployee(EmployeeDataModel employeeDataModel);
void DeleteEmployee(string id);
}

View File

@@ -0,0 +1,25 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,23 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface IProductBusinessLogicContract
{
List<ProductDataModel> GetAllProducts();
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel productDataModel);
void UpdateProduct(ProductDataModel productDataModel);
void DeleteProduct(string id);
}

View File

@@ -0,0 +1,17 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface ISalaryBusinessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,25 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BuisnessLogicContracts;
public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,17 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BusinessLogicContracts;
public interface IStorageBusinessLogicContract
{
List<StorageDataModel> GetAllComponents();
StorageDataModel GetComponentByData(string data);
void InsertComponent(StorageDataModel storageDataModel);
void UpdateComponent(StorageDataModel storageDataModel);
void DeleteComponent(string id);
}

View File

@@ -0,0 +1,16 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.BusinessLogicContracts;
public interface ISuppliesBusinessLogicContract
{
List<SuppliesDataModel> GetAllComponents();
SuppliesDataModel GetComponentByData(string data);
void InsertComponent(SuppliesDataModel componentDataModel);
void UpdateComponent(SuppliesDataModel componentDataModel);
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,42 @@
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ValidationException = CandyHouseContracts.Exceptions.ValidationException;
namespace CandyHouseContracts.DataModels;
public class ClientDataModel(string id, string fIO, string phoneNumber, double discountSize) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fIO;
public string PhoneNumber { get; private set; } = phoneNumber;
public double DiscountSize { get; private set; } = discountSize;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (PhoneNumber.IsEmpty())
throw new ValidationException("Field PhoneNumber is empty");
if (!Regex.IsMatch(PhoneNumber, @"^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$"))
throw new ValidationException("Field PhoneNumber is not a phone number");
}
}

View File

@@ -0,0 +1,61 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
public string Email { get; private set; } = email;
public string PostId { get; private set; } = postId;
public DateTime BirthDate { get; private set; } = birthDate;
public DateTime EmploymentDate { get; private set; } = employmentDate;
public bool IsDeleted { get; private set; } = isDeleted;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (FIO.IsEmpty())
throw new ValidationException("Field FIO is empty");
if (Email.IsEmpty())
throw new ValidationException("Field Email is empty");
if (!Regex.IsMatch(Email, @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
throw new ValidationException("Field Email is not a valid email address");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (BirthDate.Date > DateTime.Now.AddYears(-18).Date)
throw new ValidationException($"Only adults can be hired (BirthDate = {BirthDate.ToShortDateString()})");
if (EmploymentDate.Date < BirthDate.Date)
throw new ValidationException("The date of employment cannot be less than the date of birth");
if ((EmploymentDate - BirthDate).TotalDays / 365 < 18)
throw new ValidationException($"Only adults can be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

@@ -0,0 +1,35 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
{
public string Id { get; private set; } = id;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
}
}

View File

@@ -0,0 +1,38 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace CandyHouseContracts.DataModels;
public class ProductDataModel(string id, string productName, string productDescription, double price, ProductType productType) : IValidation
{
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
public string ProductDescription { get; private set; } = productDescription;
public double Price { get; private set; } = price;
public ProductType ProductType { get; private set; } = productType;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (ProductName.IsEmpty())
throw new ValidationException("Field ProductName is empty");
if (ProductDescription.IsEmpty())
throw new ValidationException("Field ProductDescription is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (ProductType == ProductType.None)
throw new ValidationException("Field Type is empty");
}
}

View File

@@ -0,0 +1,31 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public void Validate()
{
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (OldPrice <= 0)
throw new ValidationException("Field OldPrice is less than or equal to 0");
}
}

View File

@@ -0,0 +1,32 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class ProductStorageDataModel(string storageId, string productId, int count) : IValidation
{
public string StorageId { get; private set; } = storageId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public void Validate()
{
if (StorageId.IsEmpty())
throw new ValidationException("Field StorageId is empty");
if (!StorageId.IsGuid())
throw new ValidationException("The value in the field StorageId is not a unique identifier");
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,32 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class ProductSuppliesDataModel(string suppliesId, string productId, int count) : IValidation
{
public string SuppliesId { get; private set; } = suppliesId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SuppliesId.IsEmpty())
throw new ValidationException("Field SuppliesId is empty");
if (!SuppliesId.IsGuid())
throw new ValidationException("The value in the field SuppliesId is not a unique identifier");
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field BlandId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,31 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
public string EmployeeId { get; private set; } = employeeId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = employeeSalary;
public void Validate()
{
if (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (Salary <= 0)
throw new ValidationException("Field Salary is less than or equal to 0");
}
}

View File

@@ -0,0 +1,56 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType,
double discount, bool isCancel, List<SaleProductDataModel> saleProducts) : IValidation
{
public string Id { get; private set; } = id;
public string EmployeeId { get; private set; } = employeeId;
public string? ClientId { get; private set; } = clientId;
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; } = sum;
public DiscountType DiscountType { get; private set; } = discountType;
public double Discount { get; private set; } = discount;
public bool IsCancel { get; private set; } = isCancel;
public List<SaleProductDataModel> Products { get; private set; } = saleProducts;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (EmployeeId.IsEmpty())
throw new ValidationException("Field EmployeeId is empty");
if (!EmployeeId.IsGuid())
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
}
}

View File

@@ -0,0 +1,37 @@
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
{
public string SaleId { get; private set; } = saleId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SaleId.IsEmpty())
throw new ValidationException("Field SaleId is empty");
if (!SaleId.IsGuid())
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (ProductId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
if (!ProductId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
}
}

View File

@@ -0,0 +1,33 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
public class StorageDataModel(string id, ProductType productType, int count, List<ProductStorageDataModel> products) : IValidation
{
public string Id { get; private set; } = id;
public ProductType Type { get; private set; } = productType;
public int Count { get; private set; } = count;
public List<ProductStorageDataModel> Products { get; private set; } = products;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ProductType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
}
}

View File

@@ -0,0 +1,35 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace CandyHouseContracts.DataModels;
public class SuppliesDataModel(string id, ProductType productType, DateTime date, int count, List<ProductSuppliesDataModel> products) : IValidation
{
public string Id { get; private set; } = id;
public ProductType Type { get; private set; } = productType;
public DateTime OrderDate { get; private set; } = date;
public int Count { get; private set; } = count;
public List<ProductSuppliesDataModel> Products { get; private set; } = products;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (Type == ProductType.None)
throw new ValidationException("Field Type is empty");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if ((Products?.Count ?? 0) == 0)
throw new ValidationException("The sale must include products");
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Enums;
[Flags]
public enum DiscountType
{
None = 0,
OnSale = 1,
RegularCustomer = 2,
Certificate = 4
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Enums;
public enum PostType
{
None = 0,
Manager = 1,
SuperManager = 2,
Baker = 3,
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Enums;
public enum ProductType
{
None = 0,
Candy = 1,
Cake = 2,
Chocolate = 3,
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class ElementExistsException : Exception
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base($"The end date must be later than the start date.. StartDate: " +
$"{start:dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}") { }
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class InsufficientException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null") { }
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: {ex.Message}", ex) { }
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Exceptions;
public class ValidationException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Extensions;
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Extensions;
public static class StringExtensions
{
public static bool IsEmpty(this string str) => string.IsNullOrWhiteSpace(str);
public static bool IsGuid(this string str) => Guid.TryParse(str, out _);
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.Infrastructure;
public interface IValidation
{
void Validate();
}

View File

@@ -0,0 +1,25 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface IClientStorageContract
{
List<ClientDataModel> GetList();
ClientDataModel? GetElementById(string id);
ClientDataModel? GetElementByPhoneNumber(string phoneNumber);
ClientDataModel? GetElementByFIO(string fio);
void AddElement(ClientDataModel clientDataModel);
void UpdElement(ClientDataModel clientDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,26 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface IEmployeeStorageContract
{
List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null,
DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
EmployeeDataModel? GetElementById(string id);
EmployeeDataModel? GetElementByFIO(string fio);
EmployeeDataModel? GetElementByEmail(string email);
void AddElement(EmployeeDataModel employeeDataModel);
void UpdElement(EmployeeDataModel employeeDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,20 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,19 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface IProductStorageContract
{
List<ProductDataModel> GetList();
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,15 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,20 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null,
string? clientId = null, string? productId = null);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,18 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface IStorageStorageContract
{
List<StorageDataModel> GetList();
StorageDataModel GetElementById(string id);
void AddElement(StorageDataModel storageDataModel);
void UpdElement(StorageDataModel storageDataModel);
void DelElement(string id);
bool CheckComponents(SaleDataModel saleDataModel);
}

View File

@@ -0,0 +1,16 @@
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.StoragesContracts;
public interface ISuppliesStorageContract
{
List<SuppliesDataModel> GetList(DateTime? startDate = null);
SuppliesDataModel GetElementById(string id);
void AddElement(SuppliesDataModel suppliesDataModel);
void UpdElement(SuppliesDataModel suppliesDataModel);
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CandyHouseContracts\CandyHouseContracts.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="CandyHouseTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,66 @@
using CandyHouseContracts.Infrastructure;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase;
public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase = configurationDatabase;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
modelBuilder.Entity<Product>().HasIndex(x => x.ProductName).IsUnique();
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<ProductSupplies>().HasKey(x => new { x.SuppliesId, x.ProductId });
modelBuilder.Entity<ProductStorage>().HasKey(x => new { x.StorageId, x.ProductId });
}
public DbSet<Client> Clients { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Supplies> Supplieses { get; set; }
public DbSet<Storage> Agencies { get; set; }
public DbSet<ProductSupplies> ProductSupplieses { get; set; }
public DbSet<ProductStorage> ProductAgensies { get; set; }
}

View File

@@ -0,0 +1,144 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class ClientStorageContarct : IClientStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public ClientStorageContarct(CandyHouseDbContext magicCarpetDbContext)
{
_dbContext = magicCarpetDbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(CandyHouseDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<ClientDataModel> GetList()
{
try
{
return [.. _dbContext.Clients.Select(x => _mapper.Map<ClientDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ClientDataModel>(GetClientById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ClientDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<ClientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.PhoneNumber == phoneNumber));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ClientDataModel clientDataModel)
{
try
{
_dbContext.Clients.Add(_mapper.Map<Client>(clientDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", clientDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ClientDataModel clientDataModel)
{
try
{
var element = GetClientById(clientDataModel.Id) ?? throw new ElementNotFoundException(clientDataModel.Id);
_dbContext.Clients.Update(_mapper.Map(clientDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Clients_PhoneNumber" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PhoneNumber", clientDataModel.PhoneNumber);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetClientById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Clients.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Client? GetClientById(string id) => _dbContext.Clients.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,156 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(CandyHouseDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Employees.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. query.Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
try
{
return _mapper.Map<EmployeeDataModel>(_dbContext.Employees.FirstOrDefault(x => x.Email == email));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(EmployeeDataModel employeeDataModel)
{
try
{
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(EmployeeDataModel employeeDataModel)
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Employee? GetEmployeeById(string id) => _dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,196 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(CandyHouseDbContext dbContext)
{
_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);
}
public List<PostDataModel> GetList(bool onlyActual = true)
{
try
{
var query = _dbContext.Posts.AsQueryable();
if (onlyActual)
{
query = query.Where(x => x.IsActual);
}
return [.. query.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<PostDataModel> GetPostWithHistory(string postId)
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(PostDataModel postDataModel)
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(PostDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
public void ResElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id)
.OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -0,0 +1,169 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>();
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>(); ;
});
_mapper = new Mapper(config);
}
public List<ProductDataModel> GetList()
{
try
{
return [.. _dbContext.Products.Select(x => _mapper.Map<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
{
return [.. _dbContext.ProductHistories.Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.FirstOrDefault(x => x.ProductName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Products.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void ResElement(string id)
{
try
{
var element = GetProductById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Product? GetProductById(string id) => _dbContext.Products.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,62 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,117 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
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);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? productId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.SaleProducts).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (employeeId is not null)
{
query = query.Where(x => x.EmployeeId == employeeId);
}
if (clientId is not null)
{
query = query.Where(x => x.ClientId == clientId);
}
if (productId is not null)
{
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SaleDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SaleDataModel saleDataModel)
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,148 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
public class StorageStorageContract : IStorageStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public StorageStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Storage, StorageDataModel>()
.ConstructUsing(src => new StorageDataModel(
src.Id,
src.Type,
src.Count,
_mapper.Map<List<ProductStorageDataModel>>(src.Products)
));
cfg.CreateMap<StorageDataModel, Storage>();
cfg.CreateMap<ProductStorageDataModel, ProductStorage>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<StorageDataModel> GetList()
{
try
{
return [.. _dbContext.Agencies.Select(x => _mapper.Map<StorageDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public StorageDataModel GetElementById(string id)
{
try
{
return _mapper.Map<StorageDataModel>(GetStorageById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(StorageDataModel storageDataModel)
{
try
{
_dbContext.Agencies.Add(_mapper.Map<Storage>(storageDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(StorageDataModel storageDataModel)
{
try
{
var element = GetStorageById(storageDataModel.Id) ?? throw new ElementNotFoundException(storageDataModel.Id);
_dbContext.Agencies.Update(_mapper.Map(storageDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetStorageById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Agencies.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckComponents(SaleDataModel saleDataModel)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
foreach (SaleProductDataModel sale_product in saleDataModel.Products)
{
var product = _dbContext.Products.FirstOrDefault(x => x.Id == sale_product.ProductId);
var storage = _dbContext.Agencies.FirstOrDefault(x => x.Type == product.ProductType && x.Count >= sale_product.Count);
if (storage == null)
{
transaction.Rollback();
return false;
}
if (storage.Count - sale_product.Count == 0)
{
DelElement(storage.Id);
}
else
{
storage.Count -= sale_product.Count;
}
}
transaction.Commit();
_dbContext.SaveChanges();
return true;
}
}
private Storage? GetStorageById(string id) => _dbContext.Agencies.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Implementations;
public class SuppliesStorageContract : ISuppliesStorageContract
{
private readonly CandyHouseDbContext _dbContext;
private readonly Mapper _mapper;
public SuppliesStorageContract(CandyHouseDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Supplies, SuppliesDataModel>()
.ConstructUsing(src => new SuppliesDataModel(
src.Id,
src.Type,
src.OrderDate,
src.Count,
_mapper.Map<List<ProductSuppliesDataModel>>(src.Products)
));
cfg.CreateMap<SuppliesDataModel, Supplies>();
cfg.CreateMap<ProductSuppliesDataModel, ProductSupplies>().ReverseMap();
});
_mapper = new Mapper(config);
}
public List<SuppliesDataModel> GetList(DateTime? startDate = null)
{
try
{
return [.. _dbContext.Supplieses.Select(x => _mapper.Map<SuppliesDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SuppliesDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SuppliesDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SuppliesDataModel suppliesDataModel)
{
try
{
_dbContext.Supplieses.Add(_mapper.Map<Supplies>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(SuppliesDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplieses.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supplies? GetSuppliesById(string id) => _dbContext.Supplieses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,24 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
public class Client
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("ClientId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,32 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
public class Employee
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { get; set; }
public string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,20 @@
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,30 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ProductDataModel), ReverseMap = true)]
public class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public string? ProductDescription { get; set; }
public double Price { get; set; }
public required ProductType ProductType { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("SuppliesesId")]
public List<ProductSupplies>? ProductSupplies { get; set; }
[ForeignKey("AgenciesId")]
public List<ProductStorage>? ProductStorage { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class ProductStorage
{
public required string StorageId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Storage? Agencies { get; set; }
public Product? Products { get; set; }
}

View File

@@ -0,0 +1,19 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
[AutoMap(typeof(ProductSuppliesDataModel), ReverseMap = true)]
public class ProductSupplies
{
public required string SuppliesId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public Supplies? Supplies { get; set; }
public Product? Products { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public DateTime SalaryDate { get; set; }
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }
}

View File

@@ -0,0 +1,32 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public string? ClientId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Employee? Employee { get; set; }
public Client? Client { get; set; }
[ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class SaleProduct
{
public required string SaleId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,21 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Storage
{
public required string Id { get; set; }
public required ProductType Type { get; set; }
public required int Count { get; set; }
[ForeignKey("StorageId")]
public List<ProductStorage>? Products { get; set; }
}

View File

@@ -0,0 +1,22 @@
using AutoMapper;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseDatabase.Models;
public class Supplies
{
public required string Id { get; set; }
public required ProductType Type { get; set; }
public DateTime OrderDate { get; set; }
public required int Count { get; set; }
[ForeignKey("SuppliesId")]
public List<ProductSupplies>? Products { get; set; }
}

View File

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

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseBase", "CandyHouseBase\CandyHouseBase.csproj", "{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseContracts", "CandyHouseContracts\CandyHouseContracts.csproj", "{A963240F-08C3-4692-B0DA-AC409FCBFE2C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseTests", "CandyHouseTests\CandyHouseTests.csproj", "{396EA8C4-6102-479E-83A2-C83E6B74A14E}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseTests", "CandyHouseTests\CandyHouseTests.csproj", "{D51C9B0B-E30D-44F6-A085-E17FF4D189E2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseBusinessLogic", "CandyHouseBusinessLogic\CandyHouseBusinessLogic.csproj", "{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CandyHouseDatabase", "CandyHouseDatabase\CandyHouseDatabase.csproj", "{928DD22D-F304-4767-B950-990BEE31CFF5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -10,13 +14,21 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5DF70B46-31F7-4D15-8C60-52C0A0A364F0}.Release|Any CPU.Build.0 = Release|Any CPU
{396EA8C4-6102-479E-83A2-C83E6B74A14E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{396EA8C4-6102-479E-83A2-C83E6B74A14E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{396EA8C4-6102-479E-83A2-C83E6B74A14E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{396EA8C4-6102-479E-83A2-C83E6B74A14E}.Release|Any CPU.Build.0 = Release|Any CPU
{A963240F-08C3-4692-B0DA-AC409FCBFE2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A963240F-08C3-4692-B0DA-AC409FCBFE2C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A963240F-08C3-4692-B0DA-AC409FCBFE2C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A963240F-08C3-4692-B0DA-AC409FCBFE2C}.Release|Any CPU.Build.0 = Release|Any CPU
{D51C9B0B-E30D-44F6-A085-E17FF4D189E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D51C9B0B-E30D-44F6-A085-E17FF4D189E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D51C9B0B-E30D-44F6-A085-E17FF4D189E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D51C9B0B-E30D-44F6-A085-E17FF4D189E2}.Release|Any CPU.Build.0 = Release|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D56286D-B8FE-4A50-96B1-CE51EEBE95A2}.Release|Any CPU.Build.0 = Release|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{928DD22D-F304-4767-B950-990BEE31CFF5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,355 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class ClientBusinessLogicContractTests
{
private IClientBusinessLogicContract _clientBusinessLogicContract;
private Mock<IClientStorageContract> _clientStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_clientStorageContract = new Mock<IClientStorageContract>();
_clientBusinessLogicContract = new ClientBusinessLogicContract(_clientStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_clientStorageContract.Reset();
}
[Test]
public void GetAllCLients_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ClientDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "+7-111-111-11-11", 0),
new(Guid.NewGuid().ToString(), "fio 2", "+7-555-444-33-23", 10),
new(Guid.NewGuid().ToString(), "fio 3", "+7-777-777-7777", 0),
};
_clientStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _clientBusinessLogicContract.GetAllClients();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllClients_ReturnEmptyList_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _clientBusinessLogicContract.GetAllClients();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<NullListException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllClients_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetAllClients(), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetClientByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ClientDataModel(id, "fio", "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new ClientDataModel(Guid.NewGuid().ToString(), fio, "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_GetByPhoneNumber_ReturnRecord_Test()
{
//Arrange
var phoneNumber = "+7-111-111-11-11";
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", phoneNumber, 0);
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(phoneNumber)).Returns(record);
//Act
var element = _clientBusinessLogicContract.GetClientByData(phoneNumber);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PhoneNumber, Is.EqualTo(phoneNumber));
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetClientByData_GetByPhoneNumber_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData("+7-111-111-11-12"), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetClientByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.GetClientByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("fio"), Throws.TypeOf<StorageException>());
Assert.That(() => _clientBusinessLogicContract.GetClientByData("+7-111-111-11-12"), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertClient_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 10);
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>()))
.Callback((ClientDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber && x.DiscountSize == record.DiscountSize;
});
//Act
_clientBusinessLogicContract.InsertClient(record);
//Assert
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void InsertClient_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(null), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void InsertClient_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new ClientDataModel("id", "fio", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void InsertClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.InsertClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ClientDataModel(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0);
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>()))
.Callback((ClientDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO &&
x.PhoneNumber == record.PhoneNumber && x.DiscountSize == record.DiscountSize;
});
//Act
_clientBusinessLogicContract.UpdateClient(record);
//Assert
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateClient_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<ElementExistsException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void UpdateClient_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(null), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void UpdateClient_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new ClientDataModel("id", "fio", "+7-111-111-11-11", 10)), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Never);
}
[Test]
public void UpdateClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<ClientDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.UpdateClient(new(Guid.NewGuid().ToString(), "fio", "+7-111-111-11-11", 0)), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.UpdElement(It.IsAny<ClientDataModel>()), Times.Once);
}
[Test]
public void DeleteClient_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_clientStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_clientBusinessLogicContract.DeleteClient(id);
//Assert
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteClient_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteClient_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _clientBusinessLogicContract.DeleteClient(string.Empty), Throws.TypeOf<ArgumentNullException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteClient_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient("id"), Throws.TypeOf<ValidationException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteClient_StorageThrowError_ThrowException_Test()
{
//Arrange
_clientStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _clientBusinessLogicContract.DeleteClient(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,586 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class EmployeeBusinessLogicContractTests
{
private EmployeeBusinessLogicContract _employeeBusinessLogicContract;
private Mock<IEmployeeStorageContract> _employeeStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_employeeBusinessLogicContract = new EmployeeBusinessLogicContract(_employeeStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_employeeStorageContract.Reset();
}
[Test]
public void GetAllEmployees_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployees(true);
var list = _employeeBusinessLogicContract.GetAllEmployees(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployees_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployees(true);
var list = _employeeBusinessLogicContract.GetAllEmployees(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Exactly(2));
}
[Test]
public void GetAllEmployees_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployees_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), null, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByPost(postId, true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByPost(postId, false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_employeeStorageContract.Verify(x => x.GetList(true, postId, null, null, null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, postId, null, null, null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Exactly(2));
}
[Test]
public void GetAllEmployeesByPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(null, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(string.Empty, It.IsAny<bool>()), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost("postId", It.IsAny<bool>()), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByPost(Guid.NewGuid().ToString(), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, date, date.AddDays(1), null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, date, date.AddDays(1), null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployees(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), null, null), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByBirthDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByBirthDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByBirthDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<EmployeeDataModel>()
{
new(Guid.NewGuid().ToString(), "fio 1", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
new(Guid.NewGuid().ToString(), "fio 2", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, true),
new(Guid.NewGuid().ToString(), "fio 3", "gg@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false),
};
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns(listOriginal);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, date, date.AddDays(1)), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, date, date.AddDays(1)), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_ReturnEmptyList_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Returns([]);
//Act
var listOnlyActive = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), true);
var list = _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(list, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(list, Has.Count.EqualTo(0));
});
_employeeStorageContract.Verify(x => x.GetList(true, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetList(false, null, null, null, It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date, It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(date, date.AddSeconds(-1), It.IsAny<bool>()), Throws.TypeOf<IncorrectDatesException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Never);
}
[Test]
public void GetAllEmployeesByEmploymentDate_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllEmployeesByEmploymentDate_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployeesByEmploymentDate(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new EmployeeDataModel(id, "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByFio_ReturnRecord_Test()
{
//Arrange
var fio = "fio";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), fio, "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(fio);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.FIO, Is.EqualTo(fio));
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByEmail_ReturnRecord_Test()
{
//Arrange
var email = "123@gmail.com";
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", email, Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.GetElementByEmail(email)).Returns(record);
//Act
var element = _employeeBusinessLogicContract.GetEmployeeByData(email);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Email, Is.EqualTo(email));
_employeeStorageContract.Verify(x => x.GetElementByEmail(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_GetByFio_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("fio"), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetEmployeeByData_GetByEmail_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("123@gmail.com"), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetEmployeeByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetElementByFIO(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeByData("fio"), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_employeeStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertEmployee_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_employeeBusinessLogicContract.InsertEmployee(record);
//Assert
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertEmployee_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementExistsException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void InsertEmployee_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(null), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void InsertEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.AddElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.AddElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateEmployee_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new EmployeeDataModel(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false);
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>()))
.Callback((EmployeeDataModel x) =>
{
flag = x.Id == record.Id && x.FIO == record.FIO && x.PostId == record.PostId && x.BirthDate == record.BirthDate &&
x.EmploymentDate == record.EmploymentDate && x.IsDeleted == record.IsDeleted;
});
//Act
_employeeBusinessLogicContract.UpdateEmployee(record);
//Assert
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateEmployee_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void UpdateEmployee_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(null), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateEmployee_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new EmployeeDataModel("id", "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Never);
}
[Test]
public void UpdateEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.UpdElement(It.IsAny<EmployeeDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.UpdateEmployee(new(Guid.NewGuid().ToString(), "fio", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.Now.AddYears(-18).AddDays(-1), DateTime.Now, false)), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.UpdElement(It.IsAny<EmployeeDataModel>()), Times.Once);
}
[Test]
public void DeleteEmployee_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_employeeBusinessLogicContract.DeleteEmployee(id);
//Assert
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteEmployee_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_employeeStorageContract.Setup(x => x.DelElement(It.Is((string x) => x != id))).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteEmployee_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(string.Empty), Throws.TypeOf<ArgumentNullException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteEmployee_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee("id"), Throws.TypeOf<ValidationException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_employeeStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_employeeStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,459 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class PostBusinessLogicContractTests
{
private PostBusinessLogicContract _postBusinessLogicContract;
private Mock<IPostStorageContract> _postStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_postStorageContract = new Mock<IPostStorageContract>();
_postBusinessLogicContract = new PostBusinessLogicContract(_postStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_postStorageContract.Reset();
}
[Test]
public void GetAllPosts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10, true, DateTime.UtcNow),
};
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
{
//Arrange
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Manager, 10, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Manager, 10, false, DateTime.UtcNow)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(postId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
_postStorageContract.Verify(x => x.GetPostWithHistory(postId), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
//Act
var list = _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_PostIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_PostIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllDataOfPost_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllDataOfPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllDataOfPost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Manager, 10, true, DateTime.UtcNow);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_GetByName_ReturnRecord_Test()
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10, true, DateTime.UtcNow);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.PostName, Is.EqualTo(postName));
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetPostByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetPostByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetPostByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.GetPostByData("name"), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_postStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertPost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow.AddDays(-1));
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
x.ChangeDate == record.ChangeDate;
});
//Act
_postBusinessLogicContract.InsertPost(record);
//Assert
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertPost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void InsertPost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void InsertPost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow.AddDays(-1));
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.Salary == record.Salary &&
x.ChangeDate == record.ChangeDate;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
//Assert
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdatePost_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void UpdatePost_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(null), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
[Test]
public void UpdatePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
[Test]
public void DeletePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.DeletePost(id);
//Assert
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeletePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeletePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.DeletePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_postStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_postBusinessLogicContract.RestorePost(id);
//Assert
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void RestorePost_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void RestorePost_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _postBusinessLogicContract.RestorePost(string.Empty), Throws.TypeOf<ArgumentNullException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void RestorePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.RestorePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,404 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using CandyHouseTests.DataModelTests;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class ProductBusinessLogicContractTests
{
private ProductBusinessLogicContract _productBusinessLogicContract;
private Mock<IProductStorageContract> _productStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_productStorageContract = new Mock<IProductStorageContract>();
_productBusinessLogicContract = new ProductBusinessLogicContract(_productStorageContract.Object, new Mock<ILogger>().Object);
}
[SetUp]
public void SetUp()
{
_productStorageContract.Reset();
}
[Test]
public void GetAllProducts_ReturnListOfRecords_Test()
{
//Arrange
var listOriginal = new List<ProductDataModel>()
{
new(Guid.NewGuid().ToString(), "name 1", "description1", 15.5, ProductType.Chocolate),
new(Guid.NewGuid().ToString(), "name 2", "description2", 10.1, ProductType.Candy),
new(Guid.NewGuid().ToString(), "name 3", "description3", 13.9, ProductType.Cake),
};
_productStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetAllProducts();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllProducts_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var list = _productBusinessLogicContract.GetAllProducts();
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllProducts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllProducts_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetAllProducts(), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnListOfRecords_Test()
{
//Arrange
var productId = Guid.NewGuid().ToString();
var listOriginal = new List<ProductHistoryDataModel>()
{
new(Guid.NewGuid().ToString(), 10),
new(Guid.NewGuid().ToString(), 15),
new(Guid.NewGuid().ToString(), 12),
};
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(productId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_productStorageContract.Verify(x => x.GetHistoryByProductId(productId), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ReturnEmptyList_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Returns([]);
//Act
var list = _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct("productId"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductHistoryByProduct_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductHistoryByProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetHistoryByProductId(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductHistoryByProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetHistoryByProductId(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new ProductDataModel(id, "name", "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_ReturnRecord_Test()
{
//Arrange
var name = "name";
var record = new ProductDataModel(Guid.NewGuid().ToString(), name, "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementByName(name)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(name);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductName, Is.EqualTo(name));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByDescription_ReturnRecord_Test()
{
//Arrange
var description = "description";
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", description, 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.GetElementByName(description)).Returns(record);
//Act
var element = _productBusinessLogicContract.GetProductByData(description);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.ProductDescription, Is.EqualTo(description));
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetProductByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByName_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_GetByDescription_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData("description"), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetProductByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
_productStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.GetProductByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
Assert.That(() => _productBusinessLogicContract.GetProductByData("name"), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
_productStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name","description",10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductDescription == record.ProductDescription
&& x.Price == record.Price && x.ProductType == record.ProductType;
});
//Act
_productBusinessLogicContract.InsertProduct(record);
//Assert
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.AddElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new(Guid.NewGuid().ToString(), "name","description",10, ProductType.Chocolate)), Throws.TypeOf<ElementExistsException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void InsertProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void InsertProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.InsertProduct(new ProductDataModel("id", "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.AddElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new ProductDataModel(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate);
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>()))
.Callback((ProductDataModel x) =>
{
flag = x.Id == record.Id && x.ProductName == record.ProductName && x.ProductDescription == record.ProductDescription
&& x.Price == record.Price && x.ProductType == record.ProductType;
});
//Act
_productBusinessLogicContract.UpdateProduct(record);
//Assert
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void UpdateProduct_RecordWithIncorrectData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf <ElementExistsException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void UpdateProduct_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(null), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new ProductDataModel("id", "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Never);
}
[Test]
public void UpdateProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.UpdElement(It.IsAny<ProductDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.UpdateProduct(new(Guid.NewGuid().ToString(), "name", "description", 10, ProductType.Chocolate)), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.UpdElement(It.IsAny<ProductDataModel>()), Times.Once);
}
[Test]
public void DeleteProduct_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_productStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_productBusinessLogicContract.DeleteProduct(id);
//Assert
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void DeleteProduct_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteProduct_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _productBusinessLogicContract.DeleteProduct(string.Empty), Throws.TypeOf<ArgumentNullException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct("id"), Throws.TypeOf<ValidationException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteProduct_StorageThrowError_ThrowException_Test()
{
//Arrange
_productStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _productBusinessLogicContract.DeleteProduct(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_productStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,351 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class SalaryBusinessLogicContractTests
{
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
private Mock<ISalaryStorageContract> _salaryStorageContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IEmployeeStorageContract> _employeeStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_salaryStorageContract = new Mock<ISalaryStorageContract>();
_saleStorageContract = new Mock<ISaleStorageContract>();
_postStorageContract = new Mock<IPostStorageContract>();
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_salaryStorageContract.Reset();
_saleStorageContract.Reset();
_postStorageContract.Reset();
_employeeStorageContract.Reset();
}
[Test]
public void GetAllSalaries_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, null), Times.Once);
}
[Test]
public void GetAllSalaries_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(dateTime, dateTime.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalaries_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalaries_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_ReturnListOfRecords_Test()
{
//Arrange
var startDate = DateTime.UtcNow;
var endDate = DateTime.UtcNow.AddDays(1);
var employeeId = Guid.NewGuid().ToString();
var listOriginal = new List<SalaryDataModel>()
{
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 10),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 14),
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 30),
};
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(startDate, endDate, employeeId);
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, employeeId), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_ReturnEmptyList_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Returns([]);
//Act
var list = _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString());
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_IncorrectDates_ThrowException_Test()
{
//Arrange
var dateTime = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(dateTime, dateTime, Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(dateTime, dateTime.AddSeconds(-1), Guid.NewGuid().ToString()), Throws.TypeOf<IncorrectDatesException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByEmployee_EmployeeIdIsNUllOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), string.Empty), Throws.TypeOf<ArgumentNullException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByEmployee_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "workerId"), Throws.TypeOf<ValidationException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalariesByEmployee_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalariesByEmployee_StorageThrowError_ThrowException_Test()
{
//Arrange
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_salaryStorageContract.Verify(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void CalculateSalaryByMounth_CalculateSalary_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
var saleSum = 200.0;
var postSalary = 2000.0;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, saleSum, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_WithSeveralWorkers_Test()
{
//Arrange
var employee1Id = Guid.NewGuid().ToString();
var employee2Id = Guid.NewGuid().ToString();
var employee3Id = Guid.NewGuid().ToString();
var list = new List<EmployeeDataModel>() {
new(employee1Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee2Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee3Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee2Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, 1, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
_salaryStorageContract.Verify(x => x.AddElement(It.IsAny<SalaryDataModel>()), Times.Exactly(list.Count));
}
[Test]
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMounth_SaleStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageReturnNull_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
[Test]
public void CalculateSalaryByMounth_SaleStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_PostStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMounth_WorkerStorageThrowException_ThrowException_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, 200, DiscountType.None, 0, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000, true, DateTime.UtcNow));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
}

View File

@@ -0,0 +1,527 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class SaleBusinessLogicContractTests
{
private SaleBusinessLogicContract _saleBusinessLogicContract;
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IStorageStorageContract> _storageStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_saleStorageContract = new Mock<ISaleStorageContract>();
_storageStorageContract = new Mock<IStorageStorageContract>();
_saleBusinessLogicContract = new SaleBusinessLogicContract(_saleStorageContract.Object,
_storageStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_saleStorageContract.Reset();
_storageStorageContract.Reset();
}
[Test]
public void GetAllSalesByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, null), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var employeeId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(employeeId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), employeeId, null, null), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_EmployeeIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod("employeeId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByEmployeeByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByEmployeeByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var clientId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(clientId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, clientId, null), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ClientIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod("clientId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByClientByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByClientByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByClientByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnListOfRecords_Test()
{
//Arrange
var date = DateTime.UtcNow;
var cocktailId = Guid.NewGuid().ToString();
var listOriginal = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false, []),
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(listOriginal);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByProductByPeriod(cocktailId, date, date.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
_saleStorageContract.Verify(x => x.GetList(date, date.AddDays(1), null, null, cocktailId), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnEmptyList_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns([]);
//Act
var list = _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
//Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_IncorrectDates_ThrowException_Test()
{
//Arrange
var date = DateTime.UtcNow;
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date), Throws.TypeOf<IncorrectDatesException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), date, date.AddSeconds(-1)), Throws.TypeOf<IncorrectDatesException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ProductIdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(null, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(string.Empty, DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ProductIdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod("ProductId", DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Test]
public void GetAllSalesByProductByPeriod_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<NullListException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetAllSalesByProductByPeriod_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetAllSalesByProductByPeriod(Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow.AddDays(1)), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_GetById_ReturnRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new SaleDataModel(id, Guid.NewGuid().ToString(), null, 10, DiscountType.None, 0, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_saleStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _saleBusinessLogicContract.GetSaleByData(id);
//Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData("saleId"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSaleByData_GetById_NotFoundRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSaleByData_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.GetSaleByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSale_CorrectRecord_Test()
{
//Arrange
var flag = false;
var record = new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10,
false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>()))
.Callback((SaleDataModel x) =>
{
flag = x.Id == record.Id && x.EmployeeId == record.EmployeeId && x.ClientId == record.ClientId &&
x.SaleDate == record.SaleDate && x.Sum == record.Sum && x.DiscountType == record.DiscountType &&
x.Discount == record.Discount && x.IsCancel == record.IsCancel && x.Products.Count == record.Products.Count &&
x.Products.First().ProductId == record.Products.First().ProductId &&
x.Products.First().SaleId == record.Products.First().SaleId &&
x.Products.First().Count == record.Products.First().Count;
});
//Act
_saleBusinessLogicContract.InsertSale(record);
//Assert
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
Assert.That(flag);
}
[Test]
public void InsertSale_RecordWithExistsData_ThrowException_Test()
{
//Arrange
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_NullRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(null), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel("id", Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [])), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Never);
}
[Test]
public void InsertSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(true);
_saleStorageContract.Setup(x => x.AddElement(It.IsAny<SaleDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.InsertSale(new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
_saleStorageContract.Verify(x => x.AddElement(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void InsertSale_InsufficientError_ThrowException_Test()
{
//Arrange
_storageStorageContract.Setup(x => x.CheckComponents(It.IsAny<SaleDataModel>())).Returns(false);
Assert.That(() => _saleBusinessLogicContract.InsertSale(new SaleDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
Guid.NewGuid().ToString(), 10, DiscountType.None, 10, false,
[new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<InsufficientException>());
//Act&Assert
_storageStorageContract.Verify(x => x.CheckComponents(It.IsAny<SaleDataModel>()), Times.Once);
}
[Test]
public void CancelSale_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_saleStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_saleBusinessLogicContract.CancelSale(id);
//Assert
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
Assert.That(flag);
}
[Test]
public void CancelSale_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void CancelSale_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _saleBusinessLogicContract.CancelSale(string.Empty), Throws.TypeOf<ArgumentNullException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale("id"), Throws.TypeOf<ValidationException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void CancelSale_StorageThrowError_ThrowException_Test()
{
//Arrange
_saleStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _saleBusinessLogicContract.CancelSale(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_saleStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,296 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.BusinessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class StorageBusinessLogicContractTests
{
private IStorageBusinessLogicContract _warehouseBusinessLogicContract;
private Mock<IStorageStorageContract> _warehouseStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_warehouseStorageContract = new Mock<IStorageStorageContract>();
_warehouseBusinessLogicContract = new StorageBusinessLogicContract(_warehouseStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_warehouseStorageContract.Reset();
}
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<StorageDataModel>()
{
new(Guid.NewGuid().ToString(), ProductType.Cake, 1, []),
new(Guid.NewGuid().ToString(), ProductType.Cake, 1, []),
new(Guid.NewGuid().ToString(), ProductType.Cake, 1, []),
};
_warehouseStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns([]);
// Act
var list = _warehouseBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Returns((List<StorageDataModel>)null);
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetList()).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new StorageDataModel(id, ProductType.Cake, 1, []);
_warehouseStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _warehouseBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new StorageDataModel(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<StorageDataModel>()));
// Act
_warehouseBusinessLogicContract.InsertComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<StorageDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<StorageDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new StorageDataModel("id", ProductType.Cake, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<StorageDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.AddElement(It.IsAny<StorageDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.AddElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new StorageDataModel(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<StorageDataModel>()));
// Act
_warehouseBusinessLogicContract.UpdateComponent(record);
// Assert
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<StorageDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<StorageDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new StorageDataModel(Guid.NewGuid().ToString(), ProductType.Cake, 1, [])), Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_warehouseStorageContract.Setup(x => x.UpdElement(It.IsAny<StorageDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _warehouseBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, 1,
[new ProductStorageDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.UpdElement(It.IsAny<StorageDataModel>()), Times.Once);
}
[Test]
public void DeleteComponents_CorrectRecord_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
var flag = false;
_warehouseStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
//Act
_warehouseBusinessLogicContract.DeleteComponent(id);
//Assert
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once); Assert.That(flag);
}
[Test]
public void DeleteComponents_RecordWithIncorrectId_ThrowException_Test()
{
//Arrange
var id = Guid.NewGuid().ToString();
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<ElementNotFoundException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test]
public void DeleteComponents_IdIsNullOrEmpty_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(string.Empty), Throws.TypeOf<ArgumentNullException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent("id"),
Throws.TypeOf<ValidationException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeleteComponents_StorageThrowError_ThrowException_Test()
{
//Arrange
_warehouseStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _warehouseBusinessLogicContract.DeleteComponent(Guid.NewGuid().ToString()),
Throws.TypeOf<StorageException>());
_warehouseStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
}

View File

@@ -0,0 +1,242 @@
using CandyHouseBusinessLogic.Implementations;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.BusinessLogicContractsTests;
[TestFixture]
internal class SuppliesBusinessLogicContractTests
{
private SuppliesBusinessLogicContract _suppliesBusinessLogicContract;
private Mock<ISuppliesStorageContract> _suppliesStorageContract;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_suppliesStorageContract = new Mock<ISuppliesStorageContract>();
_suppliesBusinessLogicContract = new SuppliesBusinessLogicContract(_suppliesStorageContract.Object, new Mock<ILogger>().Object);
}
[TearDown]
public void TearDown()
{
_suppliesStorageContract.Reset();
}
[Test]
public void GetAllSupplies_ReturnListOfRecords_Test()
{
// Arrange
var listOriginal = new List<SuppliesDataModel>()
{
new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1, []),
new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1, []),
};
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns(listOriginal);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
}
[Test]
public void GetAllSupplies_ReturnEmptyList_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns([]);
// Act
var list = _suppliesBusinessLogicContract.GetAllComponents();
// Assert
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_ReturnNull_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Returns((List<SuppliesDataModel>)null);
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<NullListException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetAllSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetList(It.IsAny<DateTime?>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetAllComponents(), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetList(It.IsAny<DateTime?>()), Times.Once);
}
[Test]
public void GetSuppliesByData_GetById_ReturnRecord_Test()
{
// Arrange
var id = Guid.NewGuid().ToString();
var record = new SuppliesDataModel(id,ProductType.Cake, DateTime.Now, 1, []);
_suppliesStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
// Act
var element = _suppliesBusinessLogicContract.GetComponentByData(id);
// Assert
Assert.That(element, Is.Not.Null);
Assert.That(element.Id, Is.EqualTo(id));
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetComponentsByData_EmptyData_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
}
[Test]
public void GetSuppliesByData_GetById_NotFoundRecord_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void GetSuppliesByData_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.GetComponentByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
}
[Test]
public void InsertSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.InsertComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void InsertSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new SuppliesDataModel("id", ProductType.Cake, DateTime.UtcNow, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void InsertSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.AddElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.InsertComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.AddElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_CorrectRecord_Test()
{
// Arrange
var record = new SuppliesDataModel(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)]);
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>()));
// Act
_suppliesBusinessLogicContract.UpdateComponent(record);
// Assert
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithIncorrectData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementNotFoundException(""));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementNotFoundException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_RecordWithExistsData_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new ElementExistsException("Data", "Data"));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<ElementExistsException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
[Test]
public void UpdateSupplies_NullRecord_ThrowException_Test()
{
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(null), Throws.TypeOf<ArgumentNullException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateComponents_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new SuppliesDataModel(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1, [])), Throws.TypeOf<ValidationException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Never);
}
[Test]
public void UpdateSupplies_StorageThrowError_ThrowException_Test()
{
// Arrange
_suppliesStorageContract.Setup(x => x.UpdElement(It.IsAny<SuppliesDataModel>())).Throws(new StorageException(new InvalidOperationException()));
// Act & Assert
Assert.That(() => _suppliesBusinessLogicContract.UpdateComponent(new(Guid.NewGuid().ToString(), ProductType.Cake, DateTime.Now, 1,
[new ProductSuppliesDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5)])), Throws.TypeOf<StorageException>());
_suppliesStorageContract.Verify(x => x.UpdElement(It.IsAny<SuppliesDataModel>()), Times.Once);
}
}

Some files were not shown because too many files have changed in this diff Show More