lab5-ready

This commit is contained in:
2025-04-14 23:25:14 +04:00
parent dbc3fb8394
commit 8f5c38d239
22 changed files with 710 additions and 172 deletions

View File

@@ -14,7 +14,6 @@ public class PostBindingModel
public string? PostName { get; set; }
public string? PostType { get; set; }
public string? ConfigurationJson { get; set; }
public double Salary { get; set; }
}
}

View File

@@ -3,8 +3,14 @@ using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Extensions;
using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseContracts.DataModels;
@@ -27,7 +33,7 @@ public class PostDataModel(string postId, string postName, PostType postType, Po
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
}
public void Validate()
{

View File

@@ -8,7 +8,12 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" />
</ItemGroup>

View File

@@ -1,11 +1,10 @@
using CandyHouseContracts.Infrastructure;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CandyHouseDatabase;
@@ -43,6 +42,12 @@ public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) :
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<SaleProduct>().HasKey(x => new { x.SaleId, x.ProductId });
modelBuilder.Entity<Post>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x));
}
public DbSet<Client> Clients { get; set; }
@@ -60,4 +65,11 @@ public class CandyHouseDbContext(IConfigurationDatabase configurationDatabase) :
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Employee> Employees { get; set; }
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(ManagerPostConfiguration) => JsonConvert.DeserializeObject<ManagerPostConfiguration>(jsonString)!,
nameof(BakerPostConfiguration) => JsonConvert.DeserializeObject<BakerPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
}

View File

@@ -18,22 +18,22 @@ public class Employee
public string Email { get; set; }
public string PostId { get; set; }
public required string PostId { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EmploymentDate { get; set; }
public bool IsDeleted { get; set; }
[NotMapped]
public Post? Post { get; set; }
[ForeignKey("EmployeeId")]
public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")]
public List<Sale>? Sales { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped] public Post? Post { get; set; }
[ForeignKey("EmployeeId")] public List<Salary>? Salaries { get; set; }
[ForeignKey("EmployeeId")] public List<Sale>? Sales { get; set; }
public Employee AddPost(Post? post)
{
Post = post;
return this;
}
}
}

View File

@@ -1,10 +1,5 @@
using CandyHouseContracts.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseContracts.Infrastructure.PostConfigurations;
namespace CandyHouseDatabase.Models;
@@ -14,7 +9,8 @@ public class Post
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
public double Salary { get; set; }
public required PostConfiguration Configuration { get; set; }
public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; }
}

View File

@@ -0,0 +1,11 @@
using Microsoft.EntityFrameworkCore.Design;
namespace CandyHouseDatabase;
public class SampleContextFactory : IDesignTimeDbContextFactory<CandyHouseDbContext>
{
public CandyHouseDbContext CreateDbContext(string[] args)
{
return new CandyHouseDbContext(new DefaultConfigurationDatabase());
}
}

View File

