From df73a0d314d7ea661baaf04e3e0ed87aa71f4cc0 Mon Sep 17 00:00:00 2001 From: kotcheshir73 Date: Tue, 29 Mar 2022 13:33:32 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=B2=D1=8F=D0=B7=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B3=D0=BE=D0=B4=D0=B0=20=D0=BE=D0=B1=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=20=D1=81=D1=82=D1=83=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractGenerticEntityService.cs | 14 +- .../Common/CoreDatabase/DatabaseContext.cs | 2 +- ...9053045_ChangeOrderIndexUnique.Designer.cs | 1581 +++++++++++++++++ .../20220329053045_ChangeOrderIndexUnique.cs | 33 + .../DatabaseContextModelSnapshot.cs | 2 +- .../MainControls/GenericControlEntityList.cs | 1154 ++++++------ .../ManagmentEntity/GenericBusinessLogic.cs | 30 + .../OrderStudentRecordBusinessLogic.cs | 1 + .../OrderSyncHistoryBusinessLogic.cs | 827 +++++---- .../EnrollmentYearBindingModels.cs | 4 + .../BindingModels/OrderBindingModels.cs | 2 + .../ViewModels/AcademicPlanViewModels.cs | 4 +- .../ViewModels/OrderViewModels.cs | 2 +- .../AcademicPlanRecordService.cs | 2 +- .../AcademicPlanRecordTimeNormHourService.cs | 2 +- .../AcademicPlanService.cs | 2 +- .../BasicDepartmentService.cs | 2 +- .../ClassroomService.cs | 2 +- .../DisciplineBlockService.cs | 2 +- .../DisciplineService.cs | 2 +- .../EducationDirectionService.cs | 2 +- .../EmployeePostService.cs | 2 +- .../EmployeeService.cs | 2 +- .../EnrollmentYearService.cs | 30 +- .../LecturerAcademicDegreeService.cs | 2 +- .../LecturerAcademicRankService.cs | 2 +- .../LecturerPostService.cs | 2 +- .../LecturerService.cs | 2 +- .../OrderService.cs | 18 +- .../OrderStudentRecordService.cs | 2 +- .../PostService.cs | 2 +- .../StudentGroupService.cs | 2 +- .../StudentService.cs | 2 +- .../TimeNormService.cs | 2 +- .../AccessService.cs | 4 +- .../EnviromentSettingService.cs | 2 +- .../RoleService.cs | 2 +- .../UserRoleService.cs | 22 +- .../UserService.cs | 2 +- 39 files changed, 2771 insertions(+), 1003 deletions(-) create mode 100644 DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.Designer.cs create mode 100644 DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.cs diff --git a/DepartmentPortal/Common/CoreDatabase/AbstractGenerticEntityService.cs b/DepartmentPortal/Common/CoreDatabase/AbstractGenerticEntityService.cs index 050bc5f..c9b629f 100644 --- a/DepartmentPortal/Common/CoreDatabase/AbstractGenerticEntityService.cs +++ b/DepartmentPortal/Common/CoreDatabase/AbstractGenerticEntityService.cs @@ -24,7 +24,7 @@ namespace CoreDatabase return result; } - var exsistEntity = GetUniqueEntity(model, context); + var exsistEntity = GetUniqueEntity(model, IncludingWhenReading(context.Set().AsQueryable())); if (exsistEntity == null) { var entity = Mapper.MapToClass(model, true); @@ -94,7 +94,7 @@ namespace CoreDatabase { using var context = DatabaseManager.GetContext; var entity = model.Id.HasValue ? IncludingWhenReading(context.Set().AsQueryable()).FirstOrDefault(x => x.Id == model.Id.Value) - : GetSingleRecord(context.Set().AsQueryable(), model); + : GetSingleRecord(IncludingWhenReading(context.Set().AsQueryable()), model); if (entity == null) { return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); @@ -121,7 +121,7 @@ namespace CoreDatabase if (model.Id.HasValue || AdditionalCheckForSingleGet(model)) { var entity = model.Id.HasValue ? IncludingWhenReading(context.Set().AsQueryable()).FirstOrDefault(x => x.Id == model.Id.Value) - : GetSingleRecord(context.Set().AsQueryable(), model); + : GetSingleRecord(IncludingWhenReading(context.Set().AsQueryable()), model); if (entity == null) { return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); @@ -167,9 +167,13 @@ namespace CoreDatabase return result; } - var exsistEntity = GetUniqueEntity(model, context); + var exsistEntity = GetUniqueEntity(model, IncludingWhenReading(context.Set().AsQueryable())); if (exsistEntity != null) { + if (exsistEntity.IsDeleted) + { + return OperationResultModel.Error("Error:", "Существует удаленная запись с такими значениями", ResultServiceStatusCode.ExsistItem); + } return OperationResultModel.Error("Error:", "Существует запись с такими значениями", ResultServiceStatusCode.ExsistItem); } @@ -194,7 +198,7 @@ namespace CoreDatabase /// /// /// - protected abstract T GetUniqueEntity(S model, DbContext context); + protected abstract T GetUniqueEntity(S model, IQueryable query); /// /// Возможные дополнительные проверки при добавлении diff --git a/DepartmentPortal/Common/CoreDatabase/DatabaseContext.cs b/DepartmentPortal/Common/CoreDatabase/DatabaseContext.cs index fbf90ef..174402b 100644 --- a/DepartmentPortal/Common/CoreDatabase/DatabaseContext.cs +++ b/DepartmentPortal/Common/CoreDatabase/DatabaseContext.cs @@ -70,7 +70,7 @@ namespace CoreDatabase modelBuilder.Entity().HasIndex(d => new { d.NumberOfBook }).IsUnique(); - modelBuilder.Entity().HasIndex(d => new { d.OrderNumber }).IsUnique(); + modelBuilder.Entity().HasIndex(d => new { d.OrderNumber, d.OrderDate, d.OrderType }).IsUnique(); modelBuilder.Entity().HasIndex(d => new { d.StudentId, d.OrderId }).IsUnique(); diff --git a/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.Designer.cs b/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.Designer.cs new file mode 100644 index 0000000..62f03b3 --- /dev/null +++ b/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.Designer.cs @@ -0,0 +1,1581 @@ +// +using System; +using CoreDatabase; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace CoreDatabase.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20220329053045_ChangeOrderIndexUnique")] + partial class ChangeOrderIndexUnique + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.15") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlan", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("CreateDate") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EducationDirectionId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastUpdateDate") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("EducationDirectionId", "CreateDate") + .IsUnique() + .HasFilter("[EducationDirectionId] IS NOT NULL"); + + b.ToTable("AcademicPlans"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlanRecord", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AcademicPlanId") + .HasColumnType("uniqueidentifier"); + + b.Property("AcademicPlanRecordParentId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("DisciplineId") + .HasColumnType("uniqueidentifier"); + + b.Property("InDepartment") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsFacultative") + .HasColumnType("bit"); + + b.Property("IsParent") + .HasColumnType("bit"); + + b.Property("Semester") + .HasColumnType("int"); + + b.Property("Zet") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("DisciplineId"); + + b.HasIndex("AcademicPlanId", "DisciplineId", "Semester") + .IsUnique(); + + b.ToTable("AcademicPlanRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlanRecordTimeNormHour", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AcademicPlanRecordId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PlanHours") + .HasColumnType("decimal(18,2)"); + + b.Property("TimeNormId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TimeNormId"); + + b.HasIndex("AcademicPlanRecordId", "TimeNormId") + .IsUnique(); + + b.ToTable("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.BasicDepartment", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("BasicDepartmentDescription") + .HasColumnType("nvarchar(max)"); + + b.Property("BasicDepartmentName") + .HasColumnType("nvarchar(max)"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EnterprisesName") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LecturerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("LecturerId"); + + b.ToTable("BasicDepartment"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Classroom", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Capacity") + .HasColumnType("int"); + + b.Property("ClassroomType") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("EmployeeId") + .HasColumnType("uniqueidentifier"); + + b.Property("HaveProjector") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Number") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Photo") + .HasColumnType("varbinary(max)"); + + b.Property("SecurityCode") + .HasColumnType("nvarchar(max)"); + + b.Property("Square") + .HasColumnType("decimal(18,2)"); + + b.Property("Title") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("EmployeeId"); + + b.HasIndex("Number") + .IsUnique(); + + b.ToTable("Classrooms"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Discipline", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("BasicDepartmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DisciplineBlockId") + .HasColumnType("uniqueidentifier"); + + b.Property("DisciplineBlueAsteriskName") + .HasColumnType("nvarchar(max)"); + + b.Property("DisciplineName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("DisciplineShortName") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.HasKey("Id"); + + b.HasIndex("BasicDepartmentId"); + + b.HasIndex("DisciplineBlockId"); + + b.HasIndex("DisciplineName") + .IsUnique(); + + b.ToTable("Disciplines"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.DisciplineBlock", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("DisciplineBlockBlueAsteriskName") + .HasColumnType("nvarchar(max)"); + + b.Property("DisciplineBlockOrder") + .HasColumnType("int"); + + b.Property("DisciplineBlockUseForGrouping") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Title") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Title") + .IsUnique(); + + b.ToTable("DisciplineBlocks"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EducationDirection", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Cipher") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LecturerId") + .HasColumnType("uniqueidentifier"); + + b.Property("Profile") + .HasColumnType("nvarchar(450)"); + + b.Property("Qualification") + .HasColumnType("int"); + + b.Property("ShortName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Title") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("LecturerId"); + + b.HasIndex("Title", "Profile") + .IsUnique() + .HasFilter("[Profile] IS NOT NULL"); + + b.ToTable("EducationDirections"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Employee", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Address") + .HasColumnType("nvarchar(max)"); + + b.Property("DateBirth") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .HasColumnType("nvarchar(max)"); + + b.Property("FirstName") + .HasColumnType("nvarchar(450)"); + + b.Property("GroupElectricalSafety") + .HasColumnType("nvarchar(max)"); + + b.Property("HomeNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastName") + .HasColumnType("nvarchar(450)"); + + b.Property("MobileNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("Patronymic") + .HasColumnType("nvarchar(450)"); + + b.Property("Photo") + .HasColumnType("varbinary(max)"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("FirstName", "LastName", "Patronymic") + .IsUnique() + .HasFilter("[FirstName] IS NOT NULL AND [LastName] IS NOT NULL AND [Patronymic] IS NOT NULL"); + + b.ToTable("Employees"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EmployeePost", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EmployeeId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsExternalCombination") + .HasColumnType("bit"); + + b.Property("IsInternalCombination") + .HasColumnType("bit"); + + b.Property("PostId") + .HasColumnType("uniqueidentifier"); + + b.Property("Rate") + .HasColumnType("decimal(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("EmployeeId"); + + b.HasIndex("PostId"); + + b.ToTable("EmployeePosts"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EnrollmentYear", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AcademicPlanId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("YearEntrance") + .HasColumnType("int"); + + b.Property("YearFinish") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AcademicPlanId", "YearEntrance") + .IsUnique(); + + b.ToTable("EnrollmentYears"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Lecturer", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Abbreviation") + .HasColumnType("nvarchar(max)"); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateBirth") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupElectricalSafety") + .HasColumnType("nvarchar(max)"); + + b.Property("HomeNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("LecturerAcademicDegreeId") + .HasColumnType("uniqueidentifier"); + + b.Property("LecturerAcademicRankId") + .HasColumnType("uniqueidentifier"); + + b.Property("MobileNumber") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OnlyForPrivate") + .HasColumnType("bit"); + + b.Property("Patronymic") + .HasColumnType("nvarchar(450)"); + + b.Property("Photo") + .HasColumnType("varbinary(max)"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("LecturerAcademicDegreeId"); + + b.HasIndex("LecturerAcademicRankId"); + + b.HasIndex("UserId"); + + b.HasIndex("FirstName", "LastName", "Patronymic") + .IsUnique() + .HasFilter("[Patronymic] IS NOT NULL"); + + b.ToTable("Lecturers"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerAcademicDegree", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LecturerAcademicDegreeName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Order") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LecturerAcademicDegreeName") + .IsUnique(); + + b.ToTable("LecturerAcademicDegrees"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerAcademicRank", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LecturerAcademicRankName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Order") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LecturerAcademicRankName") + .IsUnique(); + + b.ToTable("LecturerAcademicRanks"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerPost", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsExternalCombination") + .HasColumnType("bit"); + + b.Property("IsInternalCombination") + .HasColumnType("bit"); + + b.Property("LecturerId") + .HasColumnType("uniqueidentifier"); + + b.Property("PostId") + .HasColumnType("uniqueidentifier"); + + b.Property("Rate") + .HasColumnType("decimal(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("LecturerId"); + + b.HasIndex("PostId"); + + b.ToTable("LecturerPosts"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Order", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("OrderDate") + .HasColumnType("datetime2"); + + b.Property("OrderNumber") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OrderType") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("OrderNumber", "OrderDate", "OrderType") + .IsUnique(); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderStudentRecord", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Info") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("OrderId") + .HasColumnType("uniqueidentifier"); + + b.Property("OrderStudentMoveType") + .HasColumnType("int"); + + b.Property("StudentGroupFromId") + .HasColumnType("uniqueidentifier"); + + b.Property("StudentGroupToId") + .HasColumnType("uniqueidentifier"); + + b.Property("StudentId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.HasIndex("StudentGroupFromId"); + + b.HasIndex("StudentGroupToId"); + + b.HasIndex("StudentId", "OrderId") + .IsUnique(); + + b.ToTable("OrderStudentRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderSyncHistory", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("SyncDate") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("OrderSyncHistories"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderSyncHistoryRecord", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Information") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrderSyncHistoryId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("OrderSyncHistoryId"); + + b.ToTable("OrderSyncHistoryRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Post", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Hours") + .HasColumnType("int"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Order") + .HasColumnType("int"); + + b.Property("PostName") + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("PostName") + .IsUnique() + .HasFilter("[PostName] IS NOT NULL"); + + b.ToTable("Posts"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Student", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("BasicDepartmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrollmentYearId") + .HasColumnType("uniqueidentifier"); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Iduniv") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsSteward") + .HasColumnType("bit"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("NumberOfBook") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Patronymic") + .HasColumnType("nvarchar(max)"); + + b.Property("Photo") + .HasColumnType("varbinary(max)"); + + b.Property("StudentGroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("StudentState") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("BasicDepartmentId"); + + b.HasIndex("EnrollmentYearId"); + + b.HasIndex("NumberOfBook") + .IsUnique(); + + b.HasIndex("StudentGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.StudentGroup", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AcademicCourse") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EducationDirectionId") + .HasColumnType("uniqueidentifier"); + + b.Property("GroupNumber") + .HasColumnType("int"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LecturerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("LecturerId"); + + b.HasIndex("EducationDirectionId", "AcademicCourse", "GroupNumber") + .IsUnique(); + + b.ToTable("StudentGroups"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.TimeNorm", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("DisciplineBlockId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("KindOfLoadAttributeName") + .HasColumnType("nvarchar(max)"); + + b.Property("KindOfLoadBlueAsteriskAttributeName") + .HasColumnType("nvarchar(max)"); + + b.Property("KindOfLoadBlueAsteriskName") + .HasColumnType("nvarchar(max)"); + + b.Property("KindOfLoadBlueAsteriskPracticName") + .HasColumnType("nvarchar(max)"); + + b.Property("KindOfLoadName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimeNormEducationDirectionQualification") + .HasColumnType("int"); + + b.Property("TimeNormName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("TimeNormOrder") + .HasColumnType("int"); + + b.Property("TimeNormShortName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UseInLearningProgress") + .HasColumnType("bit"); + + b.Property("UseInSite") + .HasColumnType("bit"); + + b.HasKey("Id"); + + b.HasIndex("DisciplineBlockId"); + + b.HasIndex("TimeNormName", "TimeNormShortName") + .IsUnique(); + + b.ToTable("TimeNorms"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.Access", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("AccessOperation") + .HasColumnType("int"); + + b.Property("AccessType") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("Accesses"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.EnviromentSetting", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Key") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("EnviromentSettings"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.Role", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RolePriority") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleName") + .IsUnique(); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.User", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Avatar") + .HasColumnType("varbinary(max)"); + + b.Property("CountAttempt") + .HasColumnType("int"); + + b.Property("DateBanned") + .HasColumnType("datetime2"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("DateLastVisit") + .HasColumnType("datetime2"); + + b.Property("IsBanned") + .HasColumnType("bit"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserName"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.UserRole", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlan", b => + { + b.HasOne("CoreDatabase.Models.Department.EducationDirection", "EducationDirection") + .WithMany("AcademicPlans") + .HasForeignKey("EducationDirectionId"); + + b.Navigation("EducationDirection"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlanRecord", b => + { + b.HasOne("CoreDatabase.Models.Department.AcademicPlan", "AcademicPlan") + .WithMany("AcademicPlanRecords") + .HasForeignKey("AcademicPlanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.Discipline", "Discipline") + .WithMany("AcademicPlanRecords") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AcademicPlan"); + + b.Navigation("Discipline"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlanRecordTimeNormHour", b => + { + b.HasOne("CoreDatabase.Models.Department.AcademicPlanRecord", "AcademicPlanRecord") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("AcademicPlanRecordId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.TimeNorm", "TimeNorm") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("TimeNormId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("AcademicPlanRecord"); + + b.Navigation("TimeNorm"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.BasicDepartment", b => + { + b.HasOne("CoreDatabase.Models.Department.Lecturer", "Lecturer") + .WithMany("BasicDepartments") + .HasForeignKey("LecturerId"); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Classroom", b => + { + b.HasOne("CoreDatabase.Models.Department.Employee", "Employee") + .WithMany("Classrooms") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Discipline", b => + { + b.HasOne("CoreDatabase.Models.Department.BasicDepartment", "BasicDepartment") + .WithMany("Disciplines") + .HasForeignKey("BasicDepartmentId"); + + b.HasOne("CoreDatabase.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("Disciplines") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BasicDepartment"); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EducationDirection", b => + { + b.HasOne("CoreDatabase.Models.Department.Lecturer", "Lecturer") + .WithMany("EducationDirections") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Employee", b => + { + b.HasOne("CoreDatabase.Models.Security.User", "User") + .WithMany("Employees") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EmployeePost", b => + { + b.HasOne("CoreDatabase.Models.Department.Employee", "Employee") + .WithMany("EmployeePosts") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.Post", "Post") + .WithMany("EmployeePosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EnrollmentYear", b => + { + b.HasOne("CoreDatabase.Models.Department.AcademicPlan", "AcademicPlan") + .WithMany() + .HasForeignKey("AcademicPlanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AcademicPlan"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Lecturer", b => + { + b.HasOne("CoreDatabase.Models.Department.LecturerAcademicDegree", "LecturerAcademicDegree") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicDegreeId"); + + b.HasOne("CoreDatabase.Models.Department.LecturerAcademicRank", "LecturerAcademicRank") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicRankId"); + + b.HasOne("CoreDatabase.Models.Security.User", "User") + .WithMany("Lecturers") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LecturerAcademicDegree"); + + b.Navigation("LecturerAcademicRank"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerPost", b => + { + b.HasOne("CoreDatabase.Models.Department.Lecturer", "Lecturer") + .WithMany("LecturerPosts") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.Post", "Post") + .WithMany("LecturerPosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderStudentRecord", b => + { + b.HasOne("CoreDatabase.Models.Department.Order", "Order") + .WithMany("OrderStudentRecords") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.StudentGroup", "StudentGroupFrom") + .WithMany("OrderStudentRecordFroms") + .HasForeignKey("StudentGroupFromId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("CoreDatabase.Models.Department.StudentGroup", "StudentGroupTo") + .WithMany("OrderStudentRecordTos") + .HasForeignKey("StudentGroupToId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("CoreDatabase.Models.Department.Student", "Student") + .WithMany("OrderStudentRecords") + .HasForeignKey("StudentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Order"); + + b.Navigation("Student"); + + b.Navigation("StudentGroupFrom"); + + b.Navigation("StudentGroupTo"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderSyncHistoryRecord", b => + { + b.HasOne("CoreDatabase.Models.Department.OrderSyncHistory", "OrderSyncHistory") + .WithMany("OrderSyncHistoryRecords") + .HasForeignKey("OrderSyncHistoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("OrderSyncHistory"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Student", b => + { + b.HasOne("CoreDatabase.Models.Department.BasicDepartment", "BasicDepartment") + .WithMany("Students") + .HasForeignKey("BasicDepartmentId"); + + b.HasOne("CoreDatabase.Models.Department.EnrollmentYear", "EnrollmentYear") + .WithMany("Students") + .HasForeignKey("EnrollmentYearId"); + + b.HasOne("CoreDatabase.Models.Department.StudentGroup", "StudentGroup") + .WithMany("Students") + .HasForeignKey("StudentGroupId"); + + b.HasOne("CoreDatabase.Models.Security.User", "User") + .WithMany("Students") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BasicDepartment"); + + b.Navigation("EnrollmentYear"); + + b.Navigation("StudentGroup"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.StudentGroup", b => + { + b.HasOne("CoreDatabase.Models.Department.EducationDirection", "EducationDirection") + .WithMany("StudentGroups") + .HasForeignKey("EducationDirectionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Department.Lecturer", "Lecturer") + .WithMany("StudentGroups") + .HasForeignKey("LecturerId"); + + b.Navigation("EducationDirection"); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.TimeNorm", b => + { + b.HasOne("CoreDatabase.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("TimeNorms") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.Access", b => + { + b.HasOne("CoreDatabase.Models.Security.Role", "Role") + .WithMany("Access") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.UserRole", b => + { + b.HasOne("CoreDatabase.Models.Security.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("CoreDatabase.Models.Security.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlan", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.AcademicPlanRecord", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.BasicDepartment", b => + { + b.Navigation("Disciplines"); + + b.Navigation("Students"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Discipline", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.DisciplineBlock", b => + { + b.Navigation("Disciplines"); + + b.Navigation("TimeNorms"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EducationDirection", b => + { + b.Navigation("AcademicPlans"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Employee", b => + { + b.Navigation("Classrooms"); + + b.Navigation("EmployeePosts"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.EnrollmentYear", b => + { + b.Navigation("Students"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Lecturer", b => + { + b.Navigation("BasicDepartments"); + + b.Navigation("EducationDirections"); + + b.Navigation("LecturerPosts"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerAcademicDegree", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.LecturerAcademicRank", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Order", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.OrderSyncHistory", b => + { + b.Navigation("OrderSyncHistoryRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Post", b => + { + b.Navigation("EmployeePosts"); + + b.Navigation("LecturerPosts"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.Student", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.StudentGroup", b => + { + b.Navigation("OrderStudentRecordFroms"); + + b.Navigation("OrderStudentRecordTos"); + + b.Navigation("Students"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Department.TimeNorm", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.Role", b => + { + b.Navigation("Access"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("CoreDatabase.Models.Security.User", b => + { + b.Navigation("Employees"); + + b.Navigation("Lecturers"); + + b.Navigation("Students"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.cs b/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.cs new file mode 100644 index 0000000..582a7d9 --- /dev/null +++ b/DepartmentPortal/Common/CoreDatabase/Migrations/20220329053045_ChangeOrderIndexUnique.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace CoreDatabase.Migrations +{ + public partial class ChangeOrderIndexUnique : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Orders_OrderNumber", + table: "Orders"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_OrderNumber_OrderDate_OrderType", + table: "Orders", + columns: new[] { "OrderNumber", "OrderDate", "OrderType" }, + unique: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Orders_OrderNumber_OrderDate_OrderType", + table: "Orders"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_OrderNumber", + table: "Orders", + column: "OrderNumber", + unique: true); + } + } +} diff --git a/DepartmentPortal/Common/CoreDatabase/Migrations/DatabaseContextModelSnapshot.cs b/DepartmentPortal/Common/CoreDatabase/Migrations/DatabaseContextModelSnapshot.cs index 2c0feab..b7fdb03 100644 --- a/DepartmentPortal/Common/CoreDatabase/Migrations/DatabaseContextModelSnapshot.cs +++ b/DepartmentPortal/Common/CoreDatabase/Migrations/DatabaseContextModelSnapshot.cs @@ -686,7 +686,7 @@ namespace CoreDatabase.Migrations b.HasKey("Id"); - b.HasIndex("OrderNumber") + b.HasIndex("OrderNumber", "OrderDate", "OrderType") .IsUnique(); b.ToTable("Orders"); diff --git a/DepartmentPortal/Common/ToolsDesktop/MainControls/GenericControlEntityList.cs b/DepartmentPortal/Common/ToolsDesktop/MainControls/GenericControlEntityList.cs index fa8494f..cc2d15d 100644 --- a/DepartmentPortal/Common/ToolsDesktop/MainControls/GenericControlEntityList.cs +++ b/DepartmentPortal/Common/ToolsDesktop/MainControls/GenericControlEntityList.cs @@ -16,621 +16,625 @@ using ToolsModule.ManagmentSecurity; namespace ToolsDesktop.Controls { public partial class GenericControlEntityList : MainControlViewEntityList, IControlViewEntityList - where G : GetBindingModel, new() - where S : SetBindingModel, new() - where L : ListViewModel - where E : ElementViewModel - where BL : IGenericEntityLogic - { - /// - /// Режим работы - /// - private ControlOpenMode _openMode; + where G : GetBindingModel, new() + where S : SetBindingModel, new() + where L : ListViewModel + where E : ElementViewModel + where BL : IGenericEntityLogic + { + /// + /// Режим работы + /// + private ControlOpenMode _openMode; - /// - /// Событие, вызываемое при закрытии контрола - /// - private event Action CloseListEvent; + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseListEvent; - /// - /// Событие, вызываемое при закрытии контрола - /// - private event Action CloseSelectEvent; + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseSelectEvent; - private readonly object _lockObject = new(); + private readonly object _lockObject = new(); - private bool _usePages = false; + private bool _usePages = false; - private bool _useNames = false; + private bool _useNames = false; - /// - /// Объект бизнес-логики для получения данных - /// - protected BL _businessLogic; + /// + /// Объект бизнес-логики для получения данных + /// + protected BL _businessLogic; - /// - /// Методы для реализации в generic-контроле - /// - protected IGenericControlEntityList _genericControlViewEntityList; + /// + /// Методы для реализации в generic-контроле + /// + protected IGenericControlEntityList _genericControlViewEntityList; - /// - /// Констркутор - /// - public GenericControlEntityList() - { - InitializeComponent(); - InitEvents(); - _businessLogic = DependencyManager.Instance.Resolve(); - _controlViewEntityList = this; - } + /// + /// Констркутор + /// + public GenericControlEntityList() + { + InitializeComponent(); + InitEvents(); + _businessLogic = DependencyManager.Instance.Resolve(); + _controlViewEntityList = this; + } - #region IControlViewEntityList - public void OpenControl(ControlOpenModel model) - { - _openMode = model.OpenMode; - if (model.CloseList != null) - { - CloseListEvent += model.CloseList; - } - if (model.CloseSelect != null) - { - CloseSelectEvent += model.CloseSelect; - } + #region IControlViewEntityList + public void OpenControl(ControlOpenModel model) + { + _openMode = model.OpenMode; + if (model.CloseList != null) + { + CloseListEvent += model.CloseList; + } + if (model.CloseSelect != null) + { + CloseSelectEvent += model.CloseSelect; + } - if (dataGridViewList.Columns.Count == 0) - { - try - { - Configurate(GetConfig()); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации"); - } - } - if (!model.LazyLoading) - { - LoadList(); - } - } + if (dataGridViewList.Columns.Count == 0) + { + try + { + Configurate(GetConfig()); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации"); + } + } + if (!model.LazyLoading) + { + LoadList(); + } + } - public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl(); + public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl(); - public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString(); + public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString(); - public string SaveControlToXml() => new XElement("Control", - new XAttribute("Type", GetType().FullName), - new XAttribute("ControlId", ControlId), - new XAttribute("Title", Title), - new XAttribute("AccessOperation", AccessOperation), - new XElement("Configurate", - new XElement("Page", toolStripTextBoxPage.Text), - new XElement("CountElementsOnPage", toolStripTextBoxCountRecords.Text), - new XElement("PageName", - new XElement("Key", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Key ?? "-")), - new XElement("Value", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Value ?? "-"))), - new XElement("ParentId", ParentId?.ToString() ?? "-"))).ToString(); + public string SaveControlToXml() => new XElement("Control", + new XAttribute("Type", GetType().FullName), + new XAttribute("ControlId", ControlId), + new XAttribute("Title", Title), + new XAttribute("AccessOperation", AccessOperation), + new XElement("Configurate", + new XElement("Page", toolStripTextBoxPage.Text), + new XElement("CountElementsOnPage", toolStripTextBoxCountRecords.Text), + new XElement("PageName", + new XElement("Key", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Key ?? "-")), + new XElement("Value", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Value ?? "-"))), + new XElement("ParentId", ParentId?.ToString() ?? "-"))).ToString(); - public void LoadControlFromXml(string xml) - { - var control = XElement.Parse(xml); - ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); - Title = control.Attribute("Title").Value.ToString(); - AccessOperation = (AccessOperation)Enum.Parse(typeof(AccessOperation), control.Attribute("AccessOperation").Value.ToString()); - var config = control.Element("Configurate"); - toolStripTextBoxPage.Text = config.Element("Page").Value.ToString(); - toolStripTextBoxCountRecords.Text = config.Element("CountElementsOnPage").Value.ToString(); - if (config.Element("PageName").Element("Key").Value.ToString() != "-") - { - var pageName = new PageNamesForPaginationModel - { - Key = config.Element("PageName").Element("Key").Value.ToString(), - Value = config.Element("PageName").Element("Value").Value.ToString() - }; - var elem = toolStripComboBoxPageNames.Items.Cast().FirstOrDefault(x => x.Key == pageName.Key); - if (elem != null) - { - toolStripComboBoxPageNames.SelectedIndexChanged -= ToolStripComboBoxPageNamesSelectedIndexChanged; - toolStripComboBoxPageNames.SelectedItem = elem; - toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; - } - } - if (config.Element("ParentId").Value.ToString() != "-") - { - ParentId = new Guid(config.Element("ParentId").Value.ToString()); - } - LoadList(); - } - #endregion + public void LoadControlFromXml(string xml) + { + var control = XElement.Parse(xml); + ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); + Title = control.Attribute("Title").Value.ToString(); + AccessOperation = (AccessOperation)Enum.Parse(typeof(AccessOperation), control.Attribute("AccessOperation").Value.ToString()); + var config = control.Element("Configurate"); + toolStripTextBoxPage.Text = config.Element("Page").Value.ToString(); + toolStripTextBoxCountRecords.Text = config.Element("CountElementsOnPage").Value.ToString(); + if (config.Element("PageName").Element("Key").Value.ToString() != "-") + { + var pageName = new PageNamesForPaginationModel + { + Key = config.Element("PageName").Element("Key").Value.ToString(), + Value = config.Element("PageName").Element("Value").Value.ToString() + }; + var elem = toolStripComboBoxPageNames.Items.Cast().FirstOrDefault(x => x.Key == pageName.Key); + if (elem != null) + { + toolStripComboBoxPageNames.SelectedIndexChanged -= ToolStripComboBoxPageNamesSelectedIndexChanged; + toolStripComboBoxPageNames.SelectedItem = elem; + toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; + } + } + if (config.Element("ParentId").Value.ToString() != "-") + { + ParentId = new Guid(config.Element("ParentId").Value.ToString()); + } + LoadList(); + } + #endregion - /// - /// Конфигуратор контрола - /// - /// Настройки - private void Configurate(ControlViewEntityListConfiguration config) - { - if (config == null) - { - return; - } + /// + /// Конфигуратор контрола + /// + /// Настройки + private void Configurate(ControlViewEntityListConfiguration config) + { + if (config == null) + { + return; + } - // формирование таблицы на основе модели - dataGridViewList.Columns.Clear(); - var properties = typeof(E).GetProperties(); - foreach (var property in properties) - { - var attr = property.GetCustomAttribute(); - if (attr != null) - { - var colIndex = attr.DisplayName == "Идентификатор" ? 0 : dataGridViewList.Columns.Count; - dataGridViewList.Columns.Insert(colIndex, new DataGridViewTextBoxColumn - { - HeaderText = attr.DisplayName, - Name = string.Format("Column{0}", property.Name), - ReadOnly = true, - Visible = !attr.IsHide, - Width = attr.ColumnWidth, - AutoSizeMode = attr.ColumnWidth != 0 ? DataGridViewAutoSizeColumnMode.None : DataGridViewAutoSizeColumnMode.Fill - }); - if (attr.DefaultCellStyleFormat.IsNotEmpty()) - { - dataGridViewList.Columns[colIndex].DefaultCellStyle.Format = attr.DefaultCellStyleFormat; - } - } - } + // формирование таблицы на основе модели + dataGridViewList.Columns.Clear(); + var properties = typeof(E).GetProperties(); + foreach (var property in properties) + { + var attr = property.GetCustomAttribute(); + if (attr != null) + { + var colIndex = attr.DisplayName == "Идентификатор" ? 0 : dataGridViewList.Columns.Count; + dataGridViewList.Columns.Insert(colIndex, new DataGridViewTextBoxColumn + { + HeaderText = attr.DisplayName, + Name = string.Format("Column{0}", property.Name), + ReadOnly = true, + Visible = !attr.IsHide, + Width = attr.ColumnWidth, + AutoSizeMode = attr.ColumnWidth != 0 ? DataGridViewAutoSizeColumnMode.None : DataGridViewAutoSizeColumnMode.Fill + }); + if (attr.DefaultCellStyleFormat.IsNotEmpty()) + { + dataGridViewList.Columns[colIndex].DefaultCellStyle.Format = attr.DefaultCellStyleFormat; + } + } + } - labelTitle.Text = Title; - // настройка отображения основных кнопок - if (config.HideToolStripButton != null) - { - foreach (var elem in config.HideToolStripButton) - { - var ctrl = toolStripMenu.Items.Find(elem.ToString(), false); - if (ctrl != null && ctrl.Length > 0) - { - ctrl[0].Visible = false; - switch (elem) - { - case ToolStripButtonListNames.toolStripButtonAdd: - toolStripSeparator1.Visible = false; - break; - case ToolStripButtonListNames.toolStripButtonUpd: - toolStripSeparator2.Visible = false; - break; - case ToolStripButtonListNames.toolStripButtonDel: - toolStripSeparator3.Visible = false; - break; - case ToolStripButtonListNames.toolStripButtonSearch: - toolStripSeparator4.Visible = false; - break; - case ToolStripButtonListNames.toolStripButtonRef: - toolStripSeparator5.Visible = false; - break; - } - } - } - } - // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" - if (config.ControlOnMoveElem != null) - { - foreach (var elem in config.ControlOnMoveElem) - { - ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key }; - item.Click += elem.Value.Event; - toolStripSplitButtonActions.DropDownItems.Add(item); - ToolStripMenuItem itemContext = new() { Text = elem.Value.Title, Name = elem.Key }; - itemContext.Click += elem.Value.Event; - contextMenuStripDataGrid.Items.Add(itemContext); - } - } - // либо скрытие пункта, если не предусмотренно подпунктов - else - { - toolStripSplitButtonActions.Visible = false; - toolStripSeparator5.Visible = false; - } + labelTitle.Text = Title; + // настройка отображения основных кнопок + if (config.HideToolStripButton != null) + { + foreach (var elem in config.HideToolStripButton) + { + var ctrl = toolStripMenu.Items.Find(elem.ToString(), false); + if (ctrl != null && ctrl.Length > 0) + { + ctrl[0].Visible = false; + switch (elem) + { + case ToolStripButtonListNames.toolStripButtonAdd: + toolStripSeparator1.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonUpd: + toolStripSeparator2.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonDel: + toolStripSeparator3.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonSearch: + toolStripSeparator4.Visible = false; + break; + case ToolStripButtonListNames.toolStripButtonRef: + toolStripSeparator5.Visible = false; + break; + } + } + } + } + // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" + if (config.ControlOnMoveElem != null) + { + foreach (var elem in config.ControlOnMoveElem) + { + ToolStripMenuItem item = new() { Text = elem.Value.Title, Name = elem.Key }; + item.Click += elem.Value.Event; + toolStripSplitButtonActions.DropDownItems.Add(item); + ToolStripMenuItem itemContext = new() { Text = elem.Value.Title, Name = elem.Key }; + itemContext.Click += elem.Value.Event; + contextMenuStripDataGrid.Items.Add(itemContext); + } + } + // либо скрытие пункта, если не предусмотренно подпунктов + else + { + toolStripSplitButtonActions.Visible = false; + toolStripSeparator5.Visible = false; + } - toolStripFooter.Visible = config.PaginationOn; - // Пагинация - if (config.PaginationOn) - { - // пагинация по страницам - if (config.CountElementsOnPage.HasValue) - { - _usePages = true; - toolStripTextBoxCountRecords.Text = config.CountElementsOnPage.Value.ToString(); - toolStripLabelPageName.Visible = toolStripComboBoxPageNames.Visible = false; - } - // пагинация по названиям - if (config.PageNamesForPagination != null) - { - _useNames = true; - toolStripButtonPrev.Visible = toolStripLabelPage.Visible = toolStripTextBoxPage.Visible = toolStripLabelCountPages.Visible = - toolStripLabelCountRecords.Visible = toolStripTextBoxCountRecords.Visible = toolStripButtonNext.Visible = false; + toolStripFooter.Visible = config.PaginationOn; + // Пагинация + if (config.PaginationOn) + { + // пагинация по страницам + if (config.CountElementsOnPage.HasValue) + { + _usePages = true; + toolStripTextBoxCountRecords.Text = config.CountElementsOnPage.Value.ToString(); + toolStripLabelPageName.Visible = toolStripComboBoxPageNames.Visible = false; + } + // пагинация по названиям + if (config.PageNamesForPagination != null) + { + _useNames = true; + toolStripButtonPrev.Visible = toolStripLabelPage.Visible = toolStripTextBoxPage.Visible = toolStripLabelCountPages.Visible = + toolStripLabelCountRecords.Visible = toolStripTextBoxCountRecords.Visible = toolStripButtonNext.Visible = false; - toolStripComboBoxPageNames.Items.AddRange(config.PageNamesForPagination.ToArray()); - if (toolStripComboBoxPageNames.Items.Count > 0) - { - toolStripComboBoxPageNames.SelectedIndexChanged -= ToolStripComboBoxPageNamesSelectedIndexChanged; - toolStripComboBoxPageNames.SelectedIndex = 0; - toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; - } - toolStripComboBoxPageNames.Tag = config.ParentPropertyName; - } - } + toolStripComboBoxPageNames.Items.AddRange(config.PageNamesForPagination.ToArray()); + if (toolStripComboBoxPageNames.Items.Count > 0) + { + toolStripComboBoxPageNames.SelectedIndexChanged -= ToolStripComboBoxPageNamesSelectedIndexChanged; + toolStripComboBoxPageNames.SelectedIndex = 0; + toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; + } + toolStripComboBoxPageNames.Tag = config.ParentPropertyName; + } + } - // при вызове контрола для выбора элемента, делаем возможность выбора только одной записи - dataGridViewList.MultiSelect = _openMode == ControlOpenMode.List; + // при вызове контрола для выбора элемента, делаем возможность выбора только одной записи + dataGridViewList.MultiSelect = _openMode == ControlOpenMode.List; - // Открытие через родительский элемент - if (_openMode == ControlOpenMode.Child) - { - panelHeader.Visible = false; - toolStripButtonClose.Visible = false; - toolStripSeparator6.Visible = false; - toolStripButtonSelect.Visible = false; - } - // Открытие через родительский элемент - if (_openMode == ControlOpenMode.Select) - { - toolStripSeparator6.Visible = true; - toolStripButtonSelect.Visible = true; - } + // Открытие через родительский элемент + if (_openMode == ControlOpenMode.Child) + { + panelHeader.Visible = false; + toolStripButtonClose.Visible = false; + toolStripSeparator6.Visible = false; + toolStripButtonSelect.Visible = false; + } + // Открытие через родительский элемент + if (_openMode == ControlOpenMode.Select) + { + toolStripSeparator6.Visible = true; + toolStripButtonSelect.Visible = true; + } - Dock = DockStyle.Fill; - } + Dock = DockStyle.Fill; + } - /// - /// Инициализация событий к контролам - /// - private void InitEvents() - { - toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); }; - toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); }; - toolStripButtonDel.Click += (object sender, EventArgs e) => { DelElement(); }; - toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; }; - toolStripButtonRef.Click += (object sender, EventArgs e) => { LoadList(); }; - toolStripButtonSelect.Click += (object sender, EventArgs e) => { SelectElement(); }; - toolStripButtonClose.Click += (object sender, EventArgs e) => - { - CloseListEvent?.Invoke(ControlId); - CloseSelectEvent?.Invoke(false); - Dispose(); - }; + /// + /// Инициализация событий к контролам + /// + private void InitEvents() + { + toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); }; + toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); }; + toolStripButtonDel.Click += (object sender, EventArgs e) => { DelElement(); }; + toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; }; + toolStripButtonRef.Click += (object sender, EventArgs e) => { LoadList(); }; + toolStripButtonSelect.Click += (object sender, EventArgs e) => { SelectElement(); }; + toolStripButtonClose.Click += (object sender, EventArgs e) => + { + CloseListEvent?.Invoke(ControlId); + CloseSelectEvent?.Invoke(false); + Dispose(); + }; - buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); }; - buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; LoadList(); }; + buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); }; + buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; LoadList(); }; - dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => - { - switch (e.KeyCode) - { - case Keys.Insert: - if (toolStripButtonAdd.Visible) - { - AddElement(); - } - break; - case Keys.Enter: - if (toolStripButtonUpd.Visible) - { - UpdElement(); - } - break; - case Keys.Delete: - if (toolStripButtonDel.Visible) - { - DelElement(); - } - break; - } - }; - dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) => - { - if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0) - { - SelectElement(); - } - UpdElement(); - }; + dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => + { + switch (e.KeyCode) + { + case Keys.Insert: + if (toolStripButtonAdd.Visible) + { + AddElement(); + } + break; + case Keys.Enter: + if (toolStripButtonUpd.Visible) + { + UpdElement(); + } + break; + case Keys.Delete: + if (toolStripButtonDel.Visible) + { + DelElement(); + } + break; + } + }; + dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) => + { + if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0) + { + SelectElement(); + } + UpdElement(); + }; - toolStripButtonPrev.Click += (object sender, EventArgs e) => - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page)) - { - toolStripTextBoxPage.Text = (page - 1).ToString(); - LoadList(); - } - }; - toolStripButtonNext.Click += (object sender, EventArgs e) => - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page)) - { - toolStripTextBoxPage.Text = (page + 1).ToString(); - LoadList(); - } - }; - toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) => - { - if (e.KeyData == Keys.Enter) - { - LoadList(); - } - }; + toolStripButtonPrev.Click += (object sender, EventArgs e) => + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page)) + { + toolStripTextBoxPage.Text = (page - 1).ToString(); + LoadList(); + } + }; + toolStripButtonNext.Click += (object sender, EventArgs e) => + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page)) + { + toolStripTextBoxPage.Text = (page + 1).ToString(); + LoadList(); + } + }; + toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) => + { + if (e.KeyData == Keys.Enter) + { + LoadList(); + } + }; - toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; - } + toolStripComboBoxPageNames.SelectedIndexChanged += ToolStripComboBoxPageNamesSelectedIndexChanged; + } - /// - /// Событие смены выбрарнного элемента выпдающего спика (вынесено отдельно, чтобы при настройки конфигурации не вызывать прогрузку) - /// - /// - /// - private void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => LoadList(); + /// + /// Событие смены выбрарнного элемента выпдающего спика (вынесено отдельно, чтобы при настройки конфигурации не вызывать прогрузку) + /// + /// + /// + private void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => LoadList(); - /// - /// Вызов события загрузки данных на datagrid - /// - private void LoadList() - { - var cursor = Cursor.Current; + /// + /// Вызов события загрузки данных на datagrid + /// + private void LoadList() + { + var cursor = Cursor.Current; - var selectedGuids = new List(); - foreach (DataGridViewRow row in dataGridViewList.SelectedRows) - { - selectedGuids.Add(new Guid(row.Cells[0].Value.ToString())); - } + var selectedGuids = new List(); + foreach (DataGridViewRow row in dataGridViewList.SelectedRows) + { + selectedGuids.Add(new Guid(row.Cells[0].Value.ToString())); + } - L data = null; - try - { - Cursor.Current = Cursors.WaitCursor; - var model = new G(); - if (panelSearch.Visible) - { - var controls = panelSearchControls.Controls.Cast(); - foreach (var cntrl in controls) - { - var prop = typeof(G).GetProperty(cntrl.GetPropertyName()); - if (prop != null) - { - prop.SetValue(model, cntrl.GetValueFromControl()); - } - } - } + L data = null; + try + { + Cursor.Current = Cursors.WaitCursor; + var model = new G(); + if (panelSearch.Visible) + { + var controls = panelSearchControls.Controls.Cast(); + foreach (var cntrl in controls) + { + var prop = typeof(G).GetProperty(cntrl.GetPropertyName()); + if (prop != null) + { + prop.SetValue(model, cntrl.GetValueFromControl()); + } + } + } - if (ParentPropertyName.IsNotEmpty()) - { - if (ParentId.HasValue) - { - var prop = typeof(G).GetProperty(ParentPropertyName); - if (prop != null) - { - prop.SetValue(model, ParentId); - } - Visible = true; - } - else - { - Visible = false; - } - } - // если включена пагинация - // постраничная - if (_usePages) - { - if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxCountRecords.Text.ToString(), out int count)) - { - model.PageNumber = page - 1; - model.PageSize = count; - } - } - // поименная - if (_useNames) - { - if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) - { - var prop = typeof(G).GetProperty(toolStripComboBoxPageNames.Tag.ToString()); - if (prop != null) - { - prop.SetValue(model, key.Key); - } - } - } - data = _businessLogic.GetList(model); - if (data == null && _businessLogic.Errors.Count > 0) - { - DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); - return; - } - toolStripLabelCountPages.Text = $"из {data?.MaxCount}"; - } - catch (Exception ex) - { - if (_businessLogic.Errors.Count > 0) - { - DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); - } - else - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при получении данных"); - } - } - finally - { - Cursor.Current = cursor; - } - FillDataOnGrid(data?.List, selectedGuids); - } + if (ParentPropertyName.IsNotEmpty()) + { + if (ParentId.HasValue) + { + var prop = typeof(G).GetProperty(ParentPropertyName); + if (prop != null) + { + prop.SetValue(model, ParentId); + } + Visible = true; + } + else + { + Visible = false; + } + } + // если включена пагинация + // постраничная + if (_usePages) + { + if (int.TryParse(toolStripTextBoxPage.Text, out int page) && int.TryParse(toolStripTextBoxCountRecords.Text.ToString(), out int count)) + { + model.PageNumber = page - 1; + model.PageSize = count; + } + } + // поименная + if (_useNames) + { + if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) + { + var prop = typeof(G).GetProperty(toolStripComboBoxPageNames.Tag.ToString()); + if (prop != null) + { + prop.SetValue(model, key.Key); + } + } + } + data = _businessLogic.GetList(model); + if (data == null && _businessLogic.Errors.Count > 0) + { + DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); + return; + } + toolStripLabelCountPages.Text = $"из {data?.MaxCount}"; + } + catch (Exception ex) + { + if (_businessLogic.Errors.Count > 0) + { + DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); + } + else + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при получении данных"); + } + } + finally + { + Cursor.Current = cursor; + } + FillDataOnGrid(data?.List, selectedGuids); + } - /// - /// Заполнение таблицы - /// - /// - private void FillDataOnGrid(List data, List selectedGuids) - { - if (data == null) - { - return; - } - dataGridViewList.Rows.Clear(); - foreach (var elem in data) - { - var mas = new List(); - foreach (DataGridViewColumn column in dataGridViewList.Columns) - { - mas.Add(elem.GetType().GetProperty(column.Name["Column".Length..])?.GetValue(elem)); - } + /// + /// Заполнение таблицы + /// + /// + private void FillDataOnGrid(List data, List selectedGuids) + { + if (data == null) + { + return; + } + if (dataGridViewList.Columns.Count == 0) + { + return; + } + dataGridViewList.Rows.Clear(); + foreach (var elem in data) + { + var mas = new List(); + foreach (DataGridViewColumn column in dataGridViewList.Columns) + { + mas.Add(elem.GetType().GetProperty(column.Name["Column".Length..])?.GetValue(elem)); + } - dataGridViewList.Rows.Add(mas.ToArray()); - dataGridViewList.Rows[^1].Selected = selectedGuids.Contains(new Guid(mas[0].ToString())); - } - if (selectedGuids.Count == 0 && dataGridViewList.Rows.Count > 0) - { - dataGridViewList.Rows[0].Selected = true; - } - } + dataGridViewList.Rows.Add(mas.ToArray()); + dataGridViewList.Rows[^1].Selected = selectedGuids.Contains(new Guid(mas[0].ToString())); + } + if (selectedGuids.Count == 0 && dataGridViewList.Rows.Count > 0) + { + dataGridViewList.Rows[0].Selected = true; + } + } - /// - /// Вызов события при добавлении элемента - /// - private void AddElement() => LaunchControl(null); + /// + /// Вызов события при добавлении элемента + /// + private void AddElement() => LaunchControl(null); - /// - /// Вызов события при изменении элемента - /// - private void UpdElement() - { - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) - { - LaunchControl(new Guid(selected.Cells[0].Value.ToString())); - } - } + /// + /// Вызов события при изменении элемента + /// + private void UpdElement() + { + foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + { + LaunchControl(new Guid(selected.Cells[0].Value.ToString())); + } + } - /// - /// Вызов события при удалении элемента - /// - private void DelElement() - { - if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - var cursor = Cursor.Current; - try - { - Cursor.Current = Cursors.WaitCursor; - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) - { - _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); - } - } - catch (Exception ex) - { - if (_businessLogic.Errors.Count != 0) - { - DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при удалении"); - } - else - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибки при удалении"); - } - } - finally - { - Cursor.Current = cursor; - LoadList(); - } - } - } + /// + /// Вызов события при удалении элемента + /// + private void DelElement() + { + if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + var cursor = Cursor.Current; + try + { + Cursor.Current = Cursors.WaitCursor; + foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + { + _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); + } + } + catch (Exception ex) + { + if (_businessLogic.Errors.Count != 0) + { + DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при удалении"); + } + else + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибки при удалении"); + } + } + finally + { + Cursor.Current = cursor; + LoadList(); + } + } + } - /// - /// Вызов события при выборе элемента - /// - private void SelectElement() - { - try - { - SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); - SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString(); - CloseSelectEvent?.Invoke(true); - Dispose(); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при получении выбранного значения"); - } - } + /// + /// Вызов события при выборе элемента + /// + private void SelectElement() + { + try + { + SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); + SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString(); + CloseSelectEvent?.Invoke(true); + Dispose(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при получении выбранного значения"); + } + } - /// - /// Создание формы с контролом для работы с элементом - /// - /// - private void LaunchControl(Guid? id) - { - try - { - var control = ControlViewEntityElement.GetInstance() as IControlChildEntity; - if (ParentId.HasValue) - { - control.ParentId = ParentId; - control.ParentPropertyName = ParentPropertyName; - } - else if (toolStripFooter.Visible && toolStripComboBoxPageNames.Visible) - { - if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) - { - if (key.Key.GetType().Name == "Guid") - { - control.ParentId = new Guid(key.Key.ToString()); - } - control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString(); - } - } + /// + /// Создание формы с контролом для работы с элементом + /// + /// + private void LaunchControl(Guid? id) + { + try + { + var control = ControlViewEntityElement.GetInstance() as IControlChildEntity; + if (ParentId.HasValue) + { + control.ParentId = ParentId; + control.ParentPropertyName = ParentPropertyName; + } + else if (toolStripFooter.Visible && toolStripComboBoxPageNames.Visible) + { + if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) + { + if (key.Key.GetType().Name == "Guid") + { + control.ParentId = new Guid(key.Key.ToString()); + } + control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString(); + } + } - var form = new Form - { - Text = (id.HasValue ? $"{Title}. Редактирование" : $"{Title}. Добавление"), - StartPosition = FormStartPosition.CenterScreen, - ControlBox = false - }; - control.Open(new ControlOpenModel - { - OpenMode = ControlOpenMode.List, - ElementId = id, - CloseElement = (Guid id) => - { - LoadList(); - form.Close(); - } - }); - form.Height = (control as UserControl).Height + 55; - form.Width = (control as UserControl).Width + 20; - form.Controls.Add(control as UserControl); - form.Show(); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибки при открытии элемента"); - } - } + var form = new Form + { + Text = (id.HasValue ? $"{Title}. Редактирование" : $"{Title}. Добавление"), + StartPosition = FormStartPosition.CenterScreen, + ControlBox = false + }; + control.Open(new ControlOpenModel + { + OpenMode = ControlOpenMode.List, + ElementId = id, + CloseElement = (Guid id) => + { + LoadList(); + form.Close(); + } + }); + form.Height = (control as UserControl).Height + 55; + form.Width = (control as UserControl).Width + 20; + form.Controls.Add(control as UserControl); + form.Show(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибки при открытии элемента"); + } + } - /// - /// Получение настроек для контрола - /// - /// - private ControlViewEntityListConfiguration GetConfig() => _genericControlViewEntityList?.GetConfigControl(); + /// + /// Получение настроек для контрола + /// + /// + private ControlViewEntityListConfiguration GetConfig() => _genericControlViewEntityList?.GetConfigControl(); - /// - /// Получение списка идентификаторов выбранных записей - /// - /// - protected List GetSelectedIds() - { - List guids = new(); - foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) - { - guids.Add(new Guid(selected.Cells[0].Value.ToString())); - } - return guids; - } - } + /// + /// Получение списка идентификаторов выбранных записей + /// + /// + protected List GetSelectedIds() + { + List guids = new(); + foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) + { + guids.Add(new Guid(selected.Cells[0].Value.ToString())); + } + return guids; + } + } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ToolsModule/ManagmentEntity/GenericBusinessLogic.cs b/DepartmentPortal/Common/ToolsModule/ManagmentEntity/GenericBusinessLogic.cs index c58186a..54345cd 100644 --- a/DepartmentPortal/Common/ToolsModule/ManagmentEntity/GenericBusinessLogic.cs +++ b/DepartmentPortal/Common/ToolsModule/ManagmentEntity/GenericBusinessLogic.cs @@ -61,6 +61,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка получения", ex.Message)); Errors.Add(("Ошибка получения (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка получения (Inner)", ex.Message)); + } } return null; } @@ -92,6 +97,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка получения", ex.Message)); Errors.Add(("Ошибка получения (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка получения (Inner)", ex.Message)); + } } return null; } @@ -123,6 +133,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка создания", ex.Message)); Errors.Add(("Ошибка создания (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка создания (Inner)", ex.Message)); + } } return null; } @@ -154,6 +169,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка изменения", ex.Message)); Errors.Add(("Ошибка изменения (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка изменения (Inner)", ex.Message)); + } } return null; } @@ -185,6 +205,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка удаления", ex.Message)); Errors.Add(("Ошибка удаления (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка удаления (Inner)", ex.Message)); + } } return false; } @@ -216,6 +241,11 @@ namespace ToolsModule.ManagmentEntity { Errors.Add(("Ошибка восстановления", ex.Message)); Errors.Add(("Ошибка восстановления (Stack)", ex.StackTrace)); + while (ex.InnerException != null) + { + ex = ex.InnerException; + Errors.Add(("Ошибка восстановления (Inner)", ex.Message)); + } } return null; } diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderStudentRecordBusinessLogic.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderStudentRecordBusinessLogic.cs index e7bde8f..ce4670d 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderStudentRecordBusinessLogic.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderStudentRecordBusinessLogic.cs @@ -61,6 +61,7 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic } if ((result.OrderStudentMoveType == OrderStudentMoveType.ЗачислитьПоПриказу || + result.OrderStudentMoveType == OrderStudentMoveType.Распределить || result.OrderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводу || result.OrderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводусДругогоВуза || result.OrderStudentMoveType == OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры) diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderSyncHistoryBusinessLogic.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderSyncHistoryBusinessLogic.cs index cbee417..2095822 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderSyncHistoryBusinessLogic.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/GenericBusinessLogic/OrderSyncHistoryBusinessLogic.cs @@ -18,6 +18,7 @@ using System.Threading.Tasks; using ToolsModule.ManagmentDependency; using ToolsModule.ManagmentEntity; using ToolsModule.ManagmentExtension; +using ToolsModule.ManagmentMapping; using ToolsModule.ManagmentSecurity; namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic @@ -45,77 +46,61 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic private IOrderStudentRecordLogic _orderStudentRecordLogic; + private OrderSyncHistoryViewModel _history; + public OrderSyncHistoryBusinessLogic(IOrderSyncHistoryService service) : base(service, "Синхронизация Приказов", AccessOperation.СинхронизацияПриказов) { } public async Task SyncOrders() { InitLogics(); - var history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); - if (history == null) + if (!CreateHistory()) { - Errors.Add(("Ошибка создание истории", "Не удалось создать историю")); return false; } - var address = GetAddress(history); + var address = GetAddress(); if (address == null) { return false; } - var client = GetClinet(history, address); + var client = GetClinet(address); if (client == null) { return false; } // получение списка студентов - HttpResponseMessage response = await client.GetAsync($"{address.Value}/univer/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment"); + var response = await client.GetAsync($"{address.Value}/univer/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment"); if (!response.IsSuccessStatusCode) { - Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с сервера")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveLog("Не удалось получить список студентов с сервера"); return false; } var studentFromServer = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); + if (studentFromServer == null || studentFromServer.CurrentStudentsList == null) + { + SaveLog("Не удалось распознать список приказов по студенту"); + return false; + } if (studentFromServer.CurrentStudentsList.Count == 0) { - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = "Полученный список студентов пустой" - }); - return true; + SaveLog("Полученный список студентов пустой"); + return false; } var groups = _groupsLogic.GetList(new StudentGroupGetBindingModel()); if (groups == null || groups.List == null) { - Errors = _groupsLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить список групп с базы")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveErrors(_groupsLogic.Errors, "Ошибка получения данных", "Не удалось получить список групп с базы"); return false; } var students = _studentLogic.GetList(new StudentGetBindingModel()); if (students == null || students.List == null) { - Errors = _studentLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с базы")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveErrors(_studentLogic.Errors, "Ошибка получения данных", "Не удалось получить список студентов с базы"); return false; } @@ -125,86 +110,31 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic // студент не найден, значит он ушел с кафедры, выясняем почему if (studentSync == null) { - await SyncStudentOrders(history, student, groups.List, client, address.Value); + await SyncStudentOrders(student, groups.List, client, address.Value); } // не совпадение групп else if (student.StudentGroupName != studentSync.groupName) { - await SyncStudentOrders(history, student, groups.List, client, address.Value); + await SyncStudentOrders(student, groups.List, client, address.Value); } studentFromServer.CurrentStudentsList.Remove(studentSync); } // новые студенты и восстановленцы foreach (var student in studentFromServer.CurrentStudentsList) { - var deletedStudent = _studentLogic.GetElement(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); - if (deletedStudent == null && _studentLogic.Errors.FirstOrDefault(x => x.Message == "Элемент удален") != default) + var deletedStudent = TryRestoreStudent(student); + if (deletedStudent != null) { - // восстановленец - deletedStudent = _studentLogic.Restore(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); - if (deletedStudent == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка при восстановлении студента", $"Не удалось восстановить студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - var deletedUser = _userLogic.Restore(new UserGetBindingModel { Id = deletedStudent.UserId }); - if (deletedUser == null) - { - var errors = _userLogic.Errors; - errors.Add(("Ошибка при восстановлении пользователя студента", $"Не удалось восстановить пользователя студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await SyncStudentOrders(history, deletedStudent, groups.List, client, address.Value); + await SyncStudentOrders(deletedStudent, groups.List, client, address.Value); continue; } - var user = WorkWithUser(student, history); - if (user == null) + var newStudent = CreateNewStudent(student); + if (newStudent != null) { - continue; + SaveLog($"Добавлен студент {newStudent}"); + await SyncStudentOrders(newStudent, groups.List, client, address.Value); } - - var newStudent = _studentLogic.Create(new StudentSetBindingModel - { - Iduniv = student.iduniv, - NumberOfBook = student.recordBookName, - UserId = user.Id, - FirstName = student.firstName, - LastName = student.lastName, - Patronymic = student.patronymicName, - StudentState = StudentState.Неопределен, - Description = string.Empty - }); - if (newStudent == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Добавлен студент {newStudent}" - }); - - await SyncStudentOrders(history, newStudent, groups.List, client, address.Value); } return true; } @@ -213,25 +143,19 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic { InitLogics(); - var history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); - if (history == null) + if (!CreateHistory()) { - Errors.Add(("Ошибка создание истории", "Не удалось создать историю")); return false; } - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Синхронизация приказов по студенту" - }); + SaveLog("Синхронизация приказов по студенту"); - var address = GetAddress(history); + var address = GetAddress(); if (address == null) { return false; } - var client = GetClinet(history, address); + var client = GetClinet(address); if (client == null) { return false; @@ -240,29 +164,17 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic var groups = _groupsLogic.GetList(new StudentGroupGetBindingModel()); if (groups == null || groups.List == null) { - Errors = _groupsLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить список групп с базы")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveErrors(_groupsLogic.Errors, "Ошибка получения данных", "Не удалось получить список групп с базы"); return false; } var student = _studentLogic.GetElement(new StudentGetBindingModel { Id = studentId }); if (student == null) { - Errors = _studentLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить студента")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveErrors(_studentLogic.Errors, "Ошибка получения данных", "Не удалось получить студента с базы"); return false; } - await SyncStudentOrders(history, student, groups.List, client, address.Value); + await SyncStudentOrders(student, groups.List, client, address.Value); return true; } @@ -279,23 +191,144 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic _roleLogic = DependencyManager.Instance.Resolve(); } - private EnviromentSettingViewModel GetAddress(OrderSyncHistoryViewModel history) + private bool CreateHistory() + { + _history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); + if (_history == null) + { + Errors.Add(("Ошибка создание истории", "Не удалось создать историю")); + return false; + } + return true; + } + + private EnviromentSettingViewModel GetAddress() { var address = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" })?.List?.FirstOrDefault(); if (address == null || address.Value.IsEmpty()) { - Errors = _enviromentSettingLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить адрес сервера для получения приказов по студентам")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveErrors(_enviromentSettingLogic.Errors, "Ошибка получения данных", "Не удалось получить адрес сервера для получения приказов по студентам"); return null; } return address; } + private HttpClient GetClinet(EnviromentSettingViewModel address) + { + + var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault(); + if (username == null || username.Value.IsEmpty()) + { + SaveErrors(_enviromentSettingLogic.Errors, "Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам"); + return null; + } + + var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault(); + if (password == null || password.Value.IsEmpty()) + { + SaveErrors(_enviromentSettingLogic.Errors, "Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам"); + return null; + } + + var client = new HttpClient + { + BaseAddress = new Uri(address.Value) + }; + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username.Value}:{password.Value}"))); + + return client; + } + + private StudentViewModel TryRestoreStudent(StudentSyncModel student) + { + var deletedStudent = _studentLogic.GetElement(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); + if (deletedStudent == null && _studentLogic.Errors.FirstOrDefault(x => x.Message == "Элемент удален") != default) + { + // восстановленец + deletedStudent = _studentLogic.Restore(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); + if (deletedStudent == null) + { + SaveErrors(_studentLogic.Errors, "Ошибка при восстановлении студента", $"Не удалось восстановить студента {student.lastName} {student.firstName} {student.patronymicName}"); + return null; + } + var deletedUser = _userLogic.Restore(new UserGetBindingModel { Id = deletedStudent.UserId }); + if (deletedUser == null) + { + SaveErrors(_userLogic.Errors, "Ошибка при восстановлении пользователя студента", $"Не удалось восстановить пользователя студента {student.lastName} {student.firstName} {student.patronymicName}"); + return null; + } + return deletedStudent; + } + return null; + } + + private UserViewModel WorkWithUser(StudentSyncModel student) + { + var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; + var user = _userLogic.GetOrCreateUser(new UserGetBindingModel + { + Login = student.recordBookName + }, userName); + if (user == null) + { + if (_userLogic.Errors.Count > 0) + { + SaveErrors(_userLogic.Errors, "Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}"); + return null; + } + } + var role = _roleLogic.GetElement(new RoleGetBindingModel { RoleName = "Студент" }); + if (role == null) + { + if (_roleLogic.Errors.Count > 0) + { + SaveErrors(_roleLogic.Errors, "Ошибка получения роли студента", $"Не удалось получить роль под студента {student.lastName} {student.firstName} {student.patronymicName}"); + return null; + } + } + var link = _userRoleLogic.GetElement(new UserRoleGetBindingModel { RoleId = role.Id, UserId = user.Id }); + if (link == null) + { + var manager = DependencyManager.Instance.Resolve(); + _userRoleLogic.Create(new UserRoleSetBindingModel { RoleId = role.Id, UserId = user.Id, UserIdForAccess = manager?.User }); + if (_userRoleLogic.Errors.Count > 0) + { + SaveErrors(_userRoleLogic.Errors, "Ошибка создания привязки студента к роли", $"Не удалось привязать студента {student.lastName} {student.firstName} {student.patronymicName} к роли"); + return null; + } + } + + return user; + } + + private StudentViewModel CreateNewStudent(StudentSyncModel student) + { + var user = WorkWithUser(student); + if (user == null) + { + return null; + } + var newStudent = _studentLogic.Create(new StudentSetBindingModel + { + Iduniv = student.iduniv, + NumberOfBook = student.recordBookName, + UserId = user.Id, + FirstName = student.firstName, + LastName = student.lastName, + Patronymic = student.patronymicName, + StudentState = StudentState.Неопределен, + Description = string.Empty + }); + if (newStudent == null) + { + SaveErrors(_studentLogic.Errors, "Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}"); + return null; + } + return newStudent; + } + /// /// Синхронизация приказов по студенту /// @@ -305,20 +338,20 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic /// /// /// - private async Task SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, List groups, HttpClient client, string address) + private async Task SyncStudentOrders(StudentViewModel student, List groups, HttpClient client, string address) { var response = await client.GetAsync($"{address}/univer/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={student.Iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd"); if (!response.IsSuccessStatusCode) { - Errors.Add(("Ошибка получения данных", "Не удалось получить список приказов по студенту")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); + SaveLog("Не удалось получить список приказов по студенту"); return; } var syncOrders = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); + if (syncOrders == null || syncOrders.StudentOrders == null) + { + SaveLog("Не удалось распознать список приказов по студенту"); + return; + } foreach (var syncOrder in syncOrders.StudentOrders) { if (syncOrder.orderTypeName == "Утверждение тем курсовых работ" || @@ -329,29 +362,17 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic } if (syncOrder.markOfApprove.ToLower() != "true") { - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Приказ {syncOrder.clericNumber} от {syncOrder.clericDate} ({syncOrder.orderTypeName}) по студенту {student} не утврежден " - }); + SaveLog($"Приказ {syncOrder.clericNumber} от {syncOrder.clericDate} ({syncOrder.orderTypeName}) по студенту {student} не утврежден"); continue; } if (syncOrder.clericNumber.IsEmpty()) { - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Приказ без номера от {syncOrder.clericDate} ({student})" - }); + SaveLog($"Приказ без номера от {syncOrder.clericDate} ({student})"); continue; } if (syncOrder.clericDate.IsEmpty()) { - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Приказ {syncOrder.clericNumber} - неизвестная дата ({student})" - }); + SaveLog($"Приказ {syncOrder.clericNumber} - неизвестная дата ({student})"); continue; } var orderType = GetOrderType(syncOrder.orderTypeName); @@ -363,21 +384,19 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic } if (orderType == OrderType.Неопределено) { - if (syncOrder.orderTypeName != "Корректировка" && syncOrder.orderTypeName != "Назначение стипендии" && - syncOrder.orderTypeName != "Утверждение тем курсовых работ" && syncOrder.orderTypeName != "Утверждение тем работ" - && syncOrder.orderTypeName != "Смена ФИО") - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Приказ {syncOrder.clericNumber} неопределенного типа {syncOrder.orderTypeName}" - }); + if (syncOrder.orderTypeName != "Корректировка" && syncOrder.orderTypeName != "Смена ФИО") + { + SaveLog($"Приказ {syncOrder.clericNumber} неопределенного типа {syncOrder.orderTypeName}"); + } continue; } // пытаемся найти приказ var order = _orderLogic.GetElement(new OrderGetBindingModel { - OrderNumber = syncOrder.clericNumber + OrderNumber = syncOrder.clericNumber, + OrderDate = Convert.ToDateTime(syncOrder.clericDate).Date, + OrderType = orderType }); if (order == null) { @@ -385,145 +404,38 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic order = _orderLogic.Create(new OrderSetBindingModel { OrderNumber = syncOrder.clericNumber, - OrderDate = Convert.ToDateTime(syncOrder.clericDate), + OrderDate = Convert.ToDateTime(syncOrder.clericDate).Date, OrderType = orderType }); if (order == null) { - var errors = _orderLogic.Errors; - errors.Add(("Ошибка добавления приказа", $"Не удалось добавить приказ {syncOrder.clericNumber} {syncOrder.clericDate}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); + SaveErrors(_orderLogic.Errors, "Ошибка добавления приказа", $"Не удалось добавить приказ {syncOrder.clericNumber} {syncOrder.clericDate}"); continue; } } - Guid? studentGroupFromId = null; - Guid? studentGroupToId = null; - string info = string.Empty; + StudentGroupViewModel studentGroupFrom = null; + StudentGroupViewModel studentGroupTo = null; if (syncOrder.groupNameBefore.IsNotEmpty()) { - studentGroupFromId = groups.FirstOrDefault(x => x.ToString() == syncOrder.groupNameBefore)?.Id; + syncOrder.groupNameBefore = syncOrder.groupNameBefore.Replace("пбд", "бд"); + studentGroupFrom = groups.FirstOrDefault(x => x.GroupName == syncOrder.groupNameBefore || x.ToString() == syncOrder.groupNameBefore); } if (syncOrder.groupNameAfter.IsNotEmpty()) { - studentGroupToId = groups.FirstOrDefault(x => x.ToString() == syncOrder.groupNameAfter)?.Id; + syncOrder.groupNameAfter = syncOrder.groupNameAfter.Replace("пбд", "бд"); + studentGroupTo = groups.FirstOrDefault(x => x.GroupName == syncOrder.groupNameAfter || x.ToString() == syncOrder.groupNameAfter); } // игнорируем приказы, не связанные с нашими группами - if (!studentGroupFromId.HasValue && syncOrder.groupNameBefore.IsNotEmpty() - && !studentGroupToId.HasValue && syncOrder.groupNameAfter.IsNotEmpty()) + if (studentGroupFrom == null && syncOrder.groupNameBefore.IsNotEmpty() && studentGroupTo == null && syncOrder.groupNameAfter.IsNotEmpty()) { continue; } - OrderStudentMoveType orderStudentMoveType = OrderStudentMoveType.Неопределено; - - switch (syncOrder.orderTypeName) - { - case "Перевод": - if (syncOrder.orderSubTypeName == "Распределение по группам") - { - orderStudentMoveType = OrderStudentMoveType.Распределить; - info = $"Распределение студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - } - else if (studentGroupFromId.HasValue && studentGroupToId.HasValue) - { - orderStudentMoveType = OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры; - info = $"Перевод студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - } - else if (!studentGroupFromId.HasValue && studentGroupToId.HasValue) - { - orderStudentMoveType = OrderStudentMoveType.ПринятьПоПереводу; - info = $"Перевод студента {student} c группы {syncOrder.groupNameBefore} другой кафедры в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - } - else if (studentGroupFromId.HasValue && !studentGroupToId.HasValue) - { - orderStudentMoveType = OrderStudentMoveType.УбратьПоПереводу; - info = $"Перевод студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} на другую кафедру"; - } - if (syncOrder.reason == "на другой факультет") - { - orderStudentMoveType = OrderStudentMoveType.ОтчислитьВСвязиСПереводом; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} в связи с переводом"; - } - break; - case "Зачисление в вуз вне приемной кампании": - orderStudentMoveType = OrderStudentMoveType.ЗачислитьПоПриказу; - info = $"Зачисление студента {student} по приказу"; - break; - case "Зачисление в вуз": - orderStudentMoveType = OrderStudentMoveType.ЗачислитьПоПриказу; - info = $"Зачисление студента {student} по приказу"; - break; - case "Перевод из другого вуза": - orderStudentMoveType = OrderStudentMoveType.ПринятьПоПереводусДругогоВуза; - info = $"Перевод студента {student} с другого вуза"; - break; - case "Перевод на следующий курс": - orderStudentMoveType = OrderStudentMoveType.ПеревестиНаСтаршийКурс; - info = $"Перевод студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} на следующий курс в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - break; - case "Уход в академический отпуск": - DateTime? date = null; - if (syncOrder.dateEnd.IsNotEmpty()) - { - date = Convert.ToDateTime(syncOrder.dateEnd); - } - orderStudentMoveType = OrderStudentMoveType.ОтправитьВАкадем; - info = $"Уход в АО студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} до {date?.ToShortDateString() ?? string.Empty}"; - break; - case "Продление академического отпуска": - orderStudentMoveType = OrderStudentMoveType.ПродлитьАкадем; - info = $"Продление АО студента {student}"; - break; - case "Восстановление из академического отпуска": - orderStudentMoveType = OrderStudentMoveType.ВосстановитьИзАкадема; - info = $"Выход из АО студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - break; - case "Отчисление": - switch(syncOrder.reason) - { - case "за невыполнение учебного плана": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьЗаНеуспевамость; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} за неуспеваемость"; - break; - case "по собственному желанию": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьПоСобственному; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} по собственному желанию"; - break; - case "в связи с невыходом из академического отпуска": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} в связи с невыходм из академического отпуска"; - break; - case "за невыполнение обязанностей по добросовестному освоению образовательной программы и выполнению учебного плана": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьЗаНеуспевамость; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} за неуспеваемость"; - break; - case "в связи с переводом в ___": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьВСвязиСПереводом; - info = $"Отчисление студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} в связи с переводом"; - break; - } - break; - case "Восстановление": - orderStudentMoveType = OrderStudentMoveType.Восстановить; - info = $"Восстановление отчисленного студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; - break; - case "Выпуск": - orderStudentMoveType = OrderStudentMoveType.ОтчислитьПоЗавершению; - info = $"Завершение обучения студента {student}"; - break; - } + var orderStudentMoveType = GetOrderStudentMoveType(student, syncOrder, studentGroupFrom, studentGroupTo, out string info); if (orderStudentMoveType == OrderStudentMoveType.Неопределено) { - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Неизветсный приказ {syncOrder.orderTypeName} ({syncOrder.reason}) по студенту {student}" - }); + SaveLog($"Неизветсный приказ {syncOrder.orderTypeName} ({syncOrder.reason}) по студенту {student}"); continue; } @@ -548,26 +460,18 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic StudentId = student.Id, Info = info, OrderStudentMoveType = orderStudentMoveType, - StudentGroupFromId = studentGroupFromId, - StudentGroupToId = studentGroupToId + StudentGroupFromId = studentGroupFrom?.Id, + StudentGroupToId = studentGroupTo?.Id }); if (studentOrder == null) { - var errors = _orderStudentRecordLogic.Errors; - errors.Add(("Ошибка добавления записи приказа по студенту", $"Не удалось добавить запись приказа {syncOrder.orderSubTypeName} по студенту {student}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); + SaveErrors(_orderStudentRecordLogic.Errors, "Ошибка добавления записи приказа по студенту", $"Не удалось добавить запись приказа {syncOrder.orderSubTypeName} по студенту {student}"); continue; } - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Добавили запись к приказу {order.OrderNumber} по студенту {student} с формулировкой {info}" - }); + SetYearFinish(student, studentGroupTo, order, studentOrder); + + SaveLog($"Добавили запись к приказу {order.OrderNumber} по студенту {student} с формулировкой {info}"); if (orderStudentMoveType == OrderStudentMoveType.ОтчислитьВСвязиСПереводом || orderStudentMoveType == OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема || @@ -580,103 +484,6 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic } } - private HttpClient GetClinet(OrderSyncHistoryViewModel history, EnviromentSettingViewModel address) - { - - var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault(); - if (username == null || username.Value.IsEmpty()) - { - Errors = _enviromentSettingLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); - return null; - } - - var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault(); - if (password == null || password.Value.IsEmpty()) - { - Errors = _enviromentSettingLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); - return null; - } - - var client = new HttpClient - { - BaseAddress = new Uri(address.Value) - }; - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username.Value}:{password.Value}"))); - - return client; - } - - private UserViewModel WorkWithUser(StudentSyncModel student, OrderSyncHistoryViewModel history) - { - var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; - var user = _userLogic.GetOrCreateUser(new UserGetBindingModel - { - Login = student.recordBookName - }, userName); - if (user == null) - { - if (_userLogic.Errors.Count > 0) - { - var errors = _userLogic.Errors; - errors.Add(("Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - return null; - } - } - var role = _roleLogic.GetElement(new RoleGetBindingModel { RoleName = "Студент" }); - if (role == null) - { - if (_roleLogic.Errors.Count > 0) - { - var errors = _roleLogic.Errors; - errors.Add(("Ошибка получения роли студента", $"Не удалось получить роль студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - return null; - } - } - var link = _userRoleLogic.GetElement(new UserRoleGetBindingModel { RoleId = role.Id, UserId = user.Id }); - if (link == null) - { - var manager = DependencyManager.Instance.Resolve(); - _userRoleLogic.Create(new UserRoleSetBindingModel { RoleId = role.Id, UserId = user.Id, UserIdForAccess = manager?.User }); - if (_userRoleLogic.Errors.Count > 0) - { - var errors = _userRoleLogic.Errors; - errors.Add(("Ошибка создания привязки студента к роли", $"Не удалось привязать студента {student.lastName} {student.firstName} {student.patronymicName} к роли")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - return null; - } - } - - return user; - } - private static OrderType GetOrderType(string orderTitle) => orderTitle switch { "Зачисление в вуз вне приемной кампании" => OrderType.ЗачислениеСтудентов, @@ -694,5 +501,247 @@ namespace DepartmentBusinessLogic.BusinessLogics.GenericBusinessLogic "Утверждение тем ВКР" => OrderType.Игнорировать, _ => OrderType.Неопределено, }; + + private static OrderStudentMoveType GetOrderStudentMoveType(StudentViewModel student, StudentOrderSyncModel syncOrder, StudentGroupViewModel studentGroupFrom, + StudentGroupViewModel studentGroupTo, out string info) + { + switch (syncOrder.orderTypeName) + { + case "Перевод": + if (syncOrder.orderSubTypeName == "Распределение по группам") + { + info = $"Распределение студента {student} в группу {studentGroupTo}"; + return OrderStudentMoveType.Распределить; + } + if (studentGroupFrom != null && studentGroupTo != null) + { + info = $"Перевод студента {student} из группы {studentGroupFrom} в группу {studentGroupTo}"; + return OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры; + } + if (studentGroupFrom == null && studentGroupTo != null) + { + info = $"Перевод студента {student} c группы {syncOrder.groupNameBefore} другой кафедры в группу {studentGroupTo}"; + return OrderStudentMoveType.ПринятьПоПереводу; + } + if (studentGroupFrom != null && studentGroupTo == null) + { + info = $"Перевод студента {student} из группы {studentGroupFrom} на другую кафедру в группу {syncOrder.groupNameAfter}"; + return OrderStudentMoveType.УбратьПоПереводу; + } + if (syncOrder.reason == "на другой факультет") + { + info = $"Отчисление студента {student} из группы {studentGroupFrom} в связи с переводом"; + return OrderStudentMoveType.ОтчислитьВСвязиСПереводом; + } + info = string.Empty; + return OrderStudentMoveType.Неопределено; + case "Зачисление в вуз вне приемной кампании": + info = $"Зачисление студента {student} по приказу"; + return OrderStudentMoveType.ЗачислитьПоПриказу; + case "Зачисление в вуз": + info = $"Зачисление студента {student} по приказу"; + return OrderStudentMoveType.ЗачислитьПоПриказу; + case "Перевод из другого вуза": + info = $"Перевод студента {student} с другого вуза"; + return OrderStudentMoveType.ПринятьПоПереводусДругогоВуза; + case "Перевод на следующий курс": + info = $"Перевод студента {student} из группы {studentGroupFrom} на следующий курс в группу {studentGroupTo}"; + return OrderStudentMoveType.ПеревестиНаСтаршийКурс; + case "Уход в академический отпуск": + DateTime? date = null; + if (syncOrder.dateEnd.IsNotEmpty()) + { + date = Convert.ToDateTime(syncOrder.dateEnd); + } + info = $"Уход в АО студента {student} из группы {studentGroupFrom} до {date?.ToShortDateString() ?? string.Empty}"; + return OrderStudentMoveType.ОтправитьВАкадем; + case "Продление академического отпуска": + info = $"Продление АО студента {student}"; + return OrderStudentMoveType.ПродлитьАкадем; + case "Восстановление из академического отпуска": + info = $"Выход из АО студента {student} в группу {studentGroupTo}"; + return OrderStudentMoveType.ВосстановитьИзАкадема; + case "Отчисление": + switch (syncOrder.reason) + { + case "за невыполнение учебного плана": + info = $"Отчисление студента {student} из группы {studentGroupFrom} за неуспеваемость"; + return OrderStudentMoveType.ОтчислитьЗаНеуспевамость; + case "по собственному желанию": + info = $"Отчисление студента {student} из группы {studentGroupFrom} по собственному желанию"; + return OrderStudentMoveType.ОтчислитьПоСобственному; + case "в связи с невыходом из академического отпуска": + info = $"Отчисление студента {student} из группы {studentGroupFrom} в связи с невыходм из академического отпуска"; + return OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема; + case "за невыполнение обязанностей по добросовестному освоению образовательной программы и выполнению учебного плана": + info = $"Отчисление студента {student} из группы {studentGroupFrom} за неуспеваемость"; + return OrderStudentMoveType.ОтчислитьЗаНеуспевамость; + case "в связи с переводом в ___": + info = $"Отчисление студента {student} из группы {studentGroupFrom} в связи с переводом"; + return OrderStudentMoveType.ОтчислитьВСвязиСПереводом; + default: + info = string.Empty; + return OrderStudentMoveType.Неопределено; + } + case "Восстановление": + info = $"Восстановление отчисленного студента {student} в группу {studentGroupTo}"; + return OrderStudentMoveType.Восстановить; + case "Выпуск": + info = $"Завершение обучения студента {student}"; + return OrderStudentMoveType.ОтчислитьПоЗавершению; + default: + info = string.Empty; + return OrderStudentMoveType.Неопределено; + } + } + + private void SetYearFinish(StudentViewModel student, StudentGroupViewModel group, OrderViewModel order, OrderStudentRecordViewModel studentOrder) + { + if (student == null || studentOrder == null) + { + return; + } + int year = DateTime.Now.Year; + switch (studentOrder.OrderStudentMoveType) + { + // у студента не меняется год зачисления + case OrderStudentMoveType.ПродлитьАкадем: + case OrderStudentMoveType.ОтчислитьПоЗавершению: + return; + // студент уходит с текущего года обучения, сбрасываем его + case OrderStudentMoveType.Неопределено: + case OrderStudentMoveType.ОтправитьВАкадем: + case OrderStudentMoveType.ОтчислитьВСвязиСПереводом: + case OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема: + case OrderStudentMoveType.ОтчислитьЗаНеуспевамость: + case OrderStudentMoveType.ОтчислитьПоСобственному: + case OrderStudentMoveType.УбратьПоПереводу: + student.EnrollmentYearId = null; + UpdateStudent(student); + return; + // проблема с разными направлениями групп на разных курсах + case OrderStudentMoveType.ПеревестиНаСтаршийКурс: + if (student.EnrollmentYearId.HasValue) + { + return; + } + if (group == null || order == null) + { + return; + } + year = order.OrderDate.Year; + switch (group.AcademicCourse) + { + case AcademicCourse.Курс_1: + break; + case AcademicCourse.Курс_2: + year--; + break; + case AcademicCourse.Курс_3: + year -= 2; + break; + case AcademicCourse.Курс_4: + year -= 3; + break; + } + break; + // может быть зачисление проводилось без указания группы, тогда группа определится при распределении + case OrderStudentMoveType.Распределить: + if (student.EnrollmentYearId.HasValue) + { + return; + } + if (group == null || order == null) + { + return; + } + year = order.OrderDate.Year; + break; + case OrderStudentMoveType.ЗачислитьПоПриказу: + if (group == null || order == null) + { + return; + } + year = order.OrderDate.Year; + break; + case OrderStudentMoveType.ПринятьПоПереводу: + case OrderStudentMoveType.ПринятьПоПереводусДругогоВуза: + case OrderStudentMoveType.Восстановить: + case OrderStudentMoveType.ВосстановитьИзАкадема: + case OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры: + if (group == null || order == null) + { + return; + } + year = order.OrderDate.Month < 8 ? order.OrderDate.Year - 1 : order.OrderDate.Year; + switch (group.AcademicCourse) + { + case AcademicCourse.Курс_1: + break; + case AcademicCourse.Курс_2: + year--; + break; + case AcademicCourse.Курс_3: + year -= 2; + break; + case AcademicCourse.Курс_4: + year -= 3; + break; + } + break; + } + + var logic = DependencyManager.Instance.Resolve(); + var yearEnrollment = logic.GetElement(new EnrollmentYearGetBindingModel { EducationDirectionId = group.EducationDirectionId, Year = year }); + if (yearEnrollment == null) + { + SaveErrors(logic.Errors, "Ошибка установки года выпуска студента", $"Не удалось найти год выпуска студента {student.LastName} {student.FirstName} {student.Patronymic}"); + return; + } + + student.EnrollmentYearId = yearEnrollment.Id; + UpdateStudent(student); + } + + private void UpdateStudent(StudentViewModel student) + { + if (student == null) + { + return; + } + var updateStudent = _studentLogic.GetElement(new StudentGetBindingModel { Id = student.Id }); + if (updateStudent == null) + { + SaveErrors(_studentLogic.Errors, "Ошибка обновления данных студента", $"Не удалось найти данные студента {student.LastName} {student.FirstName} {student.Patronymic}"); + return; + } + updateStudent.EnrollmentYearId = student.EnrollmentYearId; + updateStudent = _studentLogic.Update(Mapper.MapToClass(updateStudent, true)); + if (updateStudent == null) + { + SaveErrors(_studentLogic.Errors, "Ошибка обновления данных студента", $"Не удалось обновить данные студента {student?.LastName} {student?.FirstName} {student?.Patronymic}"); + } + } + + private void SaveErrors(List<(string Title, string Message)> errors, string title, string message) + { + if (_history == null) + { + return; + } + + Errors = errors ?? new List<(string Title, string Message)>(); + Errors.Add((title, message)); + SaveLog(string.Join(Environment.NewLine, Errors.Select(x => x.Message))); + } + + private void SaveLog(string info) + { + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = _history.Id, + Information = info + }); + } } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentContract/BindingModels/EnrollmentYearBindingModels.cs b/DepartmentPortal/Department/DepartmentContract/BindingModels/EnrollmentYearBindingModels.cs index 0855bbf..d24a8a4 100644 --- a/DepartmentPortal/Department/DepartmentContract/BindingModels/EnrollmentYearBindingModels.cs +++ b/DepartmentPortal/Department/DepartmentContract/BindingModels/EnrollmentYearBindingModels.cs @@ -11,6 +11,10 @@ namespace DepartmentContract.BindingModels public class EnrollmentYearGetBindingModel : GetBindingModel { public Guid? AcademicPlanId { get; set; } + + public Guid? EducationDirectionId { get; set; } + + public int? Year { get; set; } } /// diff --git a/DepartmentPortal/Department/DepartmentContract/BindingModels/OrderBindingModels.cs b/DepartmentPortal/Department/DepartmentContract/BindingModels/OrderBindingModels.cs index 7e9c10d..3738641 100644 --- a/DepartmentPortal/Department/DepartmentContract/BindingModels/OrderBindingModels.cs +++ b/DepartmentPortal/Department/DepartmentContract/BindingModels/OrderBindingModels.cs @@ -14,6 +14,8 @@ namespace DepartmentContract.BindingModels public string OrderNumber { get; set; } public DateTime? OrderDate { get; set; } + + public OrderType? OrderType { get; set; } } /// diff --git a/DepartmentPortal/Department/DepartmentContract/ViewModels/AcademicPlanViewModels.cs b/DepartmentPortal/Department/DepartmentContract/ViewModels/AcademicPlanViewModels.cs index 1b3a6d8..20dfc46 100644 --- a/DepartmentPortal/Department/DepartmentContract/ViewModels/AcademicPlanViewModels.cs +++ b/DepartmentPortal/Department/DepartmentContract/ViewModels/AcademicPlanViewModels.cs @@ -31,11 +31,11 @@ namespace DepartmentContract.ViewModels [MapConfiguration("EducationDirection.Profile")] public string EducationDirectionProfile { get; set; } - [ViewModelControlListProperty("Дата создания", ColumnWidth = 120)] + [ViewModelControlListProperty("Дата создания", ColumnWidth = 120, DefaultCellStyleFormat = "dd.MM.yyyy")] [ViewModelControlElementProperty("Дата создания", ControlType.ControlDateTime, MustHaveValue = true)] public DateTime CreateDate { get; set; } - [ViewModelControlListProperty("Дата последнего изменения", ColumnWidth = 120)] + [ViewModelControlListProperty("Дата последнего изменения", ColumnWidth = 120, DefaultCellStyleFormat = "dd.MM.yyyy")] [ViewModelControlElementProperty("Дата последнего изменения", ControlType.ControlDateTime, MustHaveValue = true)] public DateTime LastUpdateDate { get; set; } } diff --git a/DepartmentPortal/Department/DepartmentContract/ViewModels/OrderViewModels.cs b/DepartmentPortal/Department/DepartmentContract/ViewModels/OrderViewModels.cs index 42d4ea9..5cb17fa 100644 --- a/DepartmentPortal/Department/DepartmentContract/ViewModels/OrderViewModels.cs +++ b/DepartmentPortal/Department/DepartmentContract/ViewModels/OrderViewModels.cs @@ -14,7 +14,7 @@ namespace DepartmentContract.ViewModels /// Элемент приказа /// [ViewModelControlElementClass(HaveDependenceEntities = true, Width = 800, Height = 500)] - [ViewModelControlElementDependenceEntity(Title = "Записи по студентам", Order = 1, ParentPropertyName = "AcademicPlanId", + [ViewModelControlElementDependenceEntity(Title = "Записи по студентам", Order = 1, ParentPropertyName = "OrderId", ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlOrderStudentRecordList, DepartmentWindowsDesktop")] public class OrderViewModel : ElementViewModel, IOrderModel { diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordService.cs index 4839e12..581aecb 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordService.cs @@ -51,7 +51,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override AcademicPlanRecord GetUniqueEntity(AcademicPlanRecordSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.AcademicPlanId == model.AcademicPlanId && x.DisciplineId == model.DisciplineId && x.Semester == model.Semester && x.Id != model.Id); + protected override AcademicPlanRecord GetUniqueEntity(AcademicPlanRecordSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.AcademicPlanId == model.AcademicPlanId && x.DisciplineId == model.DisciplineId && x.Semester == model.Semester && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.AcademicPlan).Include(x => x.Discipline); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordTimeNormHourService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordTimeNormHourService.cs index 8d9d8c9..266ba89 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordTimeNormHourService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanRecordTimeNormHourService.cs @@ -37,7 +37,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, AcademicPlanRecordTimeNormHour entity, AcademicPlanRecordTimeNormHourGetBindingModel model) { } - protected override AcademicPlanRecordTimeNormHour GetUniqueEntity(AcademicPlanRecordTimeNormHourSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.AcademicPlanRecordId == model.AcademicPlanRecordId && x.TimeNormId == model.TimeNormId && x.Id != model.Id); + protected override AcademicPlanRecordTimeNormHour GetUniqueEntity(AcademicPlanRecordTimeNormHourSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.AcademicPlanRecordId == model.AcademicPlanRecordId && x.TimeNormId == model.TimeNormId && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.AcademicPlanRecord).Include(x => x.AcademicPlanRecord.Discipline).Include(x => x.TimeNorm); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanService.cs index cea940a..83b6b5c 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/AcademicPlanService.cs @@ -56,7 +56,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override AcademicPlan GetUniqueEntity(AcademicPlanSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.EducationDirectionId == model.EducationDirectionId && x.CreateDate == model.CreateDate && x.Id != model.Id); + protected override AcademicPlan GetUniqueEntity(AcademicPlanSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.EducationDirectionId == model.EducationDirectionId && x.CreateDate == model.CreateDate && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.EducationDirection); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/BasicDepartmentService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/BasicDepartmentService.cs index 4e9508a..e072df0 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/BasicDepartmentService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/BasicDepartmentService.cs @@ -48,7 +48,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override BasicDepartment GetUniqueEntity(BasicDepartmentSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.BasicDepartmentName == model.BasicDepartmentName && x.Id != model.Id); + protected override BasicDepartment GetUniqueEntity(BasicDepartmentSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.BasicDepartmentName == model.BasicDepartmentName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Lecturer); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/ClassroomService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/ClassroomService.cs index 0c1c198..14d8cb3 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/ClassroomService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/ClassroomService.cs @@ -39,7 +39,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, Classroom entity, ClassroomGetBindingModel model) { } - protected override Classroom GetUniqueEntity(ClassroomSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.Number == model.Number && x.Id != model.Id); + protected override Classroom GetUniqueEntity(ClassroomSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.Number == model.Number && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Employee); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineBlockService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineBlockService.cs index 8577dbb..b8b8f1d 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineBlockService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineBlockService.cs @@ -37,7 +37,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, DisciplineBlock entity, DisciplineBlockGetBindingModel model) { } - protected override DisciplineBlock GetUniqueEntity(DisciplineBlockSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.Title == model.Title && x.Id != model.Id); + protected override DisciplineBlock GetUniqueEntity(DisciplineBlockSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.Title == model.Title && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineService.cs index 71587e0..4088956 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/DisciplineService.cs @@ -49,7 +49,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, Discipline entity, DisciplineGetBindingModel model) { } - protected override Discipline GetUniqueEntity(DisciplineSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.DisciplineName == model.DisciplineName && x.Id != model.Id); + protected override Discipline GetUniqueEntity(DisciplineSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.DisciplineName == model.DisciplineName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.DisciplineBlock); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EducationDirectionService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EducationDirectionService.cs index 75a1f18..5985331 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EducationDirectionService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EducationDirectionService.cs @@ -44,7 +44,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, EducationDirection entity, EducationDirectionGetBindingModel model) { } - protected override EducationDirection GetUniqueEntity(EducationDirectionSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.Title == model.Title && x.Profile == model.Profile && x.Id != model.Id); + protected override EducationDirection GetUniqueEntity(EducationDirectionSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.Title == model.Title && x.Profile == model.Profile && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Lecturer); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeePostService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeePostService.cs index 62a36ab..48eebdb 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeePostService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeePostService.cs @@ -37,7 +37,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, EmployeePost entity, EmployeePostGetBindingModel model) { } - protected override EmployeePost GetUniqueEntity(EmployeePostSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.EmployeeId == model.EmployeeId && x.PostId == model.PostId && x.Id != model.Id); + protected override EmployeePost GetUniqueEntity(EmployeePostSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.EmployeeId == model.EmployeeId && x.PostId == model.PostId && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Post).Include(x => x.Employee); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeeService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeeService.cs index 8264956..607a12a 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeeService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EmployeeService.cs @@ -59,7 +59,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override Employee GetUniqueEntity(EmployeeSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.LastName == model.LastName && x.FirstName == model.FirstName && + protected override Employee GetUniqueEntity(EmployeeSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LastName == model.LastName && x.FirstName == model.FirstName && x.Patronymic == model.Patronymic && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EnrollmentYearService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EnrollmentYearService.cs index de55cdf..49455d6 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EnrollmentYearService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/EnrollmentYearService.cs @@ -26,6 +26,14 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit { query = query.Where(x => x.AcademicPlanId == model.AcademicPlanId.Value); } + if (model.EducationDirectionId.HasValue) + { + query = query.Where(x => x.AcademicPlan.EducationDirectionId == model.EducationDirectionId.Value); + } + if (model.Year.HasValue) + { + query = query.Where(x => x.YearEntrance == model.Year.Value); + } return query; } @@ -41,10 +49,28 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override EnrollmentYear GetUniqueEntity(EnrollmentYearSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.AcademicPlanId == model.AcademicPlanId && x.YearEntrance == model.YearEntrance && x.Id != model.Id); + protected override EnrollmentYear GetUniqueEntity(EnrollmentYearSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.AcademicPlanId == model.AcademicPlanId && x.YearEntrance == model.YearEntrance && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.AcademicPlan).Include(x => x.AcademicPlan.EducationDirection); protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.AcademicPlan.EducationDirection.Cipher).ThenBy(x => x.YearEntrance); - } + + protected override bool AdditionalCheckForSingleGet(EnrollmentYearGetBindingModel model) + { + if (model.EducationDirectionId.HasValue && model.Year.HasValue) + { + return true; + } + return base.AdditionalCheckForSingleGet(model); + } + + protected override EnrollmentYear GetSingleRecord(IQueryable list, EnrollmentYearGetBindingModel model) + { + if (model.EducationDirectionId.HasValue && model.Year.HasValue) + { + return list.FirstOrDefault(x => x.AcademicPlan.EducationDirectionId == model.EducationDirectionId && x.YearEntrance == model.Year); + } + return base.GetSingleRecord(list, model); + } + } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicDegreeService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicDegreeService.cs index 807107f..49bc85a 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicDegreeService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicDegreeService.cs @@ -33,7 +33,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, LecturerAcademicDegree entity, LecturerAcademicDegreeGetBindingModel model) { } - protected override LecturerAcademicDegree GetUniqueEntity(LecturerAcademicDegreeSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.LecturerAcademicDegreeName == model.LecturerAcademicDegreeName && x.Id != model.Id); + protected override LecturerAcademicDegree GetUniqueEntity(LecturerAcademicDegreeSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LecturerAcademicDegreeName == model.LecturerAcademicDegreeName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicRankService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicRankService.cs index cefe91f..d0774fb 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicRankService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerAcademicRankService.cs @@ -33,7 +33,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, LecturerAcademicRank entity, LecturerAcademicRankGetBindingModel model) { } - protected override LecturerAcademicRank GetUniqueEntity(LecturerAcademicRankSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.LecturerAcademicRankName == model.LecturerAcademicRankName && x.Id != model.Id); + protected override LecturerAcademicRank GetUniqueEntity(LecturerAcademicRankSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LecturerAcademicRankName == model.LecturerAcademicRankName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerPostService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerPostService.cs index da64168..7190e30 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerPostService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerPostService.cs @@ -37,7 +37,7 @@ namespace DepartmentDatabaseImplementation.Implementations protected override void AdditionalDeleting(DbContext context, LecturerPost entity, LecturerPostGetBindingModel model) { } - protected override LecturerPost GetUniqueEntity(LecturerPostSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.LecturerId == model.LecturerId && x.PostId == model.PostId && x.Id != model.Id); + protected override LecturerPost GetUniqueEntity(LecturerPostSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LecturerId == model.LecturerId && x.PostId == model.PostId && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Post).Include(x => x.Lecturer); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerService.cs index 4096118..f0c065e 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/LecturerService.cs @@ -72,7 +72,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override Lecturer GetUniqueEntity(LecturerSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.LastName == model.LastName && x.FirstName == model.FirstName && + protected override Lecturer GetUniqueEntity(LecturerSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.LastName == model.LastName && x.FirstName == model.FirstName && x.Patronymic == model.Patronymic && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderService.cs index c82681a..05993f9 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderService.cs @@ -42,7 +42,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, Order entity, OrderGetBindingModel model) { } - protected override Order GetUniqueEntity(OrderSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.OrderNumber == model.OrderNumber && x.Id != model.Id); + protected override Order GetUniqueEntity(OrderSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.OrderNumber == model.OrderNumber && x.OrderDate == model.OrderDate && x.OrderType == model.OrderType && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; @@ -50,6 +50,14 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override bool AdditionalCheckForSingleGet(OrderGetBindingModel model) { + if (model.OrderNumber.IsNotEmpty() && model.OrderDate.HasValue && model.OrderType.HasValue) + { + return true; + } + if (model.OrderNumber.IsNotEmpty() && model.OrderDate.HasValue) + { + return true; + } if (model.OrderNumber.IsNotEmpty()) { return true; @@ -59,6 +67,14 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override Order GetSingleRecord(IQueryable list, OrderGetBindingModel model) { + if (model.OrderNumber.IsNotEmpty() && model.OrderDate.HasValue && model.OrderType.HasValue) + { + return list.FirstOrDefault(x => x.OrderNumber == model.OrderNumber && x.OrderDate == model.OrderDate && x.OrderType == model.OrderType); + } + if (model.OrderNumber.IsNotEmpty() && model.OrderDate.HasValue) + { + return list.FirstOrDefault(x => x.OrderNumber == model.OrderNumber && x.OrderDate == model.OrderDate); + } if (model.OrderNumber.IsNotEmpty()) { return list.FirstOrDefault(x => x.OrderNumber == model.OrderNumber); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderStudentRecordService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderStudentRecordService.cs index 90b1f3d..5fce42b 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderStudentRecordService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/OrderStudentRecordService.cs @@ -41,7 +41,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, OrderStudentRecord entity, OrderStudentRecordGetBindingModel model) { } - protected override OrderStudentRecord GetUniqueEntity(OrderStudentRecordSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.StudentId == model.StudentId && x.OrderId == model.OrderId && x.Id != model.Id); + protected override OrderStudentRecord GetUniqueEntity(OrderStudentRecordSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.StudentId == model.StudentId && x.OrderId == model.OrderId && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Order).Include(x => x.Student).Include(x => x.StudentGroupFrom).Include(x => x.StudentGroupTo); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/PostService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/PostService.cs index 9d982f7..b9061ed 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/PostService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/PostService.cs @@ -37,7 +37,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, Post entity, PostGetBindingModel model) { } - protected override Post GetUniqueEntity(PostSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.PostName == model.PostName && x.Id != model.Id); + protected override Post GetUniqueEntity(PostSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.PostName == model.PostName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentGroupService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentGroupService.cs index cce84e5..f7a8380 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentGroupService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentGroupService.cs @@ -54,7 +54,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override StudentGroup GetUniqueEntity(StudentGroupSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.EducationDirectionId == model.EducationDirectionId && x.AcademicCourse == model.AcademicCourse && x.GroupNumber == model.GroupNumber && x.Id != model.Id); + protected override StudentGroup GetUniqueEntity(StudentGroupSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.EducationDirectionId == model.EducationDirectionId && x.AcademicCourse == model.AcademicCourse && x.GroupNumber == model.GroupNumber && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.EducationDirection).Include(x => x.Lecturer).Include(x => x.Students); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentService.cs index 9644bc7..9f732ff 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/StudentService.cs @@ -60,7 +60,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit context.SaveChanges(); } - protected override Student GetUniqueEntity(StudentSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.NumberOfBook == model.NumberOfBook && x.Id != model.Id); + protected override Student GetUniqueEntity(StudentSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.NumberOfBook == model.NumberOfBook && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.StudentGroup).Include(x => x.User); diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/TimeNormService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/TimeNormService.cs index 5a5c04f..65968d5 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/TimeNormService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/AbstractGenerticEntityService/TimeNormService.cs @@ -36,7 +36,7 @@ namespace DepartmentDatabaseImplementation.Implementations.AbstractGenerticEntit protected override void AdditionalDeleting(DbContext context, TimeNorm entity, TimeNormGetBindingModel model) { } - protected override TimeNorm GetUniqueEntity(TimeNormSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.TimeNormName == model.TimeNormName && x.TimeNormShortName == model.TimeNormShortName && x.Id != model.Id); + protected override TimeNorm GetUniqueEntity(TimeNormSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.TimeNormName == model.TimeNormName && x.TimeNormShortName == model.TimeNormShortName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.DisciplineBlock); diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/AccessService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/AccessService.cs index 876e8c2..a7407ac 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/AccessService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/AccessService.cs @@ -33,8 +33,8 @@ namespace SecurityDatabaseImplementation.Implementations.AbstractGenerticEntityS protected override void AdditionalDeleting(DbContext context, Access entity, AccessGetBindingModel model) { } - protected override Access GetUniqueEntity(AccessSetBindingModel model, DbContext context) => - context.Set().FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType && x.Id != model.Id); + protected override Access GetUniqueEntity(AccessSetBindingModel model, IQueryable query) => + query.FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Role); diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/EnviromentSettingService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/EnviromentSettingService.cs index 33760fe..1663b99 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/EnviromentSettingService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/EnviromentSettingService.cs @@ -35,7 +35,7 @@ namespace SecurityDatabaseImplementation.Implementations.AbstractGenerticEntityS protected override void AdditionalDeleting(DbContext context, EnviromentSetting entity, EnviromentSettingGetBindingModel model) { } - protected override EnviromentSetting GetUniqueEntity(EnviromentSettingSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.Key == model.Key && x.Id != model.Id); + protected override EnviromentSetting GetUniqueEntity(EnviromentSettingSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.Key == model.Key && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/RoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/RoleService.cs index f14aa96..7c002c9 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/RoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/RoleService.cs @@ -44,7 +44,7 @@ namespace SecurityDatabaseImplementation.Implementations.AbstractGenerticEntityS context.SaveChanges(); } - protected override Role GetUniqueEntity(RoleSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.RoleName == model.RoleName && x.Id != model.Id); + protected override Role GetUniqueEntity(RoleSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.RoleName == model.RoleName && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query; diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserRoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserRoleService.cs index 552f9b3..2f96431 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserRoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserRoleService.cs @@ -37,10 +37,28 @@ namespace SecurityDatabaseImplementation.Implementations.AbstractGenerticEntityS protected override void AdditionalDeleting(DbContext context, UserRole entity, UserRoleGetBindingModel model) { } - protected override UserRole GetUniqueEntity(UserRoleSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId && x.Id != model.Id); + protected override UserRole GetUniqueEntity(UserRoleSetBindingModel model, IQueryable query) => query.FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId && x.Id != model.Id); protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Role).Include(x => x.User); protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.User.UserName); - } + + protected override bool AdditionalCheckForSingleGet(UserRoleGetBindingModel model) + { + if (model.RoleId.HasValue && model.UserId.HasValue) + { + return true; + } + return base.AdditionalCheckForSingleGet(model); + } + + protected override UserRole GetSingleRecord(IQueryable list, UserRoleGetBindingModel model) + { + if (model.RoleId.HasValue && model.UserId.HasValue) + { + return list.FirstOrDefault(x => x.RoleId == model.RoleId && x.UserId == model.UserId); + } + return base.GetSingleRecord(list, model); + } + } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserService.cs index 31c31b8..b4b805d 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AbstractGenerticEntityService/UserService.cs @@ -68,7 +68,7 @@ namespace SecurityDatabaseImplementation.Implementations.AbstractGenerticEntityS context.SaveChanges(); } - protected override User GetUniqueEntity(UserSetBindingModel model, DbContext context) => context.Set().FirstOrDefault((System.Linq.Expressions.Expression>)(x => x.UserName == model.UserName && x.Id != model.Id)); + protected override User GetUniqueEntity(UserSetBindingModel model, IQueryable query) => query.FirstOrDefault((System.Linq.Expressions.Expression>)(x => x.UserName == model.UserName && x.Id != model.Id)); protected override IQueryable IncludingWhenReading(IQueryable query) => query;