4 Commits

38 changed files with 2450 additions and 84 deletions

View File

@@ -2,19 +2,22 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
namespace CatHasPawsBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract,
ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, ISaleStorageContract saleStorageContract, IPostStorageContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{
private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly ISaleStorageContract _saleStorageContract = saleStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{
@@ -52,13 +55,67 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers)
{
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Sum) ??
throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ??
throw new NullListException();
var salary = post.Salary + sales * 0.1;
var sales = _saleStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.ConfigurationModel switch
{
null => 0,
CashierPostConfiguration cpc => CalculateSalaryForCashier(sales, startDate, finishDate, cpc),
SupervisorPostConfiguration spc => CalculateSalaryForSupervisor(startDate, finishDate, spc),
PostConfiguration pc => pc.Rate,
};
_logger.LogDebug("The employee {workerId} was paid a salary of {salary}", worker.Id, salary);
_salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
}
}
private double CalculateSalaryForCashier(List<SaleDataModel> sales, DateTime startDate, DateTime finishDate, CashierPostConfiguration config)
{
var tasks = new List<Task>();
var calcPercent = 0.0;
for (var date = startDate; date < finishDate; date = date.AddDays(1))
{
tasks.Add(Task.Factory.StartNew((object? obj) =>
{
var dateInTask = (DateTime)obj!;
var salesInDay = sales.Where(x => x.SaleDate >= dateInTask && x.SaleDate <= dateInTask.AddDays(1)).ToArray();
if (salesInDay.Length > 0)
{
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Sum) / salesInDay.Length) * config.SalePercent;
}
}
}, date));
}
var calcBonusTask = Task.Run(() =>
{
return sales.Where(x => x.Sum > _salaryConfiguration.ExtraSaleSum).Sum(x => x.Sum) * config.BonusForExtraSales;
});
try
{
Task.WaitAll([Task.WhenAll(tasks), calcBonusTask]);
}
catch (AggregateException agEx)
{
foreach (var ex in agEx.InnerExceptions)
{
_logger.LogError(ex, "Error in the cashier payroll process");
}
return 0;
}
return config.Rate + calcPercent + calcBonusTask.Result;
}
private double CalculateSalaryForSupervisor(DateTime startDate, DateTime finishDate, SupervisorPostConfiguration config)
{
try
{
return config.Rate + config.PersonalCountTrendPremium * _workerStorageContract.GetWorkerTrend(startDate, finishDate);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in the supervisor payroll process");
return 0;
}
}
}

View File

@@ -10,5 +10,5 @@ public class PostBindingModel
public string? PostType { get; set; }
public double Salary { get; set; }
public string? ConfigurationJson { get; set; }
}

View File

@@ -2,10 +2,13 @@
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Extensions;
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace CatHasPawsContratcs.DataModels;
public class PostDataModel(string postId, string postName, PostType postType, double salary) : IValidation
public class PostDataModel(string postId, string postName, PostType postType, PostConfiguration configuration) : IValidation
{
public string Id { get; private set; } = postId;
@@ -13,7 +16,21 @@ public class PostDataModel(string postId, string postName, PostType postType, do
public PostType PostType { get; private set; } = postType;
public double Salary { get; private set; } = salary;
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(configurationJson)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate()
{
@@ -29,7 +46,10 @@ public class PostDataModel(string postId, string postName, PostType postType, do
if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty");
if (Salary <= 0)
throw new ValidationException("Field Salary is empty");
if (ConfigurationModel is null)
throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
}
}

View File

@@ -0,0 +1,6 @@
namespace CatHasPawsContratcs.Infrastructure;
public interface IConfigurationSalary
{
double ExtraSaleSum { get; }
}

View File

@@ -0,0 +1,10 @@
namespace CatHasPawsContratcs.Infrastructure.PostConfigurations;
public class CashierPostConfiguration : PostConfiguration
{
public override string Type => nameof(CashierPostConfiguration);
public double SalePercent { get; set; }
public double BonusForExtraSales { get; set; }
}

View File

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

View File

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

View File

@@ -15,4 +15,6 @@ public interface IWorkerStorageContract
void UpdElement(WorkerDataModel workerDataModel);
void DelElement(string id);
int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod);
}