@@ -2,6 +2,7 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
@@ -38,9 +39,9 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Manager, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Manager, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Manager, 10),
new(Guid.NewGuid().ToString(),"name 1", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
@@ -94,8 +95,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Manager, 10),
new(postId, "name 2", PostType.Manager, 10)
new(postId, "name 1", PostType.TravelAgent, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -159,7 +160,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Manager, 10);
var record = new PostDataModel(id, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -174,7 +175,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Manager, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -230,11 +231,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
_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.Salary == record.Salary;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
});
//Act
_postBusinessLogicContract.InsertPost(record);
@@ -249,7 +250,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -265,7 +266,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -275,7 +276,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_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.Manager, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -284,11 +285,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
_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.Salary == record.Salary;
flag = x.Id == record.Id && x.PostName == record.PostName && x.PostType == record.PostType && x.ConfigurationModel.Rate == record.ConfigurationModel.Rate;
});
//Act
_postBusinessLogicContract.UpdatePost(record);
@@ -303,7 +304,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -313,7 +314,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_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.Manager, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -329,7 +330,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Manager, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -339,7 +340,7 @@ internal class PostBusinessLogicContractTests
//Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Manager, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -2,7 +2,9 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.StoragesContracts;
using CandyHouseTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
using System;
@@ -10,6 +12,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace CandyHouseTests.BusinessLogicContractsTests;
@@ -21,6 +24,7 @@ internal class SalaryBusinessLogicContractTests
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IEmployeeStorageContract> _employeeStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
[OneTimeSetUp]
public void OneTimeSetUp()
@@ -30,7 +34,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>();
_employeeStorageContract = new Mock<IEmployeeStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object);
_saleStorageContract.Object, _postStorageContract.Object, _employeeStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[TearDown]
@@ -191,16 +195,14 @@ internal class SalaryBusinessLogicContractTests
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
var saleSum = 1.2 * 5;
var postSalary = 2000.0;
var rate = 2000.0;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = rate }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
@@ -209,7 +211,7 @@ internal class SalaryBusinessLogicContractTests
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
@@ -220,9 +222,9 @@ internal class SalaryBusinessLogicContractTests
var employee2Id = Guid.NewGuid().ToString();
var employee3Id = Guid.NewGuid().ToString();
var list = new List<EmployeeDataModel>() {
new(employee1Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee2Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee3Id, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
new(employee1Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee2Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false),
new(employee3Id, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employee1Id, null, DiscountType.None, false, []),
@@ -231,7 +233,7 @@ internal class SalaryBusinessLogicContractTests
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), employee3Id, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns(list);
//Act
@@ -244,16 +246,15 @@ internal class SalaryBusinessLogicContractTests
public void CalculateSalaryByMounth_WithoutSalesByEmployee_Test()
{
//Arrange
var postSalary = 2000.0;
var rate = 2000.0;
var employeeId = Guid.NewGuid().ToString();
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, postSalary));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = rate }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
@@ -262,7 +263,7 @@ internal class SalaryBusinessLogicContractTests
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
@@ -271,9 +272,9 @@ internal class SalaryBusinessLogicContractTests
//Arrange
var employeeId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -299,7 +300,7 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -312,9 +313,9 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
@@ -329,7 +330,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException()));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "123@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
@@ -342,10 +343,71 @@ internal class SalaryBusinessLogicContractTests
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 100 }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
}
[Test]
public void CalculateSalaryByMountht_WithTravelAgentPostConfiguration_CalculateSalary_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
var rate = 2000.0;
var percent = 0.1;
var bonus = 0.5;
var sales = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5000, 12)])
};
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(sales);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new ManagerPostConfiguration() { Rate = rate, SalePercent = percent, BonusForExtraSales = bonus }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0;
var expectedSum = rate + percent * (sales.Sum(x => x.Sum) / sales.Count) + sales.Where(x => x.Sum > _salaryConfigurationTest.ExtraSaleSum).Sum(x => x.Sum) * bonus;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMountht_WithChiefPostConfiguration_CalculateSalary_Test()
{
//Arrange
var employeeId = Guid.NewGuid().ToString();
var rate = 2000.0;
var trend = 3;
var bonus = 100;
_saleStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new SaleDataModel(Guid.NewGuid().ToString(), employeeId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new BakerPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus }));
_employeeStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new EmployeeDataModel(employeeId, "Test", "abc@gmail.com", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
_employeeStorageContract.Setup(x => x.GetEmployeeTrend(It.IsAny<DateTime>(), It.IsAny<DateTime>()))
.Returns(trend);
var sum = 0.0;
var expectedSum = rate + trend * bonus;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
}

View File

@@ -1,11 +1,7 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CandyHouseContracts.Infrastructure.PostConfigurations;
namespace CandyHouseTests.DataModelTests;
[TestFixture]
@@ -14,41 +10,48 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Manager, 10);
var post = CreateDataModel(null, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Manager, 10);
post = CreateDataModel(string.Empty, "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Manager, 10);
var post = CreateDataModel("id", "name", PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Manager, 10);
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Manager, 10);
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.TravelAgent, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostTypeIsNoneTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 10);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void SalaryIsLessOrZeroTest()
public void ConfigurationModelIsNullTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, 0);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, null);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Manager, -10);
}
[Test]
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.TravelAgent, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -58,18 +61,18 @@ internal class PostDataModelTests
var postId = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Manager;
var salary = 10;
var post = CreateDataModel(postId, postName, postType, salary);
var configuration = new PostConfiguration() { Rate = 10 };
var post = CreateDataModel(postId, postName, postType, configuration);
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.Salary, Is.EqualTo(salary));
Assert.That(post.ConfigurationModel.Rate, Is.EqualTo(configuration.Rate));
});
}
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, double salary) =>
new(id, postName, postType, salary);
private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, PostConfiguration configuration) =>
new(id, postName, postType, configuration);
}

