2 Commits

Author SHA1 Message Date
IlyasValiulov
eace30432d дополнения к 5 лабе 2025-04-03 10:52:33 +04:00
IlyasValiulov
a5414aecf7 лаба 5 2025-04-03 01:59:32 +04:00
42 changed files with 2073 additions and 120 deletions

View File

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

View File

@@ -1,20 +1,24 @@
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions; using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.StoragesContracts; using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace FurnitureAssemblyBusinessLogic.Implementations; namespace FurnitureAssemblyBusinessLogic.Implementations;
internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract, IPostStorageContract internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageContract, IManifacturingStorageContract manifacturingStorageContract, IPostStorageContract
postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger) : ISalaryBusinessLogicContract postStorageContract, IWorkerStorageContract workerStorageContract, ILogger logger, IConfigurationSalary сonfiguration) : ISalaryBusinessLogicContract
{ {
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract; private readonly ISalaryStorageContract _salaryStorageContract = salaryStorageContract;
private readonly IManifacturingStorageContract _manifacturingStorageContract = manifacturingStorageContract; private readonly IManifacturingStorageContract _manifacturingStorageContract = manifacturingStorageContract;
private readonly IPostStorageContract _postStorageContract = postStorageContract; private readonly IPostStorageContract _postStorageContract = postStorageContract;
private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract; private readonly IWorkerStorageContract _workerStorageContract = workerStorageContract;
private readonly IConfigurationSalary _salaryConfiguration = сonfiguration;
private readonly Lock _lockObject = new();
public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate) public List<SalaryDataModel> GetAllSalariesByPeriod(DateTime fromDate, DateTime toDate)
{ {
@@ -52,11 +56,69 @@ internal class SalaryBusinessLogicContract(ISalaryStorageContract salaryStorageC
var workers = _workerStorageContract.GetList() ?? throw new NullListException(); var workers = _workerStorageContract.GetList() ?? throw new NullListException();
foreach (var worker in workers) foreach (var worker in workers)
{ {
var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id)?.Sum(x => x.Count) ?? throw new NullListException(); var sales = _manifacturingStorageContract.GetList(startDate, finishDate, workerId: worker.Id) ?? throw new NullListException();
var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException(); var post = _postStorageContract.GetElementById(worker.PostId) ?? throw new NullListException();
var salary = post.Salary + sales * 0.1; var salary = post.ConfigurationModel switch
_logger.LogDebug("The employee {workerId} was paid a salary of { salary}", worker.Id, salary); {
null => 0,
BuilderPostConfiguration cpc => CalculateSalaryForBuilder(sales, startDate, finishDate, cpc),
ChiefPostConfiguration spc => CalculateSalaryForChief(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)); _salaryStorageContract.AddElement(new SalaryDataModel(worker.Id, finishDate, salary));
} }
} }
private double CalculateSalaryForBuilder(List<ManifacturingFurnitureDataModel> sales, DateTime startDate, DateTime finishDate, BuilderPostConfiguration config)
{
var calcPercent = 0.0;
var dates = new List<DateTime>();
for (var date = startDate; date < finishDate; date = date.AddDays(1))
{
dates.Add(date);
}
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = _salaryConfiguration.MaxConcurrentThreads
};
Parallel.ForEach(dates, parallelOptions, date =>
{
var salesInDay = sales.Where(x => x.ProductuionDate.Date == date.Date).ToArray();
if (salesInDay.Length > 0)
{
lock (_lockObject)
{
calcPercent += (salesInDay.Sum(x => x.Count) / salesInDay.Length);
}
}
});
double calcBonusTask = 0;
try
{
calcBonusTask = sales.Where(x => x.Count > _salaryConfiguration.ExtraMadeSum).Sum(x => x.Count) * config.PersonalCount;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in bonus calculation");
}
return config.Rate + calcPercent + calcBonusTask;
}
private double CalculateSalaryForChief(DateTime startDate, DateTime finishDate, ChiefPostConfiguration 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

@@ -6,5 +6,5 @@ public class PostBindingModel
public string? PostId => Id; public string? PostId => Id;
public string? PostName { get; set; } public string? PostName { get; set; }
public string? PostType { get; set; } public string? PostType { get; set; }
public double Salary { get; set; } public string? ConfigurationJson { get; set; }
} }

View File

@@ -1,16 +1,34 @@
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Extentions; using FurnitureAssemblyContracts.Extentions;
using FurnitureAssemblyContracts.Infrastructure; using FurnitureAssemblyContracts.Infrastructure;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace FurnitureAssemblyContracts.DataModels; namespace FurnitureAssemblyContracts.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; public string Id { get; private set; } = postid;
public string PostName { get; private set; } = postName; public string PostName { get; private set; } = postName;
public PostType PostType { get; private set; } = postType; 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(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(configurationJson)!,
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate() public void Validate()
{ {
@@ -22,7 +40,9 @@ public class PostDataModel(string postid, string postName, PostType postType, do
throw new ValidationException("Field PostName is empty"); throw new ValidationException("Field PostName is empty");
if (PostType == PostType.None) if (PostType == PostType.None)
throw new ValidationException("Field PostType is empty"); throw new ValidationException("Field PostType is empty");
if (Salary <= 0) if (ConfigurationModel is null)
throw new ValidationException("Field Salary is empty"); throw new ValidationException("Field ConfigurationModel is not initialized");
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException("Field Rate is less or equal zero");
} }
} }

View File

@@ -5,5 +5,5 @@ public enum PostType
None = 0, None = 0,
ComponentMaker = 1, ComponentMaker = 1,
Builder = 2, Builder = 2,
Loader = 3 Chief = 3,
} }

View File

@@ -0,0 +1,7 @@
namespace FurnitureAssemblyContracts.Infrastructure;
public interface IConfigurationSalary
{
double ExtraMadeSum { get; }
int MaxConcurrentThreads { get; }
}

View File

