11 Commits
lab2 ... lab4

Author SHA1 Message Date
8bba63c888 скидка доработана по заданию 2025-09-12 03:33:24 +04:00
0c0ad9924c скидка 2025-09-12 02:06:03 +04:00
d9288a2165 4 теста контроллера 2025-09-12 00:34:40 +04:00
d8c0ff638b тесты хранилищ 2025-09-11 17:14:41 +04:00
b1c8b4fbe8 пара адаптеров + какие-то непонятные пустые строки 2025-09-11 16:50:08 +04:00
018c94c7ff 1/2 2025-05-08 17:26:13 +04:00
7842195715 final lab3 (100%) 2025-04-14 20:04:36 +04:00
227a800d27 тесты 2025-04-14 12:06:51 +04:00
dbfb6a1fd2 без тестов и скидки 2025-04-12 12:40:33 +04:00
8d8b952a82 1 2025-04-12 12:13:55 +04:00
276c84948e 12 2025-03-31 15:32:15 +04:00
142 changed files with 7817 additions and 323 deletions

View File

@@ -9,6 +9,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RomashkiTests", "RomashkiTe
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RomashkiBusinessLogic", "RomashkiBusinessLogic\RomashkiBusinessLogic.csproj", "{DDA1EFF5-DA12-43AD-96BD-56C2A7D26804}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RomashkiDatabase", "RomashkiDatabase\RomashkiDatabase.csproj", "{84381B2C-2FCF-4EFB-85AA-F959C81C0590}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RomashkiWebApi", "RomashkiWebApi\RomashkiWebApi.csproj", "{D60989C0-EDB5-4541-B6DC-0D0B1D6F8A3D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +31,14 @@ Global
{DDA1EFF5-DA12-43AD-96BD-56C2A7D26804}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDA1EFF5-DA12-43AD-96BD-56C2A7D26804}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDA1EFF5-DA12-43AD-96BD-56C2A7D26804}.Release|Any CPU.Build.0 = Release|Any CPU
{84381B2C-2FCF-4EFB-85AA-F959C81C0590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84381B2C-2FCF-4EFB-85AA-F959C81C0590}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84381B2C-2FCF-4EFB-85AA-F959C81C0590}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84381B2C-2FCF-4EFB-85AA-F959C81C0590}.Release|Any CPU.Build.0 = Release|Any CPU
{D60989C0-EDB5-4541-B6DC-0D0B1D6F8A3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D60989C0-EDB5-4541-B6DC-0D0B1D6F8A3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D60989C0-EDB5-4541-B6DC-0D0B1D6F8A3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D60989C0-EDB5-4541-B6DC-0D0B1D6F8A3D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -1,4 +1,4 @@
using RomashkiContract.BusinessLogicContracts;
using RomashkiContract.BusinessLogicContracts;
using RomashkiContract.StoragesContracts;
using Microsoft.Extensions.Logging;
using RomashkiContracts.DataModels;
@@ -70,29 +70,7 @@ internal class BuyerBusinessLogicContract(IBuyerStorageContract buyerStorageCont
}
_buyerStorageContract.DelElement(id);
}
/*
private readonly ILogger _logger = logger;
private readonly IBuyerStorageContract _buyerStorageContract =
buyerStorageContract;
public List<BuyerDataModel> GetAllBuyers()
{
return [];
}
public BuyerDataModel GetBuyerByData(string data)
{
return new("", "", "", 0);
}
public void InsertBuyer(BuyerDataModel buyerDataModel)
{
}
public void UpdateBuyer(BuyerDataModel buyerDataModel)
{
}
public void DeleteBuyer(string id)
{
}
*/
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using RomashkiContract.BusinessLogicContracts;
@@ -132,23 +132,3 @@ internal class DiscountBusinessLogicContract : IDiscountBusinessLogicContract
}
//private readonly ILogger _logger = logger;
//private readonly IDiscountStorageContract _discountStorageContract =
//discountStorageContract;
//private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
//private readonly IPostStorageContract _postStorageContract = postStorageContract;
//private readonly IBuyerStorageContract _buyerStorageContract = buyerStorageContract;
//public List<DiscountDataModel> GetAllDiscountsByPeriod(DateTime fromDate, DateTime toDate)
//{
// return [];
//}
//public List<DiscountDataModel> GetAllDiscountsByPeriodByBuyer(DateTime fromDate, DateTime toDate, string buyerId)
//{
// return [];
//}
//public void CalculateDiscountsByMounth(DateTime date)
//{
//}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -22,10 +22,10 @@ postStorageContract, ILogger logger) : IPostBusinessLogicContract
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract =
postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
public List<PostDataModel> GetAllPosts()
{
_logger.LogInformation("GetAllPosts params: {onlyActive}", onlyActive);
return _postStorageContract.GetList(onlyActive) ?? throw new NullListException();
_logger.LogInformation("GetAllPosts");
return _postStorageContract.GetList() ?? throw new NullListException();
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
@@ -96,33 +96,4 @@ postStorageContract, ILogger logger) : IPostBusinessLogicContract
}
_postStorageContract.ResElement(id);
}
/*
private readonly ILogger _logger = logger;
private readonly IPostStorageContract _postStorageContract =
postStorageContract;
public List<PostDataModel> GetAllPosts(bool onlyActive = true)
{
return [];
}
public List<PostDataModel> GetAllDataOfPost(string postId)
{
return [];
}
public PostDataModel GetPostByData(string data)
{
return new("", "", PostType.None, true, DateTime.UtcNow);
}
public void InsertPost(PostDataModel postDataModel)
{
}
public void UpdatePost(PostDataModel postDataModel)
{
}
public void DeletePost(string id)
{
}
public void RestorePost(string id)
{
}*/
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -80,40 +80,6 @@ productStorageContract, ILogger logger) : IProductBusinessLogicContract
}
_productStorageContract.DelElement(id);
}
/*
private readonly ILogger _logger = logger;
private readonly IProductStorageContract _productStorageContract =
productStorageContract;
public List<ProductDataModel> GetAllProducts(bool onlyActive)
{
return [];
}
public List<ProductDataModel> GetAllProductsByManufacturer(string
manufacturerId, bool onlyActive = true)
{
return [];
}
public List<ProductHistoryDataModel> GetProductHistoryByProduct(string
productId)
{
return [];
}
public ProductDataModel GetProductByData(string data)
{
return new("", "", ProductType.None, 0, true);
}
public void InsertProduct(ProductDataModel productDataModel)
{
}
public void UpdateProduct(ProductDataModel productDataModel)
{
}
public void DeleteProduct(string id)
{
}
*/
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -122,44 +122,5 @@ saleStorageContract, ILogger logger) : ISaleBusinessLogicContract
}
_saleStorageContract.DelElement(id);
}
/*
private readonly ILogger _logger = logger;
private readonly ISaleStorageContract _saleStorageContract =
saleStorageContract;
public List<SaleDataModel> GetAllSalesByPeriod(DateTime fromDate, DateTime
toDate)
{
return [];
}
public List<SaleDataModel> GetAllSalesByWorkerByPeriod(string workerId,
DateTime fromDate, DateTime toDate)
{
return [];
}
public List<SaleDataModel> GetAllSalesByBuyerByPeriod(string? buyerId,
DateTime fromDate, DateTime toDate)
{
return [];
}
public List<SaleDataModel> GetAllSalesByProductByPeriod(string productId,
DateTime fromDate, DateTime toDate)
{
return [];
}
public SaleDataModel GetSaleByData(string data)
{
return new("", "", "", 0, DiscountType.None, 0, false, []);
}
public void InsertSale(SaleDataModel saleDataModel)
{
}
public void CancelSale(string id)
{
}*/
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -107,41 +107,5 @@ workerStorageContract, ILogger logger) : IWorkerBusinessLogicContract
}
_workerStorageContract.DelElement(id);
}
/* private readonly ILogger _logger = logger;
private readonly IWorkerStorageContract _workerStorageContract =
workerStorageContract;
public List<WorkerDataModel> GetAllWorkers(bool onlyActive = true)
{
return [];
}
public List<WorkerDataModel> GetAllWorkersByBirthDate(DateTime fromDate,
DateTime toDate, bool onlyActive = true)
{
return [];
}
public List<WorkerDataModel> GetAllWorkersByEmploymentDate(DateTime
fromDate, DateTime toDate, bool onlyActive = true)
{
return [];
}
public WorkerDataModel GetWorkerByData(string data)
{
return new("", "", "", DateTime.Now, DateTime.Now, true);
}
public void InsertWorker(WorkerDataModel workerDataModel)
{
}
public void UpdateWorker(WorkerDataModel workerDataModel)
{
}
public void DeleteWorker(string id)
{
}*/
}