View File

@@ -1,4 +1,5 @@
using CandyHouseContracts.Enums;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase;
using CandyHouseDatabase.Models;
using Microsoft.EntityFrameworkCore;
@@ -20,9 +21,9 @@ internal static class CandyHouseDbContextExtensions
return client;
}
public static Post InsertPostToDatabaseAndReturn(this CandyHouseDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Manager, double salary = 10, bool isActual = true, DateTime? changeDate = null)
public static Post InsertPostToDatabaseAndReturn(this CandyHouseDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.TravelAgent, PostConfiguration? config = null, bool isActual = true, DateTime? changeDate = null)
{
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Salary = salary, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
var post = new Post() { Id = Guid.NewGuid().ToString(), PostId = id ?? Guid.NewGuid().ToString(), PostName = postName, PostType = postType, Configuration = config ?? new PostConfiguration() { Rate = 100 }, IsActual = isActual, ChangeDate = changeDate ?? DateTime.UtcNow };
dbContext.Posts.Add(post);
dbContext.SaveChanges();
return post;
@@ -67,9 +68,9 @@ internal static class CandyHouseDbContextExtensions
return sale;
}
public static Employee InsertEmployeeToDatabaseAndReturn(this CandyHouseDbContext dbContext, string? id = null, string fio = "test", string email = "abc@gmail.com", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
public static Employee InsertEmployeeToDatabaseAndReturn(this CandyHouseDbContext dbContext, string? id = null, string fio = "test", string email = "abc@gmail.com", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
{
var employee = new Employee() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
var employee = new Employee() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, Email = email, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
dbContext.Employees.Add(employee);
dbContext.SaveChanges();
return employee;

View File

@@ -0,0 +1,9 @@
using CandyHouseContracts.Infrastructure;
namespace CandyHouseTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraSaleSum => 10;
public int MaxConcurrentThreads => 4;
}

View File

@@ -0,0 +1,332 @@
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseDatabase.Implementations;
using CandyHouseDatabase.Models;
using CandyHouseTests.Infrastructure;
using CandyHouseTests.StoragesContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CandyHouseTests.StoragesContracts;
[TestFixture]
internal class PostStorageContractTests : BaseStorageContractTest
{
private PostStorageContract _postStorageContract;
[SetUp]
public void SetUp()
{
_postStorageContract = new PostStorageContract(CandyHouseDbContext);
}
[TearDown]
public void TearDown()
{
CandyHouseDbContext.RemovePostsFromDatabase();
}
[Test]
public void Try_GetList_WhenHaveRecords_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 3");
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(3));
AssertElement(list.First(x => x.Id == post.PostId), post);
}
[Test]
public void Try_GetList_WhenNoRecords_Test()
{
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenDifferentConfigTypes_Test()
{
var postSimple = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postBuilder = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new ManagerPostConfiguration() { SalePercent = 500 });
var postLoader = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new BakerPostConfiguration() { PersonalCountTrendPremium = 20 });
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
AssertElement(list.First(x => x.Id == postSimple.PostId), postSimple);
AssertElement(list.First(x => x.Id == postBuilder.PostId), postBuilder);
AssertElement(list.First(x => x.Id == postLoader.PostId), postLoader);
}
[Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{
var postId = Guid.NewGuid().ToString();
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(postId);
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(2));
}
[Test]
public void Try_GetPostWithHistory_WhenNoRecords_Test()
{
var postId = Guid.NewGuid().ToString();
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: true);
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postId, "name 2", isActual: false);
var list = _postStorageContract.GetPostWithHistory(Guid.NewGuid().ToString());
Assert.That(list, Is.Not.Null);
Assert.That(list, Has.Count.EqualTo(0));
}
[Test]
public void Try_GetElementById_WhenHaveRecord_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementById(post.PostId), post);
}
[Test]
public void Try_GetElementById_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(Guid.NewGuid().ToString()), Is.Null);
}
[Test]
public void Try_GetElementById_WhenRecordWasDeleted_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostId), Is.Null);
}
[Test]
public void Try_GetElementById_WhenTrySearchById_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementById(post.Id), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenHaveRecord_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
AssertElement(_postStorageContract.GetElementByName(post.PostName), post);
}
[Test]
public void Try_GetElementByName_WhenNoRecord_Test()
{
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
Assert.That(() => _postStorageContract.GetElementByName("name"), Is.Null);
}
[Test]
public void Try_GetElementByName_WhenRecordWasDeleted_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.GetElementById(post.PostName), Is.Null);
}
[Test]
public void Try_AddElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
_postStorageContract.AddElement(post);
AssertElement(CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id), post);
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "name unique");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WhenHaveRecordWithSamePostId_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WithTravelAgentPostConfiguration_Test()
{
var salePercent = 10;
var post = CreateModel(Guid.NewGuid().ToString(), config: new ManagerPostConfiguration() { SalePercent = salePercent });
_postStorageContract.AddElement(post);
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_AddElement_WithChiefPostConfiguration_Test()
{
var trendPremium = 20;
var post = CreateModel(Guid.NewGuid().ToString(), config: new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium });
_postStorageContract.AddElement(post);
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_UpdElement_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: true);
_postStorageContract.UpdElement(post);
var posts = CandyHouseDbContext.GetPostsFromDatabaseByPostId(post.Id);
Assert.That(posts, Is.Not.Null);
Assert.That(posts, Has.Length.EqualTo(2));
AssertElement(posts[0], CreateModel(post.Id));
AssertElement(posts[^1], CreateModel(post.Id));
}
[Test]
public void Try_UpdElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.UpdElement(CreateModel(Guid.NewGuid().ToString())), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_UpdElement_WhenHaveRecordWithSameName_Test()
{
var post = CreateModel(Guid.NewGuid().ToString(), "New Name");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, postName: "name");
CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: post.PostName);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_UpdElement_WhenRecordWasDeleted_Test()
{
var post = CreateModel(Guid.NewGuid().ToString());
CandyHouseDbContext.InsertPostToDatabaseAndReturn(post.Id, isActual: false);
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_UpdElement_WithTravelAgentPostConfiguration_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var salePercent = 10;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new ManagerPostConfiguration() { SalePercent = salePercent }));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_UpdElement_WithChiefPostConfiguration_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var trendPremium = 20;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium }));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_DelElement_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: true);
_postStorageContract.DelElement(post.PostId);
Assert.That(CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId), Is.Null);
}
[Test]
public void Try_DelElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.DelElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_DelElement_WhenRecordWasDeleted_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
Assert.That(() => _postStorageContract.DelElement(post.PostId), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_ResElement_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: false);
_postStorageContract.ResElement(post.PostId);
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.Multiple(() =>
{
Assert.That(element, Is.Not.Null);
Assert.That(element!.IsActual);
});
}
[Test]
public void Try_ResElement_WhenNoRecordWithThisId_Test()
{
Assert.That(() => _postStorageContract.ResElement(Guid.NewGuid().ToString()), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_ResElement_WhenRecordNotWasDeleted_Test()
{
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(isActual: true);
Assert.That(() => _postStorageContract.ResElement(post.PostId), Throws.Nothing);
}
private static void AssertElement(PostDataModel? actual, Post expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.ConfigurationModel.Rate, Is.EqualTo(expected.Configuration.Rate));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.TravelAgent, PostConfiguration? config = null)
=> new(postId, postName, postType, config ?? new PostConfiguration() { Rate = 100 });
private static void AssertElement(Post? actual, PostDataModel expected)
{
Assert.That(actual, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType));
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
});
}
}