@@ -0,0 +1,16 @@
using Microsoft.Extensions.Configuration;
namespace FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
public class BuilderPostConfiguration : PostConfiguration
{
public override string Type => nameof(BuilderPostConfiguration);
public double PersonalCount { get; set; }
public BuilderPostConfiguration(IConfiguration? config = null)
{
if (config != null)
{
config.GetSection("BuilderSettings");
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,9 @@
using FurnitureAssemblyContracts.Infrastructure; using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyDatebase.Models; using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
namespace FurnitureAssemblyDatebase; namespace FurnitureAssemblyDatebase;
@@ -47,6 +50,13 @@ public class FurnitureAssemblyDbContext : DbContext
.WithMany(f => f.Components) .WithMany(f => f.Components)
.HasForeignKey(fc => fc.FurnitureId) .HasForeignKey(fc => fc.FurnitureId)
.OnDelete(DeleteBehavior.Restrict); .OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Post>()
.Property(x => x.Configuration)
.HasColumnType("jsonb")
.HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x));
} }
public DbSet<ManifacturingFurniture> Manufacturing { get; set; } public DbSet<ManifacturingFurniture> Manufacturing { get; set; }
@@ -56,4 +66,12 @@ public class FurnitureAssemblyDbContext : DbContext
public DbSet<Furniture> Furnitures { get; set; } public DbSet<Furniture> Furnitures { get; set; }
public DbSet<FurnitureComponent> FurnitureComponents { get; set; } public DbSet<FurnitureComponent> FurnitureComponents { get; set; }
public DbSet<Worker> Workers { 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(BuilderPostConfiguration) => JsonConvert.DeserializeObject<BuilderPostConfiguration>(jsonString)!,
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
};
} }

View File

@@ -26,7 +26,8 @@ public class PostStorageContract : IPostStorageContract
.ForMember(x => x.Id, x => x.Ignore()) .ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.PostId, x => x.MapFrom(src => src.Id)) .ForMember(x => x.PostId, x => x.MapFrom(src => src.Id))
.ForMember(x => x.IsActual, x => x.MapFrom(src => true)) .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); _mapper = new Mapper(config);
} }

View File

@@ -125,6 +125,7 @@ public class WorkerStorageContract : IWorkerStorageContract
{ {
var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id); var element = GetWorkerById(id) ?? throw new ElementNotFoundException(id);
element.IsDeleted = true; element.IsDeleted = true;
element.DateOfDelete = DateTime.UtcNow;
_dbContext.SaveChanges(); _dbContext.SaveChanges();
} }
catch (ElementNotFoundException) catch (ElementNotFoundException)
@@ -139,6 +140,21 @@ public 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 Worker? GetWorkerById(string id) => AddPost(_dbContext.Workers.FirstOrDefault(x => x.Id == id && !x.IsDeleted));
private IQueryable<Worker> JoinPost(IQueryable<Worker> query) private IQueryable<Worker> JoinPost(IQueryable<Worker> query)

View File

