38 Commits

Author SHA1 Message Date
user
9d12ff2500 вроде доделал тесты адаптера 2025-04-20 23:22:17 +04:00
c28acf5bd5 В процессе написания адаптер тестов 2025-04-20 14:54:37 +04:00
user
957d5adc0d вроде finish 2025-04-18 14:40:33 +04:00
user
45687ed29a Merge branch 'Task_3Hard' into Task_4Hard 2025-04-18 04:18:55 +04:00
user
eed08a91b2 В процессе 2025-04-18 04:17:43 +04:00
user
73dee8107d merge task3 hard 2025-04-10 01:23:12 +04:00
a74de025fa Сданный вариант 2025-04-05 10:13:18 +04:00
user
32bc39635c вроде finish 2025-04-05 00:43:28 +04:00
user
5779b9695a вроде finish 2025-04-04 23:26:45 +04:00
user
9a0e2ec59d Вроде финиш 2025-04-03 21:47:45 +04:00
user
4c7ae6bd67 начало 2025-03-30 17:33:47 +04:00
user
bce6d47a99 Merge branch 'Task_2Hard' into Task_3Hard 2025-03-30 17:26:47 +04:00
user
78d614b893 fix 2.0 2025-03-30 17:21:43 +04:00
user
22c101c77c Revert "supply fix"
This reverts commit 4e3fd46750.
2025-03-30 17:11:34 +04:00
user
4e3fd46750 supply fix 2025-03-30 17:09:41 +04:00
user
2cb5ce2793 Revert "supply fix 2.0"
This reverts commit cc7d7289f7.
2025-03-30 16:54:19 +04:00
user
cc7d7289f7 supply fix 2.0 2025-03-30 16:40:30 +04:00
user
015a963762 InsertSupply fix 2025-03-30 16:19:57 +04:00
user
69c63f5499 InsertSupply 2025-03-30 14:28:02 +04:00
user
d9d1a19ee8 Незавершенный вариант 2025-03-22 01:18:27 +04:00
user
94f2c60a08 Наследование ISaleStorage 2025-03-17 02:39:08 +04:00
user
e54574147a Revert "Добавил наследование от ISaleStorage"
This reverts commit 9045e90326.
2025-03-17 02:38:38 +04:00
user
9045e90326 Добавил наследование от ISaleStorage 2025-03-17 02:38:26 +04:00
72d33599fc Сданный вариант 2025-03-12 12:45:28 +04:00
eb3191410a Сданный вариант, Automap 2025-03-12 11:49:17 +04:00
c9753ff960 поменял переменную 2025-03-12 10:59:48 +04:00
ab45eb0546 3 готовая 2025-03-12 08:58:59 +04:00
user
98f99f607f готовая 2 hard 2025-03-12 01:01:36 +04:00
de63a5844a До начала тестов! 2025-03-10 12:22:57 +04:00
03e10326d0 начал делать 2025-03-02 23:27:51 +04:00
679672a33b Merge branch 'Task_1Hard' into Task_2Hard 2025-02-22 10:10:22 +04:00
397fd64eaf TearDown 2025-02-22 09:30:53 +04:00
user
21258b1c31 Вроде все сделанно 2025-02-21 22:47:51 +04:00
9730a641c4 Сделал datamodels 2025-02-21 17:37:05 +04:00
aac12212f3 Cocktail тесты 2025-02-19 16:00:45 +04:00
user
9d60cd4c17 В процессе работы с тестами 2025-02-19 12:42:25 +04:00
c841dc0821 Сданный вариант 2025-02-08 09:09:25 +04:00
user
63b0aa95bf Сделанный вариант 2025-02-08 01:09:11 +04:00
187 changed files with 15719 additions and 1 deletions

View File

@@ -0,0 +1,70 @@
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using System.Text.Json;
using System.Text.RegularExpressions;
using SquirrelContract.DataModels;
namespace SquirrelBusinessLogic.Implementations;
public 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,79 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
public class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;
public List<CocktailDataModel> GetAllCocktails()
{
_logger.LogInformation("GetAllCocktails");
return _cocktailStorageContract.GetList() ?? throw new NullListException();
}
public List<CocktailHistoryDataModel> GetCocktailHistoryByCocktail(string cocktailId)
{
_logger.LogInformation("GetCocktailHistoryByCocktail for {cocktailId}", cocktailId);
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _cocktailStorageContract.GetHistoryByCocktailId(cocktailId) ?? throw new NullListException();
}
public CocktailDataModel GetCocktailByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _cocktailStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _cocktailStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertCocktail(CocktailDataModel cocktailDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate();
_cocktailStorageContract.AddElement(cocktailDataModel);
}
public void UpdateCocktail(CocktailDataModel cocktailDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(cocktailDataModel));
ArgumentNullException.ThrowIfNull(cocktailDataModel);
cocktailDataModel.Validate();
_cocktailStorageContract.UpdElement(cocktailDataModel);
}
public void DeleteCocktail(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");
}
_cocktailStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
public 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,92 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? 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,63 @@
using BarBelochkaContract.DataModels;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
namespace SquirrelBusinessLogic.Implementations;
public 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, DateTime.SpecifyKind(finishDate, DateTimeKind.Utc), salary));
}
}
}

View File