View File

@@ -1,13 +1,16 @@
using CandyHouseContracts.BindingModels;
using CandyHouseContracts.Enums;
using CandyHouseContracts.Infrastructure.PostConfigurations;
using CandyHouseContracts.ViewModels;
using CandyHouseDatabase.Models;
using CandyHouseTests.Infrastructure;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
namespace CandyHouseTests.WebApiControllersTests;
@@ -82,6 +85,24 @@ internal class PostControllerTests : BaseWebApiControllerTest
});
}
[Test]
public async Task GetRecords_WhenDifferentConfigTypes_ShouldSuccess_Test()
{
//Arrange
var postSimple = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postTravelAgent = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new ManagerPostConfiguration() { SalePercent = 500 });
var postLoader = CandyHouseDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new BakerPostConfiguration() { PersonalCountTrendPremium = 20 });
//Act
var response = await HttpClient.GetAsync("/api/posts");
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var data = await GetModelFromResponseAsync<List<PostViewModel>>(response);
Assert.That(data, Is.Not.Null);
AssertElement(data.First(x => x.Id == postSimple.PostId), postSimple);
AssertElement(data.First(x => x.Id == postTravelAgent.PostId), postTravelAgent);
AssertElement(data.First(x => x.Id == postLoader.PostId), postLoader);
}
[Test]
public async Task GetHistory_WhenWrongData_ShouldBadRequest_Test()
{
@@ -200,10 +221,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.TravelAgent.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.TravelAgent.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.TravelAgent.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -237,6 +258,44 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WithTravelAgentPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new ManagerPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Post_WithLoaderPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
@@ -292,10 +351,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = 10 };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 10 };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Manager.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.TravelAgent.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.TravelAgent.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.TravelAgent.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -329,6 +388,48 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WithTravelAgentPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new ManagerPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CandyHouseDbContext.ChangeTracker.Clear();
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ManagerPostConfiguration).Name));
Assert.That((element.Configuration as ManagerPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Put_WithSupervisorPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new BakerPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CandyHouseDbContext.ChangeTracker.Clear();
var element = CandyHouseDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BakerPostConfiguration).Name));
Assert.That((element.Configuration as BakerPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
@@ -433,17 +534,17 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString()));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(JsonNode.Parse(actual.Configuration)!["Type"]!.GetValue<string>(), Is.EqualTo(expected.Configuration.Type));
});
}
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, double salary = 10)
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Manager, string? configuration = null)
=> new()
{
Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName,
PostType = postType.ToString(),
Salary = salary
ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
};
private static void AssertElement(Post? actual, PostBindingModel expected)
@@ -454,7 +555,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType));
Assert.That(actual.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.Configuration.Type, Is.EqualTo(JsonNode.Parse(expected.ConfigurationJson!)!["Type"]!.GetValue<string>()));
});
}
}

