lab2-ready

This commit is contained in:
2025-04-15 01:25:50 +04:00
parent e0f0af6754
commit 4518d36016
140 changed files with 5574 additions and 7314 deletions

View File

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

View File

@@ -1,3 +0,0 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("CandyHouseTests")]

View File

@@ -1,30 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultItems>true</EnableDefaultItems>
<OutputType>Library</OutputType>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="CatHasPawsTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>CandyHouseTests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>DynamicProxyGenAssembly2</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0-preview.1.25080.5" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.8" />
</ItemGroup>
</Project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class StorageDataModel : IValidation
{
public string Id { get; set; }
public string Title { get; set; }
public StorageType StorageType { get; set; }
public List<StorageIngredientDataModel> Ingredients { get; set; }
public StorageDataModel(string id, string title, StorageType storageType, List<StorageIngredientDataModel> ingredients)
{
Id = id;
Title = title;
StorageType = storageType;
Ingredients = ingredients;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!Id.IsGuid()) throw new ValidationException("Invalid Id format");
if (Title.IsEmpty()) throw new ValidationException("Field Title is empty");
if (!Enum.IsDefined(typeof(StorageType), StorageType))
throw new ValidationException($"Invalid StorageType: {StorageType}");
if (Ingredients == null) throw new ValidationException($"Ingredients is null");
}
}
}

View File

@@ -1,29 +0,0 @@
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class StorageIngredientDataModel : IValidation
{
public string StorageId { get; set; }
public string IngredientId { get; set; }
public decimal Quantity { get; set; }
public StorageIngredientDataModel(string storageId, string ingredientId, decimal quantity)
{
StorageId = storageId;
IngredientId = ingredientId;
Quantity = quantity;
}
public void Validate()
{
if (StorageId.IsEmpty()) throw new ValidationException("Field Id is empty");
if (!StorageId.IsGuid()) throw new ValidationException("Field Id is not a valid GUID");
if (IngredientId.IsEmpty()) throw new ValidationException("Field IngredientId is empty");
if (!IngredientId.IsGuid()) throw new ValidationException("Field IngredientId is not a valid GUID");
if (Quantity <= 0) throw new ValidationException("Field Quantity must be greater than zero");
}
}
}

View File

@@ -1,39 +0,0 @@
using System;
using System.Collections.Generic;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class SupplyDataModel : IValidation
{
public string Id { get; set; }
public DateTime Date { get; set; }
public int TotalQuantity { get; set; }
public decimal TotalPrice { get; set; }
public List<IngredientDataModel> Ingredients { get; set; }
public SupplyDataModel(string id, DateTime date, int quantity, decimal totalPrice,
List<IngredientDataModel> ingredients)
{
Id = id;
Date = date;
TotalQuantity = quantity;
TotalPrice = totalPrice;
Ingredients = ingredients;
}
public void Validate()
{
if (Id.IsEmpty()) throw new ValidationException("Supply ID cannot be null or empty");
if (!Id.IsGuid()) throw new ValidationException("Supply ID must be a valid GUID");
if (Date == default) throw new ValidationException("Supply date cannot be null");
if (TotalQuantity <= 0) throw new ValidationException("Supply quantity must be greater than zero");
if (TotalPrice < 0) throw new ValidationException("Supply total price cannot be negative");
if (Ingredients == null || Ingredients.Count == 0)
throw new ValidationException("Supply must have at least one ingredient");
}
}
}

View File

@@ -1,29 +0,0 @@
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Infrastructure;
namespace CandyHouseBase.DataModels
{
public class SupplyIngredientDataModel : IValidation
{
public string SupplyId { get; set; }
public string IngredientId { get; set; }
public int Quantity { get; set; }
public SupplyIngredientDataModel(string supplyId, string ingredientId, int quantity)
{
SupplyId = supplyId;
IngredientId = ingredientId;
Quantity = quantity;
}
public void Validate()
{
if (SupplyId.IsEmpty()) throw new ValidationException("Supply ID cannot be null or empty");
if (!SupplyId.IsGuid()) throw new ValidationException("Supply ID is not a valid GUID");
if (IngredientId.IsEmpty()) throw new ValidationException("Ingredient ID cannot be null or empty");
if (!IngredientId.IsGuid()) throw new ValidationException("Ingredient ID is not a valid GUID");
if (Quantity <= 0) throw new ValidationException("Quantity must be a positive number");
}
}
}

View File

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

View File

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

View File

@@ -1,9 +0,0 @@
namespace CandyHouseBase.Enums
{
public enum StorageType
{
Fridge,
Shelf,
Cabinet
}
}

View File

@@ -1,11 +0,0 @@
using System;
namespace CandyHouseBase.Exceptions;
public class IncorrectDatesException : Exception
{
public IncorrectDatesException(DateTime start, DateTime end) : base(
$"The end date must be later than the start date.. StartDate: {start:dd.MM.YYYY}. EndDate: {end:dd.MM.YYYY}")
{
}
}