View File

@@ -8,5 +8,5 @@ public class PostViewModel
public required string PostType { get; set; }
public double Salary { get; set; }
public required string Configuration { get; set; }
}

View File

@@ -9,6 +9,11 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2">
<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,6 +1,9 @@
using CatHasPawsContratcs.Infrastructure;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CatHasPawsDatabase;
@@ -56,6 +59,14 @@ internal class CatHasPawsDbContext : DbContext
.OnDelete(DeleteBehavior.Restrict);
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<Buyer> Buyers { get; set; }
@@ -75,4 +86,14 @@ internal class CatHasPawsDbContext : DbContext
public DbSet<SaleProduct> SaleProducts { get; set; }
public DbSet<Worker> Workers { 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(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(jsonString)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
}

View File

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

View File

@@ -24,7 +24,8 @@ internal class PostStorageContract : IPostStorageContract
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true))
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow));
.ForMember(x => x.ChangeDate, x => x.MapFrom(src => DateTime.UtcNow))
.ForMember(x => x.Configuration, x => x.MapFrom(src => src.ConfigurationModel));
});
_mapper = new Mapper(config);
}

View File

@@ -125,6 +125,7 @@ internal class WorkerStorageContract : IWorkerStorageContract
{
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
@@ -139,6 +140,21 @@ internal class WorkerStorageContract : IWorkerStorageContract
}
}
public int GetWorkerTrend(DateTime fromPeriod, DateTime toPeriod)
{
try
{
var countWorkersOnBegining = _dbContext.Workers.Count(x => x.EmploymentDate < fromPeriod && (!x.IsDeleted || x.DateOfDelete > fromPeriod));
var countWorkersOnEnding = _dbContext.Workers.Count(x => x.EmploymentDate < toPeriod && (!x.IsDeleted || x.DateOfDelete > toPeriod));
return countWorkersOnEnding - countWorkersOnBegining;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query)

View File

@@ -0,0 +1,375 @@
// <auto-generated />
using System;
using CatHasPawsDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CatHasPawsDatabase.Migrations
{
[DbContext(typeof(CatHasPawsDbContext))]
[Migration("20250327150147_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Buyers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.Property<double>("Salary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Products")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CatHasPawsDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Navigation("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,288 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CatHasPawsDatabase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Buyers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PhoneNumber = table.Column<string>(type: "text", nullable: false),
DiscountSize = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Buyers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Manufacturers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ManufacturerName = table.Column<string>(type: "text", nullable: false),
PrevManufacturerName = table.Column<string>(type: "text", nullable: true),
PrevPrevManufacturerName = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Posts",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
PostName = table.Column<string>(type: "text", nullable: false),
PostType = table.Column<int>(type: "integer", nullable: false),
Salary = table.Column<double>(type: "double precision", nullable: false),
IsActual = table.Column<bool>(type: "boolean", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Posts", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Workers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
PostId = table.Column<string>(type: "text", nullable: false),
BirthDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
EmploymentDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductName = table.Column<string>(type: "text", nullable: false),
ProductType = table.Column<int>(type: "integer", nullable: false),
ManufacturerId = table.Column<string>(type: "text", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false),
IsDeleted = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
table.ForeignKey(
name: "FK_Products_Manufacturers_ManufacturerId",
column: x => x.ManufacturerId,
principalTable: "Manufacturers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Salaries", x => x.Id);
table.ForeignKey(
name: "FK_Salaries_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Sales",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
BuyerId = table.Column<string>(type: "text", nullable: true),
SaleDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false),
DiscountType = table.Column<int>(type: "integer", nullable: false),
Discount = table.Column<double>(type: "double precision", nullable: false),
IsCancel = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Sales", x => x.Id);
table.ForeignKey(
name: "FK_Sales_Buyers_BuyerId",
column: x => x.BuyerId,
principalTable: "Buyers",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_Sales_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductHistories",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<string>(type: "text", nullable: false),
OldPrice = table.Column<double>(type: "double precision", nullable: false),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductHistories", x => x.Id);
table.ForeignKey(
name: "FK_ProductHistories_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SaleProducts",
columns: table => new
{
SaleId = table.Column<string>(type: "text", nullable: false),
ProductId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
Price = table.Column<double>(type: "double precision", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SaleProducts", x => new { x.SaleId, x.ProductId });
table.ForeignKey(
name: "FK_SaleProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SaleProducts_Sales_SaleId",
column: x => x.SaleId,
principalTable: "Sales",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Buyers_PhoneNumber",
table: "Buyers",
column: "PhoneNumber",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Manufacturers_ManufacturerName",
table: "Manufacturers",
column: "ManufacturerName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_ProductHistories_ProductId",
table: "ProductHistories",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Products_ManufacturerId",
table: "Products",
column: "ManufacturerId");
migrationBuilder.CreateIndex(
name: "IX_Products_ProductName_IsDeleted",
table: "Products",
columns: new[] { "ProductName", "IsDeleted" },
unique: true,
filter: "\"IsDeleted\" = FALSE");
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_SaleProducts_ProductId",
table: "SaleProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Sales_BuyerId",
table: "Sales",
column: "BuyerId");
migrationBuilder.CreateIndex(
name: "IX_Sales_WorkerId",
table: "Sales",
column: "WorkerId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "ProductHistories");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "SaleProducts");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Sales");
migrationBuilder.DropTable(
name: "Manufacturers");
migrationBuilder.DropTable(
name: "Buyers");
migrationBuilder.DropTable(
name: "Workers");
}
}
}

View File

@@ -0,0 +1,376 @@
// <auto-generated />
using System;
using CatHasPawsDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CatHasPawsDatabase.Migrations
{
[DbContext(typeof(CatHasPawsDbContext))]
[Migration("20250327155650_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Buyers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Products")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CatHasPawsDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Navigation("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@@ -0,0 +1,379 @@
// <auto-generated />
using System;
using CatHasPawsDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CatHasPawsDatabase.Migrations
{
[DbContext(typeof(CatHasPawsDbContext))]
[Migration("20250328162321_AddDateOfDeleteInWorker")]
partial class AddDateOfDeleteInWorker
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Buyers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Products")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CatHasPawsDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Navigation("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@@ -0,0 +1,376 @@
// <auto-generated />
using System;
using CatHasPawsDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace CatHasPawsDatabase.Migrations
{
[DbContext(typeof(CatHasPawsDbContext))]
partial class CatHasPawsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<double>("DiscountSize")
.HasColumnType("double precision");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Buyers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevManufacturerName")
.HasColumnType("text");
b.Property<string>("PrevPrevManufacturerName")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ManufacturerName")
.IsUnique();
b.ToTable("Manufacturers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Post", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Configuration")
.IsRequired()
.HasColumnType("jsonb");
b.Property<bool>("IsActual")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PostName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("PostType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PostId", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.HasIndex("PostName", "IsActual")
.IsUnique()
.HasFilter("\"IsActual\" = TRUE");
b.ToTable("Posts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("ManufacturerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("ProductType")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ManufacturerId");
b.HasIndex("ProductName", "IsDeleted")
.IsUnique()
.HasFilter("\"IsDeleted\" = FALSE");
b.ToTable("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("ChangeDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("OldPrice")
.HasColumnType("double precision");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("ProductHistories");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("SalaryDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.Property<double>("WorkerSalary")
.HasColumnType("double precision");
b.HasKey("Id");
b.HasIndex("WorkerId");
b.ToTable("Salaries");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("BuyerId")
.HasColumnType("text");
b.Property<double>("Discount")
.HasColumnType("double precision");
b.Property<int>("DiscountType")
.HasColumnType("integer");
b.Property<bool>("IsCancel")
.HasColumnType("boolean");
b.Property<DateTime>("SaleDate")
.HasColumnType("timestamp without time zone");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("WorkerId");
b.ToTable("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.Property<string>("SaleId")
.HasColumnType("text");
b.Property<string>("ProductId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<double>("Price")
.HasColumnType("double precision");
b.HasKey("SaleId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime?>("DateOfDelete")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("EmploymentDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("PostId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Workers");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Manufacturer", "Manufacturer")
.WithMany("Products")
.HasForeignKey("ManufacturerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Manufacturer");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.ProductHistory", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("ProductHistories")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Salary", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Buyer", "Buyer")
.WithMany("Sales")
.HasForeignKey("BuyerId")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("CatHasPawsDatabase.Models.Worker", "Worker")
.WithMany("Sales")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Buyer");
b.Navigation("Worker");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.SaleProduct", b =>
{
b.HasOne("CatHasPawsDatabase.Models.Product", "Product")
.WithMany("SaleProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CatHasPawsDatabase.Models.Sale", "Sale")
.WithMany("SaleProducts")
.HasForeignKey("SaleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("Sale");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Buyer", b =>
{
b.Navigation("Sales");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Manufacturer", b =>
{
b.Navigation("Products");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Product", b =>
{
b.Navigation("ProductHistories");
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Sale", b =>
{
b.Navigation("SaleProducts");
});
modelBuilder.Entity("CatHasPawsDatabase.Models.Worker", b =>
{
b.Navigation("Salaries");
b.Navigation("Sales");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,4 +1,5 @@
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
namespace CatHasPawsDatabase.Models;
@@ -12,7 +13,7 @@ internal class Post
public PostType PostType { get; set; }
public double Salary { get; set; }
public required PostConfiguration Configuration { get; set; }
public bool IsActual { get; set; }

View File

@@ -16,6 +16,8 @@ internal class Worker
public bool IsDeleted { get; set; }
public DateTime? DateOfDelete { get; set; }
[NotMapped]
public Post? Post { get; set; }

View File

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

View File

@@ -2,6 +2,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.StoragesContracts;
using Microsoft.Extensions.Logging;
using Moq;
@@ -33,9 +34,9 @@ internal class PostBusinessLogicContractTests
//Arrange
var listOriginal = new List<PostDataModel>()
{
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, 10),
new(Guid.NewGuid().ToString(),"name 1", PostType.Assistant, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.Assistant, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.Assistant, new PostConfiguration() { Rate = 10 }),
};
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act
@@ -89,8 +90,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>()
{
new(postId, "name 1", PostType.Assistant, 10),
new(postId, "name 2", PostType.Assistant, 10)
new(postId, "name 1", PostType.Assistant, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.Assistant, new PostConfiguration() { Rate = 10 })
};
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act
@@ -154,7 +155,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Assistant, 10);
var record = new PostDataModel(id, "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(id);
@@ -169,7 +170,7 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Assistant, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act
var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -225,11 +226,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 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);
@@ -244,7 +245,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.Supervisor, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -260,7 +261,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Supervisor, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -270,7 +271,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.Supervisor, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -279,11 +280,11 @@ internal class PostBusinessLogicContractTests
{
//Arrange
var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 10);
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Supervisor, 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);
@@ -298,7 +299,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.Supervisor, 10)), Throws.TypeOf<ElementNotFoundException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -308,7 +309,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.Supervisor, 10)), Throws.TypeOf<ElementExistsException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}
@@ -324,7 +325,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Supervisor, 10)), Throws.TypeOf<ValidationException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
}
@@ -334,7 +335,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.Supervisor, 10)), Throws.TypeOf<StorageException>());
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Supervisor, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
}

View File

@@ -2,7 +2,9 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.StoragesContracts;
using CatHasPawsTests.Infrastructure;
using Microsoft.Extensions.Logging;
using Moq;
@@ -16,6 +18,7 @@ internal class SalaryBusinessLogicContractTests
private Mock<ISaleStorageContract> _saleStorageContract;
private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
[OneTimeSetUp]
public void OneTimeSetUp()
@@ -25,7 +28,7 @@ internal class SalaryBusinessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object);
_saleStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
}
[SetUp]
@@ -186,16 +189,14 @@ internal class SalaryBusinessLogicContractTests
{
//Arrange
var workerId = 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(), workerId, 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.Assistant, postSalary));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = rate }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", 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) =>
{
@@ -204,7 +205,7 @@ internal class SalaryBusinessLogicContractTests
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
@@ -226,7 +227,7 @@ internal class SalaryBusinessLogicContractTests
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, DiscountType.None, false, []),
new SaleDataModel(Guid.NewGuid().ToString(), worker3Id, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.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
@@ -239,16 +240,15 @@ internal class SalaryBusinessLogicContractTests
public void CalculateSalaryByMounth_WithoutSalesByWorker_Test()
{
//Arrange
var postSalary = 2000.0;
var rate = 2000.0;
var workerId = 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.Assistant, postSalary));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = rate }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", 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) =>
{
@@ -257,7 +257,7 @@ internal class SalaryBusinessLogicContractTests
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
Assert.That(sum, Is.EqualTo(rate));
}
[Test]
@@ -266,7 +266,7 @@ internal class SalaryBusinessLogicContractTests
//Arrange
var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -294,7 +294,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(), workerId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
//Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
}
@@ -307,7 +307,7 @@ 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.Assistant, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert
@@ -337,10 +337,73 @@ 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(), workerId, null, DiscountType.None, false, [])]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, 2000));
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 100 }));
_workerStorageContract.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_WithCashierPostConfiguration_CalculateSalary_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
var rate = 2000.0;
var percent = 0.1;
var bonus = 0.5;
var sales = new List<SaleDataModel>()
{
new(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), workerId, null, DiscountType.None, false, [new SaleProductDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 5, 1.2)]),
new(Guid.NewGuid().ToString(), workerId, 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.Assistant, new CashierPostConfiguration() { Rate = rate, SalePercent = percent, BonusForExtraSales = bonus }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", 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_WithSupervisorPostConfiguration_CalculateSalary_Test()
{
//Arrange
var workerId = 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(), workerId, 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.Assistant, new SupervisorPostConfiguration() { Rate = rate, PersonalCountTrendPremium = bonus }));
_workerStorageContract.Setup(x => x.GetList(It.IsAny<bool>(), It.IsAny<string?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>()))
.Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
_workerStorageContract.Setup(x => x.GetWorkerTrend(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,6 +1,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
namespace CatHasPawsTests.DataModelsTests;
@@ -10,41 +11,49 @@ internal class PostDataModelTests
[Test]
public void IdIsNullOrEmptyTest()
{
var post = CreateDataModel(null, "name", PostType.Assistant, 10);
var post = CreateDataModel(null, "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Assistant, 10);
post = CreateDataModel(string.Empty, "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void IdIsNotGuidTest()
{
var post = CreateDataModel("id", "name", PostType.Assistant, 10);
var post = CreateDataModel("id", "name", PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
[Test]
public void PostNameIsEmptyTest()
{
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, 10);
var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Assistant, new PostConfiguration() { Rate = 10 });
Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 10);
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Assistant, 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.Assistant, 0);
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, null);
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, -10);
}
[Test]
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Assistant, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
}
@@ -54,18 +63,19 @@ internal class PostDataModelTests
var postId = Guid.NewGuid().ToString();
var postName = "name";
var postType = PostType.Assistant;
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, Is.EqualTo(configuration));
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 CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsDatabase;
using CatHasPawsDatabase.Models;
using Microsoft.EntityFrameworkCore;
@@ -23,9 +24,9 @@ internal static class CatHasPawsDbContextExtensions
return manufacturer;
}
public static Post InsertPostToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Assistant, double salary = 10, bool isActual = true, DateTime? changeDate = null)
public static Post InsertPostToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Assistant, 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;
@@ -70,9 +71,9 @@ internal static class CatHasPawsDbContextExtensions
return sale;
}
public static Worker InsertWorkerToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false)
public static Worker InsertWorkerToDatabaseAndReturn(this CatHasPawsDbContext dbContext, string? id = null, string fio = "test", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false, DateTime? dateDelete = null)
{
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted };
var worker = new Worker() { Id = id ?? Guid.NewGuid().ToString(), FIO = fio, PostId = postId ?? Guid.NewGuid().ToString(), BirthDate = birthDate ?? DateTime.UtcNow.AddYears(-20), EmploymentDate = employmentDate ?? DateTime.UtcNow, IsDeleted = isDeleted, DateOfDelete = dateDelete };
dbContext.Workers.Add(worker);
dbContext.SaveChanges();
return worker;