View File

@@ -7,11 +7,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2" />
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="RomashkiTests" />
<InternalsVisibleTo Include="RomashkiWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
using RomashkiContract.BindingModels;
namespace RomashkiContract.AdapterContracts;
public interface IBuyerAdapter
{
BuyerOperationResponse GetList();
BuyerOperationResponse GetElement(string data);
BuyerOperationResponse RegisterBuyer(BuyerBindingModel buyerModel);
BuyerOperationResponse ChangeBuyerInfo(BuyerBindingModel buyerModel);
BuyerOperationResponse RemoveBuyer(string id);
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
namespace RomashkiContract.AdapterContracts;
public interface IDiscountAdapter
{
DiscountOperationResponse GetList(DateTime startDate, DateTime endDate);
DiscountOperationResponse GetListByBuyer(DateTime startDate, DateTime endDate, string buyerId);
DiscountOperationResponse CalculateDiscountsByMonth(DateTime date);
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
using RomashkiContract.BindingModels;
namespace RomashkiContract.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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
using RomashkiContract.BindingModels;
namespace RomashkiContract.AdapterContracts;
public interface IProductAdapter
{
ProductOperationResponse GetList(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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
using RomashkiContract.BindingModels;
namespace RomashkiContract.AdapterContracts;
public interface ISaleAdapter
{
SaleOperationResponse GetList(DateTime fromDate, DateTime toDate);
SaleOperationResponse GetWorkerList(string id, DateTime fromDate, DateTime toDate);
SaleOperationResponse GetBuyerList(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,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.AdapterContracts.OperationResponses;
using RomashkiContract.BindingModels;
namespace RomashkiContract.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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.AdapterContracts.OperationResponses;
public class BuyerOperationResponse : OperationResponse
{
public static BuyerOperationResponse OK(List<BuyerViewModel> data) => OK<BuyerOperationResponse, List<BuyerViewModel>>(data);
public static BuyerOperationResponse OK(BuyerViewModel data) => OK<BuyerOperationResponse, BuyerViewModel>(data);
public static BuyerOperationResponse NoContent() => NoContent<BuyerOperationResponse>();
public static BuyerOperationResponse BadRequest(string message) => BadRequest<BuyerOperationResponse>(message);
public static BuyerOperationResponse NotFound(string message) => NotFound<BuyerOperationResponse>(message);
public static BuyerOperationResponse InternalServerError(string message) => InternalServerError<BuyerOperationResponse>(message);
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.AdapterContracts.OperationResponses;
public class DiscountOperationResponse : OperationResponse
{
public static DiscountOperationResponse OK(List<DiscountViewModel> data) => OK<DiscountOperationResponse, List<DiscountViewModel>>(data);
public static DiscountOperationResponse OK(DiscountViewModel data) => OK<DiscountOperationResponse, DiscountViewModel>(data);
public static DiscountOperationResponse OK(object data) => OK<DiscountOperationResponse, object>(data);
public static DiscountOperationResponse NoContent() => NoContent<DiscountOperationResponse>();
public static DiscountOperationResponse NotFound(string message) => NotFound<DiscountOperationResponse>(message);
public static DiscountOperationResponse BadRequest(string message) => BadRequest<DiscountOperationResponse>(message);
public static DiscountOperationResponse InternalServerError(string message) => InternalServerError<DiscountOperationResponse>(message);
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.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,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.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,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContract.Infrastructure;
using RomashkiContract.ViewModels;
namespace RomashkiContract.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class BuyerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? Email { get; set; }
public float TotalSpend { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class DiscountBindingModel
{
public string? Id { get; set; }
public string? BuyerId { get; set; }
public DateTime? DiscountDate { get; set; }
public double? DiscountSize { get; set; }
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class PostBindingModel
{
public string? Id { get; set; }
public string? PostId => Id;
public string? PostName { get; set; }
public string? PostType { get; set; }
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class ProductBindingModel
{
public string? Id { get; set; }
public string? ProductName { get; set; }
public string? ProductType { get; set; }
public double Price { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class SaleBindingModel
{
public string? Id { get; set; }
public string? WorkerId { get; set; }
public string? BuyerId { get; set; }
public int DiscountType { get; set; }
public List<SaleProductBindingModel>? Products { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.BindingModels;
public class WorkerBindingModel
{
public string? Id { get; set; }
public string? FIO { get; set; }
public string? PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -9,11 +9,11 @@ namespace RomashkiContract.BusinessLogicContracts;
public interface IPostBusinessLogicContract
{
List<PostDataModel> GetAllPosts(bool onlyActive);
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

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -11,6 +11,7 @@ namespace RomashkiContract.DataModels;
public class DiscountDataModel(string buyerId, DateTime discountDate, double discountSize) : IValidation
{
public string Id { get; private set; } = Guid.NewGuid().ToString();
public string BuyerId{ get; private set; } = buyerId;
public DateTime DiscountDate { get; private set; } = discountDate;
public double DiscountSize { get; private set; } = discountSize;
@@ -20,11 +21,10 @@ public class DiscountDataModel(string buyerId, DateTime discountDate, double dis
throw new ValidationException("Field BuyerId is empty");
if (!BuyerId.IsGuid())
throw new ValidationException("The value in the field BuyerId is not a unique identifier");
if (discountSize < 0)
if (DiscountSize < 0)
throw new ValidationException("Field DiscountSize is less than or equal to 0");
if (discountSize > 100)
if (DiscountSize > 100)
throw new ValidationException("Field DiscountSize is more than 100");
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -11,25 +11,24 @@ using RomashkiContracts.Exceptions;
namespace RomashkiContracts.DataModels;
public class PostDataModel(string id, string postName,
PostType postType, bool isActual, DateTime changeDate) : IValidation
public class PostDataModel(string postId, string postName, PostType postType) : IValidation
{
public string Id { get; private set; } = id;
public string Id { get; private set; } = postId;
public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType;
public bool IsActual { get; private set; } = isActual;
public DateTime ChangeDate { get; private set; } = changeDate;
public void Validate()
{
if (Id.IsEmpty())
throw new ValidationException("Field Id is empty");
if (!Id.IsGuid())
throw new ValidationException("The value in the field Id is not a unique identifier");
if (PostName.IsEmpty())
throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -14,6 +14,7 @@ public class ProductHistoryDataModel(string productId, double oldPrice) : IValid
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public ProductDataModel? Product { get; set; }
public void Validate()
{
if (ProductId.IsEmpty())

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -23,14 +23,15 @@ public class SaleDataModel : IValidation
public bool IsCancel { get; private set; }
public List<SaleProductDataModel>? Products { get; private set; }
public SaleDataModel(string id, string workerId, string? buyerId,
DiscountType discountType, bool isCancel, List<SaleProductDataModel> products)
DiscountType discountType, bool isCancel, List<SaleProductDataModel>
saleProducts)
{
Id = id;
WorkerId = workerId;
BuyerId = buyerId;
DiscountType = discountType;
IsCancel = isCancel;
Products = products;
Products = saleProducts;
var percent = 0.0;
foreach (DiscountType elem in Enum.GetValues<DiscountType>())
{

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -33,4 +33,3 @@ double price) : IValidation
throw new ValidationException("Field Price is less than or equal to 0");
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.Exceptions;
public class ElementDeletedException : Exception
{
public ElementDeletedException(string id) : base($"Cannot modify a deleted item(id: { id})") { }
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -12,4 +12,4 @@ public static class DateTimeExtensions
{
return date >= olderDate;
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,4 +16,4 @@ public static class StringExtensions
{
return Guid.TryParse(str, out _);
}
}
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.Infrastructure;
public interface IConfigurationDatabase
{
string ConnectionString { get; }
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

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

View File

@@ -6,4 +6,18 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -9,7 +9,7 @@ namespace RomashkiContract.StoragesContracts;
public interface IPostStorageContract
{
List<PostDataModel> GetList(bool onlyActual = true);
List<PostDataModel> GetList();
List<PostDataModel> GetPostWithHistory(string postId);
PostDataModel? GetElementById(string id);
PostDataModel? GetElementByName(string name);

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,4 +16,4 @@ public interface IProductStorageContract
void AddElement(ProductDataModel productDataModel);
void UpdElement(ProductDataModel productDataModel);
void DelElement(string id);
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.ViewModels;
public class BuyerViewModel
{
public required string Id { get; set; }
public required string FIO { get; set; }
public required string Email { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.ViewModels;
public class DiscountViewModel
{
public required string Id { get; set; }
public required string BuyerId { get; set; }
public required string BuyerFIO { get; set; }
public DateTime DiscountDate { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.ViewModels;
public class PostViewModel
{
public required string Id { get; set; }
public required string PostName { get; set; }
public required string PostType { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.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,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.ViewModels;
public class ProductViewModel
{
public required string Id { get; set; }
public required string ProductName { get; set; }
public required string ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.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,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.ViewModels;
public class SaleViewModel
{
public required string Id { get; set; }
public required string WorkerId { get; set; }
public required string WorkerFIO { get; set; }
public string? BuyerId { get; set; }
public string? BuyerFIO { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public required string DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public required List<SaleProductViewModel> Products { get; set; }
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiContract.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 bool IsDeleted { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
}

View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiContracts.DataModels;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations;
internal class BuyerStorageContract : IBuyerStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public BuyerStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Buyer));
});
_mapper = new Mapper(config);
}
public List<BuyerDataModel> GetList()
{
try
{
return [.. _dbContext.Buyers.Select(x =>
_mapper.Map<BuyerDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<BuyerDataModel>(GetBuyerById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByFIO(string fio)
{
try
{
return
_mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.FIO == fio));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public BuyerDataModel? GetElementByEmail(string email)
{
try
{
return
_mapper.Map<BuyerDataModel>(_dbContext.Buyers.FirstOrDefault(x => x.Email == email));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(BuyerDataModel buyerDataModel)
{
try
{
_dbContext.Buyers.Add(_mapper.Map<Buyer>(buyerDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name ==
"ThrowIdentityConflict")
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Id", buyerDataModel.Id);
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Buyers_Email" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Email", buyerDataModel.Email);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdElement(BuyerDataModel buyerDataModel)
{
try
{
var element = GetBuyerById(buyerDataModel.Id) ?? throw new
ElementNotFoundException(buyerDataModel.Id);
_dbContext.Buyers.Update(_mapper.Map(buyerDataModel,
element));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (DbUpdateException ex) when (ex.InnerException is
PostgresException { ConstraintName: "IX_Buyers_Email" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException("Email",buyerDataModel.Email);
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DelElement(string id)
{
try
{
var element = GetBuyerById(id) ?? throw new
ElementNotFoundException(id);
_dbContext.Buyers.Remove(element);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Buyer? GetBuyerById(string id) =>
_dbContext.Buyers.FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using RomashkiContract.DataModels;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations;
internal class DiscountStorageContract : IDiscountStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public DiscountStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Discount, DiscountDataModel>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id));
cfg.CreateMap<DiscountDataModel, Discount>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id));
});
_mapper = new Mapper(config);
}
public List<DiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? buyerId = null)
{
try
{
var query = _dbContext.Discounts.Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate);
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
return [.. query.Select(x => _mapper.Map<DiscountDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(DiscountDataModel discountDataModel)
{
try
{
_dbContext.Discounts.Add(_mapper.Map<Discount>(discountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}

View File

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

View File

@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiContracts.DataModels;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations
{
internal class ProductStorageContract : IProductStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public ProductStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductDataModel>();
cfg.CreateMap<ProductDataModel, Product>()
.ForMember(x => x.IsDeleted, x => x.MapFrom(src => false));
cfg.CreateMap<ProductHistory, ProductHistoryDataModel>()
.ForMember(dest => dest.Product, opt => opt.MapFrom(src => src.Product));
});
_mapper = new Mapper(config);
}
public List<ProductDataModel> GetList(bool onlyActive = true)
{
try
{
var query = _dbContext.Products.AsQueryable();
if (onlyActive)
{
query = query.Where(x => !x.IsDeleted);
}
return [.. query.Select(x => _mapper.Map<ProductDataModel>(x))];
}
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.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.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}
}

View File

@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiContracts.DataModels;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations;
internal class SaleStorageContract : ISaleStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public SaleStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
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? buyerId = null, string?
productId = null)
{
try
{
var query = _dbContext.Sales.Include(x =>
x.SaleProducts).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 (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
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 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.SaleProducts).FirstOrDefault(x => x.Id == id);
}

View File

@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiContracts.DataModels;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations;
internal class WorkerStorageContract : IWorkerStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public WorkerStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(Worker));
});
_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 [.. 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>(_dbContext.Workers.FirstOrDefault(x => x.FIO == fio));
}
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;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => _dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted);
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using RomashkiContracts.DataModels;
namespace RomashkiDatabase.Models;
[AutoMap(typeof(BuyerDataModel), ReverseMap = true)]
class Buyer
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public string? FIO { get; set; }
public required string Email { get; set; }
public float TotalSpend { get; set; }
public double DiscountSize { get; set; }
[ForeignKey("BuyerId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiDatabase.Models;
class Discount
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string BuyerId { get; set; }
public DateTime DiscountDate { get; set; }
public double DiscountSize { get; set; }
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContracts.Enums;
namespace RomashkiDatabase.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 bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContracts.Enums;
namespace RomashkiDatabase.Models;
class Product
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string ProductName { get; set; }
public ProductType ProductType { get; set; }
public double Price { get; set; }
public bool IsDeleted { get; set; }
public string? PrevProductName { get; set; }
public string? PrevPrevProductName { get; set; }
[ForeignKey("ProductId")]
public List<ProductHistory>? ProductHistories { get; set; }
[ForeignKey("ProductId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiDatabase.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; } = DateTime.UtcNow;
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RomashkiContracts.DataModels;
using System.Xml;
using RomashkiContracts.Enums;
using RomashkiContracts.Extensions;
using RomashkiContracts.Exceptions;
namespace RomashkiDatabase.Models;
internal class Sale
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public required string WorkerId { get; set; }
public string? BuyerId { get; set; }
public DateTime SaleDate { get; set; }
public double Sum { get; set; }
public DiscountType DiscountType { get; set; }
public double Discount { get; set; }
public bool IsCancel { get; set; }
public Worker? Worker { get; set; }
public Buyer? Buyer { get; set; }
[ForeignKey("SaleId")]
public List<SaleProduct>? SaleProducts { get; set; }
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomashkiDatabase.Models;
internal class SaleProduct
{
public required string SaleId { get; set; }
public required string ProductId { get; set; }
public int Count { get; set; }
public double Price { get; set; }
public Sale? Sale { get; set; }
public Product? Product { get; set; }
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using RomashkiContracts.DataModels;
namespace RomashkiDatabase.Models;
[AutoMap(typeof(WorkerDataModel), ReverseMap = true)]
internal class Worker
{
public required string Id { get; set; } = Guid.NewGuid().ToString();
public required string FIO { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[ForeignKey("WorkerId")]
public List<Sale>? Sales { get; set; }
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RomashkiContract\RomashkiContract.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="RomashkiTests" />
<InternalsVisibleTo Include="RomashkiWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using RomashkiContract.Infrastructure;
using RomashkiDatabase.Models;
namespace RomashkiDatabase;
internal class RomashkiDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public RomashkiDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Buyer>().HasIndex(x => x.Email).IsUnique();
modelBuilder.Entity<Sale>()
.HasOne(e => e.Buyer)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Sale>()
.HasOne(e => e.Buyer)
.WithMany(e => e.Sales)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>()
.HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Product>()
.HasIndex(x => new { x.ProductName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Product.IsDeleted)}\" = FALSE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
}
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductHistory> ProductHistories { get; set; }
public DbSet<Discount> Discounts { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Worker> Workers { get; set; }
}

View File

@@ -1,4 +1,4 @@
using Moq;
using Moq;
using RomashkiBusinessLogic.Implementations;
using RomashkiContract.StoragesContracts;
using RomashkiContracts.DataModels;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -35,36 +35,30 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, true, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, false, DateTime.UtcNow),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, true, DateTime.UtcNow),
};
_postStorageContract.Setup(x =>
x.GetList(It.IsAny<bool>())).Returns(listOriginal);
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var list = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
Assert.That(listOnlyActive, Is.Not.Null);
Assert.That(listAll, Is.Not.Null);
Assert.That(listOnlyActive, Is.EquivalentTo(listOriginal));
Assert.That(listAll, Is.EquivalentTo(listOriginal));
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.EquivalentTo(listOriginal));
});
_postStorageContract.Verify(x => x.GetList(true), Times.Once);
_postStorageContract.Verify(x => x.GetList(false), Times.Once);
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_ReturnEmptyList_Test()
{
//Arrange
_postStorageContract.Setup(x =>
x.GetList(It.IsAny<bool>())).Returns([]);
_postStorageContract.Setup(x => x.GetList()).Returns([]);
//Act
var listOnlyActive = _postBusinessLogicContract.GetAllPosts(true);
var listAll = _postBusinessLogicContract.GetAllPosts(false);
var listOnlyActive = _postBusinessLogicContract.GetAllPosts();
var listAll = _postBusinessLogicContract.GetAllPosts();
//Assert
Assert.Multiple(() =>
{
@@ -73,30 +67,30 @@ x.GetList(It.IsAny<bool>())).Returns([]);
Assert.That(listOnlyActive, Has.Count.EqualTo(0));
Assert.That(listAll, Has.Count.EqualTo(0));
});
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()),
_postStorageContract.Verify(x => x.GetList(),
Times.Exactly(2));
}
[Test]
public void GetAllPosts_ReturnNull_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()),
Assert.That(() => _postBusinessLogicContract.GetAllPosts(),
Throws.TypeOf<NullListException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllPosts_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.GetList(It.IsAny<bool>()))
_postStorageContract.Setup(x => x.GetList())
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.GetAllPosts(It.IsAny<bool>()),
Assert.That(() => _postBusinessLogicContract.GetAllPosts(),
Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.GetList(It.IsAny<bool>()), Times.Once);
_postStorageContract.Verify(x => x.GetList(), Times.Once);
}
[Test]
public void GetAllDataOfPost_ReturnListOfRecords_Test()
@@ -105,8 +99,8 @@ x.GetList(It.IsAny<bool>())).Returns([]);
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Assistant, true, DateTime.UtcNow),
new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
new(postId, "name 1", PostType.Assistant),
new(postId, "name 2", PostType.Assistant)
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -169,7 +163,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Assistant, true, DateTime.UtcNow);
var record = new PostDataModel(id, "name", PostType.Assistant);
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -183,7 +177,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, true, DateTime.UtcNow);
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant);
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -244,14 +238,13 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor,
true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor);
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName ==
record.PostName && x.PostType == record.PostType && x.ChangeDate == record.ChangeDate;
record.PostName && x.PostType == record.PostType;
});
//Act
_postBusinessLogicContract.InsertPost(record);
@@ -268,7 +261,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
.Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
PostType.Supervisor)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -284,7 +277,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name",
PostType.Supervisor,true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
PostType.Supervisor)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -295,8 +288,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor,
true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
_postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -305,13 +297,12 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor,
true, DateTime.UtcNow.AddDays(-1));
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor);
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) =>
{
flag = x.Id == record.Id && x.PostName ==
record.PostName && x.PostType == record.PostType && x.ChangeDate == record.ChangeDate;
record.PostName && x.PostType == record.PostType;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
@@ -326,8 +317,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, true, DateTime.UtcNow)),
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor)),
Throws.TypeOf<ElementNotFoundException>()); _postStorageContract
.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -338,8 +328,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() =>
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor,
true, DateTime.UtcNow)), Throws.TypeOf<ElementExistsException>());
_postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor)), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -355,7 +344,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name",
PostType.Supervisor, true, DateTime.UtcNow)), Throws.TypeOf<ValidationException>());
PostType.Supervisor)), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -368,7 +357,7 @@ new(postId, "name 2", PostType.Assistant, false, DateTime.UtcNow)
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name",
PostType.Supervisor, true, DateTime.UtcNow)), Throws.TypeOf<StorageException>());
PostType.Supervisor)), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -1,4 +1,4 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using Moq;
using RomashkiBusinessLogic.Implementations;
using RomashkiContract.Exceptions;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using RomashkiContracts.DataModels;
using RomashkiContracts.DataModels;
using RomashkiContracts.Exceptions;
namespace RomashkiTests.DataModelsTests
@@ -39,7 +39,7 @@ namespace RomashkiTests.DataModelsTests
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PhoneNumberIsIncorrectTest()
public void EmailIsIncorrectTest()
{
var buyer = CreateDataModel(Guid.NewGuid().ToString(), "fio", "email", 10, 10);
Assert.That(() => buyer.Validate(), Throws.TypeOf<ValidationException>());

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -16,10 +16,10 @@ namespace RomashkiTests.DataModelsTests
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name",
PostType.Assistant, true, DateTime.UtcNow);
PostType.Assistant);
Assert.That(() => post.Validate(),
Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Assistant, true, DateTime.UtcNow);
post = CreateDataModel(string.Empty, "name", PostType.Assistant);
Assert.That(() => post.Validate(),
Throws.TypeOf<ValidationException>());
}
@@ -27,7 +27,7 @@ namespace RomashkiTests.DataModelsTests
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name",
PostType.Assistant, true, DateTime.UtcNow);
PostType.Assistant);
Assert.That(() => post.Validate(),
Throws.TypeOf<ValidationException>());
}
@@ -37,17 +37,17 @@ namespace RomashkiTests.DataModelsTests
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(),
null, PostType.Assistant, true, DateTime.UtcNow);
null, PostType.Assistant);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(),
string.Empty, PostType.Assistant, true, DateTime.UtcNow);
string.Empty, PostType.Assistant);
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(),
"name", PostType.None, true, DateTime.UtcNow);
"name", PostType.None);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -60,19 +60,16 @@ namespace RomashkiTests.DataModelsTests
var postType = PostType.Assistant;
var isActual = false;
var changeDate = DateTime.UtcNow.AddDays(-1);
var post = CreateDataModel(postId, postName, postType, isActual, changeDate);
var post = CreateDataModel(postId, postName, postType);
Assert.That(() => post.Validate(), Throws.Nothing);
Assert.Multiple(() =>
{
Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(post.IsActual, Is.EqualTo(isActual));
Assert.That(post.ChangeDate, Is.EqualTo(changeDate));
});
}
private static PostDataModel CreateDataModel(string? id,
string? postName, PostType postType, bool isActual, DateTime
changeDate) => new(id, postName, postType, isActual, changeDate);
string? postName, PostType postType) => new(id, postName, postType);
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -156,4 +156,4 @@ new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.3)
private static List<SaleProductDataModel> CreateSubDataModel()
=> [new(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 1, 1.1)];
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -98,4 +98,4 @@ namespace RomashkiTests.DataModelsTests
productId, int count, double price) =>
new(saleId, productId, count, price);
}
}
}

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