View File

@@ -151,29 +151,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Calculate_ShouldSuccess_Test()
{
//Arrange
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId);
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
var expectedSum = sale.Sum * 0.1 + post.Salary;
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salaries = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee.Id);
Assert.Multiple(() =>
{
Assert.That(salaries, Has.Length.EqualTo(1));
Assert.That(salaries.First().EmployeeSalary, Is.EqualTo(expectedSum));
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
});
}
[Test]
public async Task Calculate_WithoutEmployees_ShouldSuccess_Test()
{
@@ -184,34 +162,4 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
var salaries = CandyHouseDbContext.Salaries.ToArray();
Assert.That(salaries, Has.Length.EqualTo(0));
}
[Test]
public async Task Calculate_WithoutSalesByEmployee_ShouldSuccess_Test()
{
//Arrange
var post = CandyHouseDbContext.InsertPostToDatabaseAndReturn(salary: 1000);
var employee1 = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
var employee2 = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee1.Id);
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var salary1 = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee1.Id).First().EmployeeSalary;
var salary2 = CandyHouseDbContext.GetSalariesFromDatabaseByEmployeeId(employee2.Id).First().EmployeeSalary;
Assert.That(salary1, Is.Not.EqualTo(salary2));
}
[Test]
public async Task Calculate_PostNotFound_ShouldNotFound_Test()
{
//Arrange
CandyHouseDbContext.InsertPostToDatabaseAndReturn();
var employee = CandyHouseDbContext.InsertEmployeeToDatabaseAndReturn(fio: "name", postId: Guid.NewGuid().ToString());
var sale = CandyHouseDbContext.InsertSaleToDatabaseAndReturn(employee.Id);
//Act
var response = await HttpClient.PostAsync($"/api/salary/calculate?date={DateTime.UtcNow:MM/dd/yyyy}", null);
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
}

