38 Commits

Author SHA1 Message Date
user
36ace5c8ef 5hard finish 2025-05-01 18:56:26 +04:00
user
7858a8c491 merge 2025-05-01 15:51:25 +04:00
user
9d12ff2500 вроде доделал тесты адаптера 2025-04-20 23:22:17 +04:00
c28acf5bd5 В процессе написания адаптер тестов 2025-04-20 14:54:37 +04:00
b2cf602602 сданный вариант 2025-04-19 10:23:03 +04:00
user
0eda3b21b0 Вроде всё 2025-04-19 00:52:05 +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
user
bb89dd1952 Почти готово 2025-04-09 01:58:17 +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
user
21258b1c31 Вроде все сделанно 2025-02-21 22:47:51 +04:00
9730a641c4 Сделал datamodels 2025-02-21 17:37:05 +04:00
174 changed files with 13939 additions and 206 deletions

View File

@@ -9,7 +9,7 @@ using SquirrelContract.DataModels;
namespace SquirrelBusinessLogic.Implementations;
internal class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
public class ClientBusinessLogicContract(IClientStorageContract clientStorageContract, ILogger logger) : IClientBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IClientStorageContract _clientStorageContract = clientStorageContract;

View File

@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
public class CocktailBusinessLogicContract(ICocktailStorageContract cocktailStorageContract, ILogger logger) : ICocktailBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ICocktailStorageContract _cocktailStorageContract = cocktailStorageContract;

View File

@@ -9,7 +9,7 @@ using System.Text.RegularExpressions;
namespace SquirrelBusinessLogic.Implementations;
internal class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
public class EmployeeBusinessLogicContract(IEmployeeStorageContract employeeStorageContract, ILogger logger) : IEmployeeBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IEmployeeStorageContract _employeeStorageContract = employeeStorageContract;

View File

@@ -8,14 +8,14 @@ using System.Text.Json;
namespace SquirrelBusinessLogic.Implementations;
internal class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
public class PostBusinessLogicContract(IPostStorageContract postStorageContract, ILogger logger) : IPostBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)

View File

@@ -1,20 +1,26 @@
using BarBelochkaContract.DataModels;
using Microsoft.Extensions.Logging;
using SquirrelContract.BusinessLogicContracts;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Infastructure.PostConfigurations;
using SquirrelContract.StoragesContracts;
namespace SquirrelBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger) : ISalaryBusinessLogicContract
public class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IEmployeeStorageContract employeeStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : 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;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}", fromDate, toDate);
@@ -51,13 +57,70 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
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;
var sales = _saleStorageContract.GetList(startDate, finishDate, employeeId: employee.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(employee.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
BartenderPostConfiguration cpc => CalculateSalaryForBartender(sales, startDate, finishDate, cpc),
ManagerPostConfiguration spc => CalculateSalaryForManager(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {employeeId} was paid a salary of {salary}", employee.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(employee.Id, finishDate, salary));
}
}
private double CalculateSalaryForBartender(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, BartenderPostConfiguration config)
{
var calcPercent = 0.0;
var days = (finishDate - startDate).Days;
var dates = Enumerable.Range(0, days)
.Select(offset => startDate.AddDays(offset))
.ToList();
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
Parallel.ForEach(dates, parallelOptions, date =>
{
var salesInDay = sales.Where(x => x.SaleDate.Date == date.Date).ToArray();
if (salesInDay.Length == 0) return;
double dailySum = salesInDay.Sum(x => x.Sum);
double averageSale = dailySum / salesInDay.Length;
lock (_lockObject)
{
calcPercent += averageSale * config.SalePercent;
}
});
double bonus = 0;
try
{
bonus = sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum)
.Sum(x => x.Sum) * config.BonusForExtraSales;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in bonus calculation");
}
return config.Rate + calcPercent + bonus;
}
private double CalculateSalaryForManager(DateTime startDate, DateTime finishDate, ManagerPostConfiguration config)
{
try
{
return config.Rate + config.PersonalCountTrendPremium * _employeeStorageContract.GetEmployeeTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the supervisor payroll process");
return 0;
}
}
}

View File