View File

@@ -0,0 +1,8 @@
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsTests.Infrastructure;
class ConfigurationSalaryTest : IConfigurationSalary
{
public double ExtraSaleSum => 10;
}

View File

@@ -1,6 +1,7 @@
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsDatabase.Implementations;
using CatHasPawsDatabase.Models;
using CatHasPawsTests.Infrastructure;
@@ -44,6 +45,19 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(list, Is.Empty);
}
[Test]
public void Try_GetList_WhenDifferentConfigTypes_Test()
{
var postSimple = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postCashier = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new CashierPostConfiguration() { SalePercent = 500 });
var postSupervisor = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new SupervisorPostConfiguration() { 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 == postCashier.PostId), postCashier);
AssertElement(list.First(x => x.Id == postSupervisor.PostId), postSupervisor);
}
[Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{
@@ -141,6 +155,36 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
}
[Test]
public void Try_AddElement_WithCashierPostConfiguration_Test()
{
var salePercent = 10;
var post = CreateModel(Guid.NewGuid().ToString(), config: new CashierPostConfiguration() { SalePercent = salePercent });
_postStorageContract.AddElement(post);
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(CashierPostConfiguration).Name));
Assert.That((element.Configuration as CashierPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_AddElement_WithSupervisorPostConfiguration_Test()
{
var trendPremium = 20;
var post = CreateModel(Guid.NewGuid().ToString(), config: new SupervisorPostConfiguration() { PersonalCountTrendPremium = trendPremium });
_postStorageContract.AddElement(post);
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(SupervisorPostConfiguration).Name));
Assert.That((element.Configuration as SupervisorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_UpdElement_Test()
{
@@ -177,6 +221,36 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
}
[Test]
public void Try_UpdElement_WithCashierPostConfiguration_Test()
{
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
var salePercent = 10;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new CashierPostConfiguration() { SalePercent = salePercent }));
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(CashierPostConfiguration).Name));
Assert.That((element.Configuration as CashierPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_UpdElement_WithSupervisorPostConfiguration_Test()
{
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
var trendPremium = 20;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new SupervisorPostConfiguration() { PersonalCountTrendPremium = trendPremium }));
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(SupervisorPostConfiguration).Name));
Assert.That((element.Configuration as SupervisorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public void Try_DelElement_Test()
{
@@ -232,12 +306,12 @@ internal class PostStorageContractTests : BaseStorageContractTest
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.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.ConfigurationModel.Rate, Is.EqualTo(expected.Configuration.Rate));
});
}
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Assistant, double salary = 10)
=> new(postId, postName, postType, salary);
private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Assistant, PostConfiguration? config = null)
=> new(postId, postName, postType, config ?? new PostConfiguration() { Rate = 100 });
private static void AssertElement(Post? actual, PostDataModel expected)
{
@@ -247,7 +321,7 @@ internal class PostStorageContractTests : BaseStorageContractTest
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.Salary, Is.EqualTo(expected.Salary));
Assert.That(actual.Configuration.Rate, Is.EqualTo(expected.ConfigurationModel.Rate));
});
}
}