View File

@@ -14,7 +14,7 @@
{
"Name": "File",
"Args": {
"path": "../logs/magiccarpet-.log",
"path": "../logs/candyhouse-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
}

View File

@@ -6,6 +6,7 @@ using CandyHouseContracts.BuisnessLogicContracts;
using CandyHouseContracts.DataModels;
using CandyHouseContracts.Exceptions;
using CandyHouseContracts.ViewModels;
using System.Text.Json;
namespace CandyHouseWebApi.Adapters;
@@ -17,6 +18,11 @@ public class PostAdapter : IPostAdapter
private readonly Mapper _mapper;
private readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNameCaseInsensitive = true
};
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{
_postBusinessLogicContract = postBusinessLogicContract;
@@ -24,7 +30,9 @@ public class PostAdapter : IPostAdapter
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>();
cfg.CreateMap<PostDataModel, PostViewModel>()
.ForMember(x => x.Configuration,
x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
}
@@ -33,7 +41,9 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([
.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))
]);
}
catch (NullListException)
{
@@ -43,7 +53,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -56,7 +67,9 @@ public class PostAdapter : IPostAdapter
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
return PostOperationResponse.OK([
.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))
]);
}
catch (ArgumentNullException ex)
{
@@ -71,7 +84,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -104,7 +118,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.InternalServerError(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -138,7 +153,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -182,7 +198,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -221,7 +238,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -255,7 +273,8 @@ public class PostAdapter : IPostAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest($"Error while working with data storage: {ex.InnerException!.Message}");
return PostOperationResponse.BadRequest(
$"Error while working with data storage: {ex.InnerException!.Message}");
}
catch (Exception ex)
{
@@ -263,4 +282,4 @@ public class PostAdapter : IPostAdapter
return PostOperationResponse.InternalServerError(ex.Message);
}
}
}
}

View File

@@ -9,6 +9,11 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
</ItemGroup>

View File

@@ -0,0 +1,16 @@
using CandyHouseContracts.Infrastructure;
namespace CandyHouseWebApi.Infrastructure;
public class ConfigurationSalary(IConfiguration configuration) : IConfigurationSalary
{
private readonly Lazy<SalarySettings> _salarySettings = new(() =>
{
return configuration.GetValue<SalarySettings>("SalarySettings") ??
throw new InvalidDataException(nameof(SalarySettings));
});
public double ExtraSaleSum => _salarySettings.Value.ExtraSaleSum;
public int MaxConcurrentThreads => _salarySettings.Value.MaxConcurrentThreads;
}

View File

@@ -0,0 +1,8 @@
namespace CandyHouseWebApi.Infrastructure;
public class SalarySettings
{
public double ExtraSaleSum { get; set; }
public int MaxConcurrentThreads { get; set; }
}

View File

@@ -71,6 +71,7 @@ builder.Services.AddTransient<IProductAdapter, ProductAdapter>();
builder.Services.AddTransient<ISaleAdapter, SaleAdapter>();
builder.Services.AddTransient<IEmployeeAdapter, EmployeeAdapter>();
builder.Services.AddTransient<ISalaryAdapter, SalaryAdapter>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddOpenApi();

View File

@@ -14,15 +14,18 @@
{
"Name": "File",
"Args": {
"path": "../logs/magiccarpet-.log",
"path": "../logs/candyhouse-.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {CorrelationId} {Level:u3} {Username} {Message:lj}{Exception}{NewLine}"
}
}
]
},
"AllowedHosts": "*"
//"DataBaseSettings": {
// "ConnectionString": "Host=127.0.0.1;Port=5432;Database=CandyHouseTest;Username=postgres;Password=postgres;"
//}
"AllowedHosts": "*",
"DataBaseSettings": {
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=CandyHouseTest;Username=postgres;Password=postgres;"
},
"SalarySettings": {
"ExtraSaleSum": 1000
}
}