@@ -0,0 +1,120 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class SaleBusinessLogicContract(ISaleStorageContract saleStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISaleBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
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> GetAllSalesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
if (!_warehouseStorageContract.CheckCocktails(saleDataModel))
{
throw new InsufficientStockException("Dont have cocktails in warehouse");
}
_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,103 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class SupplyBusinessLogicContract(ISupplyStorageContract supplyStorageContract, IWarehouseStorageContract warehouseStorageContract, ILogger logger) : ISupplyBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISupplyStorageContract _supplyStorageContract = supplyStorageContract;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _supplyStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSupplies params: {cocktailId}, {fromDate}, {toDate}", cocktailId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (cocktailId.IsEmpty())
{
throw new ArgumentNullException(nameof(cocktailId));
}
if (!cocktailId.IsGuid())
{
throw new ValidationException("The value in the field cocktailId is not a unique identifier.");
}
return _supplyStorageContract.GetList(fromDate, toDate, cocktailId: cocktailId) ?? throw new NullListException();
}
public SupplyDataModel GetSupplyByData(string data)
{
_logger.LogInformation("Get supply by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ElementNotFoundException(data);
}
return _supplyStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void ProcessSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Processing supply: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
foreach (var supplyCocktail in supplyDataModel.Cocktails)
{
var warehouses = _warehouseStorageContract.GetList();
var targetWarehouse = warehouses.FirstOrDefault(w =>
w.Cocktails.Any(c => c.CocktailId == supplyCocktail.CocktailId));
if (targetWarehouse == null)
{
targetWarehouse = warehouses.FirstOrDefault();
if (targetWarehouse == null)
{
throw new ElementNotFoundException("No warehouse found for supply.");
}
}
_warehouseStorageContract.UpdWarehouseOnSupply(targetWarehouse.Id, supplyCocktail.CocktailId, supplyCocktail.Count);
}
}
public void InsertSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.AddElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
public void UpdateSupply(SupplyDataModel supplyDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(supplyDataModel));
ArgumentNullException.ThrowIfNull(supplyDataModel);
supplyDataModel.Validate();
_supplyStorageContract.UpdateElement(supplyDataModel);
ProcessSupply(supplyDataModel);
}
}

View File

@@ -0,0 +1,65 @@
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
public class WarehouseBusinessLogicContract(IWarehouseStorageContract warehouseStorageContract, ILogger logger) : IWarehouseBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
public List<WarehouseDataModel> GetAllWarehouses()
{
_logger.LogInformation("GetAllWarehouses");
return _warehouseStorageContract.GetList() ?? throw new NullListException();
}
public WarehouseDataModel GetWarehouseByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _warehouseStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _warehouseStorageContract.GetElementByName(data) ?? throw new ElementNotFoundException(data);
}
public void InsertWarehouse(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.AddElement(warehouseDataModel);
}
public void UpdateWarehouse(WarehouseDataModel warehouseDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(warehouseDataModel));
ArgumentNullException.ThrowIfNull(warehouseDataModel);
warehouseDataModel.Validate();
_warehouseStorageContract.UpdElement(warehouseDataModel);
}
public void DeleteWarehouse(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");
}
_warehouseStorageContract.DelElement(id);
}
}

View File

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

View File

@@ -1,10 +1,18 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35707.178 d17.12
VisualStudioVersion = 17.12.35707.178
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelContract", "SquirrelContract\SquirrelContract.csproj", "{3B0E65D7-E64B-4893-803B-A59D9F2C8836}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelTests", "SquirrelTests\SquirrelTests.csproj", "{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelBusinessLogic", "SquirrelBusinessLogic\SquirrelBusinessLogic.csproj", "{C03D0604-CD06-42DA-99CB-23B8306C3714}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelDatabase", "SquirrelDatabase\SquirrelDatabase.csproj", "{A8A7A434-A278-4362-8D34-C2E3CAA938C1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelWebApi", "SquirrelWebApi\SquirrelWebApi.csproj", "{45D1F24F-AFCD-4259-88C2-3076E38254A9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,8 +23,27 @@ Global
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B0E65D7-E64B-4893-803B-A59D9F2C8836}.Release|Any CPU.Build.0 = Release|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CC02A7DA-AA53-4D19-BB16-4DDA5243EB33}.Release|Any CPU.Build.0 = Release|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C03D0604-CD06-42DA-99CB-23B8306C3714}.Release|Any CPU.Build.0 = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8A7A434-A278-4362-8D34-C2E3CAA938C1}.Release|Any CPU.Build.0 = Release|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{45D1F24F-AFCD-4259-88C2-3076E38254A9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E3B65E92-8603-4ED7-8214-9DA9A305DAFF}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,16 @@
namespace SquirrelContract.AdapterContracts;
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
public interface IClientAdapter
{
ClientOperationResponse GetList();
ClientOperationResponse GetElement(string data);
ClientOperationResponse RegisterClient(ClientBindingModel clientModel);
ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel);
ClientOperationResponse RemoveClient(string id);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.BindingModels;
using SquirrelContract.AdapterContracts.OperationResponses;
namespace SquirrelContract.AdapterContracts;
public interface ICocktailAdapter
{
CocktailOperationResponse GetList(bool includeDeleted);
CocktailOperationResponse GetHistory(string id);
CocktailOperationResponse GetElement(string data);
CocktailOperationResponse RegisterCocktail(CocktailBindingModel cocktailModel);
CocktailOperationResponse ChangeCocktailInfo(CocktailBindingModel cocktailModel);
CocktailOperationResponse RemoveCocktail(string id);
}

View File