View File

@@ -1,10 +0,0 @@
using System;
namespace CandyHouseBase.Exceptions;
public class NullListException : Exception
{
public NullListException() : base("The returned list is null")
{
}
}

View File

@@ -1,11 +0,0 @@
using System;
namespace CandyHouseBase.Exceptions;
public class StorageException : Exception
{
public StorageException(Exception ex) : base($"Error while working in storage: {ex.Message}", ex)
{
}
}

View File

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

View File

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

View File

@@ -1,86 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class IngredientBusinessLogicContract(
IIngredientStorageContact ingredientStorageContact,
ILogger logger)
: IIngredientBusinessLogicContact
{
private readonly IIngredientStorageContact _ingredientStorageContact = ingredientStorageContact;
private readonly ILogger _logger = logger;
public List<IngredientDataModel> GetAllIngredients()
{
_logger.LogInformation("GetAllIngredients");
var ingredients = _ingredientStorageContact.GetList() ?? throw new NullListException();
return ingredients;
}
public IngredientDataModel GetIngredientByData(string data)
{
_logger.LogInformation("GetIngredientByData for data: {data}", data);
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));
if (data.IsGuid())
{
var ingredient = _ingredientStorageContact.GetElementById(data);
if (ingredient == null)
throw new ElementNotFoundException(data);
return ingredient;
}
else
{
var ingredient = _ingredientStorageContact.GetElementByName(data);
if (ingredient == null)
throw new ElementNotFoundException(data);
return ingredient;
}
}
public void InsertIngredient(IngredientDataModel ingredient)
{
_logger.LogInformation("InsertIngredient: {json}", JsonSerializer.Serialize(ingredient));
if (ingredient == null)
throw new ArgumentNullException(nameof(ingredient));
ingredient.Validate();
_ingredientStorageContact.AddElement(ingredient);
}
public void UpdateIngredient(IngredientDataModel ingredient)
{
_logger.LogInformation("UpdateIngredient: {json}", JsonSerializer.Serialize(ingredient));
if (ingredient == null)
throw new ArgumentNullException(nameof(ingredient));
ingredient.Validate();
_ingredientStorageContact.UpdateElement(ingredient);
}
public void DeleteIngredient(string id)
{
_logger.LogInformation("DeleteIngredient for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var ingredient = _ingredientStorageContact.GetElementById(id);
if (ingredient == null)
throw new ElementNotFoundException(id);
_ingredientStorageContact.DeleteElement(id);
}
}
}

View File

@@ -1,136 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class OrderBusinessLogicContract(
IOrderStorageContact orderStorageContact,
IPekarStorageContact pekarStorageContact,
IProductStorageContact productStorageContact,
IStorageStorageContact storageStorageContact,
IIngredientStorageContact ingredientStorageContact,
ILogger logger)
: IOrderBusinessLogicContact
{
private readonly IOrderStorageContact _orderStorageContact = orderStorageContact;
private readonly IPekarStorageContact _pekarStorageContact = pekarStorageContact;
private readonly IProductStorageContact _productStorageContact = productStorageContact;
private readonly IStorageStorageContact _storageStorageContact = storageStorageContact;
private readonly IIngredientStorageContact _ingredientStorageContact = ingredientStorageContact;
private readonly ILogger _logger = logger;
public List<OrderDataModel> GetAllOrders()
{
_logger.LogInformation("GetAllOrders");
var orders = _orderStorageContact.GetOrders() ?? throw new NullListException();
return orders;
}
public OrderDataModel GetOrderByData(string data)
{
_logger.LogInformation("GetOrderByData for data: {data}", data);
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));
if (!data.IsGuid())
throw new ValidationException("data must be a GUID");
var order = _orderStorageContact.GetElementById(data) ?? throw new ElementNotFoundException(data);
return order;
}
public void InsertOrder(OrderDataModel order)
{
bool enoughIngredients = false;
_logger.LogInformation("InsertOrder: {json}", JsonSerializer.Serialize(order));
if (order == null)
throw new ArgumentNullException(nameof(order));
order.Validate();
var storageBusinessLogicContract = new StorageBusinessLogicContract(_storageStorageContact,
_pekarStorageContact, _logger);
storageBusinessLogicContract.EnoughIngredients(order);
// Check if Pekar exists
if (_pekarStorageContact.GetElementById(order.PekarId) == null)
throw new ElementNotFoundException(order.PekarId);
// Check if Product exists
if (_productStorageContact.GetElementById(order.ProductId) == null)
throw new ElementNotFoundException(order.ProductId);
// Check if order with this ID already exists
var existingOrder = _orderStorageContact.GetElementById(order.Id);
if (existingOrder != null)
throw new ElementExistsException("ID", order.Id);
try
{
_orderStorageContact.AddElement(order);
}
catch (Exception ex)
{
throw new StorageException(ex);
}
}
public void UpdateOrder(OrderDataModel order)
{
_logger.LogInformation("UpdateOrder: {json}", JsonSerializer.Serialize(order));
if (order == null)
throw new ArgumentNullException(nameof(order));
order.Validate();
// Check if Pekar exists
if (_pekarStorageContact.GetElementById(order.PekarId) == null)
throw new ElementNotFoundException(order.PekarId);
// Check if Product exists
if (_productStorageContact.GetElementById(order.ProductId) == null)
throw new ElementNotFoundException(order.ProductId);
try
{
_orderStorageContact.UpdateElement(order);
}
catch (Exception ex)
{
throw new StorageException(ex);
}
}
public void DeleteOrder(string id)
{
_logger.LogInformation("DeleteOrder for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var order = _orderStorageContact.GetElementById(id);
if (order == null)
throw new ElementNotFoundException(id);
try
{
_orderStorageContact.DeleteElement(order);
}
catch (Exception ex)
{
throw new StorageException(ex);
}
}
}
}

