32 Commits

Author SHA1 Message Date
52c8343003 Corrections 2025-05-28 15:11:27 +04:00
21ab6ed0eb CreateDocumentSalaryByPeriod 2025-05-27 23:48:15 +04:00
abbd84abc1 GetDataSalaryByPeriod 2025-05-27 22:53:10 +04:00
8a9d8727fe CreateDocumentSalesByPeriod 2025-05-27 22:08:13 +04:00
b06e0018d6 GetDataSaleByPeriod 2025-05-27 20:54:32 +04:00
a433ac5c79 CreateDocumentProductsByRestaurant 2025-05-27 19:09:06 +04:00
47cc5397a9 Reapply "MVC и тесты для Report"
This reverts commit 167bb1f2c5.
2025-05-27 15:19:32 +04:00
167bb1f2c5 Revert "MVC и тесты для Report"
This reverts commit a3726e4fab.
2025-05-27 15:17:21 +04:00
a3726e4fab MVC и тесты для Report 2025-05-27 15:16:46 +04:00
d206ca265c Prepare 2025-05-21 20:35:00 +04:00
1099d8c922 Сделана миграция на изменение в схеме таблицы Работник 2025-04-23 23:33:49 +04:00
5ef0ef450f Расчёт зарплаты 2025-04-23 23:28:58 +04:00
5c4f82e7b2 Изменения в должности 2025-04-23 19:06:31 +04:00
44ec32fe0f Первая миграция 2025-04-22 22:39:41 +04:00
8a3c00c94b Правки 2025-04-16 15:52:18 +04:00
e700a45762 Добаление и изменение тестов 2025-04-15 14:59:25 +04:00
54bac20e18 Добавление проекта WebApi 2025-04-15 14:58:06 +04:00
30bde774a0 Добавление и изменение контрактов и их реализаций 2025-04-15 14:57:28 +04:00
d36e722101 Добавление и изменение моделей 2025-04-15 14:53:01 +04:00
d2b57d3c85 Добавил настройки маппинга через атрибуты 2025-03-17 17:09:53 +04:00
448501ef70 Тесты 2025-03-13 14:22:15 +04:00
885d0f773f Контракты 2025-03-12 21:36:54 +04:00
d7edc8bd2b DbContext 2025-03-12 19:27:42 +04:00
c65c66fa6a Проект и модели 2025-03-12 14:21:46 +04:00
03050e6168 Реализации 2025-03-03 19:39:16 +04:00
8cf33f1313 Тесты 2025-03-03 19:38:57 +04:00
148cb645ac Расширение 2025-03-03 19:37:40 +04:00
e064835c3f Исключения 2025-03-03 19:33:05 +04:00
2bb5dc8b6d Конструкторы 2025-02-26 22:35:34 +04:00
febdfc1746 Изменение по должности 2025-02-26 20:51:37 +04:00
ef160beb70 Заготовки реализаций 2025-02-26 20:45:14 +04:00
9c9fcc9809 Контракты 2025-02-26 20:17:47 +04:00
165 changed files with 15466 additions and 117 deletions

View File

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

View File

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

View File

@@ -0,0 +1,101 @@
using Microsoft.Extensions.Logging;
using SPiluSZharuBuisnessLogic.OfficePackage;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.StorageContracts;
namespace SPiluSZharuBuisnessLogic.Implementations;
internal class ReportContract(IProductStorageContract productStorageContract, ISaleStorageContract saleStorageContract, ISalaryStorageContract salaryStorageContract, BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract
{
private readonly IProductStorageContract _productStorageContract = productStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
private readonly ILogger _logger = logger;
internal static readonly string[] documentHeader = ["Ресторан", "Товар"];
internal static readonly string[] tableHeader = ["Дата", "Сумма", "Товар", "Кол-во"];
public async Task<Stream> CreateDocumentProductsByRestaurantAsync(CancellationToken ct)
{
_logger.LogInformation("Create report ProductsByRestaurant");
var data = await GetDataByProductsAsync(ct);
return _baseWordBuilder
.AddHeader("Продукты по ресторанам")
.AddParagraph($"Сформировано на дату {DateTime.Now}")
.AddTable([3000, 5000], [.. new List<string[]>() { documentHeader }.Union([.. data.SelectMany(x => (new List<string[]>() { new string[] { x.RestaurantName, "" } }).Union(x.Products.Select(y => new string[] { "", y })))])])
.Build();
}
public async Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalesAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _baseExcelBuilder
.AddHeader("Продажи за период", 0, 4)
.AddParagraph($"c {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}", 2)
.AddTable([10, 10, 10, 10], [.. new List<string[]>() { tableHeader }.Union(data.SelectMany(x => (new List<string[]>() { new string[] { x.SaleDate.ToShortDateString(), x.Sum.ToString("N2"), "", "" } }).Union(x.Products!.Select(y => new string[] { "", "", y.ProductName, y.Count.ToString("N2") })).ToArray())).Union([["Всего", data.Sum(x => x.Sum).ToString("N2"), "", ""]])])
.Build();
}
public async Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Create report SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
var data = await GetDataBySalaryAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
return _basePdfBuilder
.AddHeader("Зарплатная ведомость")
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
.AddPieChart("Начисления", [.. data.Select(x => (x.WorkerFIO, x.TotalSalary))])
.Build();
}
public Task<List<RestaurantProductDataModel>> GetDataProductsByRestaurantAsync(CancellationToken ct)
{
_logger.LogInformation("Get data ProductsByRestaurant");
return GetDataByProductsAsync(ct);
}
public Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalesByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataBySalesAsync(dateStart, dateFinish, ct);
}
public Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
_logger.LogInformation("Get data SalaryByPeriod from {dateStart} to {dateFinish}", dateStart, dateFinish);
return GetDataBySalaryAsync(dateStart, dateFinish, ct);
}
private async Task<List<RestaurantProductDataModel>> GetDataByProductsAsync(CancellationToken ct) => [.. (await _productStorageContract.GetListAsync(ct)).GroupBy(x => x.RestaurantName).Select(x => new RestaurantProductDataModel { RestaurantName = x.Key, Products = [.. x.Select(y => y.ProductName)] })];
private async Task<List<SaleDataModel>> GetDataBySalesAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
}
return [.. (await _saleStorageContract.GetListAsync(dateStart, dateFinish, ct)).OrderBy(x => x.SaleDate)];
}
private async Task<List<WorkerSalaryByPeriodDataModel>> GetDataBySalaryAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
{
if (dateStart.IsDateNotOlder(dateFinish))
{
throw new IncorrectDatesException(dateStart, dateFinish);
}
return [.. (await _salaryStorageContract.GetListAsync(dateStart, dateFinish, ct)).GroupBy(x => x.WorkerId).Select(x => new WorkerSalaryByPeriodDataModel { WorkerFIO = x.First().WorkerName, TotalSalary = x.Sum(y => y.Salary), FromPeriod = x.Min(y => y.SalaryDate), ToPeriod = x.Max(y => y.SalaryDate) }).OrderBy(x => x.WorkerFIO)];
}
}