@@ -0,0 +1,23 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface IEmployeeAdapter
{
EmployeeOperationResponse GetList(bool includeDeleted);
EmployeeOperationResponse GetPostList(string id, bool includeDeleted);
EmployeeOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
EmployeeOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
EmployeeOperationResponse GetElement(string data);
EmployeeOperationResponse RegisterEmployee(EmployeeBindingModel employeeModel);
EmployeeOperationResponse ChangeEmployeeInfo(EmployeeBindingModel employeeModel);
EmployeeOperationResponse RemoveEmployee(string id);
}

View File

@@ -0,0 +1,21 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface IPostAdapter
{
PostOperationResponse GetList();
PostOperationResponse GetHistory(string id);
PostOperationResponse GetElement(string data);
PostOperationResponse RegisterPost(PostBindingModel postModel);
PostOperationResponse ChangePostInfo(PostBindingModel postModel);
PostOperationResponse RemovePost(string id);
PostOperationResponse RestorePost(string id);
}

View File

@@ -0,0 +1,10 @@
using SquirrelContract.AdapterContracts.OperationResponses;
namespace SquirrelContract.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetListByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetListByPeriodByEmployee(DateTime fromDate, DateTime toDate, string employeeId);
SalaryOperationResponse CalculateSalary(DateTime date);
}

View File

@@ -0,0 +1,21 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface ISaleAdapter
{
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
SaleOperationResponse GetEmployeeList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetClientList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetElement(string id);
SaleOperationResponse MakeSale(SaleBindingModel saleModel);
SaleOperationResponse CancelSale(string id);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.BindingModels;
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.DataModels;
namespace SquirrelContract.AdapterContracts;
public interface ISupplyAdapter
{
SupplyOperationResponse GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate);
SupplyOperationResponse GetCocktailList(string id, DateTime fromDate, DateTime toDate);
SupplyOperationResponse GetSupplyByData(string data);
SupplyOperationResponse InsertSupply(SupplyBindingModel supplyDataModel);
SupplyOperationResponse UpdateSupply(SupplyBindingModel supplyDataModel);
}

View File