@@ -5,14 +5,16 @@ using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.StoragesContracts;
using System.Text.Json;
using System.Threading;
namespace SquirrelBusinessLogic.Implementations;
internal class SaleBusinessLogicContract(ISaleStorageContract
saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
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;
private readonly Lock _lockObject = new();
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -24,6 +26,46 @@ saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public double CalculateTotalRevenue(DateTime fromDate, DateTime toDate)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
var sales = _saleStorageContract.GetList(fromDate, toDate);
var salesByDay = sales
.Where(x => !x.IsCancel)
.GroupBy(x => x.SaleDate.Date)
.ToList();
var revenue = 0.0;
try
{
Parallel.ForEach(salesByDay, group =>
{
var daySum = group.Sum(x => x.Sum - x.Discount);
lock (_lockObject)
{
revenue += daySum;
}
});
}
catch (AggregateException agEx)
{
foreach (var ex in agEx.InnerExceptions)
{
_logger.LogError(ex, "Error in the cashier payroll process");
}
return 0;
}
return revenue;
}
public List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {employeeId}, {fromDate}, {toDate}", employeeId, fromDate, toDate);
@@ -97,6 +139,10 @@ saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
_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);
}

View File

@@ -0,0 +1,124 @@
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 int CountByPeriod(DateTime fromDate, DateTime toDate)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
var supplies = _supplyStorageContract.GetList(fromDate, toDate);
int count = 0;
var lockObject = new object();
Parallel.ForEach(supplies, supply =>
{
int supplyCount = supply.Cocktails.Sum(c => c.Count);
if (supplyCount > 0)
{
Interlocked.Add(ref count, supplyCount);
}
});
return count;
}
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,87 @@
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, ISupplyStorageContract supplyStorageContract, ISaleStorageContract saleStorageContract, ILogger logger) : IWarehouseBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWarehouseStorageContract _warehouseStorageContract = warehouseStorageContract;
private readonly ISupplyStorageContract _supplyStorageContract = supplyStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
public List<WarehouseDataModel> GetAllWarehouses()
{
_logger.LogInformation("GetAllWarehouses");
return _warehouseStorageContract.GetList() ?? throw new NullListException();
}
public async Task<int> GetCocktailStockCountAsync()
{
var incomingTask = Task.Run(() =>
{
var supplies = _supplyStorageContract.GetList();
return supplies.SelectMany(x => x.Cocktails).Sum(x => x.Count);
});
var outcomingTask = Task.Run(() =>
{
var sales = _saleStorageContract.GetList();
return sales.SelectMany(x => x.Cocktails).Sum(x => x.Count);
});
await Task.WhenAll(incomingTask, outcomingTask);
return incomingTask.Result - outcomingTask.Result;
}
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

@@ -12,7 +12,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.3" />
</ItemGroup>
<ItemGroup>

View File

@@ -9,6 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SquirrelTests", "SquirrelTe
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
@@ -27,8 +31,19 @@ Global
{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 string? ConfigurationJson { 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

@@ -4,7 +4,7 @@ namespace SquirrelContract.BusinessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);

View File

@@ -6,6 +6,8 @@ public interface ISaleBusinessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
double CalculateTotalRevenue(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByEmployeeByPeriod(string employeeId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByClientByPeriod(string clientId, DateTime fromDate, DateTime toDate);

View File

@@ -0,0 +1,19 @@
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);
int CountByPeriod(DateTime fromDate, DateTime toDate);
SupplyDataModel GetSupplyByData(string data);
void InsertSupply(SupplyDataModel supplyDataModel);
void UpdateSupply(SupplyDataModel supplyDataModel);
}

View File

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

View File

@@ -6,12 +6,22 @@ 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())

View File

@@ -7,6 +7,8 @@ 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;
@@ -21,6 +23,15 @@ public class EmployeeDataModel(string id, string fio, string email, string postI
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())

View File