View File

@@ -1,174 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using CandyHouseBase.DataModels;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class PekarBusinessLogicContract(
IPekarStorageContact pekarStorageContact,
IProductStorageContact productStorageContact,
IPositionStorageContact positionStorageContact,
ILogger logger)
: IPekarBusinessLogicContact
{
private readonly IPekarStorageContact _pekarStorageContact = pekarStorageContact;
private readonly IProductStorageContact _productStorageContact = productStorageContact;
private readonly IPositionStorageContact _positionStorageContact = positionStorageContact;
private readonly ILogger _logger = logger;
public List<PekarDataModel> GetAllPekars()
{
_logger.LogInformation("GetAllPekars");
var pekars = _pekarStorageContact.GetList() ?? throw new NullListException();
return pekars;
}
public List<PekarDataModel> GetAllDataOfPekar(string pekarId)
{
_logger.LogInformation("GetAllDataOfPekar for pekarId: {pekarId}", pekarId);
if (pekarId.IsEmpty())
throw new ArgumentNullException(nameof(pekarId));
if (!pekarId.IsGuid())
throw new ValidationException("pekarId must be a GUID");
var pekarsWithHistory = _pekarStorageContact.GetPekarWithHistory(pekarId);
if (pekarsWithHistory == null || !pekarsWithHistory.Any())
throw new ElementNotFoundException(pekarId);
var historyRecords = new List<PekarDataModel>();
foreach (var pekar in pekarsWithHistory)
{
Guid positionGuid;
if (!Guid.TryParse(pekar.Position, out positionGuid))
{
_logger.LogWarning("Invalid Position GUID: {Position}", pekar.Position);
continue;
}
var position = _positionStorageContact.GetElementById(positionGuid.ToString());
if (position == null)
throw new ElementNotFoundException(pekar.Position);
historyRecords.Add(new PekarDataModel(pekar.Id, pekar.FIO, position.Id, pekar.BonusCoefficient,
new List<ProductDataModel>()));
}
if (!historyRecords.Any())
{
var firstPekar = pekarsWithHistory.First();
Guid positionGuid;
if (Guid.TryParse(firstPekar.Position, out positionGuid))
{
var position = _positionStorageContact.GetElementById(positionGuid.ToString());
if (position != null)
historyRecords.Add(new PekarDataModel(firstPekar.Id, firstPekar.FIO, position.Id,
firstPekar.BonusCoefficient,
new List<ProductDataModel>()));
}
}
return historyRecords;
}
public PekarDataModel GetPekarByData(string data)
{
_logger.LogInformation("GetPekarByData for data: {data}", data);
if (data.IsEmpty())
throw new ArgumentNullException(nameof(data));
if (!data.IsGuid() && !Regex.IsMatch(data, @"^[A-Za-zА-Яа-яЁё\s\-]+$"))
throw new ValidationException("data must be a GUID or FIO");
var pekar = _pekarStorageContact.GetElementById(data) ?? _pekarStorageContact.GetElementByFio(data) ??
throw new ElementNotFoundException(data);
return pekar;
}
public void InsertPekar(PekarDataModel pekar)
{
_logger.LogInformation("InsertPekar: {json}", JsonSerializer.Serialize(pekar));
if (pekar == null)
throw new ArgumentNullException(nameof(pekar));
pekar.Validate();
var existingPekar = _pekarStorageContact.GetElementById(pekar.Id);
if (existingPekar != null)
{
var history = new PekarHistoryDataModel(
existingPekar.Id,
existingPekar.FIO,
existingPekar.Position,
existingPekar.BonusCoefficient,
DateTime.Now
);
}
foreach (var product in pekar.ProductsItems)
{
if (_productStorageContact.GetElementById(product.Id) == null)
throw new ElementNotFoundException(product.Id);
}
_pekarStorageContact.AddElement(pekar);
}
public void UpdatePekar(PekarDataModel pekar)
{
_logger.LogInformation("UpdatePekar: {json}", JsonSerializer.Serialize(pekar));
if (pekar == null)
throw new ArgumentNullException(nameof(pekar));
pekar.Validate();
foreach (var product in pekar.ProductsItems)
{
if (_productStorageContact.GetElementById(product.Id) == null)
throw new ElementNotFoundException(product.Id);
}
_pekarStorageContact.UpdateElement(pekar);
}
public void DeletePekar(string id)
{
_logger.LogInformation("DeletePekar for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var pekar = _pekarStorageContact.GetElementById(id);
if (pekar == null)
throw new ElementNotFoundException(id);
_pekarStorageContact.DeleteElement(id);
}
public void RestorePekar(string id)
{
_logger.LogInformation("RestorePekar for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var pekar = _pekarStorageContact.GetElementById(id);
if (pekar == null)
throw new ElementNotFoundException(id);
_pekarStorageContact.RestoreElement(id);
}
}
}

View File

@@ -1,87 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Enums;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class PositionBusinessLogicContract(
IPositionStorageContact positionStorageContact,
ILogger logger)
: IPositionBusinessLogicContact
{
private readonly IPositionStorageContact _positionStorageContact = positionStorageContact;
private readonly ILogger _logger = logger;
public List<PositionDataModel> GetAllPositions()
{
_logger.LogInformation("GetAllPositions");
var positions = _positionStorageContact.GetList() ?? throw new NullListException();
return positions;
}
public PositionDataModel GetPositionByData(string data)
{
_logger.LogInformation("GetPositionByData for data: {data}", data);
if (data.IsEmpty())
throw new ArgumentNullException(nameof(data));
var position = _positionStorageContact.GetElementById(data);
if (position == null)
throw new ElementNotFoundException(data);
if (!data.IsGuid())
throw new ValidationException("data must be a GUID");
return position;
}
public void InsertPosition(PositionDataModel position)
{
_logger.LogInformation("InsertPosition: {json}", JsonSerializer.Serialize(position));
if (position == null)
throw new ArgumentNullException(nameof(position));
position.Validate();
_positionStorageContact.AddElement(position);
}
public void UpdatePosition(PositionDataModel position)
{
_logger.LogInformation("UpdatePosition: {json}", JsonSerializer.Serialize(position));
if (position == null)
throw new ArgumentNullException(nameof(position));
position.Validate();
_positionStorageContact.UpdateElement(position);
}
public void DeletePosition(string id)
{
_logger.LogInformation("DeletePosition for id: {id}", id);
if (id.IsEmpty())
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var position = _positionStorageContact.GetElementById(id);
if (position == null)
throw new ElementNotFoundException(id);
try
{
_positionStorageContact.DeleteElement(id);
}
catch (Exception ex)
{
throw new StorageException(ex);
}
}
}
}