@@ -0,0 +1,13 @@
using SquirrelContract.AdapterContracts.OperationResponses;
using SquirrelContract.BindingModels;
namespace SquirrelContract.AdapterContracts;
public interface IWarehouseAdapter
{
WarehouseOperationResponse GetAllWarehouses();
WarehouseOperationResponse GetWarehouseByData(string data);
WarehouseOperationResponse InsertWarehouse(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse UpdateWarehouse(WarehouseBindingModel warehouseDataModel);
WarehouseOperationResponse DeleteWarehouse(string id);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class ClientOperationResponse : OperationResponse
{
public static ClientOperationResponse OK(List<ClientViewModel> data) => OK<ClientOperationResponse, List<ClientViewModel>>(data);
public static ClientOperationResponse OK(ClientViewModel data) => OK<ClientOperationResponse, ClientViewModel>(data);
public static ClientOperationResponse NoContent() => NoContent<ClientOperationResponse>();
public static ClientOperationResponse BadRequest(string message) => BadRequest<ClientOperationResponse>(message);
public static ClientOperationResponse NotFound(string message) => NotFound<ClientOperationResponse>(message);
public static ClientOperationResponse InternalServerError(string message) => InternalServerError<ClientOperationResponse>(message);
}

View File

@@ -0,0 +1,21 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class CocktailOperationResponse : OperationResponse
{
public static CocktailOperationResponse OK(List<CocktailViewModel> data) => OK<CocktailOperationResponse, List<CocktailViewModel>>(data);
public static CocktailOperationResponse OK(List<CocktailHistoryViewModel> data) => OK<CocktailOperationResponse, List<CocktailHistoryViewModel>>(data);
public static CocktailOperationResponse OK(CocktailViewModel data) => OK<CocktailOperationResponse, CocktailViewModel>(data);
public static CocktailOperationResponse NoContent() => NoContent<CocktailOperationResponse>();
public static CocktailOperationResponse NotFound(string message) => NotFound<CocktailOperationResponse>(message);
public static CocktailOperationResponse BadRequest(string message) => BadRequest<CocktailOperationResponse>(message);
public static CocktailOperationResponse InternalServerError(string message) => InternalServerError<CocktailOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class EmployeeOperationResponse : OperationResponse
{
public static EmployeeOperationResponse OK(List<EmployeeViewModel> data) => OK<EmployeeOperationResponse, List<EmployeeViewModel>>(data);
public static EmployeeOperationResponse OK(EmployeeViewModel data) => OK<EmployeeOperationResponse, EmployeeViewModel>(data);
public static EmployeeOperationResponse NoContent() => NoContent<EmployeeOperationResponse>();
public static EmployeeOperationResponse NotFound(string message) => NotFound<EmployeeOperationResponse>(message);
public static EmployeeOperationResponse BadRequest(string message) => BadRequest<EmployeeOperationResponse>(message);
public static EmployeeOperationResponse InternalServerError(string message) => InternalServerError<EmployeeOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class PostOperationResponse : OperationResponse
{
public static PostOperationResponse OK(List<PostViewModel> data) => OK<PostOperationResponse, List<PostViewModel>>(data);
public static PostOperationResponse OK(PostViewModel data) => OK<PostOperationResponse, PostViewModel>(data);
public static PostOperationResponse NoContent() => NoContent<PostOperationResponse>();
public static PostOperationResponse NotFound(string message) => NotFound<PostOperationResponse>(message);
public static PostOperationResponse BadRequest(string message) => BadRequest<PostOperationResponse>(message);
public static PostOperationResponse InternalServerError(string message) => InternalServerError<PostOperationResponse>(message);
}

View File

@@ -0,0 +1,13 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class SalaryOperationResponse : OperationResponse
{
public static SalaryOperationResponse OK(List<SalaryViewModel> data) => OK<SalaryOperationResponse, List<SalaryViewModel>>(data);
public static SalaryOperationResponse NoContent() => NoContent<SalaryOperationResponse>();
public static SalaryOperationResponse NotFound(string message) => NotFound<SalaryOperationResponse>(message);
public static SalaryOperationResponse BadRequest(string message) => BadRequest<SalaryOperationResponse>(message);
public static SalaryOperationResponse InternalServerError(string message) => InternalServerError<SalaryOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.ViewModels;
using SquirrelContract.Infrastructure;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class SaleOperationResponse : OperationResponse
{
public static SaleOperationResponse OK(List<SaleViewModel> data) => OK<SaleOperationResponse, List<SaleViewModel>>(data);
public static SaleOperationResponse OK(SaleViewModel data) => OK<SaleOperationResponse, SaleViewModel>(data);
public static SaleOperationResponse NoContent() => NoContent<SaleOperationResponse>();
public static SaleOperationResponse NotFound(string message) => NotFound<SaleOperationResponse>(message);
public static SaleOperationResponse BadRequest(string message) => BadRequest<SaleOperationResponse>(message);
public static SaleOperationResponse InternalServerError(string message) => InternalServerError<SaleOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class SupplyOperationResponse : OperationResponse
{
public static SupplyOperationResponse OK(List<SupplyViewModel> data) => OK<SupplyOperationResponse, List<SupplyViewModel>>(data);
public static SupplyOperationResponse OK(SupplyViewModel data) => OK<SupplyOperationResponse, SupplyViewModel>(data);
public static SupplyOperationResponse NoContent() => NoContent<SupplyOperationResponse>();
public static SupplyOperationResponse NotFound(string message) => NotFound<SupplyOperationResponse>(message);
public static SupplyOperationResponse BadRequest(string message) => BadRequest<SupplyOperationResponse>(message);
public static SupplyOperationResponse InternalServerError(string message) => InternalServerError<SupplyOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SquirrelContract.Infrastructure;
using SquirrelContract.ViewModels;
namespace SquirrelContract.AdapterContracts.OperationResponses;
public class WarehouseOperationResponse : OperationResponse
{
public static WarehouseOperationResponse OK(List<WarehouseViewModel> data) => OK<WarehouseOperationResponse, List<WarehouseViewModel>>(data);
public static WarehouseOperationResponse OK(WarehouseViewModel data) => OK<WarehouseOperationResponse, WarehouseViewModel>(data);
public static WarehouseOperationResponse NoContent() => NoContent<WarehouseOperationResponse>();
public static WarehouseOperationResponse NotFound(string message) => NotFound<WarehouseOperationResponse>(message);
public static WarehouseOperationResponse BadRequest(string message) => BadRequest<WarehouseOperationResponse>(message);
public static WarehouseOperationResponse InternalServerError(string message) => InternalServerError<WarehouseOperationResponse>(message);
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.BindingModels;
public class ClientBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.BindingModels;
public class CocktailBindingModel
{
public string? Id { get; set; }
public string? CocktailName { get; set; }
public double Price { get; set; }
public string? BaseAlcohol { get; set; }
}

View File

@@ -0,0 +1,16 @@
namespace SquirrelContract.BindingModels;
public class EmployeeBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? Email { get; set; }
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.BindingModels;
public class SaleBindingModel
{
public string? Id { get; set; }
public string? EmployeeId { get; set; }
public string? ClientId { get; set; }
public int DiscountType { get; set; }
public List<SaleCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.BindingModels;
public class SaleCocktailBindingModel
{
public string? SaleId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.BindingModels;
public class SupplyBindingModel
{
public string? Id { get; set; }
public DateTime SupplyDate { get; set; }
public int Count { get; set; }
public List<SupplyCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.BindingModels;
public class SupplyCocktailBindingModel
{
public string? SupplyId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.BindingModels;
public class WarehouseBindingModel
{
public string? Id { get; set; }
public string? Name { get; set; }
public int Count { get; set; }
public List<WarehouseCocktailBindingModel>? Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.BindingModels;
public class WarehouseCocktailBindingModel
{
public string? WarehouseId { get; set; }
public string? CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,16 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
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,18 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ICocktailBusinessLogicContract
{
List<CocktailDataModel> GetAllCocktails();
List<CocktailHistoryDataModel> GetCocktailHistoryByCocktail(string productId);
CocktailDataModel GetCocktailByData(string data);
void InsertCocktail(CocktailDataModel cocktailDataModel);
void UpdateCocktail(CocktailDataModel cocktailDataModel);
void DeleteCocktail(string id);
}

View File

@@ -0,0 +1,22 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
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,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts();
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,12 @@
using BarBelochkaContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
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,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
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> GetAllSalesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,17 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface ISupplyBusinessLogicContract
{
List<SupplyDataModel> GetAllSuppliesByPeriod(DateTime fromDate, DateTime toDate);
List<SupplyDataModel> GetAllSuppliesByCocktailByPeriod(string cocktailId, DateTime fromDate, DateTime toDate);
SupplyDataModel GetSupplyByData(string data);
void InsertSupply(SupplyDataModel supplyDataModel);
void UpdateSupply(SupplyDataModel supplyDataModel);
}

View File

@@ -0,0 +1,16 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.BusinessLogicContracts;
public interface IWarehouseBusinessLogicContract
{
List<WarehouseDataModel> GetAllWarehouses();
WarehouseDataModel GetWarehouseByData(string data);
void InsertWarehouse(WarehouseDataModel cocktailDataModel);
void UpdateWarehouse(WarehouseDataModel cocktailDataModel);
void DeleteWarehouse(string id);
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Text.RegularExpressions;
namespace SquirrelContract.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,32 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class CocktailDataModel(string id, string cocktailName, double price, AlcoholType baseAlcohol) : IValidation
{
public string Id { get; private set; } = id;
public string CocktailName { get; private set; } = cocktailName;
public double Price { get; private set; } = price;
public AlcoholType BaseAlcohol { get; private set; } = baseAlcohol;
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 (CocktailName.IsEmpty())
throw new ValidationException("Field CocktailName is empty");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
if (BaseAlcohol == AlcoholType.None)
throw new ValidationException("Field BaseAlcohol is empty");
}
}

View File

@@ -0,0 +1,36 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class CocktailHistoryDataModel(string cocktailId, double oldPrice) : IValidation
{
private readonly CocktailDataModel? _cocktail;
public string CocktailId { get; private set; } = cocktailId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
public CocktailHistoryDataModel(string cocktailId, double oldPrice, DateTime changeDate, CocktailDataModel cocktail) : this(cocktailId, oldPrice)
{
ChangeDate = changeDate;
_cocktail = cocktail;
}
public void Validate()
{
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId 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,67 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Text.RegularExpressions;
namespace SquirrelContract.DataModels;
public class EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted) : IValidation
{
private readonly PostDataModel? _post;
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 string PostName => _post?.PostName ?? string.Empty;
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, email, postId, birthDate, employmentDate, isDeleted)
{
_post = post;
}
public EmployeeDataModel(string id, string fio, string email, string postId, DateTime birthDate, DateTime employmentDate) : this(id, fio, email, postId, birthDate, employmentDate, false) { }
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) // EmploymentDate.Year - BirthDate.Year
throw new ValidationException($"Only adults can be hired (EmploymentDate - {EmploymentDate.ToShortDateString()}, BirthDate - {BirthDate.ToShortDateString()})");
}
}

View File

@@ -0,0 +1,35 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
{
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public 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,36 @@
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace BarBelochkaContract.DataModels;
public class SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary) : IValidation
{
private readonly EmployeeDataModel? _employee;
public string EmployeeId { get; private set; } = employeeId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = employeeSalary;
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
public SalaryDataModel(string employeeId, DateTime salaryDate, double employeeSalary, EmployeeDataModel employee) : this(employeeId, salaryDate, employeeSalary)
{
_employee = employee;
}
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,46 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleCocktailDataModel(string saleId, string cocktailId, int count, double price) : IValidation
{
private readonly CocktailDataModel? _cocktail;
public string SaleId { get; private set; } = saleId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string CocktailName => _cocktail?.CocktailName ?? string.Empty;
public SaleCocktailDataModel(string saleId, string cocktailId, int count, double price, CocktailDataModel cocktail) : this(saleId, cocktailId, count, price)
{
_cocktail = cocktail;
}
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 (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId is not a unique identifier");
if (Count <= 0)
throw new ValidationException("Field Count is less than or equal to 0");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -0,0 +1,102 @@
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleDataModel : IValidation
{
private readonly ClientDataModel? _client;
private readonly EmployeeDataModel? _employee;
public string Id { get; private set; }
public string EmployeeId { get; private set; }
public string? ClientId { get; private set; }
public DateTime SaleDate { get; private set; } = DateTime.UtcNow;
public double Sum { get; private set; }
public DiscountType DiscountType { get; private set; }
public double Discount { get; private set; }
public bool IsCancel { get; private set; }
public List<SaleCocktailDataModel>? Cocktails { get; private set; }
public string ClientFIO => _client?.FIO ?? string.Empty;
public string EmployeeFIO => _employee?.FIO ?? string.Empty;
public SaleDataModel(string id, string employeeId, string? clientId, DiscountType discountType, bool isCancel, List<SaleCocktailDataModel> saleCocktails)
{
Id = id;
EmployeeId = employeeId;
ClientId = clientId;
DiscountType = discountType;
IsCancel = isCancel;
Cocktails = saleCocktails;
var percent = 0.0;
foreach (DiscountType elem in Enum.GetValues<DiscountType>())
{
if ((elem & discountType) != 0)
{
switch (elem)
{
case DiscountType.None:
break;
case DiscountType.OnSale:
percent += 0.1;
break;
case DiscountType.RegularCustomer:
percent += 0.5;
break;
case DiscountType.Certificate:
percent += 0.3;
break;
}
}
}
Sum = Cocktails?.Sum(x => x.Price * x.Count) ?? 0;
Discount = Sum * percent;
}
public SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> saleCocktails, EmployeeDataModel employee, ClientDataModel? client) : this(id, employeeId, clientId, discountType, isCancel, saleCocktails)
{
Sum = sum;
Discount = discount;
_employee = employee;
_client = client;
}
public SaleDataModel(string id, string employeeId, string? clientId, int discountType, List<SaleCocktailDataModel> cocktails) : this(id, employeeId, clientId, (DiscountType)discountType, false, cocktails) { }
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 ClientId is not a unique identifier");
if (Sum <= 0)
throw new ValidationException("Field Sum is less than or equal to 0");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The sale must include cocktails");
}
}

View File

@@ -0,0 +1,33 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.ComponentModel;
namespace SquirrelContract.DataModels;
public class SupplyCocktailDataModel(string? supplyId, string? cocktailId, int count) : IValidation
{
public string SupplyId { get; private set; } = supplyId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (SupplyId.IsEmpty())
throw new ValidationException("Field SupplyId is empty");
if (!SupplyId.IsGuid())
throw new ValidationException("The value in the field SupplyId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId 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,29 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SupplyDataModel(string id, DateTime supplyDate, List<SupplyCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public DateTime SupplyDate { get; private set; } = supplyDate;
public List<SupplyCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 (SupplyDate.Date > DateTime.Now)
throw new ValidationException($"It is impossible to supply things in the future");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The components must include products");
}
}

View File

@@ -0,0 +1,32 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class WarehouseCocktailDataModel(string? warehouseId, string? cocktailId, int count) : IValidation
{
public string WarehouseId { get; private set; } = warehouseId;
public string CocktailId { get; private set; } = cocktailId;
public int Count { get; private set; } = count;
public void Validate()
{
if (WarehouseId.IsEmpty())
throw new ValidationException("Field WarehouseId is empty");
if (!WarehouseId.IsGuid())
throw new ValidationException("The value in the field WarehouseId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field CocktailId 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,30 @@
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using System.Xml.Linq;
namespace SquirrelContract.DataModels;
public class WarehouseDataModel(string? id, string name, List<WarehouseCocktailDataModel> cocktails) : IValidation
{
public string Id { get; private set; } = id;
public string Name { get; private set; } = name;
public List<WarehouseCocktailDataModel> Cocktails { get; private set; } = cocktails;
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 (Name.IsEmpty())
throw new ValidationException("Field Name is empty");
if ((Cocktails?.Count ?? 0) == 0)
throw new ValidationException("The cocktails must include drinks");
}
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelContract.Enums;
public enum AlcoholType
{
None = 0,
Vodka = 1,
Whiskey = 2,
Wine = 3,
Beer = 4
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelContract.Enums;
[Flags]
public enum DiscountType
{
None = 0,
OnSale = 1,
RegularCustomer = 2,
Certificate = 4
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.Enums;
public enum PostType
{
None = 0,
Bartender = 1,
Manager = 2,
PurchasingSpecialist = 3
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item (id: {id})") { }
}

View File

@@ -0,0 +1,11 @@
namespace SquirrelContract.Exceptions;
public class ElementNotFoundException : Exception
{
public string Value { get; private set; }
public ElementNotFoundException(string value) : base($"Element not found at value = {value}")
{
Value = value;
}
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.Exceptions;
public class ElementExistsException : Exception
{
public string ParamName { get; private set; }
public string ParamValue { get; private set; }
public ElementExistsException(string paramName, string paramValue) : base($"There is already an element with value{paramValue} of parameter {paramName}")
{
ParamName = paramName;
ParamValue = paramValue;
}
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.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,5 @@
namespace SquirrelContract.Exceptions;
public class InsufficientStockException(string message) : Exception(message)
{
}

View File

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

View File

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

View File

@@ -0,0 +1,5 @@
namespace SquirrelContract.Exceptions;
public class ValidationException(string message) : Exception(message)
{
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.Extensions;
public static class DateTimeExtensions
{
public static bool IsDateNotOlder(this DateTime date, DateTime olderDate)
{
return date >= olderDate;
}
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelContract.Extensions;
public static class StringExtensions
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
public static bool IsGuid(this string str)
{
return Guid.TryParse(str, out _);
}
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Infastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -0,0 +1,6 @@
namespace SquirrelContract.Infastructure;
public interface IValidation
{
void Validate();
}

View File

@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace SquirrelContract.Infrastructure;
public class OperationResponse
{
public HttpStatusCode StatusCode { get; set; }
public object? Result { get; set; }
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(response);
response.StatusCode = (int)StatusCode;
if (Result is null)
{
return new StatusCodeResult((int)StatusCode);
}
return new ObjectResult(Result);
}
protected static TResult OK<TResult, TData>(TData data) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data };
protected static TResult NoContent<TResult>() where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
protected static TResult BadRequest<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
protected static TResult NotFound<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
protected static TResult InternalServerError<TResult>(string? errorMessage = null) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
}

View File

@@ -6,4 +6,9 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.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,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ICocktailStorageContract
{
List<CocktailDataModel> GetList();
List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId);
CocktailDataModel? GetElementById(string id);
CocktailDataModel? GetElementByName(string name);
void AddElement(CocktailDataModel cocktailDataModel);
void UpdElement(CocktailDataModel cocktailDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,20 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.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,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList();
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,10 @@
using BarBelochkaContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,14 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,11 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface ISupplyStorageContract
{
List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null);
SupplyDataModel? GetElementById(string id);
void AddElement(SupplyDataModel warehouseDataModel);
void UpdateElement(SupplyDataModel warehouseDataModel);
}

View File

@@ -0,0 +1,15 @@
using SquirrelContract.DataModels;
namespace SquirrelContract.StoragesContracts;
public interface IWarehouseStorageContract
{
List<WarehouseDataModel> GetList();
WarehouseDataModel? GetElementByName(string name);
WarehouseDataModel? GetElementById(string id);
void AddElement(WarehouseDataModel warehouseDataModel);
void UpdElement(WarehouseDataModel warehouseDataModel);
void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count);
void DelElement(string id);
bool CheckCocktails(SaleDataModel saleDataModel);
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.ViewModels;
public class ClientViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace SquirrelContract.ViewModels;
public class CocktailHistoryViewModel
{
public required string CocktailName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,13 @@
namespace SquirrelContract.ViewModels;
public class CocktailViewModel
{
public required string Id { get; set; }
public required string CocktailName { get; set; }
public required string BaseAlcohol { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,20 @@
namespace SquirrelContract.ViewModels;
public class EmployeeViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { get; set; }
public required string PostId { get; set; }
public required string PostName { get; set; }
public bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.ViewModels;
public class SalaryViewModel
{
public required string EmployeeId { get; set; }
public required string EmployeeFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SquirrelContract.ViewModels;
public class SaleCocktailViewModel
{
public required string CocktailId { get; set; }
public required string CocktailName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,26 @@
namespace SquirrelContract.ViewModels;
public class SaleViewModel
{
public required string Id { get; set; }
public required string EmployeeId { get; set; }
public required string EmployeeFIO { get; set; }
public string? ClientId { get; set; }
public string? ClientFIO { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public required string DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public required List<SaleCocktailViewModel> Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.ViewModels;
public class SupplyCocktailViewModel
{
public required string SupplyId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.ViewModels;
public class SupplyViewModel
{
public required string Id { get; set; }
public DateTime SupplyDate { get; set; }
public int Count { get; set; }
public required List<SupplyCocktailViewModel> Cocktails { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SquirrelContract.ViewModels;
public class WarehouseCocktailViewModel
{
public required string WarehouseId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace SquirrelContract.ViewModels;
public class WarehouseViewModel
{
public required string Id { get; set; }
public required string Name { get; set; }
public required int Count { get; set; }
public required List<WarehouseCocktailViewModel> Cocktails { get; set; }
}

View File

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

View File

@@ -0,0 +1,179 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class CocktailStorageContract : ICocktailStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public CocktailStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<CocktailDataModel, Cocktail>();
cfg.CreateMap<CocktailHistory, CocktailHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<CocktailDataModel> GetList()
{
try
{
return [.. _dbContext.Cocktails.Select(x => _mapper.Map<CocktailDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CocktailHistoryDataModel> GetHistoryByCocktailId(string cocktailId)
{
try
{
return [.. _dbContext.CocktailHistories.Include(x => x.Cocktail).Where(x => x.CocktailId == cocktailId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<CocktailHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<CocktailDataModel>(GetCocktailById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CocktailDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<CocktailDataModel>(_dbContext.Cocktails.FirstOrDefault(x => x.CocktailName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(CocktailDataModel cocktailDataModel)
{
try
{
_dbContext.Cocktails.Add(_mapper.Map<Cocktail>(cocktailDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", cocktailDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(CocktailDataModel cocktailDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetCocktailById(cocktailDataModel.Id) ?? throw new ElementNotFoundException(cocktailDataModel.Id);
if (element.Price != cocktailDataModel.Price)
{
_dbContext.CocktailHistories.Add(new CocktailHistory() { CocktailId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Cocktails.Update(_mapper.Map(cocktailDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Cocktails_CocktailName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("CocktailName", cocktailDataModel.CocktailName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Cocktails.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void ResElement(string id)
{
try
{
var element = GetCocktailById(id) ?? throw new ElementNotFoundException(id);
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Cocktail? GetCocktailById(string id) => _dbContext.Cocktails.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,163 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class EmployeeStorageContract : IEmployeeStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public EmployeeStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<EmployeeDataModel, Employee>();
});
_mapper = new Mapper(config);
}
public List<EmployeeDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Employees.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= DateTime.SpecifyKind(fromBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.BirthDate <= DateTime.SpecifyKind(toBirthDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= DateTime.SpecifyKind(fromEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc) && x.EmploymentDate <= DateTime.SpecifyKind(toEmploymentDate ?? DateTime.UtcNow, DateTimeKind.Utc));
}
return [.. JoinPost(query).Select(x => _mapper.Map<EmployeeDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<EmployeeDataModel>(GetEmployeeById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public EmployeeDataModel? GetElementByEmail(string email)
{
try
{
return _mapper.Map<EmployeeDataModel>(AddPost(_dbContext.Employees.FirstOrDefault(x => x.Email == email && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(EmployeeDataModel employeeDataModel)
{
try
{
_dbContext.Employees.Add(_mapper.Map<Employee>(employeeDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", employeeDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(EmployeeDataModel employeeDataModel)
{
try
{
var element = GetEmployeeById(employeeDataModel.Id) ?? throw new ElementNotFoundException(employeeDataModel.Id);
_dbContext.Employees.Update(_mapper.Map(employeeDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetEmployeeById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Employee? GetEmployeeById(string id) => AddPost(_dbContext.Employees.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Employee> JoinPost(IQueryable<Employee> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Employee = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Employee.AddPost(y));
private Employee? AddPost(Employee? employee)
=> employee?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == employee.PostId && x.IsActual));
}

View File

@@ -0,0 +1,185 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class PostStorageContract : IPostStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.CreateMap<PostDataModel, Post>()
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
});
_mapper = new Mapper(config);
}
public List<PostDataModel> GetList()
{
try
{
return [.. _dbContext.Posts.Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<PostDataModel> GetPostWithHistory(string postId)
{
try
{
return [.. _dbContext.Posts.Where(x => x.PostId == postId).Select(x => _mapper.Map<PostDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostId == id && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public PostDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<PostDataModel>(_dbContext.Posts.FirstOrDefault(x => x.PostName == name && x.IsActual));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(PostDataModel postDataModel)
{
try
{
_dbContext.Posts.Add(_mapper.Map<Post>(postDataModel));
_dbContext.SaveChanges();
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostId_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostId", postDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(PostDataModel postDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetPostById(postDataModel.Id) ?? throw new ElementNotFoundException(postDataModel.Id);
if (!element.IsActual)
{
throw new ElementDeletedException(postDataModel.Id);
}
element.IsActual = false;
_dbContext.SaveChanges();
var newElement = _mapper.Map<Post>(postDataModel);
_dbContext.Posts.Add(newElement);
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Posts_PostName_IsActual" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("PostName", postDataModel.PostName);
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
if (!element.IsActual)
{
throw new ElementDeletedException(id);
}
element.IsActual = false;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
public void ResElement(string id)
{
try
{
var element = GetPostById(id) ?? throw new ElementNotFoundException(id);
element.IsActual = true;
_dbContext.SaveChanges();
}
catch
{
_dbContext.ChangeTracker.Clear();
throw;
}
}
private Post? GetPostById(string id) => _dbContext.Posts.Where(x => x.PostId == id).OrderByDescending(x => x.ChangeDate).FirstOrDefault();
}

View File

@@ -0,0 +1,62 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class SalaryStorageContract : ISalaryStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.EmployeeSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null)
{
try
{
var query = _dbContext.Salaries.Include(d => d.Employee).AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SalaryDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SalaryDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SalaryDataModel salaryDataModel)
{
try
{
_dbContext.Salaries.Add(_mapper.Map<Salary>(salaryDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

@@ -0,0 +1,120 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace SquirrelDatabase.Implementations;
public class SaleStorageContract : ISaleStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Client, ClientDataModel>();
cfg.CreateMap<Cocktail, CocktailDataModel>();
cfg.CreateMap<Employee, EmployeeDataModel>();
cfg.CreateMap<SaleCocktail, SaleCocktailDataModel>();
cfg.CreateMap<SaleCocktailDataModel, SaleCocktail>()
.ForMember(x => x.Cocktail, x => x.Ignore());
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleCocktails, x => x.MapFrom(src => src.Cocktails))
.ForMember(x => x.Employee, x => x.Ignore())
.ForMember(x => x.Client, x => x.Ignore());
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? employeeId = null, string? clientId = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Sales
.Include(r => r.Employee)
.Include(r => r.Client)
.Include(r => r.SaleCocktails)!
.ThenInclude(d => d.Cocktail)
.AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SaleDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SaleDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (employeeId != null)
query = query.Where(x => x.EmployeeId == employeeId);
if (clientId != null)
query = query.Where(x => x.ClientId == clientId);
if (cocktailId != null)
query = query.Where(x => x.SaleCocktails!.Any(y => y.CocktailId == cocktailId));
var s = query.ToList();
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SaleDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<SaleDataModel>(GetSaleById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SaleDataModel saleDataModel)
{
try
{
_dbContext.Sales.Add(_mapper.Map<Sale>(saleDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetSaleById(id) ?? throw new ElementNotFoundException(id);
if (element.IsCancel)
{
throw new ElementDeletedException(id);
}
element.IsCancel = true;
_dbContext.SaveChanges();
}
catch (Exception ex) when (ex is ElementDeletedException || ex is ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Sale? GetSaleById(string id) => _dbContext.Sales.Include(x => x.Client).Include(x => x.Employee).Include(x => x.SaleCocktails)!.ThenInclude(x => x.Cocktail).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,100 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
using System;
namespace SquirrelDatabase.Implementations;
public class SupplyStorageContract : ISupplyStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly IMapper _mapper;
public SupplyStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SupplyCocktail, SupplyCocktailDataModel>();
cfg.CreateMap<SupplyCocktailDataModel, SupplyCocktail>();
cfg.CreateMap<Supply, SupplyDataModel>();
cfg.CreateMap<SupplyDataModel, Supply>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<SupplyDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? cocktailId = null)
{
try
{
var query = _dbContext.Supplies.Include(x => x.Cocktails).AsQueryable();
if (startDate.HasValue)
query = query.Where(x => x.SupplyDate >= DateTime.SpecifyKind(startDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (endDate.HasValue)
query = query.Where(x => x.SupplyDate <= DateTime.SpecifyKind(endDate ?? DateTime.UtcNow, DateTimeKind.Utc));
if (cocktailId is not null)
{
query = query.Where(x => x.Cocktails!.Any(y => y.CocktailId == cocktailId));
}
return [.. query.Select(x => _mapper.Map<SupplyDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public SupplyDataModel GetElementById(string id)
{
try
{
return _mapper.Map<SupplyDataModel>(GetSuppliesById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(SupplyDataModel suppliesDataModel)
{
try
{
_dbContext.Supplies.Add(_mapper.Map<Supply>(suppliesDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdateElement(SupplyDataModel suppliesDataModel)
{
try
{
var element = GetSuppliesById(suppliesDataModel.Id) ?? throw new ElementNotFoundException(suppliesDataModel.Id);
_dbContext.Supplies.Update(_mapper.Map(suppliesDataModel, element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Supply? GetSuppliesById(string id) => _dbContext.Supplies.FirstOrDefault(x => x.Id == id);
}

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