@@ -1,23 +1,36 @@
using SquirrelContract.Enums;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SquirrelContract.Enums;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
using SquirrelContract.Infastructure.PostConfigurations;
namespace SquirrelContract.DataModels;
public class PostDataModel(string id, string postName, PostType postType, double salary, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = id;
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 PostConfiguration ConfigurationModel { get; private set; } = configuration;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(BartenderPostConfiguration) => JsonConvert.DeserializeObject<BartenderPostConfiguration>(configurationJson)!,
nameof(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
@@ -33,7 +46,9 @@ public class PostDataModel(string id, string postName, PostType postType, double
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -1,4 +1,5 @@
using SquirrelContract.Exceptions;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.Extensions;
using SquirrelContract.Infastructure;
@@ -6,12 +7,21 @@ 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())

View File

@@ -4,14 +4,25 @@ using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleCocktailDataModel(string saleId, string cocktailId, int count) : IValidation
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())
@@ -21,12 +32,15 @@ public class SaleCocktailDataModel(string saleId, string cocktailId, int count)
throw new ValidationException("The value in the field SaleId is not a unique identifier");
if (CocktailId.IsEmpty())
throw new ValidationException("Field ProductId is empty");
throw new ValidationException("Field CocktailId is empty");
if (!CocktailId.IsGuid())
throw new ValidationException("The value in the field ProductId is not a unique identifier");
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

@@ -5,25 +5,76 @@ using SquirrelContract.Infastructure;
namespace SquirrelContract.DataModels;
public class SaleDataModel(string id, string employeeId, string? clientId, double sum, DiscountType discountType, double discount, bool isCancel, List<SaleCocktailDataModel> cocktails) : IValidation
public class SaleDataModel : IValidation
{
public string Id { get; private set; } = id;
private readonly ClientDataModel? _client;
public string EmployeeId { get; private set; } = employeeId;
private readonly EmployeeDataModel? _employee;
public string? ClientId { get; private set; } = clientId;
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; } = sum;
public double Sum { get; private set; }
public DiscountType DiscountType { get; private set; } = discountType;
public DiscountType DiscountType { get; private set; }
public double Discount { get; private set; } = discount;
public double Discount { get; private set; }
public bool IsCancel { get; private set; } = isCancel;
public bool IsCancel { get; private set; }
public List<SaleCocktailDataModel> Cocktails { get; private set; } = cocktails;
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()
{
@@ -40,7 +91,7 @@ public class SaleDataModel(string id, string employeeId, string? clientId, doubl
throw new ValidationException("The value in the field EmployeeId is not a unique identifier");
if (!ClientId?.IsGuid() ?? !ClientId?.IsEmpty() ?? false)
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
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");

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

View File

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

View File

@@ -0,0 +1,7 @@
namespace SquirrelContract.Infastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxConcurrentThreads { get; }
}

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

@@ -0,0 +1,17 @@
using Microsoft.Extensions.Configuration;
namespace SquirrelContract.Infastructure.PostConfigurations;
public class BartenderPostConfiguration : PostConfiguration
{
public override string Type => nameof(BartenderPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
public BartenderPostConfiguration(IConfiguration? config = null)
{
if (config != null)
{
config.GetSection("BartenderSettings");
}
}
}

View File

@@ -0,0 +1,7 @@
namespace SquirrelContract.Infastructure.PostConfigurations;
public class ManagerPostConfiguration : PostConfiguration
{
public override string Type => nameof(ManagerPostConfiguration);
public double PersonalCountTrendPremium { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace SquirrelContract.Infastructure.PostConfigurations;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
}

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

@@ -17,4 +17,6 @@ public interface IEmployeeStorageContract
void UpdElement(EmployeeDataModel employeeDataModel);
void DelElement(string id);
int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);

View File

@@ -4,7 +4,7 @@ namespace SquirrelContract.StoragesContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime startDate, DateTime endDate, string? employeeId = null);
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? employeeId = null);
void AddElement(SalaryDataModel salaryDataModel);
}

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 required string Configuration { 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,8 @@
using SquirrelContract.Infastructure;
namespace SquirrelDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

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,178 @@
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);
}
}
public int GetEmployeeTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Employees.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Employees.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
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,187 @@
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))
.ForMember(x => x.Configuration, x => x.MapFrom(src =>
src.ConfigurationModel));
});
_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);
}

View File