@@ -0,0 +1,278 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250331085649_FirstMigration")]
partial class FirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevName")
.HasColumnType("text");
b.Property<string>("PrevPrevName")
.HasColumnType("text");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.Property<string>("FurnitureId")
.HasColumnType("text");
b.Property<string>("ComponentId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("FurnitureId", "ComponentId");
b.HasIndex("ComponentId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("FurnitureId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductuionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkerId");
b.ToTable("Manufacturing");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("ChangeDate")
.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("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("ManifacturingFurniture")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Navigation("ManifacturingFurniture");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,220 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
/// <inheritdoc />
public partial class FirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
PrevName = table.Column<string>(type: "text", nullable: true),
PrevPrevName = table.Column<string>(type: "text", nullable: true),
Type = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Furnitures",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Weight = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Furnitures", 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),
ChangeDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Workers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "FurnitureComponents",
columns: table => new
{
FurnitureId = table.Column<string>(type: "text", nullable: false),
ComponentId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_FurnitureComponents", x => new { x.FurnitureId, x.ComponentId });
table.ForeignKey(
name: "FK_FurnitureComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_FurnitureComponents_Furnitures_FurnitureId",
column: x => x.FurnitureId,
principalTable: "Furnitures",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Manufacturing",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
FurnitureId = table.Column<string>(type: "text", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false),
ProductuionDate = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturing", x => x.Id);
table.ForeignKey(
name: "FK_Manufacturing_Furnitures_FurnitureId",
column: x => x.FurnitureId,
principalTable: "Furnitures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Manufacturing_Workers_WorkerId",
column: x => x.WorkerId,
principalTable: "Workers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Salaries",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
WorkerId = table.Column<string>(type: "text", nullable: false),
WorkerSalary = table.Column<double>(type: "double precision", nullable: false),
SalaryDate = table.Column<DateTime>(type: "timestamp without time zone", 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.CreateIndex(
name: "IX_Components_Name",
table: "Components",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_FurnitureComponents_ComponentId",
table: "FurnitureComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_Furnitures_Name",
table: "Furnitures",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Manufacturing_FurnitureId",
table: "Manufacturing",
column: "FurnitureId");
migrationBuilder.CreateIndex(
name: "IX_Manufacturing_WorkerId",
table: "Manufacturing",
column: "WorkerId");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostId_IsActual",
table: "Posts",
columns: new[] { "PostId", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Posts_PostName_IsActual",
table: "Posts",
columns: new[] { "PostName", "IsActual" },
unique: true,
filter: "\"IsActual\" = TRUE");
migrationBuilder.CreateIndex(
name: "IX_Salaries_WorkerId",
table: "Salaries",
column: "WorkerId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FurnitureComponents");
migrationBuilder.DropTable(
name: "Manufacturing");
migrationBuilder.DropTable(
name: "Posts");
migrationBuilder.DropTable(
name: "Salaries");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Furnitures");
migrationBuilder.DropTable(
name: "Workers");
}
}
}

View File

@@ -0,0 +1,279 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250331133531_ChangeFieldsInPost")]
partial class ChangeFieldsInPost
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevName")
.HasColumnType("text");
b.Property<string>("PrevPrevName")
.HasColumnType("text");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.Property<string>("FurnitureId")
.HasColumnType("text");
b.Property<string>("ComponentId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("FurnitureId", "ComponentId");
b.HasIndex("ComponentId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("FurnitureId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductuionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkerId");
b.ToTable("Manufacturing");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("ChangeDate")
.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("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("ManifacturingFurniture")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Navigation("ManifacturingFurniture");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatebase.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,282 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
[Migration("20250401182232_ChangeWorker")]
partial class ChangeWorker
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevName")
.HasColumnType("text");
b.Property<string>("PrevPrevName")
.HasColumnType("text");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.Property<string>("FurnitureId")
.HasColumnType("text");
b.Property<string>("ComponentId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("FurnitureId", "ComponentId");
b.HasIndex("ComponentId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("FurnitureId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductuionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkerId");
b.ToTable("Manufacturing");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("ChangeDate")
.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("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("ManifacturingFurniture")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Navigation("ManifacturingFurniture");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
/// <inheritdoc />
public partial class ChangeWorker : 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,279 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatebase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace FurnitureAssemblyDatebase.Migrations
{
[DbContext(typeof(FurnitureAssemblyDbContext))]
partial class FurnitureAssemblyDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PrevName")
.HasColumnType("text");
b.Property<string>("PrevPrevName")
.HasColumnType("text");
b.Property<int>("Type")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Weight")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.Property<string>("FurnitureId")
.HasColumnType("text");
b.Property<string>("ComponentId")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("FurnitureId", "ComponentId");
b.HasIndex("ComponentId");
b.ToTable("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<string>("FurnitureId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("ProductuionDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("WorkerId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkerId");
b.ToTable("Manufacturing");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.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("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("BirthDate")
.HasColumnType("timestamp without time zone");
b.Property<DateTime>("ChangeDate")
.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("FurnitureAssemblyDatebase.Models.FurnitureComponent", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Component", "Component")
.WithMany("FurnitureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany("Components")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Component");
b.Navigation("Furniture");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.ManifacturingFurniture", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Furniture", "Furniture")
.WithMany()
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("ManifacturingFurniture")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Salary", b =>
{
b.HasOne("FurnitureAssemblyDatebase.Models.Worker", "Worker")
.WithMany("Salaries")
.HasForeignKey("WorkerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Worker");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Component", b =>
{
b.Navigation("FurnitureComponents");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Furniture", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("FurnitureAssemblyDatebase.Models.Worker", b =>
{
b.Navigation("ManifacturingFurniture");
b.Navigation("Salaries");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,4 +1,5 @@
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
namespace FurnitureAssemblyDatebase.Models; namespace FurnitureAssemblyDatebase.Models;
@@ -8,7 +9,7 @@ public class Post
public required string PostId { get; set; } public required string PostId { get; set; }
public required string PostName { get; set; } public required string PostName { get; set; }
public PostType PostType { get; set; } public PostType PostType { get; set; }
public double Salary { get; set; } public required PostConfiguration Configuration { get; set; }
public bool IsActual { get; set; } public bool IsActual { get; set; }
public DateTime ChangeDate { get; set; } public DateTime ChangeDate { get; set; }
} }

View File

@@ -23,4 +23,5 @@ public class Worker
Post = post; Post = post;
return this; return this;
} }
public DateTime? DateOfDelete { get; set; }
} }

View File

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

View File

@@ -2,6 +2,7 @@
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts; using FurnitureAssemblyContracts.StoragesContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
@@ -32,9 +33,9 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
var listOriginal = new List<PostDataModel>() var listOriginal = new List<PostDataModel>()
{ {
new(Guid.NewGuid().ToString(), "name 1", PostType.Builder, 10), new(Guid.NewGuid().ToString(),"name 1", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, 10), new(Guid.NewGuid().ToString(), "name 2", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, 10), new(Guid.NewGuid().ToString(), "name 3", PostType.Builder, new PostConfiguration() { Rate = 10 }),
}; };
_postStorageContract.Setup(x => x.GetList()).Returns(listOriginal); _postStorageContract.Setup(x => x.GetList()).Returns(listOriginal);
//Act //Act
@@ -88,8 +89,8 @@ internal class PostBusinessLogicContractTests
var postId = Guid.NewGuid().ToString(); var postId = Guid.NewGuid().ToString();
var listOriginal = new List<PostDataModel>() var listOriginal = new List<PostDataModel>()
{ {
new(postId, "name 1", PostType.Builder, 10), new(postId, "name 1", PostType.Builder, new PostConfiguration() { Rate = 10 }),
new(postId, "name 2", PostType.Builder, 10) new(postId, "name 2", PostType.Builder, new PostConfiguration() { Rate = 10 })
}; };
_postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal); _postStorageContract.Setup(x => x.GetPostWithHistory(It.IsAny<string>())).Returns(listOriginal);
//Act //Act
@@ -153,7 +154,7 @@ internal class PostBusinessLogicContractTests
{ {
//Arrange //Arrange
var id = Guid.NewGuid().ToString(); var id = Guid.NewGuid().ToString();
var record = new PostDataModel(id, "name", PostType.Builder, 10); var record = new PostDataModel(id, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementById(id)).Returns(record); _postStorageContract.Setup(x => x.GetElementById(id)).Returns(record);
//Act //Act
var element = _postBusinessLogicContract.GetPostByData(id); var element = _postBusinessLogicContract.GetPostByData(id);
@@ -168,7 +169,7 @@ internal class PostBusinessLogicContractTests
{ {
//Arrange //Arrange
var postName = "name"; var postName = "name";
var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, 10); var record = new PostDataModel(Guid.NewGuid().ToString(), postName, PostType.Builder, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record); _postStorageContract.Setup(x => x.GetElementByName(postName)).Returns(record);
//Act //Act
var element = _postBusinessLogicContract.GetPostByData(postName); var element = _postBusinessLogicContract.GetPostByData(postName);
@@ -224,13 +225,12 @@ internal class PostBusinessLogicContractTests
{ {
//Arrange //Arrange
var flag = false; var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10); var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())) _postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>()))
.Callback((PostDataModel x) => .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 //Act
_postBusinessLogicContract.InsertPost(record); _postBusinessLogicContract.InsertPost(record);
//Assert //Assert
@@ -244,7 +244,7 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data")); _postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once); _postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
} }
@@ -260,7 +260,7 @@ internal class PostBusinessLogicContractTests
public void InsertPost_InvalidRecord_ThrowException_Test() public void InsertPost_InvalidRecord_ThrowException_Test()
{ {
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>()); Assert.That(() => _postBusinessLogicContract.InsertPost(new PostDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never); _postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Never);
} }
@@ -270,7 +270,7 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
_postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException())); _postStorageContract.Setup(x => x.AddElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>()); Assert.That(() => _postBusinessLogicContract.InsertPost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once); _postStorageContract.Verify(x => x.AddElement(It.IsAny<PostDataModel>()), Times.Once);
} }
@@ -279,10 +279,11 @@ internal class PostBusinessLogicContractTests
{ {
//Arrange //Arrange
var flag = false; var flag = false;
var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 10); var record = new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Callback((PostDataModel x) => _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 //Act
_postBusinessLogicContract.UpdatePost(record); _postBusinessLogicContract.UpdatePost(record);
@@ -297,7 +298,7 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException("")); _postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementNotFoundException(""));
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<ElementNotFoundException>()); Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementNotFoundException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once); _postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
} }
@@ -307,7 +308,7 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data")); _postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new ElementExistsException("Data", "Data"));
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, 10)), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "anme", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ElementExistsException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once); _postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
} }
@@ -323,7 +324,7 @@ internal class PostBusinessLogicContractTests
public void UpdatePost_InvalidRecord_ThrowException_Test() public void UpdatePost_InvalidRecord_ThrowException_Test()
{ {
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, 10)), Throws.TypeOf<ValidationException>()); Assert.That(() => _postBusinessLogicContract.UpdatePost(new PostDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never); _postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Never);
} }
@@ -333,7 +334,7 @@ internal class PostBusinessLogicContractTests
//Arrange //Arrange
_postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException())); _postStorageContract.Setup(x => x.UpdElement(It.IsAny<PostDataModel>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert //Act&Assert
Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, 10)), Throws.TypeOf<StorageException>()); Assert.That(() => _postBusinessLogicContract.UpdatePost(new(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 10 })), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once); _postStorageContract.Verify(x => x.UpdElement(It.IsAny<PostDataModel>()), Times.Once);
} }
@@ -371,6 +372,24 @@ internal class PostBusinessLogicContractTests
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never); _postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
} }
[Test]
public void DeletePost_IdIsNotGuid_ThrowException_Test()
{
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost("id"), Throws.TypeOf<ValidationException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Never);
}
[Test]
public void DeletePost_StorageThrowError_ThrowException_Test()
{
//Arrange
_postStorageContract.Setup(x => x.DelElement(It.IsAny<string>())).Throws(new StorageException(new InvalidOperationException()));
//Act&Assert
Assert.That(() => _postBusinessLogicContract.DeletePost(Guid.NewGuid().ToString()), Throws.TypeOf<StorageException>());
_postStorageContract.Verify(x => x.DelElement(It.IsAny<string>()), Times.Once);
}
[Test] [Test]
public void RestorePost_CorrectRecord_Test() public void RestorePost_CorrectRecord_Test()
{ {

View File

@@ -2,7 +2,9 @@
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.StoragesContracts; using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyTests.Infrastructure;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Moq; using Moq;
@@ -15,6 +17,7 @@ internal class SalaryBuisnessLogicContractTests
private Mock<IManifacturingStorageContract> _manifacturingStorageContract; private Mock<IManifacturingStorageContract> _manifacturingStorageContract;
private Mock<IPostStorageContract> _postStorageContract; private Mock<IPostStorageContract> _postStorageContract;
private Mock<IWorkerStorageContract> _workerStorageContract; private Mock<IWorkerStorageContract> _workerStorageContract;
private readonly ConfigurationSalaryTest _salaryConfigurationTest = new();
[OneTimeSetUp] [OneTimeSetUp]
public void OneTimeSetUp() public void OneTimeSetUp()
@@ -24,7 +27,7 @@ internal class SalaryBuisnessLogicContractTests
_postStorageContract = new Mock<IPostStorageContract>(); _postStorageContract = new Mock<IPostStorageContract>();
_workerStorageContract = new Mock<IWorkerStorageContract>(); _workerStorageContract = new Mock<IWorkerStorageContract>();
_salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object, _salaryBusinessLogicContract = new SalaryBusinessLogicContract(_salaryStorageContract.Object,
_manifacturingStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object); _manifacturingStorageContract.Object, _postStorageContract.Object, _workerStorageContract.Object, new Mock<ILogger>().Object, _salaryConfigurationTest);
} }
[TearDown] [TearDown]
@@ -183,18 +186,18 @@ internal class SalaryBuisnessLogicContractTests
[Test] [Test]
public void CalculateSalaryByMounth_CalculateSalary_Test() public void CalculateSalaryByMounth_CalculateSalary_Test()
{ {
//Arrange ////Arrange
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();
var saleSum = 200; var saleSum = 200;
var postSalary = 2000; var postSalary = 2000;
var rate = 2000.0;
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())) _manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, workerId)]); .Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), saleSum, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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)]); .Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0; var sum = 0.0;
var expectedSum = postSalary + saleSum * 0.1;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>())) _salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) => .Callback((SalaryDataModel x) =>
{ {
@@ -203,7 +206,7 @@ internal class SalaryBuisnessLogicContractTests
//Act //Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow); _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert //Assert
Assert.That(sum, Is.EqualTo(expectedSum)); Assert.That(sum, Is.EqualTo(rate));
} }
[Test] [Test]
@@ -225,7 +228,7 @@ internal class SalaryBuisnessLogicContractTests
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id), new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id),
new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id)]); new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, worker3Id)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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); .Returns(list);
//Act //Act
@@ -238,16 +241,15 @@ internal class SalaryBuisnessLogicContractTests
public void CalculateSalaryByMounth_WithoitSalesByWorker_Test() public void CalculateSalaryByMounth_WithoitSalesByWorker_Test()
{ {
//Arrange //Arrange
var postSalary = 2000.0; var rate = 2000.0;
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())) _manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([]); .Returns([]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, postSalary)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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)]); .Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
var sum = 0.0; var sum = 0.0;
var expectedSum = postSalary;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>())) _salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) => .Callback((SalaryDataModel x) =>
{ {
@@ -256,7 +258,7 @@ internal class SalaryBuisnessLogicContractTests
//Act //Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow); _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert //Assert
Assert.That(sum, Is.EqualTo(expectedSum)); Assert.That(sum, Is.EqualTo(rate));
} }
[Test] [Test]
@@ -265,7 +267,7 @@ internal class SalaryBuisnessLogicContractTests
//Arrange //Arrange
var workerId = Guid.NewGuid().ToString(); var workerId = Guid.NewGuid().ToString();
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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)]); .Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert //Act&Assert
@@ -293,7 +295,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())) _manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]); .Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 100 }));
//Act&Assert //Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>()); Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<NullListException>());
} }
@@ -306,7 +308,7 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())) _manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new StorageException(new InvalidOperationException())); .Throws(new StorageException(new InvalidOperationException()));
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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)]); .Returns([new WorkerDataModel(workerId, "Test", Guid.NewGuid().ToString(), DateTime.UtcNow, DateTime.UtcNow, false)]);
//Act&Assert //Act&Assert
@@ -336,10 +338,72 @@ internal class SalaryBuisnessLogicContractTests
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>())) _manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]); .Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>())) _postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 2000)); .Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 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?>())) _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())); .Throws(new StorageException(new InvalidOperationException()));
//Act&Assert //Act&Assert
Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>()); Assert.That(() => _salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow), Throws.TypeOf<StorageException>());
} }
[Test]
public void CalculateSalaryByMountht_WithBuilderPostConfiguration_CalculateSalary_Test()
{
//Arrange
var furnitureId = Guid.NewGuid().ToString();
var workerId = Guid.NewGuid().ToString();
var rate = 2000.0;
var bonus = 0.1;
var sales = new List<ManifacturingFurnitureDataModel>()
{
new(Guid.NewGuid().ToString(), furnitureId, 10, workerId),
new(Guid.NewGuid().ToString(), furnitureId, 15, workerId),
new(Guid.NewGuid().ToString(), furnitureId, 10, workerId)
};
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(sales);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new BuilderPostConfiguration() { Rate = rate, PersonalCount = 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 + (sales.Sum(x => x.Count) / sales.Count) + sales.Where(x => x.Count > _salaryConfigurationTest.ExtraMadeSum).Sum(x => x.Count) * bonus;
_salaryStorageContract.Setup(x => x.AddElement(It.IsAny<SalaryDataModel>()))
.Callback((SalaryDataModel x) =>
{
sum = x.Salary;
});
//Act
_salaryBusinessLogicContract.CalculateSalaryByMounth(DateTime.UtcNow);
//Assert
Assert.That(sum, Is.EqualTo(expectedSum));
}
[Test]
public void CalculateSalaryByMountht_WithChiefPostConfiguration_CalculateSalary_Test()
{
//Arrange
var workerId = Guid.NewGuid().ToString();
var rate = 2000.0;
var trend = 3;
var bonus = 100;
_manifacturingStorageContract.Setup(x => x.GetList(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns([new ManifacturingFurnitureDataModel(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), 10, workerId)]);
_postStorageContract.Setup(x => x.GetElementById(It.IsAny<string>()))
.Returns(new PostDataModel(Guid.NewGuid().ToString(), "name", PostType.Chief, new ChiefPostConfiguration() { 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 FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
namespace FurnitureAssemblyTests.DataModelsTests; namespace FurnitureAssemblyTests.DataModelsTests;
@@ -10,67 +11,71 @@ internal class PostDataModelTests
[Test] [Test]
public void IdIsNullOrEmptyTest() public void IdIsNullOrEmptyTest()
{ {
var model = CreateDataModel(null, "name", PostType.Builder, 100); var post = CreateDataModel(null, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(string.Empty, "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
model = CreateDataModel(string.Empty, "name", PostType.Builder, 100); Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void IdIsNotGuidTest() public void IdIsNotGuidTest()
{ {
var model = CreateDataModel("id", "name", PostType.Builder, 100); var post = CreateDataModel("id", "name", PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void PostNameIsNullOrEmptyTest() public void PostNameIsEmptyTest()
{ {
var model = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, 100); var manufacturer = CreateDataModel(Guid.NewGuid().ToString(), null, PostType.Builder, new PostConfiguration() { Rate = 10 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
manufacturer = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, new PostConfiguration() { Rate = 10 });
model = CreateDataModel(Guid.NewGuid().ToString(), string.Empty, PostType.Builder, 100); Assert.That(() => manufacturer.Validate(), Throws.TypeOf<ValidationException>());
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void PostTypeIsNoneTest() public void PostTypeIsNoneTest()
{ {
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, 100); var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.None, new PostConfiguration() { Rate = 10 });
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void SalaryIsZeroNegativeTest() public void ConfigurationModelIsNullTest()
{ {
var model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, 0); var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, null);
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>()); Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
model = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, -1); }
Assert.That(() => model.Validate(), Throws.TypeOf<ValidationException>());
[Test]
public void RateIsLessOrZeroTest()
{
var post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = 0 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
post = CreateDataModel(Guid.NewGuid().ToString(), "name", PostType.Builder, new PostConfiguration() { Rate = -10 });
Assert.That(() => post.Validate(), Throws.TypeOf<ValidationException>());
} }
[Test] [Test]
public void AllFieldsIsCorrectTest() public void AllFieldsIsCorrectTest()
{ {
var id = Guid.NewGuid().ToString(); var postId = Guid.NewGuid().ToString();
var postName = "name"; var postName = "name";
var postType = PostType.Builder; var postType = PostType.Builder;
var salary = 100.50; var configuration = new PostConfiguration() { Rate = 10 };
var isActual = true; var post = CreateDataModel(postId, postName, postType, configuration);
var changeDate = DateTime.Now; Assert.That(() => post.Validate(), Throws.Nothing);
var model = CreateDataModel(id, postName, postType, salary);
Assert.That(() => model.Validate(), Throws.Nothing);
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(model.Id, Is.EqualTo(id)); Assert.That(post.Id, Is.EqualTo(postId));
Assert.That(model.PostName, Is.EqualTo(postName)); Assert.That(post.PostName, Is.EqualTo(postName));
Assert.That(model.PostType, Is.EqualTo(postType)); Assert.That(post.PostType, Is.EqualTo(postType));
Assert.That(model.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) private static PostDataModel CreateDataModel(string? id, string? postName, PostType postType, PostConfiguration configuration) =>
=> new(id, postName, postType, salary); new(id, postName, postType, configuration);
} }

View File

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

View File

@@ -1,24 +1,29 @@
using FurnitureAssemblyContracts.Enums; 
using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyDatebase; using FurnitureAssemblyDatebase;
using FurnitureAssemblyDatebase.Models; using FurnitureAssemblyDatebase.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
namespace FurnitureAssemblyTests.Infrastructure; namespace FurnitureAssemblyTests.Infrastructure;
internal static class FurnitureAssemblyDbContextExtensions internal static class FurnitureAssemblyDbContextExtensions
{ {
public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, double salary = 10, bool isActual = true, DateTime? changeDate = null) public static Post InsertPostToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string postName = "test", PostType postType = PostType.Builder, 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.Posts.Add(post);
dbContext.SaveChanges(); dbContext.SaveChanges();
return post; return post;
} }
public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", string? postId = null, DateTime? birthDate = null, DateTime? employmentDate = null, bool isDeleted = false) public static Worker InsertWorkerToDatabaseAndReturn(this FurnitureAssemblyDbContext dbContext, string? id = null, string fio = "Иванов И.И.", 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.Workers.Add(worker);
dbContext.SaveChanges(); dbContext.SaveChanges();
return worker; return worker;

View File

@@ -1,6 +1,7 @@
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyDatebase.Implementations; using FurnitureAssemblyDatebase.Implementations;
using FurnitureAssemblyDatebase.Models; using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure; using FurnitureAssemblyTests.Infrastructure;
@@ -44,6 +45,19 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(list, Is.Empty); Assert.That(list, Is.Empty);
} }
[Test]
public void Try_GetList_WhenDifferentConfigTypes_Test()
{
var postSimple = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postBuilder = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new BuilderPostConfiguration() { PersonalCount = 500 });
var postLoader = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new ChiefPostConfiguration() { PersonalCountTrendPremium = 20 });
var list = _postStorageContract.GetList();
Assert.That(list, Is.Not.Null);
AssertElement(list.First(x => x.Id == postSimple.PostId), postSimple);
AssertElement(list.First(x => x.Id == postBuilder.PostId), postBuilder);
AssertElement(list.First(x => x.Id == postLoader.PostId), postLoader);
}
[Test] [Test]
public void Try_GetPostWithHistory_WhenHaveRecords_Test() public void Try_GetPostWithHistory_WhenHaveRecords_Test()
{ {
@@ -141,6 +155,36 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>()); Assert.That(() => _postStorageContract.AddElement(post), Throws.TypeOf<ElementExistsException>());
} }
[Test]
public void Try_AddElement_WithBuilderPostConfiguration_Test()
{
var salePercent = 10;
var post = CreateModel(Guid.NewGuid().ToString(), config: new BuilderPostConfiguration() { PersonalCount = salePercent });
_postStorageContract.AddElement(post);
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_AddElement_WithLoaderPostConfiguration_Test()
{
var trendPremium = 20;
var post = CreateModel(Guid.NewGuid().ToString(), config: new ChiefPostConfiguration() { PersonalCountTrendPremium = trendPremium });
_postStorageContract.AddElement(post);
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.Id);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test] [Test]
public void Try_UpdElement_Test() public void Try_UpdElement_Test()
{ {
@@ -177,6 +221,36 @@ internal class PostStorageContractTests : BaseStorageContractTest
Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>()); Assert.That(() => _postStorageContract.UpdElement(post), Throws.TypeOf<ElementDeletedException>());
} }
[Test]
public void Try_UpdElement_WithBuilderPostConfiguration_Test()
{
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
var salePercent = 10;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new BuilderPostConfiguration() { PersonalCount = salePercent }));
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(salePercent));
});
}
[Test]
public void Try_UpdElement_WithLoaderPostConfiguration_Test()
{
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
var trendPremium = 20;
_postStorageContract.UpdElement(CreateModel(post.PostId, config: new ChiefPostConfiguration() { PersonalCountTrendPremium = trendPremium }));
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(post.PostId);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test] [Test]
public void Try_DelElement_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.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType)); 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.Builder, double salary = 10) private static PostDataModel CreateModel(string postId, string postName = "test", PostType postType = PostType.Builder, PostConfiguration? config = null)
=> new(postId, postName, postType, salary); => new(postId, postName, postType, config ?? new PostConfiguration() { Rate = 100 });
private static void AssertElement(Post? actual, PostDataModel expected) 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.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType)); 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