View File

@@ -1,114 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class ProductBusinessLogicContract(
IProductStorageContact productStorageContact,
IIngredientStorageContact ingredientStorageContact,
ILogger logger)
: IProductBusinessLogicContact
{
private readonly IProductStorageContact _productStorageContact = productStorageContact;
private readonly IIngredientStorageContact _ingredientStorageContact = ingredientStorageContact;
private readonly ILogger _logger = logger;
public List<ProductDataModel> GetAllProducts()
{
_logger.LogInformation("GetAllProducts");
var products = _productStorageContact.GetList() ?? throw new NullListException();
return products;
}
public ProductDataModel GetProductByData(string data)
{
_logger.LogInformation("GetProductByData for data: {data}", data);
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));
if (data.IsGuid())
{
var product = _productStorageContact.GetElementById(data);
if (product == null)
throw new ElementNotFoundException(data);
if (!data.IsGuid()) // Validate after existence check (redundant but kept for consistency)
throw new ValidationException("data must be a GUID");
return product;
}
else
{
var products = _productStorageContact.GetList();
var productByName = products.FirstOrDefault(p => p.Name == data || (p.OldName != null && p.OldName == data));
if (productByName == null)
throw new ElementNotFoundException(data);
return productByName;
}
}
public void InsertProduct(ProductDataModel product)
{
_logger.LogInformation("InsertProduct: {json}", JsonSerializer.Serialize(product));
if (product == null)
throw new ArgumentNullException(nameof(product));
product.Validate();
foreach (var ingredient in product.IngredientsItems)
{
if (_ingredientStorageContact.GetElementById(ingredient.Id) == null)
throw new ElementNotFoundException(ingredient.Id);
}
_productStorageContact.AddElement(product);
}
public void UpdateProduct(ProductDataModel product)
{
_logger.LogInformation("UpdateProduct: {json}", JsonSerializer.Serialize(product));
if (product == null)
throw new ArgumentNullException(nameof(product));
product.Validate();
foreach (var ingredient in product.IngredientsItems)
{
if (_ingredientStorageContact.GetElementById(ingredient.Id) == null)
throw new ElementNotFoundException(ingredient.Id);
}
_productStorageContact.UpdateElement(product);
}
public void DeleteProduct(string id)
{
_logger.LogInformation("DeleteProduct for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var product = _productStorageContact.GetElementById(id);
if (product == null)
throw new ElementNotFoundException(id);
try
{
_productStorageContact.DeleteElement(id);
}
catch (Exception ex)
{
throw new StorageException(ex);
}
}
}
}