@@ -0,0 +1,211 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SquirrelContract.DataModels;
using SquirrelContract.Exceptions;
using SquirrelContract.StoragesContracts;
using SquirrelDatabase.Models;
namespace SquirrelDatabase.Implementations;
public class WarehouseStorageContract : IWarehouseStorageContract
{
private readonly SquirrelDbContext _dbContext;
private readonly Mapper _mapper;
public WarehouseStorageContract(SquirrelDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<WarehouseCocktail, WarehouseCocktailDataModel>();
cfg.CreateMap<WarehouseCocktailDataModel, WarehouseCocktail>();
cfg.CreateMap<Warehouse, WarehouseDataModel>();
cfg.CreateMap<WarehouseDataModel, Warehouse>()
.ForMember(x => x.Cocktails, x => x.MapFrom(src => src.Cocktails));
});
_mapper = new Mapper(config);
}
public List<WarehouseDataModel> GetList()
{
try
{
return [.. _dbContext.Warehouses.Select(x => _mapper.Map<WarehouseDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementById(string id)
{
try
{
return _mapper.Map<WarehouseDataModel>(GetWarehouseById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WarehouseDataModel GetElementByName(string name)
{
try
{
return _mapper.Map<WarehouseDataModel>(_dbContext.Warehouses.FirstOrDefault(x => x.Name == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WarehouseDataModel warehouseDataModel)
{
try
{
_dbContext.Warehouses.Add(_mapper.Map<Warehouse>(warehouseDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WarehouseDataModel warehouseDataModel)
{
try
{
var element = GetWarehouseById(warehouseDataModel.Id) ?? throw new ElementNotFoundException(warehouseDataModel.Id);
_dbContext.Warehouses.Update(_mapper.Map(warehouseDataModel, 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 = GetWarehouseById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Warehouses.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdWarehouseOnSupply(string warehouseId, string cocktailId, int count)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
var warehouse = _dbContext.Warehouses
.Include(w => w.Cocktails)
.FirstOrDefault(w => w.Id == warehouseId);
if (warehouse == null)
{
throw new ElementNotFoundException($"Warehouse with id {warehouseId} not found.");
}
var warehouseCocktail = warehouse.Cocktails.FirstOrDefault(c => c.CocktailId == cocktailId);
if (warehouseCocktail != null)
{
warehouseCocktail.Count += count;
}
else
{
warehouse.Cocktails.Add(new WarehouseCocktail
{
WarehouseId = warehouseId,
CocktailId = cocktailId,
Count = count
});
}
_dbContext.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public bool CheckCocktails(SaleDataModel saleDataModel)
{
using var transaction = _dbContext.Database.BeginTransaction();
try
{
foreach (var saleCocktail in saleDataModel.Cocktails)
{
int requiredCount = saleCocktail.Count;
var warehousesWithCocktail = _dbContext.Warehouses.Include(w => w.Cocktails)
.Where(w => w.Cocktails.Any(c => c.CocktailId == saleCocktail.CocktailId && c.Count > 0))
.ToList();
foreach (var warehouse in warehousesWithCocktail)
{
var warehouseCocktail = warehouse.Cocktails
.FirstOrDefault(c => c.CocktailId == saleCocktail.CocktailId);
if (warehouseCocktail == null || warehouseCocktail.Count == 0)
continue;
int toWithdraw = Math.Min(warehouseCocktail.Count, requiredCount);
warehouseCocktail.Count -= toWithdraw;
requiredCount -= toWithdraw;
_dbContext.SaveChanges();
if (requiredCount == 0)
break;
}
if (requiredCount > 0)
{
transaction.Rollback();
return false;
}
}
_dbContext.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
throw new StorageException(ex);
}
}
private Warehouse? GetWarehouseById(string id) => _dbContext.Warehouses.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,330 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SquirrelDatabase;
#nullable disable
namespace SquirrelDatabase.Migrations
{
[DbContext(typeof(SquirrelDbContext))]
[Migration("20250407181533_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clients");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("BaseAlcohol")
.HasColumnType("integer");
b.Property<string>("CocktailName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailName")
.IsUnique();
b.ToTable("Cocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("CocktailId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailId");
b.ToTable("CocktailHistories");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SquirrelDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("EmployeeSalary")
.HasColumnType("double precision");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.ToTable("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("CocktailId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "CocktailId");
b.HasIndex("CocktailId");
b.ToTable("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("CocktailHistories")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.HasOne("SquirrelDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("SaleCocktails")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SquirrelDatabase.Models.Sale", "Sale")
.WithMany("SaleCocktails")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
b.Navigation("Sale");
});
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Navigation("CocktailHistories");
b.Navigation("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Navigation("SaleCocktails");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,252 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SquirrelDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PhoneNumber = table.Column<string>(type: "text", nullable: false),
DiscountSize = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Cocktails",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
CocktailName = table.Column<string>(type: "text", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
BaseAlcohol = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Cocktails", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PostName = table.Column<string>(type: "text", nullable: false),
PostType = table.Column<int>(type: "integer", nullable: false),
Salary = table.Column<double>(type: "double precision", nullable: false),
IsActual = table.Column<bool>(type: "boolean", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Posts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CocktailHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
CocktailId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CocktailHistories", x => x.Id);
table.ForeignKey(
name: "FK_CocktailHistories_Cocktails_CocktailId",
column: x => x.CocktailId,
principalTable: "Cocktails",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
EmployeeId = table.Column<string>(type: "text", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmployeeSalary = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Employees_EmployeeId",
column: x => x.EmployeeId,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Sales",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
EmployeeId = table.Column<string>(type: "text", nullable: false),
ClientId = table.Column<string>(type: "text", nullable: true),
SaleDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
DiscountType = table.Column<int>(type: "integer", nullable: false),
Discount = table.Column<double>(type: "double precision", nullable: false),
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sales", x => x.Id);
table.ForeignKey(
name: "FK_Sales_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_Sales_Employees_EmployeeId",
column: x => x.EmployeeId,
principalTable: "Employees",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SaleCocktails",
columns: table => new
{
SaleId = table.Column<string>(type: "text", nullable: false),
CocktailId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SaleCocktails", x => new { x.SaleId, x.CocktailId });
table.ForeignKey(
name: "FK_SaleCocktails_Cocktails_CocktailId",
column: x => x.CocktailId,
principalTable: "Cocktails",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SaleCocktails_Sales_SaleId",
column: x => x.SaleId,
principalTable: "Sales",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Clients_PhoneNumber",
table: "Clients",
column: "PhoneNumber",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CocktailHistories_CocktailId",
table: "CocktailHistories",
column: "CocktailId");
migrationBuilder.CreateIndex(
name: "IX_Cocktails_CocktailName",
table: "Cocktails",
column: "CocktailName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Salaries_EmployeeId",
table: "Salaries",
column: "EmployeeId");
migrationBuilder.CreateIndex(
name: "IX_SaleCocktails_CocktailId",
table: "SaleCocktails",
column: "CocktailId");
migrationBuilder.CreateIndex(
name: "IX_Sales_ClientId",
table: "Sales",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Sales_EmployeeId",
table: "Sales",
column: "EmployeeId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CocktailHistories");
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "SaleCocktails");
migrationBuilder.DropTable(
name: "Cocktails");
migrationBuilder.DropTable(
name: "Sales");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Employees");
}
}
}

View File

@@ -0,0 +1,331 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SquirrelDatabase;
#nullable disable
namespace SquirrelDatabase.Migrations
{
[DbContext(typeof(SquirrelDbContext))]
[Migration("20250407203820_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clients");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("BaseAlcohol")
.HasColumnType("integer");
b.Property<string>("CocktailName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailName")
.IsUnique();
b.ToTable("Cocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("CocktailId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailId");
b.ToTable("CocktailHistories");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SquirrelDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("EmployeeSalary")
.HasColumnType("double precision");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.ToTable("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("CocktailId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "CocktailId");
b.HasIndex("CocktailId");
b.ToTable("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("CocktailHistories")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.HasOne("SquirrelDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("SaleCocktails")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SquirrelDatabase.Models.Sale", "Sale")
.WithMany("SaleCocktails")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
b.Navigation("Sale");
});
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Navigation("CocktailHistories");
b.Navigation("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Navigation("SaleCocktails");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SquirrelDatabase.Migrations
{
/// <inheritdoc />
public partial class ChangeFieldsInPost : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Salary",
table: "Posts");
migrationBuilder.AddColumn<string>(
name: "Configuration",
table: "Posts",
type: "jsonb",
nullable: false,
defaultValue: "{\"Rate\": 0, \"Type\": \"PostConfiguration\"}");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Configuration",
table: "Posts");
migrationBuilder.AddColumn<double>(
name: "Salary",
table: "Posts",
type: "double precision",
nullable: false,
defaultValue: 0.0);
}
}
}

View File

@@ -0,0 +1,334 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SquirrelDatabase;
#nullable disable
namespace SquirrelDatabase.Migrations
{
[DbContext(typeof(SquirrelDbContext))]
[Migration("20250408214441_ChangeEmployee")]
partial class ChangeEmployee
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clients");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("BaseAlcohol")
.HasColumnType("integer");
b.Property<string>("CocktailName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailName")
.IsUnique();
b.ToTable("Cocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("CocktailId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailId");
b.ToTable("CocktailHistories");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SquirrelDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("EmployeeSalary")
.HasColumnType("double precision");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.ToTable("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("CocktailId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "CocktailId");
b.HasIndex("CocktailId");
b.ToTable("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("CocktailHistories")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.HasOne("SquirrelDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("SaleCocktails")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SquirrelDatabase.Models.Sale", "Sale")
.WithMany("SaleCocktails")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
b.Navigation("Sale");
});
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Navigation("CocktailHistories");
b.Navigation("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Navigation("SaleCocktails");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SquirrelDatabase.Migrations
{
/// <inheritdoc />
public partial class ChangeEmployee : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "DateOfDelete",
table: "Employees",
type: "timestamp without time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DateOfDelete",
table: "Employees");
}
}
}

View File

@@ -0,0 +1,331 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SquirrelDatabase;
#nullable disable
namespace SquirrelDatabase.Migrations
{
[DbContext(typeof(SquirrelDbContext))]
partial class SquirrelDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clients");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("BaseAlcohol")
.HasColumnType("integer");
b.Property<string>("CocktailName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailName")
.IsUnique();
b.ToTable("Cocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("CocktailId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("CocktailId");
b.ToTable("CocktailHistories");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("SquirrelDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("EmployeeSalary")
.HasColumnType("double precision");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.HasIndex("EmployeeId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<string>("EmployeeId")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EmployeeId");
b.ToTable("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("CocktailId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "CocktailId");
b.HasIndex("CocktailId");
b.ToTable("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.CocktailHistory", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("CocktailHistories")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
});
modelBuilder.Entity("SquirrelDatabase.Models.Salary", b =>
{
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Salaries")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.HasOne("SquirrelDatabase.Models.Client", "Client")
.WithMany("Sales")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SquirrelDatabase.Models.Employee", "Employee")
.WithMany("Sales")
.HasForeignKey("EmployeeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Employee");
});
modelBuilder.Entity("SquirrelDatabase.Models.SaleCocktail", b =>
{
b.HasOne("SquirrelDatabase.Models.Cocktail", "Cocktail")
.WithMany("SaleCocktails")
.HasForeignKey("CocktailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SquirrelDatabase.Models.Sale", "Sale")
.WithMany("SaleCocktails")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Cocktail");
b.Navigation("Sale");
});
modelBuilder.Entity("SquirrelDatabase.Models.Client", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Cocktail", b =>
{
b.Navigation("CocktailHistories");
b.Navigation("SaleCocktails");
});
modelBuilder.Entity("SquirrelDatabase.Models.Employee", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
modelBuilder.Entity("SquirrelDatabase.Models.Sale", b =>
{
b.Navigation("SaleCocktails");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(ClientDataModel), ReverseMap = true)]
public class Client
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string FIO { get; set; }
public required string PhoneNumber { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("ClientId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,18 @@
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Cocktail
{
public required string Id { get; set; }
public required string CocktailName { get; set; }
public double Price { get; set; }
public required AlcoholType BaseAlcohol { get; set; }
[ForeignKey("CocktailId")]
public List<CocktailHistory>? CocktailHistories { get; set; }
[ForeignKey("CocktailId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SquirrelDatabase.Models;
public class CocktailHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string CocktailId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Cocktail? Cocktail { get; set; }
}

View File

@@ -0,0 +1,40 @@
using AutoMapper;
using SquirrelContract.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
[AutoMap(typeof(EmployeeDataModel), ReverseMap = true)]
public class Employee
{
public required string Id { get; set; }
public required string FIO { get; set; }
public string Email { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
public Employee AddPost(Post? post)
{
Post = post;
return this;
}
}

View File

@@ -0,0 +1,23 @@
using AutoMapper;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using SquirrelContract.Infastructure.PostConfigurations;
namespace SquirrelDatabase.Models;
public class Post
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public required PostConfiguration Configuration { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,18 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
namespace SquirrelDatabase.Models;
public class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public DateTime SalaryDate { get; set; }
public double EmployeeSalary { get; set; }
public Employee? Employee { get; set; }
}

View File

@@ -0,0 +1,33 @@
using AutoMapper;
using BarBelochkaContract.DataModels;
using SquirrelContract.DataModels;
using SquirrelContract.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SquirrelDatabase.Models;
public class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string EmployeeId { get; set; }
public string? ClientId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Employee? Employee { get; set; }
public Client? Client { get; set; }
[ForeignKey("SaleId")]
public List<SaleCocktail>? SaleCocktails { get; set; }
}

View File

@@ -0,0 +1,16 @@
namespace SquirrelDatabase.Models;
public class SaleCocktail
{
public required string SaleId { get; set; }
public required string CocktailId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Cocktail? Cocktail { get; set; }
}

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