@@ -183,6 +183,42 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(() => _workerStorageContract.DelElement(worker.Id), Throws.TypeOf<ElementNotFoundException>()); 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);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
FurnitureAssemblyDbContext.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);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-4));
FurnitureAssemblyDbContext.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);
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-9));
FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(employmentDate: DateTime.UtcNow.AddDays(-10), isDeleted: true, dateDelete: DateTime.UtcNow.AddDays(-4));
FurnitureAssemblyDbContext.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) private static void AssertElement(WorkerDataModel? actual, Worker expected)
{ {
Assert.That(actual, Is.Not.Null); Assert.That(actual, Is.Not.Null);
@@ -211,6 +247,7 @@ internal class WorkerStorageContractTests : BaseStorageContractTest
Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate)); Assert.That(actual.BirthDate, Is.EqualTo(expected.BirthDate));
Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate)); Assert.That(actual.EmploymentDate, Is.EqualTo(expected.EmploymentDate));
Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted)); Assert.That(actual.IsDeleted, Is.EqualTo(expected.IsDeleted));
Assert.That(actual.DateOfDelete.HasValue, Is.EqualTo(expected.IsDeleted));
}); });
} }
} }

View File

@@ -1,9 +1,12 @@
using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.Enums; using FurnitureAssemblyContracts.Enums;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using FurnitureAssemblyContracts.ViewModels; using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDatebase.Models; using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyTests.Infrastructure; using FurnitureAssemblyTests.Infrastructure;
using System.Net; using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace FurnitureAssemblyTests.WebApiControllerTests; namespace FurnitureAssemblyTests.WebApiControllerTests;
@@ -51,6 +54,24 @@ internal class PostControllerTests : BaseWebApiControllerTest
}); });
} }
[Test]
public async Task GetRecords_WhenDifferentConfigTypes_ShouldSuccess_Test()
{
//Arrange
var postSimple = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 1");
var postBuilder = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 2", config: new BuilderPostConfiguration() { PersonalCount = 500 });
var postLoader = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(postName: "name 3", config: new ChiefPostConfiguration() { 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 == postBuilder.PostId), postBuilder);
AssertElement(data.First(x => x.Id == postLoader.PostId), postLoader);
}
[Test] [Test]
public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test() public async Task GetHistory_WhenHaveRecords_ShouldSuccess_Test()
{ {
@@ -210,10 +231,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test() public async Task Post_WhenDataIsIncorrect_ShouldBadRequest_Test()
{ {
//Arrange //Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Builder.ToString(), Salary = 10 }; var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Builder.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = 10 }; var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 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.Builder.ToString(), Salary = -10 }; var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), ConfigurationJson = null };
//Act //Act
var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect)); var responseWithIdIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect)); var responseWithNameIncorrect = await HttpClient.PostAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -247,6 +268,44 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task Post_WithBuilderPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new BuilderPostConfiguration() { PersonalCount = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PostAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Post_WithLoaderPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var postModel = CreateModel(configuration: JsonSerializer.Serialize(new ChiefPostConfiguration() { 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 = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test] [Test]
public async Task Put_ShouldSuccess_Test() public async Task Put_ShouldSuccess_Test()
{ {
@@ -302,10 +361,10 @@ internal class PostControllerTests : BaseWebApiControllerTest
public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test() public async Task Put_WhenDataIsIncorrect_ShouldBadRequest_Test()
{ {
//Arrange //Arrange
var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Builder.ToString(), Salary = 10 }; var postModelWithIdIncorrect = new PostBindingModel { Id = "Id", PostName = "name", PostType = PostType.Builder.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), Salary = 10 }; var postModelWithNameIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), ConfigurationJson = JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 }) };
var postModelWithPostTypeIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = string.Empty, Salary = 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.Builder.ToString(), Salary = -10 }; var postModelWithSalaryIncorrect = new PostBindingModel { Id = Guid.NewGuid().ToString(), PostName = string.Empty, PostType = PostType.Builder.ToString(), ConfigurationJson = null};
//Act //Act
var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect)); var responseWithIdIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithIdIncorrect));
var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect)); var responseWithNameIncorrect = await HttpClient.PutAsync($"/api/posts", MakeContent(postModelWithNameIncorrect));
@@ -339,6 +398,48 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
} }
[Test]
public async Task Put_WithBuilderPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var salePercent = 10;
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new BuilderPostConfiguration() { PersonalCount = salePercent, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
FurnitureAssemblyDbContext.ChangeTracker.Clear();
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(BuilderPostConfiguration).Name));
Assert.That((element.Configuration as BuilderPostConfiguration)!.PersonalCount, Is.EqualTo(salePercent));
});
}
[Test]
public async Task Put_WithSupervisorPostConfiguration_ShouldSuccess_Test()
{
//Arrange
var trendPremium = 20;
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
var postModel = CreateModel(post.PostId, configuration: JsonSerializer.Serialize(new ChiefPostConfiguration() { PersonalCountTrendPremium = trendPremium, Rate = 10 }));
//Act
var response = await HttpClient.PutAsync($"/api/posts", MakeContent(postModel));
//Assert
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
FurnitureAssemblyDbContext.ChangeTracker.Clear();
var element = FurnitureAssemblyDbContext.GetPostFromDatabaseByPostId(postModel.Id!);
Assert.That(element, Is.Not.Null);
Assert.Multiple(() =>
{
Assert.That(element.Configuration.Type, Is.EqualTo(typeof(ChiefPostConfiguration).Name));
Assert.That((element.Configuration as ChiefPostConfiguration)!.PersonalCountTrendPremium, Is.EqualTo(trendPremium));
});
}
[Test] [Test]
public async Task Delete_ShouldSuccess_Test() public async Task Delete_ShouldSuccess_Test()
{ {
@@ -443,17 +544,17 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.Id, Is.EqualTo(expected.PostId)); Assert.That(actual.Id, Is.EqualTo(expected.PostId));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType, Is.EqualTo(expected.PostType.ToString())); 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.Builder, double salary = 10) private static PostBindingModel CreateModel(string? postId = null, string postName = "name", PostType postType = PostType.Builder, string? configuration = null)
=> new() => new()
{ {
Id = postId ?? Guid.NewGuid().ToString(), Id = postId ?? Guid.NewGuid().ToString(),
PostName = postName, PostName = postName,
PostType = postType.ToString(), PostType = postType.ToString(),
Salary = salary ConfigurationJson = configuration ?? JsonSerializer.Serialize(new PostConfiguration() { Rate = 10 })
}; };
private static void AssertElement(Post? actual, PostBindingModel expected) private static void AssertElement(Post? actual, PostBindingModel expected)
@@ -464,7 +565,7 @@ internal class PostControllerTests : BaseWebApiControllerTest
Assert.That(actual.PostId, Is.EqualTo(expected.Id)); Assert.That(actual.PostId, Is.EqualTo(expected.Id));
Assert.That(actual.PostName, Is.EqualTo(expected.PostName)); Assert.That(actual.PostName, Is.EqualTo(expected.PostName));
Assert.That(actual.PostType.ToString(), Is.EqualTo(expected.PostType)); 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