View File

@@ -1,85 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class SalaryBusinessLogicContract(
ISalaryStorageContact salaryStorageContact,
IPekarStorageContact pekarStorageContact,
ILogger logger)
: ISalaryBusinessLogicContact
{
private readonly ISalaryStorageContact _salaryStorageContact = salaryStorageContact;
private readonly IPekarStorageContact _pekarStorageContact = pekarStorageContact;
private readonly ILogger _logger = logger;
public List<SalaryDataModel> GetAllSalaries()
{
_logger.LogInformation("GetAllSalaries");
var salaries = _salaryStorageContact.GetList() ?? throw new NullListException();
return salaries;
}
public SalaryDataModel GetSalaryByData(string data)
{
_logger.LogInformation("GetSalaryByData for data: {data}", data);
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(data))
throw new ArgumentNullException(nameof(data));
if (!data.IsGuid())
throw new ValidationException("data must be a GUID");
var salary = _salaryStorageContact.GetElementById(data) ?? throw new ElementNotFoundException(data);
if (_pekarStorageContact.GetElementById(salary.PekarId) == null)
throw new ElementNotFoundException(salary.PekarId);
return salary;
}
public void InsertSalary(SalaryDataModel salary)
{
_logger.LogInformation("InsertSalary: {json}", JsonSerializer.Serialize(salary));
if (salary == null)
throw new ArgumentNullException(nameof(salary));
salary.Validate();
if (_pekarStorageContact.GetElementById(salary.PekarId) == null)
throw new ElementNotFoundException(salary.PekarId);
_salaryStorageContact.AddElement(salary);
}
public void UpdateSalary(SalaryDataModel salary)
{
_logger.LogInformation("UpdateSalary: {json}", JsonSerializer.Serialize(salary));
if (salary == null)
throw new ArgumentNullException(nameof(salary));
salary.Validate();
if (_pekarStorageContact.GetElementById(salary.PekarId) == null)
throw new ElementNotFoundException(salary.PekarId);
_salaryStorageContact.UpdateElement(salary);
}
public void DeleteSalary(string id)
{
_logger.LogInformation("DeleteSalary for id: {id}", id);
if (id == null)
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (!id.IsGuid())
throw new ValidationException("id must be a GUID");
var salary = _salaryStorageContact.GetElementById(id);
if (salary == null)
throw new ElementNotFoundException(id);
_salaryStorageContact.DeleteElement(id);
}
}
}

View File