View File

@@ -0,0 +1,66 @@
using Microsoft.Extensions.Logging;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.StorageContracts;
using System.Text.Json;
namespace SPiluSZharuBuisnessLogic.Implementations;
internal class RestaurantBuisnessLogicContract(IRestaurantStorageContract restaurantStorageContract, ILogger logger) : IRestaurantBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IRestaurantStorageContract _restaurantStorageContract = restaurantStorageContract;
public List<RestaurantDataModel> GetAllRestaurants()
{
_logger.LogInformation("GetAllRestaurants");
return _restaurantStorageContract.GetList() ?? throw new NullListException();
}
public RestaurantDataModel GetRestaurantByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _restaurantStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
return _restaurantStorageContract.GetElementByName(data) ?? _restaurantStorageContract.GetElementByOldName(data) ??
throw new ElementNotFoundException(data);
}
public void InsertRestaurant(RestaurantDataModel restaurantDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(restaurantDataModel));
ArgumentNullException.ThrowIfNull(restaurantDataModel);
restaurantDataModel.Validate();
_restaurantStorageContract.AddElement(restaurantDataModel);
}
public void UpdateRestaurant(RestaurantDataModel restaurantDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(restaurantDataModel));
ArgumentNullException.ThrowIfNull(restaurantDataModel);
restaurantDataModel.Validate();
_restaurantStorageContract.UpdElement(restaurantDataModel);
}
public void DeleteRestaurant(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");
}
_restaurantStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,123 @@
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
using Microsoft.Extensions.Logging;
namespace SPiluSZharuBuisnessLogic.Implementations;
internal class SalaryBuisnessLogicContract(ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract,
IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
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);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _salaryStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId)
{
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
_logger.LogInformation("GetAllSalaries params: {fromDate}, {toDate}, {workerId}", fromDate, toDate, workerId);
return _salaryStorageContract.GetList(fromDate, toDate, workerId) ?? throw new NullListException();
}
public void CalculateSalaryByMounth(DateTime date)
{
_logger.LogInformation("CalculateSalaryByMounth: {date}", date);
var startDate = new DateTime(date.Year, date.Month, 1);
var finishDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
DeliveryManPostConfiguration dpc => CalculateSalaryForDeliveryMan(sales, startDate, finishDate, dpc),
OperatorPostConfiguration opc => CalculateSalaryForOperator(startDate, finishDate, opc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
private double CalculateSalaryForDeliveryMan(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, DeliveryManPostConfiguration config)
{
var calcPercent = 0.0;
var dates = new List<DateTime>();
for (var date = startDate; date < finishDate; date = date.AddDays(1))
{
dates.Add(date);
}
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)
{
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
}
}
});
double calcBonusTask = 0;
try
{
calcBonusTask = 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 + calcBonusTask;
}
private double CalculateSalaryForOperator(DateTime startDate, DateTime finishDate, OperatorPostConfiguration config)
{
try
{
return config.Rate + config.PersonalCountTrendPremium * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the operator payroll process");
return 0;
}
}
}

View File

