Compare commits
5 Commits
Task_1_Mod
...
Task_3_Sto
| Author | SHA1 | Date | |
|---|---|---|---|
| 743acbfd23 | |||
| 32d868f0e1 | |||
| 4a55a5f859 | |||
| 0ee7cc1bef | |||
| a52a37f9e1 |
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="AndDietCokeTests" />
|
||||
<InternalsVisibleTo Include ="DynamicProxyGenAssembly2"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeContracts\AndDietCokeContracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,109 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;
|
||||
|
||||
public List<СlientDataModel> GetAllClients()
|
||||
{
|
||||
_logger.LogInformation("GetAllClients");
|
||||
return _clientStorageContract.GetList() ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public СlientDataModel GetClientByData(string data)
|
||||
{
|
||||
_logger.LogInformation("Get client 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(СlientDataModel clientDataModel)
|
||||
{
|
||||
_logger.LogInformation("New client data: {json}",
|
||||
JsonSerializer.Serialize(clientDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(clientDataModel);
|
||||
clientDataModel.Validate();
|
||||
|
||||
try
|
||||
{
|
||||
_clientStorageContract.AddElement(clientDataModel);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to insert client - already exists");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdateClient(СlientDataModel clientDataModel)
|
||||
{
|
||||
_logger.LogInformation("Update client data: {json}",
|
||||
JsonSerializer.Serialize(clientDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(clientDataModel);
|
||||
clientDataModel.Validate();
|
||||
|
||||
try
|
||||
{
|
||||
_clientStorageContract.UpdElement(clientDataModel);
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to update client - not found");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void DeleteClient(string id)
|
||||
{
|
||||
_logger.LogInformation("Delete client by id: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("Id is not a unique identifier");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_clientStorageContract.DelElement(id);
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to delete client - not found");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
|
||||
internal class DishBusinessLogicContract(
|
||||
IDishStorageContracts dishStorageContracts,
|
||||
ILogger<DishBusinessLogicContract> logger) : IDishBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IDishStorageContracts _dishStorageContract = dishStorageContracts;
|
||||
|
||||
public List<DishDataModel> GetAllDishes()
|
||||
{
|
||||
_logger.LogInformation("GetAllDishes called");
|
||||
|
||||
var result = _dishStorageContract.GetList();
|
||||
return result ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public List<DishHistoryDataModel> GetDishHistory(string dishId)
|
||||
{
|
||||
_logger.LogInformation("GetDishHistory called for dishId: {dishId}", dishId);
|
||||
|
||||
if (dishId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(dishId));
|
||||
}
|
||||
|
||||
if (!dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("DishId must be a valid GUID");
|
||||
}
|
||||
|
||||
var result = _dishStorageContract.GetHistoryByProductId(dishId);
|
||||
return result ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public DishDataModel? GetDishById(string id)
|
||||
{
|
||||
_logger.LogInformation("GetDishById called with id: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("Id must be a valid GUID");
|
||||
}
|
||||
|
||||
return _dishStorageContract.GetElementById(id)
|
||||
?? throw new ElementNotFoundException(id);
|
||||
}
|
||||
|
||||
public DishDataModel? GetDishByName(string name)
|
||||
{
|
||||
_logger.LogInformation("GetDishByName called with name: {name}", name);
|
||||
|
||||
if (name.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(name));
|
||||
}
|
||||
|
||||
return _dishStorageContract.GetElementByName(name)
|
||||
?? throw new ElementNotFoundException(name);
|
||||
}
|
||||
|
||||
public void InsertDish(DishDataModel dishDataModel)
|
||||
{
|
||||
_logger.LogInformation("InsertDish called with data: {data}",
|
||||
JsonSerializer.Serialize(dishDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(dishDataModel);
|
||||
dishDataModel.Validate();
|
||||
|
||||
// Проверка на уникальность имени
|
||||
var existingByName = _dishStorageContract.GetElementByName(dishDataModel.Name);
|
||||
if (existingByName != null)
|
||||
{
|
||||
throw new ValidationException($"Dish with name '{dishDataModel.Name}' already exists");
|
||||
}
|
||||
|
||||
// Проверка на уникальность ID
|
||||
var existingById = _dishStorageContract.GetElementById(dishDataModel.Id);
|
||||
if (existingById != null)
|
||||
{
|
||||
throw new ValidationException($"Dish with ID {dishDataModel.Id} already exists");
|
||||
}
|
||||
|
||||
_dishStorageContract.AddElement(dishDataModel);
|
||||
_logger.LogInformation("Dish successfully inserted: {id}", dishDataModel.Id);
|
||||
}
|
||||
|
||||
public void UpdateDish(DishDataModel dishDataModel)
|
||||
{
|
||||
_logger.LogInformation("UpdateDish called with data: {data}",
|
||||
JsonSerializer.Serialize(dishDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(dishDataModel);
|
||||
dishDataModel.Validate();
|
||||
|
||||
// Проверка что блюдо существует
|
||||
var existingDish = _dishStorageContract.GetElementById(dishDataModel.Id);
|
||||
if (existingDish == null)
|
||||
{
|
||||
throw new ElementNotFoundException(dishDataModel.Id);
|
||||
}
|
||||
|
||||
// Проверка на уникальность имени (если имя изменилось)
|
||||
if (!existingDish.Name.Equals(dishDataModel.Name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var dishWithSameName = _dishStorageContract.GetElementByName(dishDataModel.Name);
|
||||
if (dishWithSameName != null)
|
||||
{
|
||||
throw new ValidationException($"Dish with name '{dishDataModel.Name}' already exists");
|
||||
}
|
||||
}
|
||||
|
||||
_dishStorageContract.UpdElement(dishDataModel);
|
||||
_logger.LogInformation("Dish successfully updated: {id}", dishDataModel.Id);
|
||||
}
|
||||
|
||||
public void DeleteDish(string id)
|
||||
{
|
||||
_logger.LogInformation("DeleteDish called with id: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("Id must be a valid GUID");
|
||||
}
|
||||
|
||||
// Проверка что блюдо существует
|
||||
var existingDish = _dishStorageContract.GetElementById(id);
|
||||
if (existingDish == null)
|
||||
{
|
||||
throw new ElementNotFoundException(id);
|
||||
}
|
||||
|
||||
_dishStorageContract.DelElement(id);
|
||||
_logger.LogInformation("Dish successfully deleted: {id}", id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
|
||||
internal class Dish_OrderBusinessLogicContract(
|
||||
IDish_OrderStorageContract dishOrderStorageContract,
|
||||
ILogger<Dish_OrderBusinessLogicContract> logger) : IDish_OrderBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IDish_OrderStorageContract _dishOrderStorageContract = dishOrderStorageContract;
|
||||
|
||||
public List<Dish_OrderDataModel> GetAllDishOrders(string? orderId = null, string? dishId = null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"GetAllDishOrders called with params: orderId={orderId}, dishId={dishId}",
|
||||
orderId, dishId);
|
||||
|
||||
if (orderId != null && !orderId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("OrderId must be a valid GUID");
|
||||
}
|
||||
|
||||
if (dishId != null && !dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("DishId must be a valid GUID");
|
||||
}
|
||||
|
||||
var result = _dishOrderStorageContract.GetList(orderId, dishId);
|
||||
|
||||
return result ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public Dish_OrderDataModel? GetDishOrderById(string orderId, string dishId)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"GetDishOrderById called with params: orderId={orderId}, dishId={dishId}",
|
||||
orderId, dishId);
|
||||
|
||||
if (orderId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(orderId));
|
||||
}
|
||||
|
||||
if (!orderId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("OrderId must be a valid GUID");
|
||||
}
|
||||
|
||||
if (dishId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(dishId));
|
||||
}
|
||||
|
||||
if (!dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("DishId must be a valid GUID");
|
||||
}
|
||||
|
||||
return _dishOrderStorageContract.GetElementById(orderId, dishId)
|
||||
?? throw new ElementNotFoundException($"DishOrder with orderId={orderId} and dishId={dishId} not found");
|
||||
}
|
||||
|
||||
public void InsertDishOrder(Dish_OrderDataModel dishOrderDataModel)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"InsertDishOrder called with data: {data}",
|
||||
JsonSerializer.Serialize(dishOrderDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(dishOrderDataModel);
|
||||
dishOrderDataModel.Validate();
|
||||
|
||||
// Проверка на существование записи
|
||||
var existing = _dishOrderStorageContract.GetElementById(
|
||||
dishOrderDataModel.OrderId,
|
||||
dishOrderDataModel.DishId);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
throw new ValidationException(
|
||||
$"DishOrder with orderId={dishOrderDataModel.OrderId} and dishId={dishOrderDataModel.DishId} already exists");
|
||||
}
|
||||
|
||||
_dishOrderStorageContract.AddElement(dishOrderDataModel);
|
||||
_logger.LogInformation(
|
||||
"DishOrder successfully inserted: orderId={orderId}, dishId={dishId}",
|
||||
dishOrderDataModel.OrderId, dishOrderDataModel.DishId);
|
||||
}
|
||||
|
||||
public void UpdateDishOrder(Dish_OrderDataModel dishOrderDataModel)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"UpdateDishOrder called with data: {data}",
|
||||
JsonSerializer.Serialize(dishOrderDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(dishOrderDataModel);
|
||||
dishOrderDataModel.Validate();
|
||||
|
||||
// Проверка что запись существует
|
||||
var existing = _dishOrderStorageContract.GetElementById(
|
||||
dishOrderDataModel.OrderId,
|
||||
dishOrderDataModel.DishId);
|
||||
|
||||
if (existing == null)
|
||||
{
|
||||
throw new ElementNotFoundException(
|
||||
$"DishOrder with orderId={dishOrderDataModel.OrderId} and dishId={dishOrderDataModel.DishId} not found");
|
||||
}
|
||||
|
||||
_dishOrderStorageContract.UpdElement(dishOrderDataModel);
|
||||
_logger.LogInformation(
|
||||
"DishOrder successfully updated: orderId={orderId}, dishId={dishId}",
|
||||
dishOrderDataModel.OrderId, dishOrderDataModel.DishId);
|
||||
}
|
||||
|
||||
public void DeleteDishOrder(string orderId, string dishId)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"DeleteDishOrder called with params: orderId={orderId}, dishId={dishId}",
|
||||
orderId, dishId);
|
||||
|
||||
if (orderId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(orderId));
|
||||
}
|
||||
|
||||
if (!orderId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("OrderId must be a valid GUID");
|
||||
}
|
||||
|
||||
if (dishId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(dishId));
|
||||
}
|
||||
|
||||
if (!dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("DishId must be a valid GUID");
|
||||
}
|
||||
|
||||
// Проверка что запись существует
|
||||
var existing = _dishOrderStorageContract.GetElementById(orderId, dishId);
|
||||
if (existing == null)
|
||||
{
|
||||
throw new ElementNotFoundException(
|
||||
$"DishOrder with orderId={orderId} and dishId={dishId} not found");
|
||||
}
|
||||
|
||||
_dishOrderStorageContract.DelElement(orderId, dishId);
|
||||
_logger.LogInformation(
|
||||
"DishOrder successfully deleted: orderId={orderId}, dishId={dishId}",
|
||||
orderId, dishId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
|
||||
internal class EmployeeBusinessLogicContract(
|
||||
IEmployeeStoragesContracts employeeStoragesContracts,
|
||||
ILogger<EmployeeBusinessLogicContract> logger) : IEmployeeBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IEmployeeStoragesContracts _employeeStorageContract = employeeStoragesContracts;
|
||||
|
||||
public List<EmployeeDataModel> GetAllEmployees(
|
||||
bool onlyActive = true,
|
||||
string? positionId = null,
|
||||
DateTime? fromBirthDate = null,
|
||||
DateTime? toBirthDate = null,
|
||||
DateTime? fromEmploymentDate = null,
|
||||
DateTime? toEmploymentDate = null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"GetAllEmployees params: onlyActive={onlyActive}, positionId={positionId}, " +
|
||||
"fromBirthDate={fromBirthDate}, toBirthDate={toBirthDate}, " +
|
||||
"fromEmploymentDate={fromEmploymentDate}, toEmploymentDate={toEmploymentDate}",
|
||||
onlyActive, positionId, fromBirthDate, toBirthDate, fromEmploymentDate, toEmploymentDate);
|
||||
|
||||
if (positionId != null && positionId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(positionId));
|
||||
}
|
||||
|
||||
if (positionId != null && !positionId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("The value in the field positionId is not a unique identifier.");
|
||||
}
|
||||
|
||||
if (fromBirthDate.HasValue && toBirthDate.HasValue && fromBirthDate > toBirthDate)
|
||||
{
|
||||
throw new IncorrectDatesException(fromBirthDate.Value, toBirthDate.Value);
|
||||
}
|
||||
|
||||
if (fromEmploymentDate.HasValue && toEmploymentDate.HasValue && fromEmploymentDate > toEmploymentDate)
|
||||
{
|
||||
throw new IncorrectDatesException(fromEmploymentDate.Value, toEmploymentDate.Value);
|
||||
}
|
||||
|
||||
var result = _employeeStorageContract.GetList(
|
||||
onlyActive,
|
||||
positionId,
|
||||
fromBirthDate,
|
||||
toBirthDate,
|
||||
fromEmploymentDate,
|
||||
toEmploymentDate);
|
||||
|
||||
return result ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public EmployeeDataModel? GetEmployeeById(string id)
|
||||
{
|
||||
_logger.LogInformation("GetEmployeeById params: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("The value in the field id is not a unique identifier.");
|
||||
}
|
||||
|
||||
return _employeeStorageContract.GetElementById(id) ?? throw new ElementNotFoundException(id);
|
||||
}
|
||||
|
||||
public EmployeeDataModel? GetEmployeeByFIO(string fio)
|
||||
{
|
||||
_logger.LogInformation("GetEmployeeByFIO params: {fio}", fio);
|
||||
|
||||
if (fio.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(fio));
|
||||
}
|
||||
|
||||
return _employeeStorageContract.GetElementByFIO(fio) ?? throw new ElementNotFoundException(fio);
|
||||
}
|
||||
|
||||
public void InsertEmployee(EmployeeDataModel employeeDataModel)
|
||||
{
|
||||
_logger.LogInformation("InsertEmployee params: {json}", JsonSerializer.Serialize(employeeDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(employeeDataModel);
|
||||
employeeDataModel.Validate();
|
||||
|
||||
if (_employeeStorageContract.GetElementById(employeeDataModel.Id) != null)
|
||||
{
|
||||
throw new DuplicateEmployeeException(employeeDataModel.Id);
|
||||
}
|
||||
|
||||
_employeeStorageContract.AddElement(employeeDataModel);
|
||||
}
|
||||
|
||||
public void UpdateEmployee(EmployeeDataModel employeeDataModel)
|
||||
{
|
||||
_logger.LogInformation("UpdateEmployee params: {json}", JsonSerializer.Serialize(employeeDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(employeeDataModel);
|
||||
employeeDataModel.Validate();
|
||||
|
||||
if (_employeeStorageContract.GetElementById(employeeDataModel.Id) == null)
|
||||
{
|
||||
throw new ElementNotFoundException(employeeDataModel.Id);
|
||||
}
|
||||
|
||||
_employeeStorageContract.UpdElement(employeeDataModel);
|
||||
}
|
||||
|
||||
public void DeleteEmployee(string id)
|
||||
{
|
||||
_logger.LogInformation("DeleteEmployee params: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("The value in the field id is not a unique identifier.");
|
||||
}
|
||||
|
||||
if (_employeeStorageContract.GetElementById(id) == null)
|
||||
{
|
||||
throw new ElementNotFoundException(id);
|
||||
}
|
||||
|
||||
_employeeStorageContract.DelElement(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
|
||||
internal class OrderBusinessLogicContract(
|
||||
IOrderStorageContracts orderStorageContract,
|
||||
ILogger<OrderBusinessLogicContract> logger) : IOrderBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IOrderStorageContracts _orderStorageContract = orderStorageContract;
|
||||
|
||||
public List<OrderDataModels> GetAllOrders(string? clientId = null, string? employeedId = null, string? dishId = null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"GetAllOrders called with filters - ClientId: {clientId}, EmployeeId: {employeedId}, DishId: {dishId}",
|
||||
clientId, employeedId, dishId);
|
||||
|
||||
// Валидация параметров фильтрации
|
||||
if (clientId != null && !clientId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("ClientId must be a valid GUID");
|
||||
}
|
||||
|
||||
if (employeedId != null && !employeedId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("EmployeeId must be a valid GUID");
|
||||
}
|
||||
|
||||
if (dishId != null && !dishId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("DishId must be a valid GUID");
|
||||
}
|
||||
|
||||
var result = _orderStorageContract.GetList(clientId, employeedId, dishId);
|
||||
return result ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public OrderDataModels? GetOrderById(string id)
|
||||
{
|
||||
_logger.LogInformation("GetOrderById called with id: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("OrderId must be a valid GUID");
|
||||
}
|
||||
|
||||
var order = _orderStorageContract.GetElementById(id);
|
||||
return order ?? throw new ElementNotFoundException($"Order with id {id} not found");
|
||||
}
|
||||
|
||||
public void InsertOrder(OrderDataModels orderDataModel)
|
||||
{
|
||||
_logger.LogInformation("InsertOrder called with data: {data}",
|
||||
JsonSerializer.Serialize(orderDataModel));
|
||||
|
||||
ArgumentNullException.ThrowIfNull(orderDataModel);
|
||||
orderDataModel.Validate();
|
||||
|
||||
// Проверка на существование заказа с таким ID
|
||||
var existingOrder = _orderStorageContract.GetElementById(orderDataModel.Id);
|
||||
if (existingOrder != null)
|
||||
{
|
||||
throw new ValidationException($"Order with id {orderDataModel.Id} already exists");
|
||||
}
|
||||
|
||||
_orderStorageContract.AddElement(orderDataModel);
|
||||
_logger.LogInformation("Order successfully created with id: {id}", orderDataModel.Id);
|
||||
}
|
||||
|
||||
public void DeleteOrder(string id)
|
||||
{
|
||||
_logger.LogInformation("DeleteOrder called for id: {id}", id);
|
||||
|
||||
if (id.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(id));
|
||||
}
|
||||
|
||||
if (!id.IsGuid())
|
||||
{
|
||||
throw new ValidationException("OrderId must be a valid GUID");
|
||||
}
|
||||
|
||||
// Проверка что заказ существует
|
||||
var existingOrder = _orderStorageContract.GetElementById(id);
|
||||
if (existingOrder == null)
|
||||
{
|
||||
throw new ElementNotFoundException($"Order with id {id} not found");
|
||||
}
|
||||
|
||||
_orderStorageContract.DelElement(id);
|
||||
_logger.LogInformation("Order successfully deleted with id: {id}", id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AndDietCokeBusinessLogic.Implementations;
|
||||
|
||||
internal class PositionBusinessLogicContract(IPositionStorageContract positionStorageContract, ILogger logger)
|
||||
: IPositionBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly IPositionStorageContract _positionStorageContract = positionStorageContract;
|
||||
|
||||
public List<PositionDataModel> GetAllPositions(bool onlyActive = true)
|
||||
{
|
||||
_logger.LogInformation("GetAllPositions params: {onlyActive}", onlyActive);
|
||||
return _positionStorageContract.GetList(onlyActive) ?? throw new NullListException();
|
||||
|
||||
}
|
||||
|
||||
public List<PositionDataModel> GetAllDataOfPosition(string positionId)
|
||||
{
|
||||
_logger.LogInformation("GetAllDataOfPost for {postId}", positionId);
|
||||
if (positionId.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(positionId));
|
||||
}
|
||||
if (!positionId.IsGuid())
|
||||
{
|
||||
throw new ValidationException("The value in the field postId is not a unique identifier.");
|
||||
}
|
||||
return _positionStorageContract.GetPostWithHistory(positionId) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public PositionDataModel GetPositionByData(string data)
|
||||
{
|
||||
_logger.LogInformation("Get element by data: {data}", data);
|
||||
if (data.IsEmpty())
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
PositionDataModel position;
|
||||
if (data.IsGuid())
|
||||
{
|
||||
position = _positionStorageContract.GetElementById(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
position = _positionStorageContract.GetElementByName(data);
|
||||
}
|
||||
|
||||
return position ?? throw new ElementNotFoundException(data);
|
||||
}
|
||||
|
||||
public void InsertPosition(PositionDataModel positionDataModel)
|
||||
{
|
||||
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(positionDataModel));
|
||||
ArgumentNullException.ThrowIfNull(positionDataModel);
|
||||
positionDataModel.Validate();
|
||||
_positionStorageContract.AddElement(positionDataModel);
|
||||
}
|
||||
|
||||
public void UpdatePosition(PositionDataModel positionDataModel)
|
||||
{
|
||||
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(positionDataModel));
|
||||
ArgumentNullException.ThrowIfNull(positionDataModel);
|
||||
positionDataModel.Validate();
|
||||
_positionStorageContract.UpdElement(positionDataModel);
|
||||
}
|
||||
|
||||
public void DeletePosition(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");
|
||||
}
|
||||
_positionStorageContract.DelElement(id);
|
||||
}
|
||||
|
||||
public void RestorePosition(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");
|
||||
}
|
||||
_positionStorageContract.ResElement(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StorageContract;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, ILogger logger) : ISalaryBusinessLogicsContracts
|
||||
{
|
||||
private readonly ILogger _logger = logger;
|
||||
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
|
||||
|
||||
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
_logger.LogInformation("GetAllSalariesByPeriod 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)
|
||||
{
|
||||
_logger.LogInformation("GetAllSalariesByPeriodByEmployee params: {fromDate}, {toDate}, {employeeId}",
|
||||
fromDate, toDate, 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.");
|
||||
}
|
||||
|
||||
return _salaryStorageContract.GetList(fromDate, toDate, employeeId) ?? throw new NullListException();
|
||||
}
|
||||
|
||||
public void CalculateSalaryByMonth(DateTime date)
|
||||
{
|
||||
_logger.LogInformation("CalculateSalaryByMonth: {date}", date);
|
||||
|
||||
var startDate = new DateTime(date.Year, date.Month, 1);
|
||||
var endDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
|
||||
|
||||
// Get all salaries for the month to avoid duplicate calculations
|
||||
var existingSalaries = _salaryStorageContract.GetList(startDate, endDate);
|
||||
|
||||
if (existingSalaries != null && existingSalaries.Any())
|
||||
{
|
||||
_logger.LogWarning("Salaries for period {startDate} to {endDate} already exist", startDate, endDate);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IClientBusinessLogicsContracts
|
||||
{
|
||||
List<СlientDataModel> GetAllClients();
|
||||
|
||||
СlientDataModel GetClientByData(string data);
|
||||
|
||||
void InsertClient(СlientDataModel clientDataModel);
|
||||
|
||||
void UpdateClient(СlientDataModel clientDataModel);
|
||||
|
||||
void DeleteClient(string id);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IDishBusinessLogicsContracts
|
||||
{
|
||||
List<DishDataModel> GetAllDishes();
|
||||
|
||||
List<DishHistoryDataModel> GetDishHistory(string dishId);
|
||||
|
||||
DishDataModel? GetDishById(string id);
|
||||
|
||||
DishDataModel? GetDishByName(string name);
|
||||
|
||||
void InsertDish(DishDataModel dishDataModel);
|
||||
|
||||
void UpdateDish(DishDataModel dishDataModel);
|
||||
|
||||
void DeleteDish(string id);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IDish_OrderBusinessLogicsContracts
|
||||
{
|
||||
List<Dish_OrderDataModel> GetAllDishOrders(string? orderId = null, string? dishId = null);
|
||||
Dish_OrderDataModel? GetDishOrderById(string orderId, string dishId);
|
||||
void InsertDishOrder(Dish_OrderDataModel dishOrderDataModel);
|
||||
void UpdateDishOrder(Dish_OrderDataModel dishOrderDataModel);
|
||||
void DeleteDishOrder(string orderId, string dishId);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IEmployeeBusinessLogicsContracts
|
||||
{
|
||||
List<EmployeeDataModel> GetAllEmployees(bool onlyActive = true, string? positionId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
|
||||
|
||||
EmployeeDataModel? GetEmployeeById(string id);
|
||||
|
||||
EmployeeDataModel? GetEmployeeByFIO(string fio);
|
||||
|
||||
void InsertEmployee(EmployeeDataModel employeeDataModel);
|
||||
|
||||
void UpdateEmployee(EmployeeDataModel employeeDataModel);
|
||||
|
||||
void DeleteEmployee(string id);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IOrderBusinessLogicsContracts
|
||||
{
|
||||
List<OrderDataModels> GetAllOrders(string? clientId = null, string? employeedId = null, string? dishId = null);
|
||||
|
||||
OrderDataModels? GetOrderById(string id);
|
||||
|
||||
void InsertOrder(OrderDataModels orderDataModel);
|
||||
|
||||
void DeleteOrder(string id);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts;
|
||||
|
||||
public interface IPositionBusinessLogicsContracts
|
||||
{
|
||||
List<PositionDataModel> GetAllPositions(bool onlyActive);
|
||||
List<PositionDataModel> GetAllDataOfPosition(string positionId);
|
||||
PositionDataModel GetPositionByData(string data);
|
||||
void InsertPosition(PositionDataModel positionDataModel);
|
||||
void UpdatePosition(PositionDataModel positionDataModel);
|
||||
void DeletePosition(string id);
|
||||
void RestorePosition(string id);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeContracts.BusinessLogicsContracts
|
||||
{
|
||||
public interface ISalaryBusinessLogicsContracts
|
||||
{
|
||||
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
|
||||
|
||||
List<SalaryDataModel> GetAllSalariesByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
|
||||
|
||||
void CalculateSalaryByMonth(DateTime date);
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,12 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class DishHistoryDataModel(string productId, double oldPrice, string orderid) : IValidation
|
||||
|
||||
public class DishHistoryDataModel(string dishId, double oldPrice, string orderId) : IValidation
|
||||
{
|
||||
public string DishId { get; private set; } = productId;
|
||||
public string DishId { get; private set; } = dishId;
|
||||
public double OldPrice { get; private set; } = oldPrice;
|
||||
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
|
||||
public string OrderId { get; private set; } = orderid;
|
||||
public string OrderId { get; private set; } = orderId;
|
||||
public void Validate()
|
||||
{
|
||||
if (DishId.IsEmpty())
|
||||
|
||||
@@ -1,39 +1,24 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
public class Dish_OrderDataModel(string orderid, string dishid, int count)
|
||||
public class Dish_OrderDataModel(string orderId, string dishId, int count)
|
||||
{
|
||||
public string OrderId { get; private set; } = orderid;
|
||||
public string DishId { get; private set; } = dishid;
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
|
||||
if (OrderId.IsEmpty())
|
||||
throw new ValidationException("Field OrderId is empty");
|
||||
if (!OrderId.IsGuid())
|
||||
throw new ValidationException("The value in the field OrderId is not a unique identifier");
|
||||
if (DishId.IsEmpty())
|
||||
throw new ValidationException("Field DishId is empty");
|
||||
if (!DishId.IsGuid())
|
||||
throw new ValidationException("The value in the field DishId is not a unique identifier");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
public string OrderId { get; private set; } = orderId;
|
||||
public string DishId { get; private set; } = dishId;
|
||||
public int Count { get; private set; } = count;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (OrderId.IsEmpty())
|
||||
throw new ValidationException("Field OrderId is empty");
|
||||
if (!OrderId.IsGuid())
|
||||
throw new ValidationException("The value in the field OrderId is not a unique identifier");
|
||||
if (DishId.IsEmpty())
|
||||
throw new ValidationException("Field DishId is empty");
|
||||
if (!DishId.IsGuid())
|
||||
throw new ValidationException("The value in the field DishId is not a unique identifier");
|
||||
if (Count <= 0)
|
||||
throw new ValidationException("Field Count is less than or equal to 0");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@ using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastructure;
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class OrderDataModels(string id, string clientid, string employeedid, List<Dish_OrderDataModel> dishes) : IValidation
|
||||
public class OrderDataModels(string id, string clientId, string employeeId, List<Dish_OrderDataModel> orderDishes) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string ClientId { get; private set; } = clientid;
|
||||
public string EmloyeedId { get; private set; } = employeedid;
|
||||
public List<Dish_OrderDataModel> Dishes { get; private set; } = dishes;
|
||||
public string ClientId { get; private set; } = clientId;
|
||||
public string EmloyeedId { get; private set; } = employeeId;
|
||||
public List<Dish_OrderDataModel> Dishes { get; private set; } = orderDishes;
|
||||
public void Validate()
|
||||
{
|
||||
if (Id.IsEmpty())
|
||||
|
||||
@@ -2,14 +2,11 @@
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.Infrastructure;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml;
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class PositionDataModell(string id, string positionId, string positionName, PositionType positionType, double salary, bool isActual, DateTime changeDate) : IValidation
|
||||
public class PositionDataModel(string positionId, string positionName, PositionType positionType, double salary, bool isActual, DateTime changeDate) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public string PositionId { get; private set; } = positionId;
|
||||
public string Id { get; private set; } = positionId;
|
||||
public string PositionName { get; private set; } = positionName;
|
||||
public PositionType PositionType { get; private set; } = positionType;
|
||||
public double Salary { get; private set; } = salary;
|
||||
@@ -21,10 +18,6 @@ public class PositionDataModell(string id, string positionId, string positionNam
|
||||
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 (PositionId.IsEmpty())
|
||||
throw new ValidationException("Field PostId is empty");
|
||||
if (!PositionId.IsGuid())
|
||||
throw new ValidationException("The value in the field PostId is not a unique identifier");
|
||||
if (PositionName.IsEmpty())
|
||||
throw new ValidationException("Field PostName is empty");
|
||||
if (PositionType == PositionType.None)
|
||||
|
||||
@@ -4,12 +4,12 @@ using AndDietCokeContracts.Infrastructure;
|
||||
|
||||
namespace AndDietCokeContracts.DataModels;
|
||||
|
||||
public class SalaryDataModel(string id, DateTime salaryDate, double salary, string employeedid) : IValidation
|
||||
public class SalaryDataModel(string id, DateTime salaryDate, double salary, string emloyeedid) : IValidation
|
||||
{
|
||||
public string Id { get; private set; } = id;
|
||||
public DateTime SalaryDate { get; private set; } = salaryDate;
|
||||
public double Salary { get; private set; } = salary;
|
||||
public string EmloyeedId { get; private set; } = employeedid;
|
||||
public string EmloyeedId { get; private set; } = emloyeedid;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
|
||||
@@ -13,6 +13,8 @@ public enum DishType
|
||||
Pepperoni = 2,
|
||||
BBQChicken = 3,
|
||||
Veggie = 4,
|
||||
Cola = 5
|
||||
Cola = 5,
|
||||
Soup = 6,
|
||||
MainCourse = 7
|
||||
}
|
||||
|
||||
|
||||
@@ -12,5 +12,8 @@ public enum PositionType
|
||||
Waiter = 1,
|
||||
Сhef = 2,
|
||||
Manager = 3,
|
||||
Assistant = 4
|
||||
Assistant = 4,
|
||||
Staff = 5,
|
||||
Developer = 6,
|
||||
QA = 7
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
public class DuplicateEmployeeException : Exception
|
||||
{
|
||||
public DuplicateEmployeeException(string id)
|
||||
: base($"Employee with ID {id} already exists") { }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AndDietCokeContracts.Exceptions;
|
||||
|
||||
public class ElementDeletedException : Exception
|
||||
{
|
||||
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace AndDietCokeContracts.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace AndDietCokeContracts.Exceptions;
|
||||
public class ElementNotFoundException : Exception
|
||||
{
|
||||
public string Value { get; private set; }
|
||||
|
||||
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace AndDietCokeContracts.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}") { }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AndDietCokeContracts.Exceptions;
|
||||
|
||||
public class NullListException : Exception
|
||||
{
|
||||
public NullListException() : base("The returned list is null") { }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace AndDietCokeContracts.Exceptions;
|
||||
public class StorageException : Exception
|
||||
{
|
||||
public StorageException(Exception ex) : base($"Error while working in storage: {ex.Message}", ex) { }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace AndDietCokeContracts.Extensions;
|
||||
|
||||
public static class DateTimeExtensions
|
||||
{
|
||||
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
|
||||
{
|
||||
return date >= olderDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace AndDietCokeContracts.Infrastructure;
|
||||
|
||||
public interface IConfigurationDatabase
|
||||
{
|
||||
string ConnectionString { get; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeContracts.StoragesContracts;
|
||||
|
||||
public interface IClientStorageContract
|
||||
{
|
||||
List<СlientDataModel> GetList();
|
||||
|
||||
СlientDataModel? GetElementById(string id);
|
||||
|
||||
СlientDataModel? GetElementByPhoneNumber(string phoneNumber);
|
||||
|
||||
СlientDataModel? GetElementByFIO(string fio);
|
||||
|
||||
void AddElement(СlientDataModel clientDataModel);
|
||||
|
||||
void UpdElement(СlientDataModel clientDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.StoragesContracts;
|
||||
|
||||
public interface IDishStorageContracts
|
||||
{
|
||||
List<DishDataModel> GetList();
|
||||
|
||||
List<DishHistoryDataModel> GetHistoryByProductId(string dishId);
|
||||
|
||||
DishDataModel? GetElementById(string id);
|
||||
|
||||
DishDataModel? GetElementByName(string name);
|
||||
|
||||
void AddElement(DishDataModel dishDataModel);
|
||||
|
||||
void UpdElement(DishDataModel dishDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.StoragesContracts;
|
||||
|
||||
public interface IDish_OrderStorageContract
|
||||
{
|
||||
List<Dish_OrderDataModel> GetList(string? orderId = null, string? dishId = null);
|
||||
|
||||
Dish_OrderDataModel? GetElementById(string orderId, string dishId);
|
||||
|
||||
void AddElement(Dish_OrderDataModel dishOrderDataModel);
|
||||
|
||||
void UpdElement(Dish_OrderDataModel dishOrderDataModel);
|
||||
|
||||
void DelElement(string orderId, string dishId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
namespace AndDietCokeContracts.StoragesContracts;
|
||||
public interface IEmployeeStoragesContracts
|
||||
{
|
||||
List<EmployeeDataModel> GetList(bool onlyActive = true, string? positionId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
|
||||
|
||||
EmployeeDataModel? GetElementById(string id);
|
||||
|
||||
EmployeeDataModel? GetElementByFIO(string fio);
|
||||
|
||||
void AddElement(EmployeeDataModel employeeDataModel);
|
||||
|
||||
void UpdElement(EmployeeDataModel employeeDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeContracts.StorageContracts;
|
||||
|
||||
public interface IOrderStorageContracts
|
||||
{
|
||||
List<OrderDataModels> GetList(string? clientId = null, string? employeedId = null, string? dishId = null);
|
||||
|
||||
OrderDataModels? GetElementById(string id);
|
||||
|
||||
void AddElement(OrderDataModels orderDataModel);
|
||||
|
||||
void DelElement(string id);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AndDietCokeContracts.StoragesContracts;
|
||||
public interface IPositionStorageContract
|
||||
{
|
||||
List<PositionDataModel> GetList(bool onlyActual = true);
|
||||
List<PositionDataModel> GetPostWithHistory(string postId);
|
||||
PositionDataModel? GetElementById(string id);
|
||||
PositionDataModel? GetElementByName(string name);
|
||||
void AddElement(PositionDataModel positionDataModell);
|
||||
void UpdElement(PositionDataModel positionDataModell);
|
||||
void DelElement(string id);
|
||||
void ResElement(string id);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeContracts.StorageContract
|
||||
{
|
||||
public interface ISalaryStorageContract
|
||||
{
|
||||
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
|
||||
|
||||
void AddElement(SalaryDataModel salaryDataModel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.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.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeBusinessLogic\AndDietCokeBusinessLogic.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,54 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Infrastructure;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
namespace AndDietCokeDatabase;
|
||||
|
||||
public class AndDietCokeDbContext(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.Contact).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Dish>().HasIndex(x => x.Name).IsUnique();
|
||||
|
||||
modelBuilder.Entity<Position>()
|
||||
.HasIndex(e => new { e.PositionName, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Position.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<Position>()
|
||||
.HasIndex(e => new { e.PositionId, e.IsActual })
|
||||
.IsUnique()
|
||||
.HasFilter($"\"{nameof(Position.IsActual)}\" = TRUE");
|
||||
|
||||
modelBuilder.Entity<Dish_Order>().HasKey(x => new { x.DishId, x.OrderId });
|
||||
|
||||
}
|
||||
|
||||
public DbSet<Client> Clients { get; set; }
|
||||
|
||||
public DbSet<Position> Posts { get; set; }
|
||||
|
||||
public DbSet<Dish> Dishes { get; set; }
|
||||
|
||||
public DbSet<DishHistory> DishHistories { get; set; }
|
||||
|
||||
public DbSet<Salaries> Salaries { get; set; }
|
||||
|
||||
public DbSet<Order> Orders { get; set; }
|
||||
|
||||
public DbSet<Dish_Order> Dish_Orders { get; set; }
|
||||
|
||||
public DbSet<Employee> Employees { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class ClientStorageContract : IClientStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClientStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(Client));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<СlientDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Clients.Select(x => _mapper.Map<СlientDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public СlientDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<СlientDataModel>(GetClientById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public СlientDataModel? GetElementByFIO(string fio)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<СlientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.FIO == fio));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public СlientDataModel? GetElementByPhoneNumber(string phoneNumber)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<СlientDataModel>(_dbContext.Clients.FirstOrDefault(x => x.Contact == phoneNumber));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(СlientDataModel 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_Contact" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Contact", clientDataModel.Contact);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(СlientDataModel 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_Contact" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Contact", clientDataModel.Contact);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class DishStorageContract : IDishStorageContracts
|
||||
{
|
||||
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public DishStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(Dish));
|
||||
cfg.AddMaps(typeof(DishHistory));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<DishDataModel> GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Dishes.AsQueryable();
|
||||
return [.. query.Select(x => _mapper.Map<DishDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<DishHistoryDataModel> GetHistoryByProductId(string productId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.DishHistories.Where(x => x.DishId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<DishHistoryDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public DishDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<DishDataModel>(GetDishById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public DishDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<DishDataModel>(_dbContext.Dishes.FirstOrDefault(x => x.Name == name));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(DishDataModel DishDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Dishes.Add(_mapper.Map<Dish>(DishDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Id", DishDataModel.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", DishDataModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(DishDataModel DishDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetDishById(DishDataModel.Id) ?? throw new ElementNotFoundException(DishDataModel.Id);
|
||||
if (element.Price != DishDataModel.Price)
|
||||
{
|
||||
_dbContext.DishHistories.Add(new DishHistory() { DishId = element.Id, OldPrice = element.Price, OrderId = element.OrderId });
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
_dbContext.Dishes.Update(_mapper.Map(DishDataModel, element));
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Dishes_Name" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("Name", DishDataModel.Name);
|
||||
}
|
||||
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 = GetDishById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Dishes.Remove(element);
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Dish? GetDishById(string id) => _dbContext.Dishes.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class EmployeeStorageContract : IEmployeeStoragesContracts
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public EmployeeStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.AddMaps(typeof(Employee));
|
||||
});
|
||||
_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.PositionId == 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 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);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StorageContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class OrderStorageContract : IOrderStorageContracts
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public OrderStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Dish_Order, Dish_OrderDataModel>();
|
||||
cfg.CreateMap<Dish_OrderDataModel, Dish_Order>();
|
||||
cfg.CreateMap<Order, OrderDataModels>();
|
||||
cfg.CreateMap<OrderDataModels, Order>()
|
||||
.ForMember(x => x.OrderDishes, x => x.MapFrom(src => src.Dishes));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<OrderDataModels> GetList(string? clientId = null, string? employeedId = null, string? dishId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Orders.Include(x => x.OrderDishes).AsQueryable();
|
||||
if (employeedId is not null)
|
||||
{
|
||||
query = query.Where(x => x.EmloyeedId == employeedId);
|
||||
}
|
||||
if (clientId is not null)
|
||||
{
|
||||
query = query.Where(x => x.ClientId == clientId);
|
||||
}
|
||||
if (dishId is not null)
|
||||
{
|
||||
query = query.Where(x => x.OrderDishes!.Any(y => y.DishId == dishId));
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<OrderDataModels>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public OrderDataModels? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<OrderDataModels>(GetOrderById(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(OrderDataModels orderDataModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Orders.Add(_mapper.Map<Order>(orderDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void DelElement(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var element = GetOrderById(id) ?? throw new ElementNotFoundException(id);
|
||||
_dbContext.Remove(element);
|
||||
_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 Order? GetOrderById(string id) => _dbContext.Orders.FirstOrDefault(x => x.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Npgsql;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class PositionStorageContract : IPositionStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PositionStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Position, PositionDataModel>()
|
||||
.ForMember(x => x.Id, x => x.MapFrom(src => src.PositionId));
|
||||
cfg.CreateMap<PositionDataModel, Position>()
|
||||
.ForMember(x => x.Id, x => x.Ignore())
|
||||
.ForMember(x => x.PositionId, 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<PositionDataModel> GetList(bool onlyActual = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Posts.AsQueryable();
|
||||
if (onlyActual)
|
||||
{
|
||||
query = query.Where(x => x.IsActual);
|
||||
}
|
||||
return [.. query.Select(x => _mapper.Map<PositionDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PositionDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PositionDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PositionId == id && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public PositionDataModel? GetElementByName(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _mapper.Map<PositionDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PositionName == name && x.IsActual));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PositionDataModel> GetPostWithHistory(string postId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return [.. _dbContext.Posts.Where(x => x.PositionId == postId).Select(x => _mapper.Map<PositionDataModel>(x))];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddElement(PositionDataModel positionDataModell)
|
||||
{
|
||||
try
|
||||
{
|
||||
_dbContext.Posts.Add(_mapper.Map<Position>(positionDataModell));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PositionName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PositionName", positionDataModell.PositionName);
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PositionId_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PositionId", positionDataModell.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(PositionDataModel positionDataModell)
|
||||
{
|
||||
try
|
||||
{
|
||||
var transaction = _dbContext.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var element = GetPostById(positionDataModell.Id) ?? throw new ElementNotFoundException(positionDataModell.Id);
|
||||
if (!element.IsActual)
|
||||
{
|
||||
throw new ElementDeletedException(positionDataModell.Id);
|
||||
}
|
||||
element.IsActual = false;
|
||||
_dbContext.SaveChanges();
|
||||
var newElement = _mapper.Map<Position>(positionDataModell);
|
||||
_dbContext.Posts.Add(newElement);
|
||||
_dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PositionName_IsActual" })
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new ElementExistsException("PositionName", positionDataModell.PositionName);
|
||||
}
|
||||
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 Position? GetPostById(string id) => _dbContext.Posts.Where(x => x.PositionId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StorageContract;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Implementations;
|
||||
|
||||
public class SalaryStorageContract : ISalaryStorageContract
|
||||
{
|
||||
private readonly AndDietCokeDbContext _dbContext;
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public SalaryStorageContract(AndDietCokeDbContext dbContext)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Salaries, SalaryDataModel>();
|
||||
cfg.CreateMap<SalaryDataModel, Salaries>()
|
||||
.ForMember(dest => dest.Salary, opt => opt.MapFrom(src => src.Salary));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? workerId = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Salaries.Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate);
|
||||
if (workerId is not null)
|
||||
{
|
||||
query = query.Where(x => x.EmloyeedId == workerId);
|
||||
}
|
||||
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<Salaries>(salaryDataModel));
|
||||
_dbContext.SaveChanges();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
17
AndDietCokeProject/AndDietCokeDatabase/Models/Client.cs
Normal file
17
AndDietCokeProject/AndDietCokeDatabase/Models/Client.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AutoMapper;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(СlientDataModel), ReverseMap = true)]
|
||||
public class Client
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string FIO { get; set; }
|
||||
public required string Contact { get; set; }
|
||||
public double DiscountSize { get; set; }
|
||||
|
||||
[ForeignKey("ClientId")]
|
||||
public List<Order>? Orders { get; set; }
|
||||
}
|
||||
22
AndDietCokeProject/AndDietCokeDatabase/Models/Dish.cs
Normal file
22
AndDietCokeProject/AndDietCokeDatabase/Models/Dish.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AutoMapper;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(DishDataModel), ReverseMap = true)]
|
||||
public class Dish
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public DishType DishType { get; set; }
|
||||
public double Price { get; set; }
|
||||
public required string OrderId { get; set; }
|
||||
|
||||
[ForeignKey("DishId")]
|
||||
public List<Dish_Order>? DishOrders { get; set; }
|
||||
|
||||
[ForeignKey("DishId")]
|
||||
public List<DishHistory>? DishHistories { get; set; }
|
||||
}
|
||||
15
AndDietCokeProject/AndDietCokeDatabase/Models/DishHistory.cs
Normal file
15
AndDietCokeProject/AndDietCokeDatabase/Models/DishHistory.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AutoMapper;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(DishHistoryDataModel), ReverseMap = true)]
|
||||
public class DishHistory
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public required string DishId { get; set; }
|
||||
public double OldPrice { get; set; }
|
||||
public DateTime ChangeDate { get; set; } = DateTime.UtcNow;
|
||||
public required string OrderId { get; set; }
|
||||
public Dish? Dish { get; set; }
|
||||
}
|
||||
10
AndDietCokeProject/AndDietCokeDatabase/Models/Dish_Order.cs
Normal file
10
AndDietCokeProject/AndDietCokeDatabase/Models/Dish_Order.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
public class Dish_Order
|
||||
{
|
||||
public required string OrderId { get; set; }
|
||||
public required string DishId { get; set; }
|
||||
public int Count { get; set; }
|
||||
public Order? Order { get; set; }
|
||||
public Dish? Dish { get; set; }
|
||||
}
|
||||
24
AndDietCokeProject/AndDietCokeDatabase/Models/Employee.cs
Normal file
24
AndDietCokeProject/AndDietCokeDatabase/Models/Employee.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AutoMapper;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
|
||||
public class Employee
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string FIO { get; set; }
|
||||
public required string PositionId { get; set; }
|
||||
public PositionType PositionType { get; set; }
|
||||
public DateTime BirthDate { get; set; }
|
||||
public DateTime EmploymentDate { get; set; }
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
[ForeignKey("EmployeeId")]
|
||||
public List<Order>? Orders { get; set; }
|
||||
|
||||
[ForeignKey("EmployeeId")]
|
||||
public List<Salaries>? Salaries { get; set; }
|
||||
}
|
||||
15
AndDietCokeProject/AndDietCokeDatabase/Models/Order.cs
Normal file
15
AndDietCokeProject/AndDietCokeDatabase/Models/Order.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
public class Order
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public string? ClientId { get; set; }
|
||||
public required string EmloyeedId { get; set; }
|
||||
public Employee? Employee { get; set; }
|
||||
public Client? Client { get; set; }
|
||||
|
||||
[ForeignKey("OrderId")]
|
||||
public List<Dish_Order>? OrderDishes { get; set; }
|
||||
}
|
||||
14
AndDietCokeProject/AndDietCokeDatabase/Models/Position.cs
Normal file
14
AndDietCokeProject/AndDietCokeDatabase/Models/Position.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
public class Position
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public required string PositionId { get; set; }
|
||||
public required string PositionName { get; set; }
|
||||
public PositionType PositionType { get; set; }
|
||||
public double Salary { get; set; }
|
||||
public bool IsActual { get; set; }
|
||||
public DateTime ChangeDate { get; set; }
|
||||
}
|
||||
10
AndDietCokeProject/AndDietCokeDatabase/Models/Salaries.cs
Normal file
10
AndDietCokeProject/AndDietCokeDatabase/Models/Salaries.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace AndDietCokeDatabase.Models;
|
||||
|
||||
public class Salaries
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||
public DateTime SalaryDate { get; set; }
|
||||
public double Salary { get; set; }
|
||||
public required string EmloyeedId { get; set; }
|
||||
public Employee? Employee { get; set; }
|
||||
}
|
||||
@@ -7,6 +7,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeContracts", "And
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeTests", "AndDietCokeTests\AndDietCokeTests.csproj", "{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeBusinessLogic", "AndDietCokeBusinessLogic\AndDietCokeBusinessLogic.csproj", "{950B374D-94CC-4EE2-BD25-E78D5CDA5F2F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AndDietCokeDatabase", "AndDietCokeDatabase\AndDietCokeDatabase.csproj", "{C303A979-1D68-4503-7DFA-928014D2D78A}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -21,8 +25,19 @@ Global
|
||||
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{97CF49C2-6F17-4FCB-B2AD-D84AED6A1AF9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{950B374D-94CC-4EE2-BD25-E78D5CDA5F2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{950B374D-94CC-4EE2-BD25-E78D5CDA5F2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{950B374D-94CC-4EE2-BD25-E78D5CDA5F2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{950B374D-94CC-4EE2-BD25-E78D5CDA5F2F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C303A979-1D68-4503-7DFA-928014D2D78A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C303A979-1D68-4503-7DFA-928014D2D78A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C303A979-1D68-4503-7DFA-928014D2D78A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C303A979-1D68-4503-7DFA-928014D2D78A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6545237B-96EA-4C80-963A-F4CB39480436}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
@@ -11,14 +11,18 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AndDietCokeBusinessLogic\AndDietCokeBusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeContracts\AndDietCokeContracts.csproj" />
|
||||
<ProjectReference Include="..\AndDietCokeDatabase\AndDietCokeDatabase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests
|
||||
{
|
||||
[TestFixture]
|
||||
internal class DishBusinessLogicContractTests
|
||||
{
|
||||
private DishBusinessLogicContract _dishBusinessLogic;
|
||||
private Mock<IDishStorageContracts> _dishStorageMock;
|
||||
private Mock<ILogger<DishBusinessLogicContract>> _loggerMock;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_dishStorageMock = new Mock<IDishStorageContracts>();
|
||||
_loggerMock = new Mock<ILogger<DishBusinessLogicContract>>();
|
||||
_dishBusinessLogic = new DishBusinessLogicContract(
|
||||
_dishStorageMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_dishStorageMock.Reset();
|
||||
_loggerMock.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishes_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testDishes = new List<DishDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Борщ", DishType.Soup, 250.50, Guid.NewGuid().ToString()),
|
||||
new(Guid.NewGuid().ToString(), "Стейк", DishType.MainCourse, 1200.00, Guid.NewGuid().ToString())
|
||||
};
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetList()).Returns(testDishes);
|
||||
|
||||
// Act
|
||||
var result = _dishBusinessLogic.GetAllDishes();
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Is.EquivalentTo(testDishes));
|
||||
});
|
||||
_dishStorageMock.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishes_ReturnEmptyList_Test()
|
||||
{
|
||||
// Arrange
|
||||
_dishStorageMock.Setup(x => x.GetList()).Returns(new List<DishDataModel>());
|
||||
|
||||
// Act
|
||||
var result = _dishBusinessLogic.GetAllDishes();
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Has.Count.EqualTo(0));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishes_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_dishStorageMock.Setup(x => x.GetList()).Returns((List<DishDataModel>)null);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishBusinessLogic.GetAllDishes(),
|
||||
Throws.TypeOf<NullListException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishHistory_InvalidId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishBusinessLogic.GetDishHistory("invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishById_ValidId_ReturnsDish_Test()
|
||||
{
|
||||
// Arrange
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var testDish = new DishDataModel(dishId, "Борщ", DishType.Soup, 250.50, Guid.NewGuid().ToString());
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetElementById(dishId))
|
||||
.Returns(testDish);
|
||||
|
||||
// Act
|
||||
var result = _dishBusinessLogic.GetDishById(dishId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testDish));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishById_NotFound_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishBusinessLogic.GetDishById(dishId),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishByName_ValidName_ReturnsDish_Test()
|
||||
{
|
||||
// Arrange
|
||||
var dishName = "Борщ";
|
||||
var testDish = new DishDataModel(Guid.NewGuid().ToString(), dishName, DishType.Soup, 250.50, Guid.NewGuid().ToString());
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetElementByName(dishName))
|
||||
.Returns(testDish);
|
||||
|
||||
// Act
|
||||
var result = _dishBusinessLogic.GetDishByName(dishName);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testDish));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDish_ValidData_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testDish = new DishDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
"Борщ",
|
||||
DishType.Soup,
|
||||
250.50,
|
||||
Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
_dishBusinessLogic.InsertDish(testDish);
|
||||
|
||||
// Assert
|
||||
_dishStorageMock.Verify(x => x.AddElement(testDish), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDish_DuplicateName_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testDish = new DishDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
"Борщ",
|
||||
DishType.Soup,
|
||||
250.50,
|
||||
Guid.NewGuid().ToString());
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetElementByName(testDish.Name))
|
||||
.Returns(testDish);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishBusinessLogic.InsertDish(testDish),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateDish_ValidData_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testDish = new DishDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
"Борщ",
|
||||
DishType.Soup,
|
||||
250.50,
|
||||
Guid.NewGuid().ToString());
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetElementById(testDish.Id))
|
||||
.Returns(testDish);
|
||||
|
||||
// Act
|
||||
_dishBusinessLogic.UpdateDish(testDish);
|
||||
|
||||
// Assert
|
||||
_dishStorageMock.Verify(x => x.UpdElement(testDish), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDish_ValidId_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var testDish = new DishDataModel(
|
||||
dishId,
|
||||
"Борщ",
|
||||
DishType.Soup,
|
||||
250.50,
|
||||
Guid.NewGuid().ToString());
|
||||
|
||||
_dishStorageMock.Setup(x => x.GetElementById(dishId))
|
||||
.Returns(testDish);
|
||||
|
||||
// Act
|
||||
_dishBusinessLogic.DeleteDish(dishId);
|
||||
|
||||
// Assert
|
||||
_dishStorageMock.Verify(x => x.DelElement(dishId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDish_InvalidId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishBusinessLogic.DeleteDish("invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests
|
||||
{
|
||||
[TestFixture]
|
||||
internal class Dish_OrderBusinessLogicContractTests
|
||||
{
|
||||
private Dish_OrderBusinessLogicContract _dishOrderBusinessLogic;
|
||||
private Mock<IDish_OrderStorageContract> _dishOrderStorageMock;
|
||||
private Mock<ILogger<Dish_OrderBusinessLogicContract>> _loggerMock;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_dishOrderStorageMock = new Mock<IDish_OrderStorageContract>();
|
||||
_loggerMock = new Mock<ILogger<Dish_OrderBusinessLogicContract>>();
|
||||
_dishOrderBusinessLogic = new Dish_OrderBusinessLogicContract(
|
||||
_dishOrderStorageMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_dishOrderStorageMock.Reset();
|
||||
_loggerMock.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testData = new List<Dish_OrderDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1)
|
||||
};
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(testData);
|
||||
|
||||
// Act
|
||||
var result = _dishOrderBusinessLogic.GetAllDishOrders();
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Is.EquivalentTo(testData));
|
||||
});
|
||||
_dishOrderStorageMock.Verify(x => x.GetList(null, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_WithOrderIdFilter_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var testData = new List<Dish_OrderDataModel>
|
||||
{
|
||||
new(orderId, Guid.NewGuid().ToString(), 3)
|
||||
};
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetList(orderId, It.IsAny<string>()))
|
||||
.Returns(testData);
|
||||
|
||||
// Act
|
||||
var result = _dishOrderBusinessLogic.GetAllDishOrders(orderId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EquivalentTo(testData));
|
||||
_dishOrderStorageMock.Verify(x => x.GetList(orderId, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_WithDishIdFilter_Test()
|
||||
{
|
||||
// Arrange
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var testData = new List<Dish_OrderDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), dishId, 1)
|
||||
};
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetList(It.IsAny<string>(), dishId))
|
||||
.Returns(testData);
|
||||
|
||||
// Act
|
||||
var result = _dishOrderBusinessLogic.GetAllDishOrders(null, dishId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EquivalentTo(testData));
|
||||
_dishOrderStorageMock.Verify(x => x.GetList(null, dishId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_dishOrderStorageMock.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns((List<Dish_OrderDataModel>)null);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetAllDishOrders(),
|
||||
Throws.TypeOf<NullListException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_InvalidOrderId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetAllDishOrders("invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDishOrders_InvalidDishId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetAllDishOrders(null, "invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishOrderById_ValidIds_ReturnsRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var testRecord = new Dish_OrderDataModel(orderId, dishId, 2);
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetElementById(orderId, dishId))
|
||||
.Returns(testRecord);
|
||||
|
||||
// Act
|
||||
var result = _dishOrderBusinessLogic.GetDishOrderById(orderId, dishId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testRecord));
|
||||
_dishOrderStorageMock.Verify(x => x.GetElementById(orderId, dishId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishOrderById_InvalidOrderId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetDishOrderById("invalid", Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishOrderById_InvalidDishId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetDishOrderById(Guid.NewGuid().ToString(), "invalid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetDishOrderById_NotFound_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.GetDishOrderById(orderId, dishId),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDishOrder_ValidData_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testRecord = new Dish_OrderDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
2);
|
||||
|
||||
// Act
|
||||
_dishOrderBusinessLogic.InsertDishOrder(testRecord);
|
||||
|
||||
// Assert
|
||||
_dishOrderStorageMock.Verify(x => x.AddElement(testRecord), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDishOrder_NullData_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.InsertDishOrder(null),
|
||||
Throws.TypeOf<ArgumentNullException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDishOrder_InvalidCount_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var invalidRecord = new Dish_OrderDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
0); // Invalid count
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.InsertDishOrder(invalidRecord),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertDishOrder_Duplicate_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testRecord = new Dish_OrderDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
1);
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetElementById(testRecord.OrderId, testRecord.DishId))
|
||||
.Returns(testRecord);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.InsertDishOrder(testRecord),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateDishOrder_ValidData_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testRecord = new Dish_OrderDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
3);
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetElementById(testRecord.OrderId, testRecord.DishId))
|
||||
.Returns(testRecord);
|
||||
|
||||
// Act
|
||||
_dishOrderBusinessLogic.UpdateDishOrder(testRecord);
|
||||
|
||||
// Assert
|
||||
_dishOrderStorageMock.Verify(x => x.UpdElement(testRecord), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateDishOrder_NotExists_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testRecord = new Dish_OrderDataModel(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
2);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.UpdateDishOrder(testRecord),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDishOrder_ValidIds_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
var testRecord = new Dish_OrderDataModel(orderId, dishId, 1);
|
||||
|
||||
_dishOrderStorageMock.Setup(x => x.GetElementById(orderId, dishId))
|
||||
.Returns(testRecord);
|
||||
|
||||
// Act
|
||||
_dishOrderBusinessLogic.DeleteDishOrder(orderId, dishId);
|
||||
|
||||
// Assert
|
||||
_dishOrderStorageMock.Verify(x => x.DelElement(orderId, dishId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDishOrder_NotExists_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var dishId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.DeleteDishOrder(orderId, dishId),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDishOrder_InvalidOrderId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.DeleteDishOrder("invalid", Guid.NewGuid().ToString()),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteDishOrder_InvalidDishId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _dishOrderBusinessLogic.DeleteDishOrder(Guid.NewGuid().ToString(), "invalid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class EmployeeBusinessLogicContractTests
|
||||
{
|
||||
private EmployeeBusinessLogicContract _employeeBusinessLogicContract;
|
||||
private Mock<IEmployeeStoragesContracts> _employeeStorageContract;
|
||||
private Mock<ILogger<EmployeeBusinessLogicContract>> _logger;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_employeeStorageContract = new Mock<IEmployeeStoragesContracts>();
|
||||
_logger = new Mock<ILogger<EmployeeBusinessLogicContract>>();
|
||||
_employeeBusinessLogicContract = new EmployeeBusinessLogicContract(
|
||||
_employeeStorageContract.Object,
|
||||
_logger.Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_employeeStorageContract.Reset();
|
||||
_logger.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllEmployees_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testEmployees = new List<EmployeeDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false),
|
||||
new(Guid.NewGuid().ToString(), "Петров П.П.", Guid.NewGuid().ToString(),
|
||||
PositionType.Developer, DateTime.Now.AddYears(-25), DateTime.Now.AddYears(-3), true)
|
||||
};
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetList(
|
||||
It.IsAny<bool>(), It.IsAny<string>(),
|
||||
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
|
||||
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns(testEmployees);
|
||||
|
||||
// Act
|
||||
var resultActive = _employeeBusinessLogicContract.GetAllEmployees(true);
|
||||
var resultAll = _employeeBusinessLogicContract.GetAllEmployees(false);
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(resultActive, Is.Not.Null);
|
||||
Assert.That(resultAll, Is.Not.Null);
|
||||
Assert.That(resultActive, Is.EquivalentTo(testEmployees));
|
||||
Assert.That(resultAll, Is.EquivalentTo(testEmployees));
|
||||
});
|
||||
|
||||
_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_WithPositionFilter_Test()
|
||||
{
|
||||
// Arrange
|
||||
var positionId = Guid.NewGuid().ToString();
|
||||
var testEmployees = new List<EmployeeDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Сидоров С.С.", positionId,
|
||||
PositionType.Developer, DateTime.Now.AddYears(-28), DateTime.Now.AddYears(-4), false)
|
||||
};
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetList(
|
||||
It.IsAny<bool>(), positionId,
|
||||
It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
|
||||
It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
|
||||
.Returns(testEmployees);
|
||||
|
||||
// Act
|
||||
var result = _employeeBusinessLogicContract.GetAllEmployees(true, positionId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EquivalentTo(testEmployees));
|
||||
_employeeStorageContract.Verify(x => x.GetList(true, positionId, null, null, null, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllEmployees_WithDateFilters_Test()
|
||||
{
|
||||
// Arrange
|
||||
var fromDate = DateTime.Now.AddYears(-5);
|
||||
var toDate = DateTime.Now;
|
||||
var testEmployees = new List<EmployeeDataModel>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Кузнецов К.К.", Guid.NewGuid().ToString(),
|
||||
PositionType.QA, DateTime.Now.AddYears(-35), DateTime.Now.AddYears(-2), false)
|
||||
};
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetList(
|
||||
It.IsAny<bool>(), It.IsAny<string>(),
|
||||
fromDate, toDate,
|
||||
fromDate, toDate))
|
||||
.Returns(testEmployees);
|
||||
|
||||
// Act
|
||||
var result = _employeeBusinessLogicContract.GetAllEmployees(
|
||||
true, null, fromDate, toDate, fromDate, toDate);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EquivalentTo(testEmployees));
|
||||
_employeeStorageContract.Verify(x => x.GetList(
|
||||
true, null, fromDate, toDate, fromDate, toDate), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllEmployees_ReturnNull_ThrowsException_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((List<EmployeeDataModel>)null);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.GetAllEmployees(),
|
||||
Throws.TypeOf<NullListException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetEmployeeById_ValidId_ReturnsEmployee_Test()
|
||||
{
|
||||
// Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var testEmployee = new EmployeeDataModel(
|
||||
employeeId, "Иванов И.И.", Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false);
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetElementById(employeeId))
|
||||
.Returns(testEmployee);
|
||||
|
||||
// Act
|
||||
var result = _employeeBusinessLogicContract.GetEmployeeById(employeeId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testEmployee));
|
||||
_employeeStorageContract.Verify(x => x.GetElementById(employeeId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetEmployeeById_InvalidId_ThrowsException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var invalidId = "not-a-guid";
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.GetEmployeeById(invalidId),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetEmployeeByFIO_ValidFIO_ReturnsEmployee_Test()
|
||||
{
|
||||
// Arrange
|
||||
var fio = "Иванов И.И.";
|
||||
var testEmployee = new EmployeeDataModel(
|
||||
Guid.NewGuid().ToString(), fio, Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false);
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetElementByFIO(fio))
|
||||
.Returns(testEmployee);
|
||||
|
||||
// Act
|
||||
var result = _employeeBusinessLogicContract.GetEmployeeByFIO(fio);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testEmployee));
|
||||
_employeeStorageContract.Verify(x => x.GetElementByFIO(fio), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertEmployee_ValidEmployee_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testEmployee = new EmployeeDataModel(
|
||||
Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false);
|
||||
|
||||
// Act
|
||||
_employeeBusinessLogicContract.InsertEmployee(testEmployee);
|
||||
|
||||
// Assert
|
||||
_employeeStorageContract.Verify(x => x.AddElement(testEmployee), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertEmployee_InvalidEmployee_ThrowsException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var invalidEmployee = new EmployeeDataModel(
|
||||
"invalid-id", "Иванов", "invalid-post",
|
||||
PositionType.None, DateTime.Now, DateTime.Now, false);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.InsertEmployee(invalidEmployee),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateEmployee_ValidEmployee_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testEmployee = new EmployeeDataModel(
|
||||
Guid.NewGuid().ToString(), "Иванов И.И.", Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false);
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetElementById(testEmployee.Id))
|
||||
.Returns(testEmployee);
|
||||
|
||||
// Act
|
||||
_employeeBusinessLogicContract.UpdateEmployee(testEmployee);
|
||||
|
||||
// Assert
|
||||
_employeeStorageContract.Verify(x => x.UpdElement(testEmployee), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteEmployee_ValidId_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var employeeId = Guid.NewGuid().ToString();
|
||||
var testEmployee = new EmployeeDataModel(
|
||||
employeeId, "Иванов И.И.", Guid.NewGuid().ToString(),
|
||||
PositionType.Manager, DateTime.Now.AddYears(-30), DateTime.Now.AddYears(-5), false);
|
||||
|
||||
_employeeStorageContract.Setup(x => x.GetElementById(employeeId))
|
||||
.Returns(testEmployee);
|
||||
|
||||
// Act
|
||||
_employeeBusinessLogicContract.DeleteEmployee(employeeId);
|
||||
|
||||
// Assert
|
||||
_employeeStorageContract.Verify(x => x.DelElement(employeeId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteEmployee_InvalidId_ThrowsException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var invalidId = "not-a-guid";
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _employeeBusinessLogicContract.DeleteEmployee(invalidId),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests
|
||||
{
|
||||
[TestFixture]
|
||||
internal class OrderBusinessLogicContractTests
|
||||
{
|
||||
private OrderBusinessLogicContract _orderBusinessLogic;
|
||||
private Mock<IOrderStorageContracts> _orderStorageMock;
|
||||
private Mock<ILogger<OrderBusinessLogicContract>> _loggerMock;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_orderStorageMock = new Mock<IOrderStorageContracts>();
|
||||
_loggerMock = new Mock<ILogger<OrderBusinessLogicContract>>();
|
||||
_orderBusinessLogic = new OrderBusinessLogicContract(
|
||||
_orderStorageMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_orderStorageMock.Reset();
|
||||
_loggerMock.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllOrders_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testOrders = new List<OrderDataModels>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) }),
|
||||
new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 2) })
|
||||
};
|
||||
|
||||
_orderStorageMock.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(testOrders);
|
||||
|
||||
// Act
|
||||
var result = _orderBusinessLogic.GetAllOrders();
|
||||
|
||||
// Assert
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Is.EquivalentTo(testOrders));
|
||||
});
|
||||
_orderStorageMock.Verify(x => x.GetList(null, null, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllOrders_WithClientFilter_Test()
|
||||
{
|
||||
// Arrange
|
||||
var clientId = Guid.NewGuid().ToString();
|
||||
var testOrders = new List<OrderDataModels>
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), clientId, Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) })
|
||||
};
|
||||
|
||||
_orderStorageMock.Setup(x => x.GetList(clientId, It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(testOrders);
|
||||
|
||||
// Act
|
||||
var result = _orderBusinessLogic.GetAllOrders(clientId: clientId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EquivalentTo(testOrders));
|
||||
_orderStorageMock.Verify(x => x.GetList(clientId, null, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllOrders_InvalidClientId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _orderBusinessLogic.GetAllOrders(clientId: "invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetOrderById_ValidId_ReturnsOrder_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var testOrder = new OrderDataModels(
|
||||
orderId,
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) });
|
||||
|
||||
_orderStorageMock.Setup(x => x.GetElementById(orderId))
|
||||
.Returns(testOrder);
|
||||
|
||||
// Act
|
||||
var result = _orderBusinessLogic.GetOrderById(orderId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.EqualTo(testOrder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetOrderById_InvalidId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _orderBusinessLogic.GetOrderById("invalid-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertOrder_ValidData_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testOrder = new OrderDataModels(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) });
|
||||
|
||||
// Act
|
||||
_orderBusinessLogic.InsertOrder(testOrder);
|
||||
|
||||
// Assert
|
||||
_orderStorageMock.Verify(x => x.AddElement(testOrder), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertOrder_DuplicateId_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testOrder = new OrderDataModels(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) });
|
||||
|
||||
_orderStorageMock.Setup(x => x.GetElementById(testOrder.Id))
|
||||
.Returns(testOrder);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _orderBusinessLogic.InsertOrder(testOrder),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteOrder_ValidId_Success_Test()
|
||||
{
|
||||
// Arrange
|
||||
var orderId = Guid.NewGuid().ToString();
|
||||
var testOrder = new OrderDataModels(
|
||||
orderId,
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
new List<Dish_OrderDataModel> { new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1) });
|
||||
|
||||
_orderStorageMock.Setup(x => x.GetElementById(orderId))
|
||||
.Returns(testOrder);
|
||||
|
||||
// Act
|
||||
_orderBusinessLogic.DeleteOrder(orderId);
|
||||
|
||||
// Assert
|
||||
_orderStorageMock.Verify(x => x.DelElement(orderId), Times.Once);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PositionBusinessLogicContractTests
|
||||
{
|
||||
private PositionBusinessLogicContract _positionBusinessLogicContract;
|
||||
private Mock<IPositionStorageContract> _positionStorageContract;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_positionStorageContract = new Mock<IPositionStorageContract>();
|
||||
_positionBusinessLogicContract = new PositionBusinessLogicContract(_positionStorageContract.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void SetUp()
|
||||
{
|
||||
_positionStorageContract.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPositions_ReturnListOfRecords_Test()
|
||||
{
|
||||
//Arrange
|
||||
var listOriginal = new List<PositionDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(),"name 1", PositionType.Assistant, 10, true, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 2", PositionType.Assistant, 10, false, DateTime.UtcNow),
|
||||
new(Guid.NewGuid().ToString(), "name 3", PositionType.Assistant, 10, true, DateTime.UtcNow),
|
||||
};
|
||||
_positionStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns(listOriginal);
|
||||
//Act
|
||||
var listOnlyActive = _positionBusinessLogicContract.GetAllPositions(true);
|
||||
var listAll = _positionBusinessLogicContract.GetAllPositions(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));
|
||||
});
|
||||
_positionStorageContract.Verify(x => x.GetList(true), Times.Once);
|
||||
_positionStorageContract.Verify(x => x.GetList(false), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPositions_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Returns([]);
|
||||
//Act
|
||||
var listOnlyActive = _positionBusinessLogicContract.GetAllPositions(true);
|
||||
var listAll = _positionBusinessLogicContract.GetAllPositions(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));
|
||||
});
|
||||
_positionStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPositions_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllPositions(It.IsAny<bool>()), Throws.TypeOf<NullListException>());
|
||||
_positionStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllPositions_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.GetList(It.IsAny<bool>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllPositions(It.IsAny<bool>()), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_ReturnListOfRecords_Test()
|
||||
{
|
||||
//Arrange
|
||||
var PositionId = Guid.NewGuid().ToString();
|
||||
var listOriginal = new List<PositionDataModel>()
|
||||
{
|
||||
new(PositionId, "name 1", PositionType.Assistant, 10, true, DateTime.UtcNow),
|
||||
new(PositionId, "name 2", PositionType.Assistant, 10, false, DateTime.UtcNow)
|
||||
};
|
||||
_positionStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
|
||||
//Act
|
||||
var list = _positionBusinessLogicContract.GetAllDataOfPosition(PositionId);
|
||||
//Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(PositionId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_ReturnEmptyList_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns([]);
|
||||
//Act
|
||||
var list = _positionBusinessLogicContract.GetAllDataOfPosition(Guid.NewGuid().ToString());
|
||||
//Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_PositionIdIsNullOrEmpty_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllDataOfPosition(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllDataOfPosition(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_PositionIdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllDataOfPosition("id"), Throws.TypeOf<ValidationException>());
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllDataOfPosition(Guid.NewGuid().ToString()), Throws.TypeOf<NullListException>());
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllDataOfPosition_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetAllDataOfPosition(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.GetPostWithHistory(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_GetById_ReturnRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new PositionDataModel(id, "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
_positionStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
//Act
|
||||
var element = _positionBusinessLogicContract.GetPositionByData(id);
|
||||
//Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.Id, Is.EqualTo(id));
|
||||
_positionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_GetByName_ReturnRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var PositionName = "name";
|
||||
var record = new PositionDataModel(Guid.NewGuid().ToString(), PositionName, PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
_positionStorageContract.Setup(x => x.GetElementByName(PositionName)).Returns(record);
|
||||
//Act
|
||||
var element = _positionBusinessLogicContract.GetPositionByData(PositionName);
|
||||
//Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.PositionName, Is.EqualTo(PositionName));
|
||||
_positionStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_EmptyData_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
_positionStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_GetById_NotFoundRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
_positionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
_positionStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_GetByName_NotFoundRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData("name"), Throws.TypeOf<ElementNotFoundException>());
|
||||
_positionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
_positionStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetPositionByData_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
_positionStorageContract.Setup(x => x.GetElementByName(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
Assert.That(() => _positionBusinessLogicContract.GetPositionByData("name"), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Once);
|
||||
_positionStorageContract.Verify(x => x.GetElementByName(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertPosition_CorrectRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PositionDataModel(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
_positionStorageContract.Setup(x => x.AddElement(It.IsAny<PositionDataModel>()))
|
||||
.Callback((PositionDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PositionName == record.PositionName && x.PositionType == record.PositionType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
});
|
||||
//Act
|
||||
_positionBusinessLogicContract.InsertPosition(record);
|
||||
//Assert
|
||||
_positionStorageContract.Verify(x => x.AddElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
Assert.That(flag);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertPosition_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.AddElement(It.IsAny<PositionDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.InsertPosition(new(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
_positionStorageContract.Verify(x => x.AddElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertPosition_NullRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.InsertPosition(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.AddElement(It.IsAny<PositionDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertPosition_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.InsertPosition(new PositionDataModel("id", "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
_positionStorageContract.Verify(x => x.AddElement(It.IsAny<PositionDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertPosition_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.AddElement(It.IsAny<PositionDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.InsertPosition(new(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.AddElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_CorrectRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var flag = false;
|
||||
var record = new PositionDataModel(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow.AddDays(-1));
|
||||
_positionStorageContract.Setup(x => x.UpdElement(It.IsAny<PositionDataModel>()))
|
||||
.Callback((PositionDataModel x) =>
|
||||
{
|
||||
flag = x.Id == record.Id && x.PositionName == record.PositionName && x.PositionType == record.PositionType && x.Salary == record.Salary &&
|
||||
x.ChangeDate == record.ChangeDate;
|
||||
});
|
||||
//Act
|
||||
_positionBusinessLogicContract.UpdatePosition(record);
|
||||
//Assert
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
Assert.That(flag);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_RecordWithIncorrectData_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.UpdElement(It.IsAny<PositionDataModel>())).Throws(new ElementNotFoundException(""));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.UpdatePosition(new(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementNotFoundException>());
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_RecordWithExistsData_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.UpdElement(It.IsAny<PositionDataModel>())).Throws(new ElementExistsException("Data", "Data"));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.UpdatePosition(new(Guid.NewGuid().ToString(), "anme", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_NullRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.UpdatePosition(null), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.UpdatePosition(new PositionDataModel("id", "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdatePosition_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.UpdElement(It.IsAny<PositionDataModel>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.UpdatePosition(new(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.UpdElement(It.IsAny<PositionDataModel>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletePosition_CorrectRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var flag = false;
|
||||
_positionStorageContract.Setup(x => x.DelElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
|
||||
//Act
|
||||
_positionBusinessLogicContract.DeletePosition(id);
|
||||
//Assert
|
||||
_positionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
|
||||
Assert.That(flag);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletePosition_RecordWithIncorrectId_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
_positionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.DeletePosition(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
_positionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletePosition_IdIsNullOrEmpty_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.DeletePosition(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _positionBusinessLogicContract.DeletePosition(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletePosition_IdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.DeletePosition("id"), Throws.TypeOf<ValidationException>());
|
||||
_positionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletePosition_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.DeletePosition(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestorePosition_CorrectRecord_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var flag = false;
|
||||
_positionStorageContract.Setup(x => x.ResElement(It.Is((string x) => x == id))).Callback(() => { flag = true; });
|
||||
//Act
|
||||
_positionBusinessLogicContract.RestorePosition(id);
|
||||
//Assert
|
||||
_positionStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
|
||||
Assert.That(flag);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestorePosition_RecordWithIncorrectId_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
_positionStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new ElementNotFoundException(id));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.RestorePosition(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
_positionStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestorePosition_IdIsNullOrEmpty_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.RestorePosition(null), Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _positionBusinessLogicContract.RestorePosition(string.Empty), Throws.TypeOf<ArgumentNullException>());
|
||||
_positionStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestorePosition_IdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.RestorePosition("id"), Throws.TypeOf<ValidationException>());
|
||||
_positionStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RestorePosition_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
//Arrange
|
||||
_positionStorageContract.Setup(x => x.ResElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
|
||||
//Act&Assert
|
||||
Assert.That(() => _positionBusinessLogicContract.RestorePosition(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
|
||||
_positionStorageContract.Verify(x => x.ResElement(It.IsAny<string>()), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using AndDietCokeContracts.BusinessLogicsContracts;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.Extensions;
|
||||
using AndDietCokeContracts.StorageContract;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryBusinessLogicsContractsTests
|
||||
{
|
||||
private SalaryBusinessLogicContract _salaryBusinessLogicContract;
|
||||
private Mock<ISalaryStorageContract> _salaryStorageContract;
|
||||
private Mock<ILogger> _logger;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_salaryStorageContract = new Mock<ISalaryStorageContract>();
|
||||
_logger = new Mock<ILogger>();
|
||||
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(
|
||||
_salaryStorageContract.Object,
|
||||
_logger.Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract.Reset();
|
||||
_logger.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSalariesByPeriod_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var startDate = DateTime.UtcNow;
|
||||
var endDate = DateTime.UtcNow.AddDays(1);
|
||||
var listOriginal = new List<SalaryDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), DateTime.UtcNow, 1000, Guid.NewGuid().ToString()),
|
||||
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 1500, Guid.NewGuid().ToString()),
|
||||
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(-1), 800, Guid.NewGuid().ToString()),
|
||||
};
|
||||
|
||||
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), null))
|
||||
.Returns(listOriginal);
|
||||
|
||||
// Act
|
||||
var result = _salaryBusinessLogicContract.GetAllSalariesByPeriod(startDate, endDate);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Is.EquivalentTo(listOriginal));
|
||||
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, null), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSalariesByPeriod_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 GetAllSalariesByPeriod_ReturnNull_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), null))
|
||||
.Returns((List<SalaryDataModel>)null);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
|
||||
Throws.TypeOf<NullListException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSalariesByPeriod_StorageThrowError_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), null))
|
||||
.Throws(new StorageException(new InvalidOperationException()));
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriod(DateTime.UtcNow, DateTime.UtcNow.AddDays(1)),
|
||||
Throws.TypeOf<StorageException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSalariesByPeriodByEmployee_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, 1000, employeeId),
|
||||
new(Guid.NewGuid().ToString(), DateTime.UtcNow.AddDays(1), 1500, employeeId),
|
||||
};
|
||||
|
||||
_salaryStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), employeeId))
|
||||
.Returns(listOriginal);
|
||||
|
||||
// Act
|
||||
var result = _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(startDate, endDate, employeeId);
|
||||
|
||||
// Assert
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Is.EquivalentTo(listOriginal));
|
||||
_salaryStorageContract.Verify(x => x.GetList(startDate, endDate, employeeId), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllSalariesByPeriodByEmployee_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 GetAllSalariesByPeriodByEmployee_EmployeeIdIsNotGuid_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _salaryBusinessLogicContract.GetAllSalariesByPeriodByEmployee(DateTime.UtcNow, DateTime.UtcNow.AddDays(1), "invalid-id"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
using AndDietCokeBusinessLogic.Implementations;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeContracts.StoragesContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace AndDietCokeTests.BusinessLogicsContractsTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class СlientBusinessLogicsContractsTests
|
||||
{
|
||||
private ClientBusinessLogicContract _clientLogicContract;
|
||||
private Mock<IClientStorageContract> _clientStorageContract;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_clientStorageContract = new Mock<IClientStorageContract>();
|
||||
_clientLogicContract = new ClientBusinessLogicContract(
|
||||
_clientStorageContract.Object,
|
||||
new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientStorageContract.Reset();
|
||||
}
|
||||
|
||||
// GetAllClients tests
|
||||
[Test]
|
||||
public void GetAllClients_ReturnListOfRecords_Test()
|
||||
{
|
||||
// Arrange
|
||||
var listOriginal = new List<СlientDataModel>()
|
||||
{
|
||||
new(Guid.NewGuid().ToString(), "Client 1", "+7-111-111-11-11", 0),
|
||||
new(Guid.NewGuid().ToString(), "Client 2", "+7-222-222-22-22", 5),
|
||||
};
|
||||
|
||||
_clientStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
|
||||
|
||||
// Act
|
||||
var list = _clientLogicContract.GetAllClients();
|
||||
|
||||
// Assert
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.EquivalentTo(listOriginal));
|
||||
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetAllClients_ReturnEmptyList_Test()
|
||||
{
|
||||
// Arrange
|
||||
_clientStorageContract.Setup(x => x.GetList()).Returns([]);
|
||||
|
||||
// Act
|
||||
var list = _clientLogicContract.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()
|
||||
{
|
||||
// Arrange
|
||||
_clientStorageContract.Setup(x => x.GetList()).Returns(null as List<СlientDataModel>);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.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(() => _clientLogicContract.GetAllClients(),
|
||||
Throws.TypeOf<StorageException>());
|
||||
_clientStorageContract.Verify(x => x.GetList(), Times.Once);
|
||||
}
|
||||
|
||||
// GetClientByData tests
|
||||
[Test]
|
||||
public void GetClientByData_GetById_ReturnRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var record = new СlientDataModel(id, "Client", "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
|
||||
|
||||
// Act
|
||||
var element = _clientLogicContract.GetClientByData(id);
|
||||
|
||||
// Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.Id, Is.EqualTo(id));
|
||||
_clientStorageContract.Verify(x => x.GetElementById(id), Times.Once);
|
||||
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
|
||||
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetClientByData_GetByFio_ReturnRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var fio = "Client Name";
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), fio, "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.GetElementByFIO(fio)).Returns(record);
|
||||
|
||||
// Act
|
||||
var element = _clientLogicContract.GetClientByData(fio);
|
||||
|
||||
// Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.FIO, Is.EqualTo(fio));
|
||||
_clientStorageContract.Verify(x => x.GetElementByFIO(fio), Times.Once);
|
||||
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetClientByData_GetByPhoneNumber_ReturnRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var phone = "+7-111-111-11-11";
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), "Client", phone, 0);
|
||||
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(phone)).Returns(record);
|
||||
|
||||
// Act
|
||||
var element = _clientLogicContract.GetClientByData(phone);
|
||||
|
||||
// Assert
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.Contact, Is.EqualTo(phone));
|
||||
_clientStorageContract.Verify(x => x.GetElementByPhoneNumber(phone), Times.Once);
|
||||
_clientStorageContract.Verify(x => x.GetElementById(It.IsAny<string>()), Times.Never);
|
||||
_clientStorageContract.Verify(x => x.GetElementByFIO(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetClientByData_EmptyData_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.GetClientByData(null),
|
||||
Throws.TypeOf<ArgumentNullException>());
|
||||
Assert.That(() => _clientLogicContract.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_NotFound_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var testData = Guid.NewGuid().ToString();
|
||||
_clientStorageContract.Setup(x => x.GetElementById(testData)).Returns(null as СlientDataModel);
|
||||
_clientStorageContract.Setup(x => x.GetElementByFIO(testData)).Returns(null as СlientDataModel);
|
||||
_clientStorageContract.Setup(x => x.GetElementByPhoneNumber(testData)).Returns(null as СlientDataModel);
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.GetClientByData(testData),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
// InsertClient tests
|
||||
[Test]
|
||||
public void InsertClient_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), "Client", "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.AddElement(It.IsAny<СlientDataModel>()));
|
||||
|
||||
// Act
|
||||
_clientLogicContract.InsertClient(record);
|
||||
|
||||
// Assert
|
||||
_clientStorageContract.Verify(x => x.AddElement(record), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertClient_NullRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.InsertClient(null),
|
||||
Throws.TypeOf<ArgumentNullException>());
|
||||
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<СlientDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertClient_InvalidRecord_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.InsertClient(
|
||||
new СlientDataModel("invalid-id", "Client", "invalid-phone", 0)),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
_clientStorageContract.Verify(x => x.AddElement(It.IsAny<СlientDataModel>()), Times.Never);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InsertClient_DuplicateData_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), "Client", "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.AddElement(record))
|
||||
.Throws(new ElementExistsException("Client", "already exists"));
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.InsertClient(record),
|
||||
Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
// UpdateClient tests
|
||||
[Test]
|
||||
public void UpdateClient_CorrectRecord_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), "Client", "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.UpdElement(It.IsAny<СlientDataModel>()));
|
||||
|
||||
// Act
|
||||
_clientLogicContract.UpdateClient(record);
|
||||
|
||||
// Assert
|
||||
_clientStorageContract.Verify(x => x.UpdElement(record), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateClient_NotFound_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var record = new СlientDataModel(Guid.NewGuid().ToString(), "Client", "+7-111-111-11-11", 0);
|
||||
_clientStorageContract.Setup(x => x.UpdElement(record))
|
||||
.Throws(new ElementNotFoundException("Client not found"));
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.UpdateClient(record),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
// DeleteClient tests
|
||||
[Test]
|
||||
public void DeleteClient_CorrectId_Test()
|
||||
{
|
||||
// Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
_clientStorageContract.Setup(x => x.DelElement(id));
|
||||
|
||||
// Act
|
||||
_clientLogicContract.DeleteClient(id);
|
||||
|
||||
// Assert
|
||||
_clientStorageContract.Verify(x => x.DelElement(id), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteClient_NotFound_ThrowException_Test()
|
||||
{
|
||||
// Arrange
|
||||
var id = Guid.NewGuid().ToString();
|
||||
_clientStorageContract.Setup(x => x.DelElement(id))
|
||||
.Throws(new ElementNotFoundException("Client not found"));
|
||||
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.DeleteClient(id),
|
||||
Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeleteClient_InvalidId_ThrowException_Test()
|
||||
{
|
||||
// Act & Assert
|
||||
Assert.That(() => _clientLogicContract.DeleteClient("not-a-guid"),
|
||||
Throws.TypeOf<ValidationException>());
|
||||
_clientStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using NUnit.Framework;
|
||||
using System;
|
||||
|
||||
namespace AndDietCokeTests.DataModelsTests
|
||||
{
|
||||
@@ -12,91 +10,67 @@ namespace AndDietCokeTests.DataModelsTests
|
||||
[Test]
|
||||
public void IdIsNullOrEmptyTest()
|
||||
{
|
||||
var position = CreateDataModel(null, Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
position = CreateDataModel(string.Empty, Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var post = CreateDataModel(null, "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(string.Empty, "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdIsNotGuidTest()
|
||||
{
|
||||
var position = CreateDataModel("id", Guid.NewGuid().ToString(), "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var post = CreateDataModel("id", "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PositionIdIsNullOrEmptyTest()
|
||||
public void PostNameIsEmptyTest()
|
||||
{
|
||||
var position = CreateDataModel(Guid.NewGuid().ToString(), null, "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
position = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PositionIdIsNotGuidTest()
|
||||
{
|
||||
var position = CreateDataModel(Guid.NewGuid().ToString(), "positionId", "name", PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PositionNameIsEmptyTest()
|
||||
{
|
||||
var position = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), null, PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
position = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), string.Empty, PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PositionType.Assistant, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PositionTypeIsNoneTest()
|
||||
{
|
||||
var position = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PositionType.None, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PositionType.None, 10, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SalaryIsLessOrZeroTest()
|
||||
{
|
||||
var position = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PositionType.Assistant, 0, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
|
||||
position = CreateDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "name", PositionType.Assistant, -10, true, DateTime.UtcNow);
|
||||
Assert.That(() => position.Validate(), Throws.TypeOf<ValidationException>());
|
||||
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PositionType.Assistant, 0, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PositionType.Assistant, -10, true, DateTime.UtcNow);
|
||||
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AllFieldsAreCorrectTest()
|
||||
public void AllFieldsIsCorrectTest()
|
||||
{
|
||||
var id = Guid.NewGuid().ToString();
|
||||
var positionId = Guid.NewGuid().ToString();
|
||||
var positionName = "name";
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
var postName = "name";
|
||||
var positionType = PositionType.Assistant;
|
||||
var salary = 10;
|
||||
var isActual = false;
|
||||
var changeDate = DateTime.UtcNow.AddDays(-1);
|
||||
|
||||
var position = CreateDataModel(id, positionId, positionName, positionType, salary, isActual, changeDate);
|
||||
|
||||
Assert.That(() => position.Validate(), Throws.Nothing);
|
||||
var post = CreateDataModel(postId, postName, positionType, salary, isActual, changeDate);
|
||||
Assert.That(() => post.Validate(), Throws.Nothing);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(position.Id, Is.EqualTo(id));
|
||||
Assert.That(position.PositionId, Is.EqualTo(positionId));
|
||||
Assert.That(position.PositionName, Is.EqualTo(positionName));
|
||||
Assert.That(position.PositionType, Is.EqualTo(positionType));
|
||||
Assert.That(position.Salary, Is.EqualTo(salary));
|
||||
Assert.That(position.IsActual, Is.EqualTo(isActual));
|
||||
Assert.That(position.ChangeDate, Is.EqualTo(changeDate));
|
||||
Assert.That(post.Id, Is.EqualTo(postId));
|
||||
Assert.That(post.PositionName, Is.EqualTo(postName));
|
||||
Assert.That(post.PositionType, Is.EqualTo(positionType));
|
||||
Assert.That(post.Salary, Is.EqualTo(salary));
|
||||
Assert.That(post.IsActual, Is.EqualTo(isActual));
|
||||
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
|
||||
});
|
||||
}
|
||||
|
||||
private static PositionDataModell CreateDataModel(string? id, string? positionId, string? positionName, PositionType positionType, double salary, bool isActual, DateTime changeDate) =>
|
||||
new(id, positionId, positionName, positionType, salary, isActual, changeDate);
|
||||
private static PositionDataModel CreateDataModel(string? id, string? postName, PositionType positionType, double salary, bool isActual, DateTime changeDate) =>
|
||||
new(id, postName, positionType, salary, isActual, changeDate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using AndDietCokeContracts.Infrastructure;
|
||||
|
||||
namespace AndDietCokeTests.Infrastucture;
|
||||
|
||||
internal class ConfigurationDatabaseTest : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString => "Host=127.0.0.1;Port=5432;Database=AndDietCokeTest;Username=postgres;Password=postgres;";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using AndDietCokeDatabase;
|
||||
using AndDietCokeTests.Infrastucture;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
internal abstract class BaseStorageContractTest
|
||||
{
|
||||
protected AndDietCokeDbContext AndDietCokeDbContext { get; private set; }
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
AndDietCokeDbContext = new AndDietCokeDbContext(new ConfigurationDatabaseTest());
|
||||
|
||||
AndDietCokeDbContext.Database.EnsureDeleted();
|
||||
AndDietCokeDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.EnsureDeleted();
|
||||
AndDietCokeDbContext.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private ClientStorageContract _clientStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientStorageContract = new ClientStorageContract(AndDietCokeDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Orders\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), contact: "+5-555-555-55-55");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), contact: "+6-666-666-66-66");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), contact: "+7-777-777-77-77");
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _clientStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementById(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementByFIO(client.FIO), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenHaveRecord_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_clientStorageContract.GetElementByPhoneNumber(client.Contact), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByPhoneNumber_WhenNoRecord_Test()
|
||||
{
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _clientStorageContract.GetElementByPhoneNumber("+8-888-888-88-88"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString());
|
||||
_clientStorageContract.AddElement(client);
|
||||
AssertElement(GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), contact: client.Contact);
|
||||
Assert.That(() => _clientStorageContract.AddElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id);
|
||||
_clientStorageContract.UpdElement(client);
|
||||
AssertElement(GetClientFromDatabase(client.Id), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _clientStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSamePhoneNumber_Test()
|
||||
{
|
||||
var client = CreateModel(Guid.NewGuid().ToString(), "New Fio", "+5-555-555-55-55", 500);
|
||||
InsertClientToDatabaseAndReturn(client.Id, contact: "+7-777-777-77-77");
|
||||
InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString(), contact: client.Contact);
|
||||
Assert.That(() => _clientStorageContract.UpdElement(client), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
var element = GetClientFromDatabase(client.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenHaveSalesByThisBuyer_Test()
|
||||
{
|
||||
var client = InsertClientToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
var workerId = Guid.NewGuid().ToString();
|
||||
AndDietCokeDbContext.Employees.Add(new Employee() { Id = workerId, FIO = "test", PositionId = Guid.NewGuid().ToString() });
|
||||
AndDietCokeDbContext.Orders.Add(new Order() { Id = Guid.NewGuid().ToString(), EmloyeedId = workerId, ClientId = client.Id });
|
||||
AndDietCokeDbContext.Orders.Add(new Order() { Id = Guid.NewGuid().ToString(), EmloyeedId = workerId, ClientId = client.Id });
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
var ordersBeforeDelete = AndDietCokeDbContext.Orders.Where(x => x.ClientId == client.Id).ToArray();
|
||||
_clientStorageContract.DelElement(client.Id);
|
||||
var element = GetClientFromDatabase(client.Id);
|
||||
var salesAfterDelete = AndDietCokeDbContext.Orders.Where(x => x.ClientId == client.Id).ToArray();
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Null);
|
||||
Assert.That(ordersBeforeDelete, Has.Length.EqualTo(2));
|
||||
Assert.That(salesAfterDelete, Is.Empty);
|
||||
Assert.That(AndDietCokeDbContext.Orders.Count(), Is.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _clientStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Client InsertClientToDatabaseAndReturn(string id, string fio = "test", string contact = "+7-777-777-77-77", double discountSize = 10)
|
||||
{
|
||||
var buyer = new Client() { Id = id, FIO = fio, Contact = contact, DiscountSize = discountSize };
|
||||
AndDietCokeDbContext.Clients.Add(buyer);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return buyer;
|
||||
}
|
||||
|
||||
private static void AssertElement(СlientDataModel? actual, Client expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.Contact, Is.EqualTo(expected.Contact));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
|
||||
private static СlientDataModel CreateModel(string id, string fio = "test", string contact = "+7-777-777-77-77", double discountSize = 10)
|
||||
=> new(id, fio, contact, discountSize);
|
||||
|
||||
private Client? GetClientFromDatabase(string id) => AndDietCokeDbContext.Clients.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Client? actual, СlientDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.Contact, Is.EqualTo(expected.Contact));
|
||||
Assert.That(actual.DiscountSize, Is.EqualTo(expected.DiscountSize));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static NUnit.Framework.Internal.OSPlatform;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class DishStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private DishStorageContract _dishStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_dishStorageContract = new DishStorageContract(AndDietCokeDbContext); }
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var list = _dishStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _dishStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetHistoryByDishId_WhenHaveRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _dishStorageContract.GetHistoryByProductId(dish.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetHistoryByProductId_WhenNoRecords_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 20, DateTime.UtcNow.AddDays(-1));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 30, DateTime.UtcNow.AddMinutes(-10));
|
||||
InsertDishHistoryToDatabaseAndReturn(dish.Id, 40, DateTime.UtcNow.AddDays(1));
|
||||
var list = _dishStorageContract.GetHistoryByProductId(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_dishStorageContract.GetElementById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _dishStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_dishStorageContract.GetElementByName(dish.Name), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _dishStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var dish = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _dishStorageContract.GetElementById(dish.Name), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
_dishStorageContract.AddElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.Nothing);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertDishToDatabaseAndReturn(dish.Id, name: "name unique");
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), name: dish.Name);
|
||||
Assert.That(() => _dishStorageContract.AddElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertDishToDatabaseAndReturn(dish.Id);
|
||||
_dishStorageContract.UpdElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), dish);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertDishToDatabaseAndReturn(dish.Id);
|
||||
_dishStorageContract.UpdElement(dish);
|
||||
AssertElement(GetDishFromDatabaseById(dish.Id), CreateModel(dish.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _dishStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var dish = CreateModel(Guid.NewGuid().ToString(), "name unique");
|
||||
InsertDishToDatabaseAndReturn(dish.Id, name: "name");
|
||||
InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString(), name: dish.Name);
|
||||
Assert.That(() => _dishStorageContract.UpdElement(dish), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var product = InsertDishToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_dishStorageContract.DelElement(product.Id);
|
||||
var element = GetDishFromDatabaseById(product.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _dishStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Dish InsertDishToDatabaseAndReturn(string id, string name = "test", DishType dishType = DishType.Pepperoni, double price = 1, string? orderId = null)
|
||||
{
|
||||
var product = new Dish() { Id = id, Name = name, DishType = dishType, Price = price, OrderId = orderId ?? Guid.NewGuid().ToString() };
|
||||
AndDietCokeDbContext.Dishes.Add(product);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
private DishHistory InsertDishHistoryToDatabaseAndReturn(string dishId, double price, DateTime changeDate, string? orderId = null)
|
||||
{
|
||||
var productHistory = new DishHistory() { Id = Guid.NewGuid().ToString(), DishId = dishId, OldPrice = price, ChangeDate = changeDate, OrderId = orderId ?? Guid.NewGuid().ToString() };
|
||||
AndDietCokeDbContext.DishHistories.Add(productHistory);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return productHistory;
|
||||
}
|
||||
|
||||
private static void AssertElement(DishDataModel? actual, Dish expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.DishType, Is.EqualTo(expected.DishType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
});
|
||||
}
|
||||
|
||||
private static DishDataModel CreateModel(string id, string name = "test", DishType dishType = DishType.Pepperoni, double price = 1, string? orderId = null)
|
||||
=> new(id, name, dishType, price, orderId ?? Guid.NewGuid().ToString());
|
||||
|
||||
private Dish? GetDishFromDatabaseById(string id) => AndDietCokeDbContext.Dishes.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Dish? actual, DishDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.DishType, Is.EqualTo(expected.DishType));
|
||||
Assert.That(actual.Price, Is.EqualTo(expected.Price));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class EmployeeStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private EmployeeStorageContract _workerStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_workerStorageContract = new EmployeeStorageContract(AndDietCokeDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1");
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2");
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _workerStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByPostId_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId);
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId);
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3");
|
||||
var list = _workerStorageContract.GetList(postId: postId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.PositionId == postId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByBirthDate_Test()
|
||||
{
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", birthDate: DateTime.UtcNow.AddYears(-25));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", birthDate: DateTime.UtcNow.AddYears(-21));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", birthDate: DateTime.UtcNow.AddYears(-20));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-19));
|
||||
var list = _workerStorageContract.GetList(fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByEmploymentDate_Test()
|
||||
{
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", employmentDate: DateTime.UtcNow.AddDays(2));
|
||||
var list = _workerStorageContract.GetList(fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var postId = Guid.NewGuid().ToString();
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 1", postId, birthDate: DateTime.UtcNow.AddYears(-25), employmentDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 2", postId, birthDate: DateTime.UtcNow.AddYears(-22), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 3", postId, birthDate: DateTime.UtcNow.AddYears(-21), employmentDate: DateTime.UtcNow.AddDays(-1));
|
||||
InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString(), "fio 4", birthDate: DateTime.UtcNow.AddYears(-20), employmentDate: DateTime.UtcNow.AddDays(1));
|
||||
var list = _workerStorageContract.GetList(postId: postId, fromBirthDate: DateTime.UtcNow.AddYears(-21).AddMinutes(-1), toBirthDate: DateTime.UtcNow.AddYears(-20).AddMinutes(1), fromEmploymentDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-1), toEmploymentDate: DateTime.UtcNow.AddDays(1).AddMinutes(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_workerStorageContract.GetElementById(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenHaveRecord_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_workerStorageContract.GetElementByFIO(worker.FIO), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByFIO_WhenNoRecord_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.GetElementByFIO("New Fio"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.AddElement(worker);
|
||||
AssertElement(GetEmployeeFromDatabase(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameId_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(worker.Id);
|
||||
Assert.That(() => _workerStorageContract.AddElement(worker), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString(), "New Fio");
|
||||
InsertEmployeeToDatabaseAndReturn(worker.Id);
|
||||
_workerStorageContract.UpdElement(worker);
|
||||
AssertElement(GetEmployeeFromDatabase(worker.Id), worker);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.UpdElement(worker), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
_workerStorageContract.DelElement(worker.Id);
|
||||
var element = GetEmployeeFromDatabase(worker.Id);
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element.IsDeleted);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _workerStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWasDeleted_Test()
|
||||
{
|
||||
var worker = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertEmployeeToDatabaseAndReturn(worker.Id, isDeleted: true);
|
||||
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string id, string fio = "test", string? postId = null, PositionType positionType = PositionType.Assistant, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
|
||||
{
|
||||
var worker = new Employee() { Id = id, FIO = fio, PositionId = postId ?? Guid.NewGuid().ToString(), PositionType = positionType, BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
|
||||
AndDietCokeDbContext.Employees.Add(worker);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private static void AssertElement(EmployeeDataModel? actual, Employee expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PositionId, Is.EqualTo(expected.PositionId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
|
||||
private static EmployeeDataModel CreateModel(string id, string fio = "fio", string? positionId = null, PositionType positionType = PositionType.Assistant, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) =>
|
||||
new(id, fio, positionId ?? Guid.NewGuid().ToString(), positionType, birthDate ?? DateTime.UtcNow.AddYears(-20), employmentDate ?? DateTime.UtcNow, isDeleted);
|
||||
|
||||
private Employee? GetEmployeeFromDatabase(string id) => AndDietCokeDbContext.Employees.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Employee? actual, EmployeeDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PositionId, Is.EqualTo(expected.PositionId));
|
||||
Assert.That(actual.FIO, Is.EqualTo(expected.FIO));
|
||||
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
|
||||
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
|
||||
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AndDietCokeContracts.DataModels;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class OrderStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private OrderStorageContract _ordertStorageContract;
|
||||
private Client _client;
|
||||
private Employee _employee;
|
||||
private Dish _dish;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_ordertStorageContract = new OrderStorageContract(AndDietCokeDbContext);
|
||||
_client = InsertClientToDatabaseAndReturn();
|
||||
_employee = InsertEmployeeToDatabaseAndReturn();
|
||||
_dish = InsertDishToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Orders\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Clients\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Dishes\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var order = InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 5)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, null, products: [(_dish.Id, 10)]);
|
||||
var list = _ordertStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == order.Id), order);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _ordertStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerId_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn("Other worker");
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(worker.Id, null, products: [(_dish.Id, 1)]);
|
||||
var list = _ordertStorageContract.GetList(employeedId: _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.EmloyeedId == _employee.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByBuyerId_Test()
|
||||
{
|
||||
var buyer = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, buyer.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, null, products: [(_dish.Id, 1)]);
|
||||
var list = _ordertStorageContract.GetList(clientId: _client.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.ClientId == _client.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByProductId_Test()
|
||||
{
|
||||
var product = InsertDishToDatabaseAndReturn("Other name");
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 5)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1), (product.Id, 4)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, null, products: [(product.Id, 1), (_dish.Id, 1)]);
|
||||
var list = _ordertStorageContract.GetList(dishId: _dish.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.All(x => x.Dishes.Any(y => y.DishId == _dish.Id)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByAllParameters_Test()
|
||||
{
|
||||
var worker = InsertEmployeeToDatabaseAndReturn("Other worker");
|
||||
var buyer = InsertClientToDatabaseAndReturn("Other fio", "+8-888-888-88-88");
|
||||
var product = InsertDishToDatabaseAndReturn("Other name");
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(worker.Id, null, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(worker.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(worker.Id, _client.Id, products: [(product.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, buyer.Id, products: [(_dish.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(product.Id, 1)]);
|
||||
InsertOrderToDatabaseAndReturn(worker.Id, null, products: [(_dish.Id, 1)]);
|
||||
var list = _ordertStorageContract.GetList(employeedId: _employee.Id, clientId: _client.Id, dishId: product.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var order = InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
AssertElement(_ordertStorageContract.GetElementById(order.Id), order);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
Assert.That(() => _ordertStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasCanceled_Test()
|
||||
{
|
||||
var order = InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
AssertElement(_ordertStorageContract.GetElementById(order.Id), order);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var order = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id, [_dish.Id]);
|
||||
_ordertStorageContract.AddElement(order);
|
||||
AssertElement(GetOrderFromDatabaseById(order.Id), order);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenIsDeletedIsTrue_Test()
|
||||
{
|
||||
var order = CreateModel(Guid.NewGuid().ToString(), _employee.Id, _client.Id,[_dish.Id]);
|
||||
Assert.That(() => _ordertStorageContract.AddElement(order), Throws.Nothing);
|
||||
AssertElement(GetOrderFromDatabaseById(order.Id), CreateModel(order.Id, _employee.Id, _client.Id, [_dish.Id]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var order = InsertOrderToDatabaseAndReturn(_employee.Id, _client.Id, products: [(_dish.Id, 1)]);
|
||||
_ordertStorageContract.DelElement(order.Id);
|
||||
var element = GetOrderFromDatabaseById(order.Id);
|
||||
Assert.That(element, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _ordertStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
private Client InsertClientToDatabaseAndReturn(string fio = "test", string phoneNumber = "+7-777-777-77-77")
|
||||
{
|
||||
var buyer = new Client() { Id = Guid.NewGuid().ToString(), FIO = fio, Contact = phoneNumber, DiscountSize = 10 };
|
||||
AndDietCokeDbContext.Clients.Add(buyer);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return buyer;
|
||||
}
|
||||
|
||||
private Employee InsertEmployeeToDatabaseAndReturn(string fio = "test")
|
||||
{
|
||||
var worker = new Employee() { Id = Guid.NewGuid().ToString(), FIO = fio, PositionId = Guid.NewGuid().ToString() };
|
||||
AndDietCokeDbContext.Employees.Add(worker);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Dish InsertDishToDatabaseAndReturn(string name = "test", DishType dishType = DishType.Pepperoni, double price = 1, string? orderId = null)
|
||||
{
|
||||
var product = new Dish() { Id = Guid.NewGuid().ToString(), Name = name, DishType = dishType, Price = price, OrderId = orderId ?? Guid.NewGuid().ToString() };
|
||||
AndDietCokeDbContext.Dishes.Add(product);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return product;
|
||||
}
|
||||
|
||||
private Order InsertOrderToDatabaseAndReturn(string employeeId, string? clientId, List<(string, int)>? products = null)
|
||||
{
|
||||
var order = new Order() { EmloyeedId = employeeId, ClientId = clientId, OrderDishes = [] };
|
||||
if (products is not null)
|
||||
{
|
||||
foreach (var elem in products)
|
||||
{
|
||||
order.OrderDishes.Add(new Dish_Order { DishId = elem.Item1, OrderId = order.Id, Count = elem.Item2 });
|
||||
}
|
||||
}
|
||||
AndDietCokeDbContext.Orders.Add(order);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return order;
|
||||
}
|
||||
|
||||
private static void AssertElement(OrderDataModels? actual, Order expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.EmloyeedId, Is.EqualTo(expected.EmloyeedId));
|
||||
Assert.That(actual.ClientId, Is.EqualTo(expected.ClientId)); ;
|
||||
});
|
||||
|
||||
if (expected.OrderDishes is not null)
|
||||
{
|
||||
Assert.That(actual.Dishes, Is.Not.Null);
|
||||
Assert.That(actual.Dishes, Has.Count.EqualTo(expected.OrderDishes.Count));
|
||||
for (int i = 0; i < actual.Dishes.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Dishes[i].DishId, Is.EqualTo(expected.OrderDishes[i].DishId));
|
||||
Assert.That(actual.Dishes[i].Count, Is.EqualTo(expected.OrderDishes[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.Dishes, Is.Null);
|
||||
}
|
||||
}
|
||||
|
||||
private static OrderDataModels CreateModel(string id, string employeeId, string clientId, List<string> productIds)
|
||||
{
|
||||
var products = productIds.Select(x => new Dish_OrderDataModel(id, x, 1)).ToList();
|
||||
return new(id, clientId, employeeId, products);
|
||||
}
|
||||
|
||||
private Order? GetOrderFromDatabaseById(string id) => AndDietCokeDbContext.Orders.Include(x => x.OrderDishes).FirstOrDefault(x => x.Id == id);
|
||||
|
||||
private static void AssertElement(Order? actual, OrderDataModels expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.EmloyeedId, Is.EqualTo(expected.EmloyeedId));
|
||||
Assert.That(actual.ClientId, Is.EqualTo(expected.ClientId));;
|
||||
});
|
||||
|
||||
if (expected.Dishes is not null)
|
||||
{
|
||||
Assert.That(actual.OrderDishes, Is.Not.Null);
|
||||
Assert.That(actual.OrderDishes, Has.Count.EqualTo(expected.Dishes.Count));
|
||||
for (int i = 0; i < actual.OrderDishes.Count; ++i)
|
||||
{
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.OrderDishes[i].DishId, Is.EqualTo(expected.Dishes[i].DishId));
|
||||
Assert.That(actual.OrderDishes[i].Count, Is.EqualTo(expected.Dishes[i].Count));
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(actual.OrderDishes, Is.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeContracts.Enums;
|
||||
using AndDietCokeContracts.Exceptions;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class PositionStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private PositionStorageContract _postStorageContract;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_postStorageContract = new PositionStorageContract(AndDietCokeDbContext);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Posts\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3");
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(x => x.Id == post.PositionId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _postStorageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyActual_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: true);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(!list.Any(x => !x.IsActual));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_IncludeNoActual_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 3", isActual: false);
|
||||
var list = _postStorageContract.GetList(onlyActual: false);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
Assert.That(list.Count(x => x.IsActual), Is.EqualTo(2));
|
||||
Assert.That(list.Count(x => !x.IsActual), Is.EqualTo(1));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
|
||||
{
|
||||
var PositionId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(PositionId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(PositionId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(PositionId);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetPostWithHistory_WhenNoRecords_Test()
|
||||
{
|
||||
var PositionId = Guid.NewGuid().ToString();
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), "name 1", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(PositionId, "name 2", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(PositionId, "name 2", isActual: false);
|
||||
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_postStorageContract.GetElementById(post.PositionId), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PositionId), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenTrySearchById_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenHaveRecord_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
AssertElement(_postStorageContract.GetElementByName(post.PositionName), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenNoRecord_Test()
|
||||
{
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString());
|
||||
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByName_WhenRecordHasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.GetElementById(post.PositionName), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
_postStorageContract.AddElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPositionId(post.Id), post);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.Nothing);
|
||||
AssertElement(GetPostFromDatabaseByPositionId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "name unique", isActual: true);
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PositionName, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSamePositionIdAndActualIsTrue_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: true);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
var posts = AndDietCokeDbContext.Posts.Where(x => x.PositionId == post.Id).OrderByDescending(x => x.ChangeDate);
|
||||
Assert.That(posts.Count(), Is.EqualTo(2));
|
||||
AssertElement(posts.First(), CreateModel(post.Id, isActual: true));
|
||||
AssertElement(posts.Last(), CreateModel(post.Id, isActual: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenActualIsFalse_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), isActual: false);
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: true);
|
||||
_postStorageContract.UpdElement(post);
|
||||
AssertElement(GetPostFromDatabaseByPositionId(post.Id), CreateModel(post.Id, isActual: true));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
|
||||
InsertPostToDatabaseAndReturn(post.Id, postName: "name");
|
||||
InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), postName: post.PositionName);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = CreateModel(Guid.NewGuid().ToString());
|
||||
InsertPostToDatabaseAndReturn(post.Id, isActual: false);
|
||||
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
_postStorageContract.DelElement(post.PositionId);
|
||||
var element = GetPostFromDatabaseByPositionId(post.PositionId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(!element!.IsActual);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_DelElement_WhenRecordWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
Assert.That(() => _postStorageContract.DelElement(post.PositionId), Throws.TypeOf<ElementDeletedException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: false);
|
||||
_postStorageContract.ResElement(post.PositionId);
|
||||
var element = GetPostFromDatabaseByPositionId(post.PositionId);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(element, Is.Not.Null);
|
||||
Assert.That(element!.IsActual);
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenNoRecordWithThisId_Test()
|
||||
{
|
||||
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
|
||||
{
|
||||
var post = InsertPostToDatabaseAndReturn(Guid.NewGuid().ToString(), isActual: true);
|
||||
Assert.That(() => _postStorageContract.ResElement(post.PositionId), Throws.Nothing);
|
||||
}
|
||||
|
||||
private Position InsertPostToDatabaseAndReturn(string id, string postName = "test", PositionType postType = PositionType.Assistant, double salary = 10, bool isActual = true, DateTime? changeDate = null)
|
||||
{
|
||||
var post = new Position() { Id = Guid.NewGuid().ToString(), PositionId = id, PositionName = postName, PositionType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
|
||||
AndDietCokeDbContext.Posts.Add(post);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return post;
|
||||
}
|
||||
|
||||
private static void AssertElement(PositionDataModel? actual, Position expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.PositionId));
|
||||
Assert.That(actual.PositionName, Is.EqualTo(expected.PositionName));
|
||||
Assert.That(actual.PositionType, Is.EqualTo(expected.PositionType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
});
|
||||
}
|
||||
|
||||
private static PositionDataModel CreateModel(string PositionId, string postName = "test", PositionType postType = PositionType.Assistant, double salary = 10, bool isActual = false, DateTime? changeDate = null)
|
||||
=> new(PositionId, postName, postType, salary, isActual, changeDate ?? DateTime.UtcNow);
|
||||
|
||||
private Position? GetPostFromDatabaseByPositionId(string id) => AndDietCokeDbContext.Posts.Where(x => x.PositionId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
|
||||
|
||||
private static void AssertElement(Position? actual, PositionDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.PositionId, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.PositionName, Is.EqualTo(expected.PositionName));
|
||||
Assert.That(actual.PositionType, Is.EqualTo(expected.PositionType));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
Assert.That(actual.IsActual, Is.EqualTo(expected.IsActual));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using AndDietCokeContracts.DataModels;
|
||||
using AndDietCokeDatabase.Implementations;
|
||||
using AndDietCokeDatabase.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AndDietCokeTests.StorageContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class SalaryStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
private SalaryStorageContract _salaryStorageContract;
|
||||
private Employee _employee;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_salaryStorageContract = new SalaryStorageContract(AndDietCokeDbContext);
|
||||
_employee = InsertWorkerToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Salaries\" CASCADE;");
|
||||
AndDietCokeDbContext.Database.ExecuteSqlRaw("TRUNCATE \"Employees\" CASCADE;");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenHaveRecords_Test()
|
||||
{
|
||||
var salary = InsertSalaryToDatabaseAndReturn(_employee.Id, workerSalary: 100);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(3));
|
||||
AssertElement(list.First(), salary);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WhenNoRecords_Test()
|
||||
{
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-10), DateTime.UtcNow.AddDays(10));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_OnlyInDatePeriod_Test()
|
||||
{
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorker_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id);
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id);
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.EmloyeedId == _employee.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByWorkerOnlyInDatePeriod_Test()
|
||||
{
|
||||
var worker = InsertWorkerToDatabaseAndReturn("name 2");
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(-1).AddMinutes(5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(worker.Id, salaryDate: DateTime.UtcNow.AddDays(1).AddMinutes(-5));
|
||||
InsertSalaryToDatabaseAndReturn(_employee.Id, salaryDate: DateTime.UtcNow.AddDays(-2));
|
||||
var list = _salaryStorageContract.GetList(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), _employee.Id);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.EmloyeedId == _employee.Id));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_Test()
|
||||
{
|
||||
var salary = CreateModel(_employee.Id);
|
||||
_salaryStorageContract.AddElement(salary);
|
||||
AssertElement(GetSalaryFromDatabaseByWorkerId(_employee.Id), salary);
|
||||
}
|
||||
|
||||
private Employee InsertWorkerToDatabaseAndReturn(string workerFIO = "fio")
|
||||
{
|
||||
var worker = new Employee() { Id = Guid.NewGuid().ToString(), PositionId = Guid.NewGuid().ToString(), FIO = workerFIO, IsDeleted = false };
|
||||
AndDietCokeDbContext.Employees.Add(worker);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private Salaries InsertSalaryToDatabaseAndReturn(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
{
|
||||
var salary = new Salaries() { EmloyeedId = workerId, Salary = workerSalary, SalaryDate = salaryDate ?? DateTime.UtcNow };
|
||||
AndDietCokeDbContext.Salaries.Add(salary);
|
||||
AndDietCokeDbContext.SaveChanges();
|
||||
return salary;
|
||||
}
|
||||
|
||||
private static void AssertElement(SalaryDataModel? actual, Salaries expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.EmloyeedId, Is.EqualTo(expected.EmloyeedId));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
|
||||
private static SalaryDataModel CreateModel(string workerId, double workerSalary = 1, DateTime? salaryDate = null)
|
||||
=> new(workerId, salaryDate ?? DateTime.UtcNow, workerSalary, workerId);
|
||||
|
||||
private Salaries? GetSalaryFromDatabaseByWorkerId(string id) => AndDietCokeDbContext.Salaries.FirstOrDefault(x => x.EmloyeedId == id);
|
||||
|
||||
private static void AssertElement(Salaries? actual, SalaryDataModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.EmloyeedId, Is.EqualTo(expected.EmloyeedId));
|
||||
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user