@@ -1,227 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class StorageBusinessLogicContract : IStorageBusinessLogicContact
{
private readonly IStorageStorageContact _storageStorageContact;
private readonly IPekarStorageContact _pekarStorageContact;
private readonly ILogger _logger;
public StorageBusinessLogicContract(
IStorageStorageContact storageStorageContact,
IPekarStorageContact pekarStorageContact,
ILogger logger)
{
_storageStorageContact = storageStorageContact;
_pekarStorageContact = pekarStorageContact;
_logger = logger;
}
public List<StorageDataModel> GetAllStorages()
{
try
{
var storages = _storageStorageContact.GetList();
if (storages == null)
{
_logger.LogError("Storage list is null");
throw new NullListException();
}
_logger.LogInformation($"Retrieved {storages.Count} storage records");
return storages;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is NullListException))
{
_logger.LogError($"Error retrieving storage list: {ex.Message}");
throw new StorageException(ex);
}
}
public StorageDataModel GetStorageByData(string data)
{
if (data.IsEmpty())
{
_logger.LogError("Storage data parameter is null or empty");
throw new ArgumentNullException(nameof(data), "Storage data parameter cannot be null or empty");
}
try
{
StorageDataModel storage = null;
if (data.IsGuid())
{
storage = _storageStorageContact.GetElementById(data);
}
if (storage == null)
{
storage = _storageStorageContact.GetElementByTitle(data);
}
if (storage == null)
{
_logger.LogError($"Storage not found for data: {data}");
throw new ElementNotFoundException($"Storage not found for data: {data}");
}
_logger.LogInformation($"Retrieved storage: {JsonSerializer.Serialize(storage)}");
return storage;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ElementNotFoundException || ex is ArgumentNullException))
{
_logger.LogError($"Error retrieving storage by data: {ex.Message}");
throw new StorageException(ex);
}
}
public void EnoughIngredients(OrderDataModel order)
{
try
{
_storageStorageContact.ExtractIngredients(order); // Mock ExtractIngredients
}
catch (StorageException ex)
{
throw new StorageException(ex);
}
catch (Exception ex)
{
throw ex;
}
}
public void InsertStorage(StorageDataModel storage)
{
if (storage == null)
{
_logger.LogError("Storage is null");
throw new ArgumentNullException(nameof(storage), "Storage cannot be null");
}
try
{
storage.Validate();
var existingStorage = _storageStorageContact.GetElementById(storage.Id);
if (existingStorage != null)
{
throw new ElementExistsException("ID", storage.Id);
}
_storageStorageContact.AddElement(storage);
_logger.LogInformation($"Storage inserted: {JsonSerializer.Serialize(storage)}");
}
catch (ValidationException ex)
{
_logger.LogError($"Validation error during storage insertion: {ex.Message}");
throw;
}
catch (ElementExistsException ex)
{
_logger.LogError($"Storage already exists: {ex.Message}");
throw;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ArgumentNullException || ex is ElementNotFoundException))
{
_logger.LogError($"Error inserting storage: {ex.Message}");
throw new StorageException(ex);
}
}
public void UpdateStorage(StorageDataModel storage)
{
if (storage == null)
{
_logger.LogError("Storage is null");
throw new ArgumentNullException(nameof(storage), "Storage cannot be null");
}
try
{
storage.Validate();
_storageStorageContact.UpdateElement(storage);
_logger.LogInformation($"Storage updated: {JsonSerializer.Serialize(storage)}");
}
catch (ValidationException ex)
{
_logger.LogError($"Validation error during storage update: {ex.Message}");
throw;
}
catch (ElementNotFoundException ex)
{
_logger.LogError($"Storage not found: {ex.Message}");
throw;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ArgumentNullException))
{
_logger.LogError($"Error updating storage: {ex.Message}");
throw new StorageException(ex);
}
}
public void DeleteStorage(string id)
{
if (id.IsEmpty())
{
_logger.LogError("Storage ID is null or empty");
throw new ArgumentNullException(nameof(id), "Storage ID cannot be null or empty");
}
if (!id.IsGuid())
{
_logger.LogError($"Invalid Storage ID format: {id}");
throw new ValidationException($"Invalid Storage ID format: {id}");
}
try
{
var existingStorage = _storageStorageContact.GetElementById(id);
if (existingStorage == null)
{
_logger.LogError($"Storage not found with ID: {id}");
throw new ElementNotFoundException($"Storage not found with ID: {id}");
}
_storageStorageContact.DeleteElement(id);
_logger.LogInformation($"Storage deleted: {id}");
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ValidationException || ex is ElementNotFoundException))
{
_logger.LogError($"Error deleting storage: {ex.Message}");
throw new StorageException(ex);
}
}
}
}

View File