View File

@@ -182,6 +182,43 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>());
}
[Test]
public void Try_GetWorkerTrend_WhenNoNewAndDeletedWorkers_Test()
{
var startDate = DateTime.UtcNow.AddDays(-5);
var endDate = DateTime.UtcNow.AddDays(-3);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
Assert.That(count, Is.EqualTo(0));
}
[Test]
public void Try_GetWorkerTrend_WhenHaveNewAndNoDeletedWorkers_Test()
{
var startDate = DateTime.UtcNow.AddDays(-5);
var endDate = DateTime.UtcNow.AddDays(-3);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-4));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-1));
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
Assert.That(count, Is.EqualTo(1));
}
[Test]
public void Try_GetWorkerTrend_WhenNoNewAndHaveDeletedWorkers_Test()
{
var startDate = DateTime.UtcNow.AddDays(-5);
var endDate = DateTime.UtcNow.AddDays(-3);
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-4));
CatHasPawsDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-1));
var count = _workerStorageContract.GetWorkerTrend(startDate, endDate);
Assert.That(count, Is.EqualTo(-1));
}
private static void AssertElement(WorkerDataModel? actual, Worker expected)
{
Assert.That(actual, Is.Not.Null);
@@ -210,6 +247,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
Assert.That(actual.DateOfDelete.HasValue, Is.EqualTo(expected.IsDeleted));
});
}
}