@@ -3,6 +3,8 @@ using System.Net;
using System; using System;
using FurnitureAssemblyTests.Infrastructure; using FurnitureAssemblyTests.Infrastructure;
using FurnitureAssemblyDatebase.Models; using FurnitureAssemblyDatebase.Models;
using FurnitureAssemblyContracts.Infrastructure.PostConfigurations;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace FurnitureAssemblyTests.WebApiControllerTests; namespace FurnitureAssemblyTests.WebApiControllerTests;
@@ -155,7 +157,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
public async Task Calculate_ShouldSuccess_Test() public async Task Calculate_ShouldSuccess_Test()
{ {
//Arrange //Arrange
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(salary: 1000); var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn();
var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId); var worker = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "Иванов И.И.", postId: post.PostId);
var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(); var furniture = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();
FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(worker.Id, furniture.Id); FurnitureAssemblyDbContext.InsertManifacturingToDatabaseAndReturn(worker.Id, furniture.Id);
@@ -167,7 +169,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
Assert.Multiple(() => Assert.Multiple(() =>
{ {
Assert.That(salaries, Has.Length.EqualTo(1)); Assert.That(salaries, Has.Length.EqualTo(1));
Assert.That(salaries.First().WorkerSalary, Is.EqualTo(1000.5)); Assert.That(salaries.First().WorkerSalary, Is.EqualTo(100));
Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month)); Assert.That(salaries.First().SalaryDate.Month, Is.EqualTo(DateTime.UtcNow.Month));
}); });
} }
@@ -187,7 +189,7 @@ internal class SalaryControllerTests : BaseWebApiControllerTest
public async Task Calculate_WithoutSalesByWorker_ShouldSuccess_Test() public async Task Calculate_WithoutSalesByWorker_ShouldSuccess_Test()
{ {
//Arrange //Arrange
var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(salary: 1000); var post = FurnitureAssemblyDbContext.InsertPostToDatabaseAndReturn(config: new BuilderPostConfiguration());
var worker1 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId); var worker1 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 1", postId: post.PostId);
var worker2 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId); var worker2 = FurnitureAssemblyDbContext.InsertWorkerToDatabaseAndReturn(fio: "name 2", postId: post.PostId);
var man = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn(); var man = FurnitureAssemblyDbContext.InsertFurnitureToDatabaseAndReturn();