@@ -1,232 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using CandyHouseBase.DataModels;
using CandyHouseBase.Exceptions;
using CandyHouseBase.Extensions;
using CandyHouseBase.Interfaces.BusinessLogicsContracts;
using CandyHouseBase.Interfaces.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CandyHouseBase.Implementations
{
internal class SupplyBusinessLogicContract : ISupplyBusinessLogicContact
{
private readonly ISupplyStorageContact _supplyStorageContact;
private readonly IIngredientStorageContact _ingredientStorageContact;
private readonly ILogger _logger;
public SupplyBusinessLogicContract(
ISupplyStorageContact supplyStorageContact,
IIngredientStorageContact ingredientStorageContact,
ILogger logger)
{
_supplyStorageContact = supplyStorageContact;
_ingredientStorageContact = ingredientStorageContact;
_logger = logger;
}
public List<SupplyDataModel> GetAllSupplies()
{
try
{
var supplies = _supplyStorageContact.GetList();
if (supplies == null)
{
_logger.LogError("Supply list is null");
throw new NullListException();
}
_logger.LogInformation($"Retrieved {supplies.Count} supply records");
return supplies;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is NullListException))
{
_logger.LogError($"Error retrieving supply list: {ex.Message}");
throw new StorageException(ex);
}
}
public SupplyDataModel GetSupplyByData(string data)
{
if (data.IsEmpty())
{
_logger.LogError("Supply data parameter is null or empty");
throw new ArgumentNullException(nameof(data), "Supply data parameter cannot be null or empty");
}
if (!data.IsGuid())
{
_logger.LogError($"Invalid Supply ID format: {data}");
throw new ValidationException($"Invalid Supply ID format: {data}");
}
try
{
var supply = _supplyStorageContact.GetElementById(data);
if (supply == null)
{
_logger.LogError($"Supply not found for ID: {data}");
throw new ElementNotFoundException($"Supply not found for ID: {data}");
}
_logger.LogInformation($"Retrieved supply: {JsonSerializer.Serialize(supply)}");
return supply;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ElementNotFoundException || ex is ArgumentNullException || ex is ValidationException))
{
_logger.LogError($"Error retrieving supply by data: {ex.Message}");
throw new StorageException(ex);
}
}
public void InsertSupply(SupplyDataModel supply)
{
if (supply == null)
{
_logger.LogError("Supply is null");
throw new ArgumentNullException(nameof(supply), "Supply cannot be null");
}
try
{
supply.Validate();
if (supply.Ingredients != null)
{
foreach (var ingredient in supply.Ingredients)
{
if (ingredient != null && !ingredient.Id.IsEmpty() && ingredient.Id.IsGuid())
{
var existingIngredient = _ingredientStorageContact.GetElementById(ingredient.Id);
if (existingIngredient == null)
{
_logger.LogError($"Ingredient with ID {ingredient.Id} not found");
throw new ElementNotFoundException($"Ingredient with ID {ingredient.Id} not found");
}
}
}
}
_supplyStorageContact.AddElement(supply);
_logger.LogInformation($"Supply inserted: {JsonSerializer.Serialize(supply)}");
}
catch (ValidationException ex)
{
_logger.LogError($"Validation error during supply insertion: {ex.Message}");
throw;
}
catch (ElementExistsException ex)
{
_logger.LogError($"Supply already exists: {ex.Message}");
throw;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ArgumentNullException || ex is ElementNotFoundException))
{
_logger.LogError($"Error inserting supply: {ex.Message}");
throw new StorageException(ex);
}
}
public void UpdateSupply(SupplyDataModel supply)
{
if (supply == null)
{
_logger.LogError("Supply is null");
throw new ArgumentNullException(nameof(supply), "Supply cannot be null");
}
try
{
supply.Validate();
if (supply.Ingredients != null)
{
foreach (var ingredient in supply.Ingredients)
{
if (ingredient != null && !ingredient.Id.IsEmpty() && ingredient.Id.IsGuid())
{
var existingIngredient = _ingredientStorageContact.GetElementById(ingredient.Id);
if (existingIngredient == null)
{
_logger.LogError($"Ingredient with ID {ingredient.Id} not found");
throw new ElementNotFoundException($"Ingredient with ID {ingredient.Id} not found");
}
}
}
}
_supplyStorageContact.UpdateElement(supply);
_logger.LogInformation($"Supply updated: {JsonSerializer.Serialize(supply)}");
}
catch (ValidationException ex)
{
_logger.LogError($"Validation error during supply update: {ex.Message}");
throw;
}
catch (ElementNotFoundException ex)
{
_logger.LogError($"Supply not found: {ex.Message}");
throw;
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ArgumentNullException))
{
_logger.LogError($"Error updating supply: {ex.Message}");
throw new StorageException(ex);
}
}
public void DeleteSupply(string id)
{
if (id.IsEmpty())
{
_logger.LogError("Supply ID is null or empty");
throw new ArgumentNullException(nameof(id), "Supply ID cannot be null or empty");
}
if (!id.IsGuid())
{
_logger.LogError($"Invalid Supply ID format: {id}");
throw new ValidationException($"Invalid Supply ID format: {id}");
}
try
{
var existingSupply = _supplyStorageContact.GetElementById(id);
if (existingSupply == null)
{
_logger.LogError($"Supply not found with ID: {id}");
throw new ElementNotFoundException($"Supply not found with ID: {id}");
}
_supplyStorageContact.DeleteElement(id);
_logger.LogInformation($"Supply deleted: {id}");
}
catch (StorageException)
{
throw;
}
catch (Exception ex) when (!(ex is ValidationException || ex is ElementNotFoundException))
{
_logger.LogError($"Error deleting supply: {ex.Message}");
throw new StorageException(ex);
}
}
}
}