@@ -0,0 +1,116 @@
using Microsoft.Extensions.Logging;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.StorageContracts;
using System.Text.Json;
namespace SPiluSZharuBuisnessLogic.Implementations;
internal class SaleBuisnessLogicContract(ISaleStorageContract saleStorageContract, ILogger logger) : ISaleBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {fromDate}, {toDate}", fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _saleStorageContract.GetList(fromDate, toDate) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {workerId}, {fromDate}, {toDate}", workerId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (workerId.IsEmpty())
{
throw new ArgumentNullException(nameof(workerId));
}
if (!workerId.IsGuid())
{
throw new ValidationException("The value in the field workerId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, workerId: workerId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByRestaurantByPeriod(string restaurantId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {restaurantId}, {fromDate}, {toDate}", restaurantId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (restaurantId.IsEmpty())
{
throw new ArgumentNullException(nameof(restaurantId));
}
if (!restaurantId.IsGuid())
{
throw new ValidationException("The value in the field restaurantId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, restaurantId: restaurantId) ?? throw new NullListException();
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate)
{
_logger.LogInformation("GetAllSales params: {productId}, {fromDate}, {toDate}", productId, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
if (productId.IsEmpty())
{
throw new ArgumentNullException(nameof(productId));
}
if (!productId.IsGuid())
{
throw new ValidationException("The value in the field productId is not a unique identifier.");
}
return _saleStorageContract.GetList(fromDate, toDate, productId: productId) ?? throw new NullListException();
}
public SaleDataModel GetSaleByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (!data.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
return _saleStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
public void InsertSale(SaleDataModel saleDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(saleDataModel));
ArgumentNullException.ThrowIfNull(saleDataModel);
saleDataModel.Validate();
_saleStorageContract.AddElement(saleDataModel);
}
public void CancelSale(string id)
{
_logger.LogInformation("Cancel by id: {id}", id);
if (id.IsEmpty())
{
throw new ArgumentNullException(nameof(id));
}
if (!id.IsGuid())
{
throw new ValidationException("Id is not a unique identifier");
}
_saleStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,104 @@
using Microsoft.Extensions.Logging;
using SPiluSZharuContracts.BuisnessLogicContracts;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.StorageContracts;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace SPiluSZharuBuisnessLogic.Implementations;
internal class WorkerBuisnessLogicContract(IWorkerStorageContract workerStorageContract, ILogger logger) : IWorkerBuisnessLogicContract
{
private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}", onlyActive);
return _workerStorageContract.GetList(onlyActive) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {postId}, {onlyActive},", postId, onlyActive);
if (postId.IsEmpty())
{
throw new ArgumentNullException(nameof(postId));
}
if (!postId.IsGuid())
{
throw new ValidationException("The value in the field postId is not a unique identifier.");
}
return _workerStorageContract.GetList(onlyActive, postId) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromBirthDate: fromDate, toBirthDate: toDate) ?? throw new NullListException();
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true)
{
_logger.LogInformation("GetAllWorkers params: {onlyActive}, {fromDate}, {toDate}", onlyActive, fromDate, toDate);
if (fromDate.IsDateNotOlder(toDate))
{
throw new IncorrectDatesException(fromDate, toDate);
}
return _workerStorageContract.GetList(onlyActive, fromEmploymentDate: fromDate, toEmploymentDate: toDate) ?? throw new NullListException();
}
public WorkerDataModel GetWorkerByData(string data)
{
_logger.LogInformation("Get element by data: {data}", data);
if (data.IsEmpty())
{
throw new ArgumentNullException(nameof(data));
}
if (data.IsGuid())
{
return _workerStorageContract.GetElementById(data) ?? throw new ElementNotFoundException(data);
}
if (Regex.IsMatch(data, @"^(8|\+7)(\s|\(|\-)?(\d{3})(\s|\)|\-)?(\d{3})(\s|\-)?(\d{2})(\s|\-)?(\d{2})$"))
{
return _workerStorageContract.GetElementByPhoneNumber(data) ?? throw new ElementNotFoundException(data);
}
return _workerStorageContract.GetElementByFIO(data) ?? throw new ElementNotFoundException(data);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("New data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.AddElement(workerDataModel);
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
_logger.LogInformation("Update data: {json}", JsonSerializer.Serialize(workerDataModel));
ArgumentNullException.ThrowIfNull(workerDataModel);
workerDataModel.Validate();
_workerStorageContract.UpdElement(workerDataModel);
}
public void DeleteWorker(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");
}
_workerStorageContract.DelElement(id);
}
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuBuisnessLogic.OfficePackage;
public abstract class BaseExcelBuilder
{
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuBuisnessLogic.OfficePackage;
public abstract class BasePdfBuilder
{
public abstract BasePdfBuilder AddHeader(string header);
public abstract BasePdfBuilder AddParagraph(string text);
public abstract BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuBuisnessLogic.OfficePackage;
public abstract class BaseWordBuilder
{
public abstract BaseWordBuilder AddHeader(string header);
public abstract BaseWordBuilder AddParagraph(string text);
public abstract BaseWordBuilder AddTable(int[] widths, List<string[]> data);
public abstract Stream Build();
}

View File

@@ -0,0 +1,85 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering;
using System.Text;
namespace SPiluSZharuBuisnessLogic.OfficePackage;
internal class MigraDocPdfBuilder : BasePdfBuilder
{
private readonly Document _document;
public MigraDocPdfBuilder()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_document = new Document();
DefineStyles();
}
public override BasePdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public override BasePdfBuilder AddParagraph(string text)
{
_document.LastSection.AddParagraph(text, "Normal");
return this;
}
public override BasePdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(stream);
return stream;
}
private void DefineStyles()
{
var style = _document.Styles.AddStyle("NormalBold", "Normal");
style.Font.Bold = true;
}
}

View File

@@ -0,0 +1,303 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace SPiluSZharuBuisnessLogic.OfficePackage;
internal class OpenXmlExcelBuilder : BaseExcelBuilder
{
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public OpenXmlExcelBuilder()
{
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference =
new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public override BaseExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public override BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
return stream;
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2, KnownFonts = BooleanValue.FromBoolean(true) };
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) },
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@@ -0,0 +1,94 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace SPiluSZharuBuisnessLogic.OfficePackage;
internal class OpenXmlWordBuilder : BaseWordBuilder
{
private readonly Document _document;
private readonly Body _body;
public OpenXmlWordBuilder()
{
_document = new Document();
_body = _document.AppendChild(new Body());
}
public override BaseWordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text(header));
return this;
}
public override BaseWordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public override BaseWordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public override Stream Build()
{
var stream = new MemoryStream();
using var wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
return stream;
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="SPiluSZharuTests" />
<InternalsVisibleTo Include="SPiluSZharuWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SPiluSZharuContracts\SPiluSZharuContracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,21 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
namespace SPiluSZharuContracts.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,21 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
namespace SPiluSZharuContracts.AdapterContracts;
public interface IProductAdapter
{
ProductOperationResponse GetList(bool includeDeleted);
ProductOperationResponse GetRestaurantList(string id, bool includeDeleted);
ProductOperationResponse GetHistory(string id);
ProductOperationResponse GetElement(string data);
ProductOperationResponse RegisterProduct(ProductBindingModel productModel);
ProductOperationResponse ChangeProductInfo(ProductBindingModel productModel);
ProductOperationResponse RemoveProduct(string id);
}

View File

@@ -0,0 +1,18 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
namespace SPiluSZharuContracts.AdapterContracts;
public interface IReportAdapter
{
Task<ReportOperationResponse> GetDataProductsByRestaurantAsync(CancellationToken ct);
Task<ReportOperationResponse> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentProductsByRestaurantAsync(CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,17 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
namespace SPiluSZharuContracts.AdapterContracts;
public interface IRestaurantAdapter
{
RestaurantOperationResponse GetList();
RestaurantOperationResponse GetElement(string data);
RestaurantOperationResponse RegisterRestaurant(RestaurantBindingModel restaurantModel);
RestaurantOperationResponse ChangeRestaurantInfo(RestaurantBindingModel restaurantModel);
RestaurantOperationResponse RemoveRestaurant(string id);
}

View File

@@ -0,0 +1,13 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.AdapterContracts;
public interface ISalaryAdapter
{
SalaryOperationResponse GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
SalaryOperationResponse GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
SalaryOperationResponse CalculateSalaryByMounth(DateTime date);
}

View File

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

View File

@@ -0,0 +1,23 @@
using SPiluSZharuContracts.AdapterContracts.OperationResponses;
using SPiluSZharuContracts.BindingModels;
namespace SPiluSZharuContracts.AdapterContracts;
public interface IWorkerAdapter
{
WorkerOperationResponse GetList(bool includeDeleted);
WorkerOperationResponse GetPostList(string id, bool includeDeleted);
WorkerOperationResponse GetListByBirthDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetListByEmploymentDate(DateTime fromDate, DateTime toDate, bool includeDeleted);
WorkerOperationResponse GetElement(string data);
WorkerOperationResponse RegisterWorker(WorkerBindingModel workerModel);
WorkerOperationResponse ChangeWorkerInfo(WorkerBindingModel workerModel);
WorkerOperationResponse RemoveWorker(string id);
}

View File

@@ -0,0 +1,19 @@
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.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,21 @@
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
public class ProductOperationResponse : OperationResponse
{
public static ProductOperationResponse OK(List<ProductViewModel> data) => OK<ProductOperationResponse, List<ProductViewModel>>(data);
public static ProductOperationResponse OK(List<ProductHistoryViewModel> data) => OK<ProductOperationResponse, List<ProductHistoryViewModel>>(data);
public static ProductOperationResponse OK(ProductViewModel data) => OK<ProductOperationResponse, ProductViewModel>(data);
public static ProductOperationResponse NoContent() => NoContent<ProductOperationResponse>();
public static ProductOperationResponse NotFound(string message) => NotFound<ProductOperationResponse>(message);
public static ProductOperationResponse BadRequest(string message) => BadRequest<ProductOperationResponse>(message);
public static ProductOperationResponse InternalServerError(string message) => InternalServerError<ProductOperationResponse>(message);
}

View File

@@ -0,0 +1,19 @@
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
public class ReportOperationResponse : OperationResponse
{
public static ReportOperationResponse OK(List<RestaurantProductViewModel> data) => OK<ReportOperationResponse, List<RestaurantProductViewModel>>(data);
public static ReportOperationResponse OK(List<SaleViewModel> data) => OK<ReportOperationResponse, List<SaleViewModel>>(data);
public static ReportOperationResponse OK(List<WorkerSalaryByPeriodViewModel> data) => OK<ReportOperationResponse, List<WorkerSalaryByPeriodViewModel>>(data);
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
}

View File

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

View File

@@ -0,0 +1,17 @@
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.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 SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.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 SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.ViewModels;
namespace SPiluSZharuContracts.AdapterContracts.OperationResponses;
public class WorkerOperationResponse : OperationResponse
{
public static WorkerOperationResponse OK(List<WorkerViewModel> data) => OK<WorkerOperationResponse, List<WorkerViewModel>>(data);
public static WorkerOperationResponse OK(WorkerViewModel data) => OK<WorkerOperationResponse, WorkerViewModel>(data);
public static WorkerOperationResponse NoContent() => NoContent<WorkerOperationResponse>();
public static WorkerOperationResponse NotFound(string message) => NotFound<WorkerOperationResponse>(message);
public static WorkerOperationResponse BadRequest(string message) => BadRequest<WorkerOperationResponse>(message);
public static WorkerOperationResponse InternalServerError(string message) => InternalServerError<WorkerOperationResponse>(message);
}

View File

@@ -0,0 +1,14 @@
namespace SPiluSZharuContracts.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 SPiluSZharuContracts.BindingModels;
public class ProductBindingModel
{
public string? Id { get; set; }
public string? ProductName { get; set; }
public string? ProductType { get; set; }
public string? RestaurantId { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.BindingModels;
public class RestaurantBindingModel
{
public string? Id { get; set; }
public string? RestaurantName { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.BindingModels;
public class SaleBindingModel
{
public string? Id { get; set; }
public string? WorkerId { get; set; }
public string? RestaurantId { get; set; }
public List<SaleProductBindingModel>? Products { get; set; }
}

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface IPostBuisnessLogicContract
{
List<PostDataModel> GetAllPosts();
List<PostDataModel> GetAllDataOfPost(string postId);
PostDataModel GetPostByData(string data);
void InsertPost(PostDataModel postDataModel);
void UpdatePost(PostDataModel postDataModel);
void DeletePost(string id);
void RestorePost(string id);
}

View File

@@ -0,0 +1,20 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface IProductBuisnessLogicContract
{
List<ProductDataModel> GetAllProducts(bool onlyActive = true);
List<ProductDataModel> GetAllProductsByRestaurant(string restaurantId, bool onlyActive = true);
List<ProductHistoryDataModel> GetProductHistoryByProduct(string productId);
ProductDataModel GetProductByData(string data);
void InsertProduct(ProductDataModel productDataModel);
void UpdateProduct(ProductDataModel productDataModel);
void DeleteProduct(string id);
}

View File

@@ -0,0 +1,18 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface IReportContract
{
Task<List<RestaurantProductDataModel>> GetDataProductsByRestaurantAsync(CancellationToken ct);
Task<List<SaleDataModel>> GetDataSaleByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<List<WorkerSalaryByPeriodDataModel>> GetDataSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentProductsByRestaurantAsync(CancellationToken ct);
Task<Stream> CreateDocumentSalesByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentSalaryByPeriodAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,16 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface IRestaurantBuisnessLogicContract
{
List<RestaurantDataModel> GetAllRestaurants();
RestaurantDataModel GetRestaurantByData(string data);
void InsertRestaurant(RestaurantDataModel restaurantDataModel);
void UpdateRestaurant(RestaurantDataModel restaurantDataModel);
void DeleteRestaurant(string id);
}

View File

@@ -0,0 +1,12 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface ISalaryBuisnessLogicContract
{
List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate);
List<SalaryDataModel> GetAllSalariesByPeriodByWorker(DateTime fromDate, DateTime toDate, string workerId);
void CalculateSalaryByMounth(DateTime date);
}

View File

@@ -0,0 +1,20 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface ISaleBuisnessLogicContract
{
List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByRestaurantByPeriod(string restaurantId, DateTime fromDate, DateTime toDate);
List<SaleDataModel> GetAllSalesByProductByPeriod(string productId, DateTime fromDate, DateTime toDate);
SaleDataModel GetSaleByData(string data);
void InsertSale(SaleDataModel saleDataModel);
void CancelSale(string id);
}

View File

@@ -0,0 +1,22 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.BuisnessLogicContracts;
public interface IWorkerBuisnessLogicContract
{
List<WorkerDataModel> GetAllWorkers(bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByPost(string postId, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime fromDate, DateTime toDate, bool onlyActive = true);
WorkerDataModel GetWorkerByData(string data);
void InsertWorker(WorkerDataModel workerDataModel);
void UpdateWorker(WorkerDataModel workerDataModel);
void DeleteWorker(string id);
}

View File

@@ -1,25 +1,36 @@
using SPiluSZharuContracts.Enums;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
namespace SPiluSZharuContracts.DataModels;
public class PostDataModel(string id, string postId, 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 PostId { get; private set; } = postId;
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(OperatorPostConfiguration) => JsonConvert.DeserializeObject<OperatorPostConfiguration>(configurationJson)!,
nameof(DeliveryManPostConfiguration) => JsonConvert.DeserializeObject<DeliveryManPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
@@ -29,19 +40,16 @@ public class PostDataModel(string id, string postId, string postName, PostType p
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostId.IsEmpty())
throw new ValidationException("Field PostId is empty");
if (!PostId.IsGuid())
throw new ValidationException("The value in the field PostId is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
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

@@ -5,18 +5,31 @@ using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuContracts.DataModels;
public class ProductDataModel(string id, string productName, ProductType productType, double price, bool isDeleted) : IValidation
public class ProductDataModel(string id, string productName, ProductType productType, string restaurantId, double price, bool isDeleted) : IValidation
{
private readonly RestaurantDataModel? _restaurant;
public string Id { get; private set; } = id;
public string ProductName { get; private set; } = productName;
public ProductType ProductType { get; private set; } = productType;
public string RestaurantId { get; private set; } = restaurantId;
public double Price { get; private set; } = price;
public bool IsDeleted { get; private set; } = isDeleted;
public string RestaurantName => _restaurant?.RestaurantName ?? string.Empty;
public ProductDataModel(string id, string productName, ProductType productType, string restaurantId, double price, bool isDeleted, RestaurantDataModel restaurant) : this(id, productName, productType, restaurantId, price, isDeleted)
{
_restaurant = restaurant;
}
public ProductDataModel(string id, string productName, ProductType productType, string restaurantId, double price) : this(id, productName, productType, restaurantId, price, false) { }
public void Validate()
{
if (Id.IsEmpty())
@@ -31,6 +44,12 @@ public class ProductDataModel(string id, string productName, ProductType product
if (ProductType == ProductType.None)
throw new ValidationException("Field ProductType is empty");
if (RestaurantId.IsEmpty())
throw new ValidationException("Field RestaurantId is empty");
if (!RestaurantId.IsGuid())
throw new ValidationException("The value in the field RestaurantId is not a unique identifier");
if (Price <= 0)
throw new ValidationException("Field Price is less than or equal to 0");
}

View File

@@ -6,12 +6,22 @@ namespace SPiluSZharuContracts.DataModels;
public class ProductHistoryDataModel(string productId, double oldPrice) : IValidation
{
private readonly ProductDataModel? _product;
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public string ProductName => _product?.ProductName ?? string.Empty;
public ProductHistoryDataModel(string productId, double oldPrice, DateTime changeDate, ProductDataModel product) : this(productId, oldPrice)
{
ChangeDate = changeDate;
_product = product;
}
public void Validate()
{
if (ProductId.IsEmpty())

View File

@@ -14,6 +14,8 @@ public class RestaurantDataModel(string id, string restaurantName, string? prevR
public string? PrevPrevRestaurantName { get; private set; } = prevPrevRestaurantName;
public RestaurantDataModel(string id, string restaurantName) : this(id, restaurantName, null, null) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.DataModels;
public class RestaurantProductDataModel
{
public required string RestaurantName { get; set; }
public required List<string> Products { get; set; }
}

View File

@@ -1,4 +1,5 @@
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
@@ -6,12 +7,21 @@ namespace SPiluSZharuContracts.DataModels;
public class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
private readonly WorkerDataModel? _worker;
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate;
public double Salary { get; private set; } = workerSalary;
public string WorkerName => _worker?.FIO ?? string.Empty;
public SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary, WorkerDataModel worker) : this(workerId, salaryDate, workerSalary)
{
_worker = worker;
}
public void Validate()
{
if (WorkerId.IsEmpty())

View File

@@ -4,21 +4,48 @@ using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuContracts.DataModels;
public class SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> products) : IValidation
public class SaleDataModel : IValidation
{
public string Id { get; private set; } = id;
private readonly RestaurantDataModel? _restaurant;
public string WorkerId { get; private set; } = workerId;
private readonly WorkerDataModel? _worker;
public string? RestaurantId { get; private set; } = restaurantId;
public string Id { get; private set; }
public string WorkerId { get; private set; }
public string? RestaurantId { 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 bool IsCancel { get; private set; } = isCancel;
public bool IsCancel { get; private set; }
public List<SaleProductDataModel> Products { get; private set; } = products;
public List<SaleProductDataModel>? Products { get; private set; }
public string RestaurantName => _restaurant?.RestaurantName ?? string.Empty;
public string WorkerFIO => _worker?.FIO ?? string.Empty;
public SaleDataModel(string id, string workerId, string? restaurantId, bool isCancel, List<SaleProductDataModel> saleProducts)
{
Id = id;
WorkerId = workerId;
RestaurantId = restaurantId;
IsCancel = isCancel;
Products = saleProducts;
Sum = Products?.Sum(x => x.Price * x.Count) ?? 0;
}
public SaleDataModel(string id, string workerId, string? restaurantId, double sum, bool isCancel, List<SaleProductDataModel> saleProducts, WorkerDataModel worker, RestaurantDataModel? restaurant) : this(id, workerId, restaurantId, isCancel, saleProducts)
{
Sum = sum;
_worker = worker;
_restaurant = restaurant;
}
public SaleDataModel(string id, string workerId, string? restaurantId, List<SaleProductDataModel> products) : this(id, workerId, restaurantId, false, products) { }
public void Validate()
{

View File

@@ -4,14 +4,25 @@ using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuContracts.DataModels;
public class SaleProductDataModel(string saleId, string productId, int count) : IValidation
public class SaleProductDataModel(string saleId, string productId, int count, double price) : IValidation
{
private readonly ProductDataModel? _product;
public string SaleId { get; private set; } = saleId;
public string ProductId { get; private set; } = productId;
public int Count { get; private set; } = count;
public double Price { get; private set; } = price;
public string ProductName => _product?.ProductName ?? string.Empty;
public SaleProductDataModel(string saleId, string productId, int count, double price, ProductDataModel product) : this(saleId, productId, count, price)
{
_product = product;
}
public void Validate()
{
if (SaleId.IsEmpty())

View File

@@ -1,4 +1,5 @@
using SPiluSZharuContracts.Exceptions;
using Microsoft.Extensions.Hosting;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.Extensions;
using SPiluSZharuContracts.Infrastructure;
using System.Text.RegularExpressions;
@@ -7,6 +8,8 @@ namespace SPiluSZharuContracts.DataModels;
public class WorkerDataModel(string id, string fio, string postId, string phoneNumber, 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 +24,15 @@ public class WorkerDataModel(string id, string fio, string postId, string phoneN
public bool IsDeleted { get; private set; } = isDeleted;
public string PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate, bool isDeleted, PostDataModel post) : this(id, fio, postId, phoneNumber, birthDate, employmentDate, isDeleted)
{
_post = post;
}
public WorkerDataModel(string id, string fio, string postId, string phoneNumber, DateTime birthDate, DateTime employmentDate) : this(id, fio, postId, phoneNumber, birthDate, employmentDate, false) { }
public void Validate()
{
if (Id.IsEmpty())

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.DataModels;
public class WorkerSalaryByPeriodDataModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
int MaxConcurrentThreads { get; }
}

View File

@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace SPiluSZharuContracts.Infrastructure;
public class OperationResponse
{
protected HttpStatusCode StatusCode { get; set; }
protected object? Result { get; set; }
protected string? FileName { 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);
}
if (Result is Stream stream)
{
return new FileStreamResult(stream, "application/octet-stream")
{
FileDownloadName = FileName
};
}
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 OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
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,10 @@
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
public class DeliveryManPostConfiguration : PostConfiguration
{
public override string Type => nameof(DeliveryManPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
public class OperatorPostConfiguration : PostConfiguration
{
public override string Type => nameof(OperatorPostConfiguration);
public double PersonalCountTrendPremium { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.Infrastructure.PostConfiguration;
public class PostConfiguration
{
public virtual string Type => nameof(PostConfiguration);
public double Rate { get; set; }
}

View File

@@ -6,4 +6,11 @@
<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" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,22 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);
void AddElement(PostDataModel postDataModel);
void UpdElement(PostDataModel postDataModel);
void DelElement(string id);
void ResElement(string id);
}

View File

@@ -0,0 +1,22 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface IProductStorageContract
{
List<ProductDataModel> GetList(bool onlyActive = true, string? restaurantId = null);
Task<List<ProductDataModel>> GetListAsync(CancellationToken ct);
List<ProductHistoryDataModel> GetHistoryByProductId(string productId);
ProductDataModel? GetElementById(string id);
ProductDataModel? GetElementByName(string name);
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,20 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface IRestaurantStorageContract
{
List<RestaurantDataModel> GetList();
RestaurantDataModel? GetElementById(string id);
RestaurantDataModel? GetElementByName(string name);
RestaurantDataModel? GetElementByOldName(string name);
void AddElement(RestaurantDataModel restaurantDataModel);
void UpdElement(RestaurantDataModel restaurantDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,12 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface ISalaryStorageContract
{
List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? workerId = null);
Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
void AddElement(SalaryDataModel salaryDataModel);
}

View File

@@ -0,0 +1,17 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface ISaleStorageContract
{
List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null,
string? workerId = null, string? restaurantId = null, string? productId = null);
Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
SaleDataModel? GetElementById(string id);
void AddElement(SaleDataModel saleDataModel);
void DelElement(string id);
}

View File

@@ -0,0 +1,23 @@
using SPiluSZharuContracts.DataModels;
namespace SPiluSZharuContracts.StorageContracts;
public interface IWorkerStorageContract
{
List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null,
DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null);
WorkerDataModel? GetElementById(string id);
WorkerDataModel? GetElementByFIO(string fio);
WorkerDataModel? GetElementByPhoneNumber(string phoneNumber);
void AddElement(WorkerDataModel workerDataModel);
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.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,10 @@
namespace SPiluSZharuContracts.ViewModels;
public class ProductHistoryViewModel
{
public required string ProductName { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,18 @@
namespace SPiluSZharuContracts.ViewModels;
public class ProductViewModel
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public required string RestaurantId { get; set; }
public required string RestaurantName { get; set; }
public required string ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace SPiluSZharuContracts.ViewModels;
public class RestaurantProductViewModel
{
public required string RestaurantName { get; set; }
public required List<string> Products { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.ViewModels;
public class RestaurantViewModel
{
public required string Id { get; set; }
public required string RestaurantName { get; set; }
public string? PrevRestaurantName { get; set; }
public string? PrevPrevRestaurantName { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.ViewModels;
public class SalaryViewModel
{
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public DateTime SalaryDate { get; set; }
public double Salary { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.ViewModels;
public class SaleProductViewModel
{
public required string ProductId { get; set; }
public required string ProductName { get; set; }
public int Count { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,22 @@
namespace SPiluSZharuContracts.ViewModels;
public class SaleViewModel
{
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public string? RestaurantId { get; set; }
public string? RestaurantName { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public bool IsCancel { get; set; }
public required List<SaleProductViewModel> Products { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace SPiluSZharuContracts.ViewModels;
public class WorkerSalaryByPeriodViewModel
{
public required string WorkerFIO { get; set; }
public double TotalSalary { get; set; }
public DateTime FromPeriod { get; set; }
public DateTime ToPeriod { get; set; }
}

View File

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

View File

@@ -0,0 +1,8 @@
using SPiluSZharuContracts.Infrastructure;
namespace SPiluSZharuDatabase;
class DefaultConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "";
}

View File

@@ -0,0 +1,186 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class PostStorageContract : IPostStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public PostStorageContract(SPiluSZharuDbContext 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,189 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class ProductStorageContract : IProductStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Restaurant, RestaurantDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>();
});
_mapper = new Mapper(config);
}
public List<ProductDataModel> GetList(bool onlyActive = true, string? restaurantId = null)
{
try
{
var query = _dbContext.Products.Include(x => x.Restaurant).AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (restaurantId is not null)
{
query = query.Where(x => x.RestaurantId == restaurantId);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public async Task<List<ProductDataModel>> GetListAsync(CancellationToken ct)
{
try
{
return [.. await _dbContext.Products.Include(x => x.Restaurant).Select(x => _mapper.Map<ProductDataModel>(x)).ToListAsync(ct)];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<ProductHistoryDataModel> GetHistoryByProductId(string productId)
{
try
{
return [.. _dbContext.ProductHistories.Include(x => x.Product).Where(x => x.ProductId == productId).OrderByDescending(x => x.ChangeDate).Select(x => _mapper.Map<ProductHistoryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<ProductDataModel>(GetProductById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public ProductDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<ProductDataModel>(_dbContext.Products.Include(x => x.Restaurant).FirstOrDefault(x => x.ProductName == name && !x.IsDeleted));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(ProductDataModel productDataModel)
{
try
{
_dbContext.Products.Add(_mapper.Map<Product>(productDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", productDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(ProductDataModel productDataModel)
{
try
{
var transaction = _dbContext.Database.BeginTransaction();
try
{
var element = GetProductById(productDataModel.Id) ?? throw new ElementNotFoundException(productDataModel.Id);
if (element.Price != productDataModel.Price)
{
_dbContext.ProductHistories.Add(new ProductHistory() { ProductId = element.Id, OldPrice = element.Price });
_dbContext.SaveChanges();
}
_dbContext.Products.Update(_mapper.Map(productDataModel, element));
_dbContext.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Products_ProductName_IsDeleted" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("ProductName", productDataModel.ProductName);
}
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 = GetProductById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Product? GetProductById(string id) => _dbContext.Products.Include(x => x.Restaurant).FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,155 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class RestaurantStorageContract : IRestaurantStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public RestaurantStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<RestaurantDataModel> GetList()
{
try
{
return [.. _dbContext.Restaurants.Select(x => _mapper.Map<RestaurantDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<RestaurantDataModel>(GetRestaurantById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementByName(string name)
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.RestaurantName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public RestaurantDataModel? GetElementByOldName(string name)
{
try
{
return _mapper.Map<RestaurantDataModel>(_dbContext.Restaurants.FirstOrDefault(x => x.PrevRestaurantName == name ||
x.PrevPrevRestaurantName == name));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(RestaurantDataModel RestaurantDataModel)
{
try
{
_dbContext.Restaurants.Add(_mapper.Map<Restaurant>(RestaurantDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", RestaurantDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Restaurants_RestaurantName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RestaurantName", RestaurantDataModel.RestaurantName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(RestaurantDataModel RestaurantDataModel)
{
try
{
var element = GetRestaurantById(RestaurantDataModel.Id) ?? throw new ElementNotFoundException(RestaurantDataModel.Id);
if (element.RestaurantName != RestaurantDataModel.RestaurantName)
{
element.PrevPrevRestaurantName = element.PrevRestaurantName;
element.PrevRestaurantName = element.RestaurantName;
element.RestaurantName = RestaurantDataModel.RestaurantName;
}
_dbContext.Restaurants.Update(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "IX_Restaurants_RestaurantName" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("RestaurantName", RestaurantDataModel.RestaurantName);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetRestaurantById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Restaurants.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Restaurant? GetRestaurantById(string id) => _dbContext.Restaurants.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,74 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class SalaryStorageContract : ISalaryStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public SalaryStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<Salary, SalaryDataModel>();
cfg.CreateMap<SalaryDataModel, Salary>()
.ForMember(dest => dest.WorkerSalary, opt => opt.MapFrom(src => src.Salary));
});
_mapper = new Mapper(config);
}
public List<SalaryDataModel> GetList(DateTime? startDate, DateTime? endDate, string? workerId = null)
{
try
{
var query = _dbContext.Salaries.Include(x => x.Worker).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 (workerId != null)
query = query.Where(x => x.WorkerId == workerId);
return [.. query.Select(x => _mapper.Map<SalaryDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public async Task<List<SalaryDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Salaries.Include(x => x.Worker).Where(x => x.SalaryDate >= startDate && x.SalaryDate <= endDate).Select(x => _mapper.Map<SalaryDataModel>(x)).ToListAsync(ct)];
}
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,129 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
using System;
namespace SPiluSZharuDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Restaurant, RestaurantDataModel>();
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<Worker, WorkerDataModel>();
cfg.CreateMap<SaleProduct, SaleProductDataModel>();
cfg.CreateMap<SaleProductDataModel, SaleProduct>();
cfg.CreateMap<Sale, SaleDataModel>();
cfg.CreateMap<SaleDataModel, Sale>()
.ForMember(x => x.IsCancel, x => x.MapFrom(src => false))
.ForMember(x => x.SaleProducts, x => x.MapFrom(src => src.Products));
});
_mapper = new Mapper(config);
}
public List<SaleDataModel> GetList(DateTime? startDate = null, DateTime? endDate = null, string? workerId = null, string? restaurantId = null, string? productId = null)
{
try
{
var query = _dbContext.Sales.Include(x => x.Restaurant).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).AsQueryable();
if (startDate is not null && endDate is not null)
{
query = query.Where(x => x.SaleDate >= startDate && x.SaleDate < endDate);
}
if (workerId is not null)
{
query = query.Where(x => x.WorkerId == workerId);
}
if (restaurantId is not null)
{
query = query.Where(x => x.RestaurantId == restaurantId);
}
if (productId is not null)
{
query = query.Where(x => x.SaleProducts!.Any(y => y.ProductId == productId));
}
return [.. query.Select(x => _mapper.Map<SaleDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public async Task<List<SaleDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
{
try
{
return [.. await _dbContext.Sales.Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).Where(x => x.SaleDate >= startDate && x.SaleDate < endDate).Select(x => _mapper.Map<SaleDataModel>(x)).ToListAsync(ct)];
}
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.Restaurant).Include(x => x.Worker).Include(x => x.SaleProducts)!.ThenInclude(x => x.Product).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,178 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using SPiluSZharuContracts.Exceptions;
using SPiluSZharuContracts.StorageContracts;
using SPiluSZharuDatabase.Models;
namespace SPiluSZharuDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly SPiluSZharuDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(SPiluSZharuDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Post, PostDataModel>()
.ForMember(x => x.Id, x => x.MapFrom(src => src.PostId));
cfg.AddMaps(typeof(SPiluSZharuDbContext).Assembly);
});
_mapper = new Mapper(config);
}
public List<WorkerDataModel> GetList(bool onlyActive = true, string? postId = null, DateTime? fromBirthDate = null, DateTime? toBirthDate = null, DateTime? fromEmploymentDate = null, DateTime? toEmploymentDate = null)
{
try
{
var query = _dbContext.Workers.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
if (postId is not null)
{
query = query.Where(x => x.PostId == postId);
}
if (fromBirthDate is not null && toBirthDate is not null)
{
query = query.Where(x => x.BirthDate >= fromBirthDate && x.BirthDate <= toBirthDate);
}
if (fromEmploymentDate is not null && toEmploymentDate is not null)
{
query = query.Where(x => x.EmploymentDate >= fromEmploymentDate && x.EmploymentDate <= toEmploymentDate);
}
return [.. JoinPost(query).Select(x => _mapper.Map<WorkerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<WorkerDataModel>(GetWorkerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByFIO(string fio)
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public WorkerDataModel? GetElementByPhoneNumber(string phoneNumber)
{
try
{
return _mapper.Map<WorkerDataModel>(AddPost(_dbContext.Workers.FirstOrDefault(x => x.PhoneNumber == phoneNumber && !x.IsDeleted)));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(WorkerDataModel workerDataModel)
{
try
{
_dbContext.Workers.Add(_mapper.Map<Worker>(workerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", workerDataModel.Id);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(WorkerDataModel workerDataModel)
{
try
{
var element = GetWorkerById(workerDataModel.Id) ?? throw new ElementNotFoundException(workerDataModel.Id);
_dbContext.Workers.Update(_mapper.Map(workerDataModel, 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 = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Workers.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Workers.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)
=> query.GroupJoin(_dbContext.Posts.Where(x => x.IsActual), x => x.PostId, y => y.PostId, (x, y) => new { Worker = x, Post = y })
.SelectMany(xy => xy.Post.DefaultIfEmpty(), (x, y) => x.Worker.AddPost(y));
private Worker? AddPost(Worker? worker)
=> worker?.AddPost(_dbContext.Posts.FirstOrDefault(x => x.PostId == worker.PostId && x.IsActual));
}

View File

@@ -0,0 +1,324 @@
// <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 SPiluSZharuDatabase;
#nullable disable
namespace SPiluSZharuDatabase.Migrations
{
[DbContext(typeof(SPiluSZharuDbContext))]
[Migration("20250422183326_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("SPiluSZharuDatabase.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("SPiluSZharuDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("PrevPrevRestaurantName")
.HasColumnType("text");
b.Property<string>("PrevRestaurantName")
.HasColumnType("text");
b.Property<string>("RestaurantName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantName")
.IsUnique();
b.ToTable("Restaurants");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<string>("RestaurantId")
.HasColumnType("text");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
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>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Workers");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
.WithMany()
.HasForeignKey("RestaurantId");
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Restaurant");
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,257 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SPiluSZharuDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
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: "Products",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductName = table.Column<string>(type: "text", nullable: false),
ProductType = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Restaurants",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
RestaurantName = table.Column<string>(type: "text", nullable: false),
PrevRestaurantName = table.Column<string>(type: "text", nullable: true),
PrevPrevRestaurantName = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Restaurants", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Workers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PhoneNumber = 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_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ProductHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductId = 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_ProductHistories", x => x.Id);
table.ForeignKey(
name: "FK_ProductHistories_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Sales",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
RestaurantId = 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),
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sales", x => x.Id);
table.ForeignKey(
name: "FK_Sales_Restaurants_RestaurantId",
column: x => x.RestaurantId,
principalTable: "Restaurants",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Sales_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SaleProducts",
columns: table => new
{
SaleId = table.Column<string>(type: "text", nullable: false),
ProductId = 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_SaleProducts", x => new { x.SaleId, x.ProductId });
table.ForeignKey(
name: "FK_SaleProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SaleProducts_Sales_SaleId",
column: x => x.SaleId,
principalTable: "Sales",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
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_ProductHistories_ProductId",
table: "ProductHistories",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Products_ProductName_IsDeleted",
table: "Products",
columns: new[] { "ProductName", "IsDeleted" },
unique: true,
filter: "\"IsDeleted\" = FALSE");
migrationBuilder.CreateIndex(
name: "IX_Restaurants_RestaurantName",
table: "Restaurants",
column: "RestaurantName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_SaleProducts_ProductId",
table: "SaleProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Sales_RestaurantId",
table: "Sales",
column: "RestaurantId");
migrationBuilder.CreateIndex(
name: "IX_Sales_WorkerId",
table: "Sales",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_Workers_PhoneNumber",
table: "Workers",
column: "PhoneNumber",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "ProductHistories");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "SaleProducts");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Sales");
migrationBuilder.DropTable(
name: "Restaurants");
migrationBuilder.DropTable(
name: "Workers");
}
}
}

View File

@@ -0,0 +1,325 @@
// <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 SPiluSZharuDatabase;
#nullable disable
namespace SPiluSZharuDatabase.Migrations
{
[DbContext(typeof(SPiluSZharuDbContext))]
[Migration("20250423150347_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("SPiluSZharuDatabase.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("SPiluSZharuDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("PrevPrevRestaurantName")
.HasColumnType("text");
b.Property<string>("PrevRestaurantName")
.HasColumnType("text");
b.Property<string>("RestaurantName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantName")
.IsUnique();
b.ToTable("Restaurants");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<string>("RestaurantId")
.HasColumnType("text");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
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>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Workers");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
.WithMany()
.HasForeignKey("RestaurantId");
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Restaurant");
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SPiluSZharuDatabase.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,328 @@
// <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 SPiluSZharuDatabase;
#nullable disable
namespace SPiluSZharuDatabase.Migrations
{
[DbContext(typeof(SPiluSZharuDbContext))]
[Migration("20250423193249_AddDateOfDeleteInWorker")]
partial class AddDateOfDeleteInWorker
{
/// <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("SPiluSZharuDatabase.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("SPiluSZharuDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("PrevPrevRestaurantName")
.HasColumnType("text");
b.Property<string>("PrevRestaurantName")
.HasColumnType("text");
b.Property<string>("RestaurantName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantName")
.IsUnique();
b.ToTable("Restaurants");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<string>("RestaurantId")
.HasColumnType("text");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", 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<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Workers");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
.WithMany()
.HasForeignKey("RestaurantId");
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Restaurant");
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@@ -0,0 +1,325 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using SPiluSZharuDatabase;
#nullable disable
namespace SPiluSZharuDatabase.Migrations
{
[DbContext(typeof(SPiluSZharuDbContext))]
partial class SPiluSZharuDbContextModelSnapshot : 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("SPiluSZharuDatabase.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("SPiluSZharuDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Restaurant", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("PrevPrevRestaurantName")
.HasColumnType("text");
b.Property<string>("PrevRestaurantName")
.HasColumnType("text");
b.Property<string>("RestaurantName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantName")
.IsUnique();
b.ToTable("Restaurants");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<string>("RestaurantId")
.HasColumnType("text");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RestaurantId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", 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<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Workers");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.ProductHistory", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Salary", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Restaurant", "Restaurant")
.WithMany()
.HasForeignKey("RestaurantId");
b.HasOne("SPiluSZharuDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Restaurant");
b.Navigation("Worker");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.SaleProduct", b =>
{
b.HasOne("SPiluSZharuDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SPiluSZharuDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("SPiluSZharuDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,21 @@
using SPiluSZharuContracts.Enums;
using SPiluSZharuContracts.Infrastructure.PostConfiguration;
namespace SPiluSZharuDatabase.Models;
internal 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,27 @@
using SPiluSZharuContracts.Enums;
using System.ComponentModel.DataAnnotations.Schema;
namespace SPiluSZharuDatabase.Models;
internal class Product
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public ProductType ProductType { get; set; }
public required string RestaurantId { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
public Restaurant? Restaurant { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SPiluSZharuDatabase.Models;
internal class ProductHistory
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductId { get; set; }
public double OldPrice { get; set; }
public DateTime ChangeDate { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,20 @@
using AutoMapper;
using SPiluSZharuContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace SPiluSZharuDatabase.Models;
[AutoMap(typeof(RestaurantDataModel), ReverseMap = true)]
internal class Restaurant
{
public required string Id { get; set; }
public required string RestaurantName { get; set; }
public string? PrevRestaurantName { get; set; }
public string? PrevPrevRestaurantName { get; set; }
[ForeignKey("ManufacturerId")]
public List<Product>? Products { get; set; }
}

View File

@@ -0,0 +1,14 @@
namespace SPiluSZharuDatabase.Models;
internal class Salary
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public DateTime SalaryDate { get; set; }
public double WorkerSalary { get; set; }
public Worker? Worker { get; set; }
}

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