View File

@@ -6,6 +6,7 @@ using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.ViewModels; using FurnitureAssemblyContracts.ViewModels;
using System.Text.Json;
namespace FurnitureAssemblyWebApi.Adapters; namespace FurnitureAssemblyWebApi.Adapters;
@@ -17,6 +18,11 @@ public class PostAdapter : IPostAdapter
private readonly Mapper _mapper; private readonly Mapper _mapper;
private readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNameCaseInsensitive = true
};
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger) public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, ILogger<PostAdapter> logger)
{ {
_postBusinessLogicContract = postBusinessLogicContract; _postBusinessLogicContract = postBusinessLogicContract;
@@ -24,7 +30,8 @@ public class PostAdapter : IPostAdapter
var config = new MapperConfiguration(cfg => var config = new MapperConfiguration(cfg =>
{ {
cfg.CreateMap<PostBindingModel, PostDataModel>(); 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); _mapper = new Mapper(config);
} }

View File

@@ -4,6 +4,7 @@ using FurnitureAssemblyContracts.AdapterContracts.OperationResponses;
using FurnitureAssemblyContracts.BusinessLogicsContracts; using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.DataModels; using FurnitureAssemblyContracts.DataModels;
using FurnitureAssemblyContracts.Exceptions; using FurnitureAssemblyContracts.Exceptions;
using FurnitureAssemblyContracts.Infrastructure;
using FurnitureAssemblyContracts.ViewModels; using FurnitureAssemblyContracts.ViewModels;
namespace FurnitureAssemblyWebApi.Adapters; namespace FurnitureAssemblyWebApi.Adapters;

View File

@@ -9,6 +9,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
</ItemGroup> </ItemGroup>
@@ -23,4 +27,10 @@
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,16 @@
using FurnitureAssemblyContracts.Infrastructure;
namespace FurnitureAssemblyWebApi.Infrastucture;
public class ConfigurationSalary(IConfiguration configuration) : IConfigurationSalary
{
private readonly Lazy<SalarySettings> _salarySettings = new(() =>
{
var settings = configuration.GetSection("SalarySettings").Get<SalarySettings>();
return settings ?? throw new InvalidDataException("SalarySettings configuration section is missing or invalid");
});
public double ExtraMadeSum => _salarySettings.Value.ExtraMadeSum;
public int MaxConcurrentThreads => _salarySettings.Value.MaxConcurrentThreads;
}

View File

@@ -0,0 +1,7 @@
namespace FurnitureAssemblyWebApi.Infrastucture;
public class SalarySettings
{
public double ExtraMadeSum { get; set; }
public int MaxConcurrentThreads { get; set; }
}

View File

@@ -48,6 +48,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJw
}); });
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>(); builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
builder.Services.AddSingleton<IConfigurationSalary, ConfigurationSalary>();
builder.Services.AddTransient<IComponentBusinessLogicContract, ComponentBusinessLogicContract>(); builder.Services.AddTransient<IComponentBusinessLogicContract, ComponentBusinessLogicContract>();
builder.Services.AddTransient<IFurnitureBusinessLogicContract, FurnitureBusinessLogicContract>(); builder.Services.AddTransient<IFurnitureBusinessLogicContract, FurnitureBusinessLogicContract>();

View File

@@ -21,5 +21,12 @@
} }
] ]
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"SalarySettings": {
"ExtraMadeSum": 10,
"MaxConcurrentThreads": 2
},
"BuilderSettings": {
"PersonalCount": 0.1
}
} }