View File

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

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface IIngredientBusinessLogicContact
{
List<IngredientDataModel> GetAllIngredients();
IngredientDataModel GetIngredientByData(string data);
void InsertIngredient(IngredientDataModel ingredient);
void UpdateIngredient(IngredientDataModel ingredient);
void DeleteIngredient(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface IOrderBusinessLogicContact
{
List<OrderDataModel> GetAllOrders();
OrderDataModel GetOrderByData(string data);
void InsertOrder(OrderDataModel order);
void UpdateOrder(OrderDataModel order);
void DeleteOrder(string id);
}
}

View File

@@ -1,16 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface IPekarBusinessLogicContact
{
List<PekarDataModel> GetAllPekars();
List<PekarDataModel> GetAllDataOfPekar(string pekarId);
PekarDataModel GetPekarByData(string data);
void InsertPekar(PekarDataModel order);
void UpdatePekar(PekarDataModel order);
void DeletePekar(string id);
void RestorePekar(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface IPositionBusinessLogicContact
{
List<PositionDataModel> GetAllPositions();
PositionDataModel GetPositionByData(string data);
void InsertPosition(PositionDataModel position);
void UpdatePosition(PositionDataModel position);
void DeletePosition(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface IProductBusinessLogicContact
{
List<ProductDataModel> GetAllProducts();
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel product);
void UpdateProduct(ProductDataModel product);
void DeleteProduct(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts
{
public interface ISalaryBusinessLogicContact
{
List<SalaryDataModel> GetAllSalaries();
SalaryDataModel GetSalaryByData(string data);
void InsertSalary(SalaryDataModel salary);
void UpdateSalary(SalaryDataModel salary);
void DeleteSalary(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts;
public interface IStorageBusinessLogicContact
{
List<StorageDataModel> GetAllStorages();
StorageDataModel GetStorageByData(string data);
void EnoughIngredients(OrderDataModel order);
void InsertStorage(StorageDataModel storage);
void UpdateStorage(StorageDataModel storage);
void DeleteStorage(string id);
}

View File

@@ -1,13 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.BusinessLogicsContracts;
public interface ISupplyBusinessLogicContact
{
List<SupplyDataModel> GetAllSupplies();
SupplyDataModel GetSupplyByData(string data);
void InsertSupply(SupplyDataModel supply);
void UpdateSupply(SupplyDataModel supply);
void DeleteSupply(string id);
}

View File

@@ -1,15 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface IIngredientStorageContact
{
List<IngredientDataModel> GetList();
IngredientDataModel GetElementById(string id);
IngredientDataModel GetElementByName(string name);
void AddElement(IngredientDataModel ingredient);
void UpdateElement(IngredientDataModel ingredient);
void DeleteElement(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface IOrderStorageContact
{
List<OrderDataModel> GetOrders();
void AddElement(OrderDataModel order);
void UpdateElement(OrderDataModel order);
void DeleteElement(OrderDataModel order);
OrderDataModel GetElementById(string orderId);
}
}

View File

@@ -1,17 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface IPekarStorageContact
{
List<PekarDataModel> GetList();
List<PekarDataModel> GetPekarWithHistory(string id);
PekarDataModel GetElementById(string id);
PekarDataModel GetElementByFio(string fio);
void AddElement(PekarDataModel item);
void UpdateElement(PekarDataModel item);
void DeleteElement(string id);
void RestoreElement(string id);
}
}

View File

@@ -1,16 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface IProductStorageContact
{
List<ProductDataModel> GetList();
ProductDataModel GetElementById(string id);
ProductDataModel GetElementByName(string name);
ProductDataModel GetElementByOldName(string name);
void AddElement(ProductDataModel element);
void UpdateElement(ProductDataModel element);
void DeleteElement(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface IPositionStorageContact
{
List<PositionDataModel> GetList();
PositionDataModel GetElementById(string id);
void AddElement(PositionDataModel element);
void UpdateElement(PositionDataModel element);
void DeleteElement(string id);
}
}

View File

@@ -1,14 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts
{
public interface ISalaryStorageContact
{
List<SalaryDataModel> GetList();
SalaryDataModel GetElementById(string id);
void AddElement(SalaryDataModel element);
void UpdateElement(SalaryDataModel element);
void DeleteElement(string id);
}
}

View File

@@ -1,16 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts;
public interface IStorageStorageContact
{
List<StorageDataModel> GetList();
StorageDataModel GetElementById(string id);
StorageDataModel GetElementByTitle(string title);
void ExtractIngredients(OrderDataModel order);
void AddElement(StorageDataModel element);
void UpdateElement(StorageDataModel element);
void DeleteElement(string id);
}

View File

@@ -1,13 +0,0 @@
using System.Collections.Generic;
using CandyHouseBase.DataModels;
namespace CandyHouseBase.Interfaces.StoragesContracts;
public interface ISupplyStorageContact
{
List<SupplyDataModel> GetList();
SupplyDataModel GetElementById(string id);
void AddElement(SupplyDataModel element);
void UpdateElement(SupplyDataModel element);
void DeleteElement(string id);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,10 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseBase.Exceptions;
namespace CandyHouseContracts.Exceptions;
public class ElementNotFoundException : Exception
{
@@ -10,4 +14,4 @@ public class ElementNotFoundException : Exception
{
Value = value;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,10 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseBase.Exceptions;
namespace CandyHouseContracts.Extensions;
public static class DateTimeExtensions
{
@@ -8,4 +12,4 @@ public static class DateTimeExtensions
{
return date >= olderDate;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,10 @@

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

View File

@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

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

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