View File

@@ -1,13 +1,15 @@
using CatHasPawsContratcs.BindingModels;
using CatHasPawsContratcs.Enums;
using CatHasPawsContratcs.Infrastructure.PostConfigurations;
using CatHasPawsContratcs.ViewModels;
using CatHasPawsDatabase.Models;
using CatHasPawsTests.Infrastructure;
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace CatHasPawsTests.WebApiControllersTests;
[TestFixture]
internal class PostControllerTests : BaseWebApiControllerTest
{
@@ -52,6 +54,24 @@ internal class PostControllerTests : BaseWebApiControllerTest
});
}
[Test]
public async Task GetRecords_WhenDifferentConfigTypes_ShouldSuccess_Test()
{
//Arrange
var postSimple = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postCashier = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new CashierPostConfiguration() { SalePercent = 500 });
var postSupervisor = CatHasPawsDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new SupervisorPostConfiguration() { 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 == postCashier.PostId), postCashier);
AssertElement(data.First(x => x.Id == postSupervisor.PostId), postSupervisor);
}
[Test]
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
{
@@ -211,10 +231,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.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.Assistant.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.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.Assistant.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -248,6 +268,44 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Post_WithCashierPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new CashierPostConfiguration() { 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 = CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(CashierPostConfiguration).Name));
Assert.That((element.Configuration as CashierPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Post_WithSupervisorPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new SupervisorPostConfiguration() { 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 = CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(SupervisorPostConfiguration).Name));
Assert.That((element.Configuration as SupervisorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Put_ShouldSuccess_Test()
{
@@ -303,10 +361,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{
//Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), Salary = 10 };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.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.Assistant.ToString(), Salary = -10 };
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Assistant.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Assistant.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.Assistant.ToString(), ConfigurationJson = null };
//Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -340,6 +398,48 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
}
[Test]
public async Task Put_WithCashierPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new CashierPostConfiguration() { SalePercent = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CatHasPawsDbContext.ChangeTracker.Clear();
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(CashierPostConfiguration).Name));
Assert.That((element.Configuration as CashierPostConfiguration)!.SalePercent, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Put_WithSupervisorPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var post = CatHasPawsDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new SupervisorPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
CatHasPawsDbContext.ChangeTracker.Clear();
var element = CatHasPawsDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(SupervisorPostConfiguration).Name));
Assert.That((element.Configuration as SupervisorPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test]
public async Task Delete_ShouldSuccess_Test()
{
@@ -444,17 +544,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.Assistant, double salary = 10)
private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Assistant, 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)
@@ -465,7 +565,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

@@ -6,6 +6,7 @@ using CatHasPawsContratcs.BusinessLogicsContracts;
using CatHasPawsContratcs.DataModels;
using CatHasPawsContratcs.Exceptions;
using CatHasPawsContratcs.ViewModels;
using System.Text.Json;
namespace CatHasPawsWebApi.Adapters;
@@ -17,6 +18,8 @@ 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 +27,8 @@ 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);
}

View File

@@ -9,6 +9,10 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.2">
<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,14 @@
using CatHasPawsContratcs.Infrastructure;
namespace CatHasPawsWebApi.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;
}

View File

@@ -0,0 +1,6 @@
namespace CatHasPawsWebApi.Infrastructure;
public class SalarySettings
{
public double ExtraSaleSum { get; set; }
}

View File

@@ -49,6 +49,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
});
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
builder.Services.AddTransient<IBuyerBusinessLogicContract, BuyerBusinessLogicContract>();
builder.Services.AddTransient<IManufacturerBusinessLogicContract, ManufacturerBusinessLogicContract>();

View File

@@ -24,5 +24,8 @@
"AllowedHosts": "*",
"DataBaseSettings": {
"ConnectionString": "Host=127.0.0.1;Port=5432;Database=CatHasPaws;Username=postgres;Password=postgres;"
},
"SalarySettings": {
"ExtraSaleSum": 1000
}
}