diff --git a/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs b/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs index 9c996b8..57564da 100644 --- a/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs +++ b/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs @@ -8,18 +8,17 @@ using ModuleTools.Models; using ModuleTools.ViewModels; using System; using System.Linq; -using System.Threading.Tasks; namespace DatabaseCore { - public abstract class AbstractGenerticEntityService : IGenerticEntityService + public abstract class AbstractGenerticEntityService : IGenerticEntityService where G : GetBindingModel where S : SetBindingModel where T : BaseEntity where L : ListViewModel, new() where E : ElementViewModel { - public async Task CreateAsync(S model) + public OperationResultModel Create(S model) { using var context = DatabaseManager.GetContext; @@ -33,8 +32,8 @@ namespace DatabaseCore if (exsistEntity == null) { var entity = Mapper.MapToClass(model, true); - await context.Set().AddAsync(entity); - await context.SaveChangesAsync(); + context.Set().Add(entity); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } else @@ -43,7 +42,7 @@ namespace DatabaseCore { exsistEntity = Mapper.MapToClass(model, exsistEntity, true); exsistEntity.IsDeleted = false; - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); } else @@ -53,13 +52,13 @@ namespace DatabaseCore } } - public async Task DeleteAsync(G model) + public OperationResultModel Delete(G model) { using var context = DatabaseManager.GetContext; using var transaction = context.Database.BeginTransaction(); try { - var entity = await context.Set().FirstOrDefaultAsync(x => x.Id == model.Id); + var entity = context.Set().FirstOrDefault(x => x.Id == model.Id); if (entity == null) { return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); @@ -78,22 +77,22 @@ namespace DatabaseCore entity.IsDeleted = true; entity.DateDelete = DateTime.Now; - await context.SaveChangesAsync(); + context.SaveChanges(); AdditionalDeleting(context, entity, model); - await transaction.CommitAsync(); + transaction.Commit(); } catch (Exception) { - await transaction.RollbackAsync(); + transaction.Rollback(); throw; } return OperationResultModel.Success(true); } - public async Task RestoreAsync(G model) + public OperationResultModel Restore(G model) { if (model.Id.HasValue || AdditionalCheckForSingleGet(model)) { @@ -110,14 +109,14 @@ namespace DatabaseCore } entity.IsDeleted = false; - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); } - public async Task ReadAsync(G model) + public OperationResultModel Read(G model) { int countPages = 0; using var context = DatabaseManager.GetContext; @@ -146,27 +145,23 @@ namespace DatabaseCore query = IncludingWhenReading(query); - return await Task.Run(() => + if (model.PageNumber.HasValue && model.PageSize.HasValue) { + countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); + query = query + .Skip(model.PageSize.Value * model.PageNumber.Value) + .Take(model.PageSize.Value); + } + var result = new L + { + MaxCount = countPages, + List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() + }; - if (model.PageNumber.HasValue && model.PageSize.HasValue) - { - countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); - query = query - .Skip(model.PageSize.Value * model.PageNumber.Value) - .Take(model.PageSize.Value); - } - var result = new L - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); - }); + return OperationResultModel.Success(result); } - public async Task UpdateAsync(S model) + public OperationResultModel Update(S model) { using var context = DatabaseManager.GetContext; @@ -193,7 +188,7 @@ namespace DatabaseCore } entity = Mapper.MapToClass(model, entity, true); - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.Designer.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.Designer.cs new file mode 100644 index 0000000..25f986c --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.Designer.cs @@ -0,0 +1,1453 @@ +// +using System; +using DatabaseCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace DatabaseCore.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20210430050931_UpdateStudnet2")] + partial class UpdateStudnet2 + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.5") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EducationDirectionId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("YearEntrance") + .HasColumnType("int"); + + b.Property("YearFinish") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("EducationDirectionId", "YearEntrance") + .IsUnique() + .HasFilter("[EducationDirectionId] IS NOT NULL"); + + b.ToTable("AcademicPlans"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.Discipline", b => + { + b.Property("Id") + .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("DisciplineBlockId"); + + b.HasIndex("DisciplineName") + .IsUnique(); + + b.ToTable("Disciplines"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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") + .IsUnique(); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.Models.Department.OrderSyncHistory", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("SyncDate") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("OrderSyncHistories"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.Student", b => + { + b.Property("Id") + .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("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") + .IsRequired() + .HasColumnType("uniqueidentifier"); + + b.Property("StudentState") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("NumberOfBook") + .IsUnique(); + + b.HasIndex("StudentGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.HasOne("DatabaseCore.Models.Department.EducationDirection", "EducationDirection") + .WithMany("AcademicPlans") + .HasForeignKey("EducationDirectionId"); + + b.Navigation("EducationDirection"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.AcademicPlan", "AcademicPlan") + .WithMany("AcademicPlanRecords") + .HasForeignKey("AcademicPlanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Discipline", "Discipline") + .WithMany("AcademicPlanRecords") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AcademicPlan"); + + b.Navigation("Discipline"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecordTimeNormHour", b => + { + b.HasOne("DatabaseCore.Models.Department.AcademicPlanRecord", "AcademicPlanRecord") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("AcademicPlanRecordId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.TimeNorm", "TimeNorm") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("TimeNormId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("AcademicPlanRecord"); + + b.Navigation("TimeNorm"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Classroom", b => + { + b.HasOne("DatabaseCore.Models.Department.Employee", "Employee") + .WithMany("Classrooms") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b => + { + b.HasOne("DatabaseCore.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("Disciplines") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EducationDirection", b => + { + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("EducationDirections") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b => + { + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Employees") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b => + { + b.HasOne("DatabaseCore.Models.Department.Employee", "Employee") + .WithMany("EmployeePosts") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Post", "Post") + .WithMany("EmployeePosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b => + { + b.HasOne("DatabaseCore.Models.Department.LecturerAcademicDegree", "LecturerAcademicDegree") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicDegreeId"); + + b.HasOne("DatabaseCore.Models.Department.LecturerAcademicRank", "LecturerAcademicRank") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicRankId"); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Lecturers") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LecturerAcademicDegree"); + + b.Navigation("LecturerAcademicRank"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerPost", b => + { + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("LecturerPosts") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Post", "Post") + .WithMany("LecturerPosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.OrderStudentRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.Order", "Order") + .WithMany("OrderStudentRecords") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroupFrom") + .WithMany("OrderStudentRecordFroms") + .HasForeignKey("StudentGroupFromId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroupTo") + .WithMany("OrderStudentRecordTos") + .HasForeignKey("StudentGroupToId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("DatabaseCore.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("DatabaseCore.Models.Department.OrderSyncHistoryRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.OrderSyncHistory", "OrderSyncHistory") + .WithMany("OrderSyncHistoryRecords") + .HasForeignKey("OrderSyncHistoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("OrderSyncHistory"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Student", b => + { + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroup") + .WithMany("Students") + .HasForeignKey("StudentGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Students") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("StudentGroup"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.StudentGroup", b => + { + b.HasOne("DatabaseCore.Models.Department.EducationDirection", "EducationDirection") + .WithMany("StudentGroups") + .HasForeignKey("EducationDirectionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("StudentGroups") + .HasForeignKey("LecturerId"); + + b.Navigation("EducationDirection"); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.TimeNorm", b => + { + b.HasOne("DatabaseCore.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("TimeNorms") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Access", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("Access") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecord", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.DisciplineBlock", b => + { + b.Navigation("Disciplines"); + + b.Navigation("TimeNorms"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EducationDirection", b => + { + b.Navigation("AcademicPlans"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b => + { + b.Navigation("Classrooms"); + + b.Navigation("EmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b => + { + b.Navigation("EducationDirections"); + + b.Navigation("LecturerPosts"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicDegree", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicRank", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Order", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.OrderSyncHistory", b => + { + b.Navigation("OrderSyncHistoryRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Post", b => + { + b.Navigation("EmployeePosts"); + + b.Navigation("LecturerPosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Student", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.StudentGroup", b => + { + b.Navigation("OrderStudentRecordFroms"); + + b.Navigation("OrderStudentRecordTos"); + + b.Navigation("Students"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.TimeNorm", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Role", b => + { + b.Navigation("Access"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("DatabaseCore.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/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.cs new file mode 100644 index 0000000..40f778f --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430050931_UpdateStudnet2.cs @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DatabaseCore.Migrations +{ + public partial class UpdateStudnet2 : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Email", + table: "Students", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(max)"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Email", + table: "Students", + type: "nvarchar(max)", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.Designer.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.Designer.cs new file mode 100644 index 0000000..72bab8a --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.Designer.cs @@ -0,0 +1,1450 @@ +// +using System; +using DatabaseCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace DatabaseCore.Migrations +{ + [DbContext(typeof(DatabaseContext))] + [Migration("20210430051530_UpdateStudnet3")] + partial class UpdateStudnet3 + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.5") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EducationDirectionId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("YearEntrance") + .HasColumnType("int"); + + b.Property("YearFinish") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("EducationDirectionId", "YearEntrance") + .IsUnique() + .HasFilter("[EducationDirectionId] IS NOT NULL"); + + b.ToTable("AcademicPlans"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.Discipline", b => + { + b.Property("Id") + .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("DisciplineBlockId"); + + b.HasIndex("DisciplineName") + .IsUnique(); + + b.ToTable("Disciplines"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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") + .IsUnique(); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.Models.Department.OrderSyncHistory", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("SyncDate") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("OrderSyncHistories"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.Student", b => + { + b.Property("Id") + .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("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("NumberOfBook") + .IsUnique(); + + b.HasIndex("StudentGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.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("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.HasOne("DatabaseCore.Models.Department.EducationDirection", "EducationDirection") + .WithMany("AcademicPlans") + .HasForeignKey("EducationDirectionId"); + + b.Navigation("EducationDirection"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.AcademicPlan", "AcademicPlan") + .WithMany("AcademicPlanRecords") + .HasForeignKey("AcademicPlanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Discipline", "Discipline") + .WithMany("AcademicPlanRecords") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("AcademicPlan"); + + b.Navigation("Discipline"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecordTimeNormHour", b => + { + b.HasOne("DatabaseCore.Models.Department.AcademicPlanRecord", "AcademicPlanRecord") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("AcademicPlanRecordId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.TimeNorm", "TimeNorm") + .WithMany("AcademicPlanRecordTimeNormHours") + .HasForeignKey("TimeNormId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("AcademicPlanRecord"); + + b.Navigation("TimeNorm"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Classroom", b => + { + b.HasOne("DatabaseCore.Models.Department.Employee", "Employee") + .WithMany("Classrooms") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b => + { + b.HasOne("DatabaseCore.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("Disciplines") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EducationDirection", b => + { + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("EducationDirections") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b => + { + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Employees") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b => + { + b.HasOne("DatabaseCore.Models.Department.Employee", "Employee") + .WithMany("EmployeePosts") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Post", "Post") + .WithMany("EmployeePosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b => + { + b.HasOne("DatabaseCore.Models.Department.LecturerAcademicDegree", "LecturerAcademicDegree") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicDegreeId"); + + b.HasOne("DatabaseCore.Models.Department.LecturerAcademicRank", "LecturerAcademicRank") + .WithMany("Lecturers") + .HasForeignKey("LecturerAcademicRankId"); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Lecturers") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LecturerAcademicDegree"); + + b.Navigation("LecturerAcademicRank"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerPost", b => + { + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("LecturerPosts") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Post", "Post") + .WithMany("LecturerPosts") + .HasForeignKey("PostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Lecturer"); + + b.Navigation("Post"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.OrderStudentRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.Order", "Order") + .WithMany("OrderStudentRecords") + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroupFrom") + .WithMany("OrderStudentRecordFroms") + .HasForeignKey("StudentGroupFromId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroupTo") + .WithMany("OrderStudentRecordTos") + .HasForeignKey("StudentGroupToId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("DatabaseCore.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("DatabaseCore.Models.Department.OrderSyncHistoryRecord", b => + { + b.HasOne("DatabaseCore.Models.Department.OrderSyncHistory", "OrderSyncHistory") + .WithMany("OrderSyncHistoryRecords") + .HasForeignKey("OrderSyncHistoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("OrderSyncHistory"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Student", b => + { + b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroup") + .WithMany("Students") + .HasForeignKey("StudentGroupId"); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Students") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("StudentGroup"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.StudentGroup", b => + { + b.HasOne("DatabaseCore.Models.Department.EducationDirection", "EducationDirection") + .WithMany("StudentGroups") + .HasForeignKey("EducationDirectionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("StudentGroups") + .HasForeignKey("LecturerId"); + + b.Navigation("EducationDirection"); + + b.Navigation("Lecturer"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.TimeNorm", b => + { + b.HasOne("DatabaseCore.Models.Department.DisciplineBlock", "DisciplineBlock") + .WithMany("TimeNorms") + .HasForeignKey("DisciplineBlockId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DisciplineBlock"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Access", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("Access") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.UserRole", b => + { + b.HasOne("DatabaseCore.Models.Security.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlan", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.AcademicPlanRecord", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Discipline", b => + { + b.Navigation("AcademicPlanRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.DisciplineBlock", b => + { + b.Navigation("Disciplines"); + + b.Navigation("TimeNorms"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EducationDirection", b => + { + b.Navigation("AcademicPlans"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b => + { + b.Navigation("Classrooms"); + + b.Navigation("EmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b => + { + b.Navigation("EducationDirections"); + + b.Navigation("LecturerPosts"); + + b.Navigation("StudentGroups"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicDegree", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerAcademicRank", b => + { + b.Navigation("Lecturers"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Order", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.OrderSyncHistory", b => + { + b.Navigation("OrderSyncHistoryRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Post", b => + { + b.Navigation("EmployeePosts"); + + b.Navigation("LecturerPosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Student", b => + { + b.Navigation("OrderStudentRecords"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.StudentGroup", b => + { + b.Navigation("OrderStudentRecordFroms"); + + b.Navigation("OrderStudentRecordTos"); + + b.Navigation("Students"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.TimeNorm", b => + { + b.Navigation("AcademicPlanRecordTimeNormHours"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Security.Role", b => + { + b.Navigation("Access"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("DatabaseCore.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/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.cs new file mode 100644 index 0000000..61e6bfd --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210430051530_UpdateStudnet3.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DatabaseCore.Migrations +{ + public partial class UpdateStudnet3 : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Students_StudentGroups_StudentGroupId", + table: "Students"); + + migrationBuilder.AlterColumn( + name: "StudentGroupId", + table: "Students", + type: "uniqueidentifier", + nullable: true, + oldClrType: typeof(Guid), + oldType: "uniqueidentifier"); + + migrationBuilder.AddForeignKey( + name: "FK_Students_StudentGroups_StudentGroupId", + table: "Students", + column: "StudentGroupId", + principalTable: "StudentGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Students_StudentGroups_StudentGroupId", + table: "Students"); + + migrationBuilder.AlterColumn( + name: "StudentGroupId", + table: "Students", + type: "uniqueidentifier", + nullable: false, + defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), + oldClrType: typeof(Guid), + oldType: "uniqueidentifier", + oldNullable: true); + + migrationBuilder.AddForeignKey( + name: "FK_Students_StudentGroups_StudentGroupId", + table: "Students", + column: "StudentGroupId", + principalTable: "StudentGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs index e6a89f3..1825d60 100644 --- a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs @@ -796,7 +796,6 @@ namespace DatabaseCore.Migrations .HasColumnType("nvarchar(max)"); b.Property("Email") - .IsRequired() .HasColumnType("nvarchar(max)"); b.Property("FirstName") @@ -828,7 +827,6 @@ namespace DatabaseCore.Migrations .HasColumnType("varbinary(max)"); b.Property("StudentGroupId") - .IsRequired() .HasColumnType("uniqueidentifier"); b.Property("StudentState") @@ -1332,9 +1330,7 @@ namespace DatabaseCore.Migrations { b.HasOne("DatabaseCore.Models.Department.StudentGroup", "StudentGroup") .WithMany("Students") - .HasForeignKey("StudentGroupId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); + .HasForeignKey("StudentGroupId"); b.HasOne("DatabaseCore.Models.Security.User", "User") .WithMany("Students") diff --git a/DepartmentPortal/Common/DatabaseCore/Models/Department/Student.cs b/DepartmentPortal/Common/DatabaseCore/Models/Department/Student.cs index 1d74a5d..c630846 100644 --- a/DepartmentPortal/Common/DatabaseCore/Models/Department/Student.cs +++ b/DepartmentPortal/Common/DatabaseCore/Models/Department/Student.cs @@ -26,7 +26,6 @@ namespace DatabaseCore.Models.Department public Guid UserId { get; set; } [DataMember] - [Required] [MapConfiguration("StudentGroupId")] public Guid? StudentGroupId { get; set; } @@ -55,7 +54,6 @@ namespace DatabaseCore.Models.Department public string Patronymic { get; set; } [DataMember] - [Required] [MapConfiguration("Email")] public string Email { get; set; } diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs index 37f8d8d..e1baccc 100644 --- a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityElement.cs @@ -18,396 +18,396 @@ using System.Xml.Linq; namespace DesktopTools.Controls { - public partial class GenericControlEntityElement : MainControlViewEntityElement, IControlViewEntityElement - where G : GetBindingModel, new() - where S : SetBindingModel, new() - where L : ListViewModel - where E : ElementViewModel - where BL : GenericBusinessLogic - { - /// - /// Объект бизнес-логики для получения данных - /// - protected readonly BL _businessLogic; + public partial class GenericControlEntityElement : MainControlViewEntityElement, IControlViewEntityElement + where G : GetBindingModel, new() + where S : SetBindingModel, new() + where L : ListViewModel + where E : ElementViewModel + where BL : GenericBusinessLogic + { + /// + /// Объект бизнес-логики для получения данных + /// + protected readonly BL _businessLogic; - /// - /// Методы для реализации в generic-контроле - /// - protected IGenericControlEntityElement _genericControlViewEntityElement; + /// + /// Методы для реализации в generic-контроле + /// + protected IGenericControlEntityElement _genericControlViewEntityElement; - /// - /// Признак налиичия изменений - /// - private bool _haveChages = false; + /// + /// Признак налиичия изменений + /// + private bool _haveChages = false; - /// - /// Ширина контрола по умолчанию - /// - private readonly int _defaultControlWidth = 350; + /// + /// Ширина контрола по умолчанию + /// + private readonly int _defaultControlWidth = 350; - protected E _element = null; + protected E _element = null; - /// - /// Событие, вызываемое при закрытии контрола - /// - private event Action CloseElementEvent; + /// + /// Событие, вызываемое при закрытии контрола + /// + private event Action CloseElementEvent; - /// - /// События установки одинаковой ширины для заголовков контролов - /// - private event Action SetTitleWidth; + /// + /// События установки одинаковой ширины для заголовков контролов + /// + private event Action SetTitleWidth; - /// - /// Событие установки значения - /// - private event Action SetValues; + /// + /// Событие установки значения + /// + private event Action SetValues; - /// - /// Событие сброса значения в исходное состояние - /// - private event Action DropValues; + /// + /// Событие сброса значения в исходное состояние + /// + private event Action DropValues; - /// - /// Событие проверки заполненности контрола - /// - private event Func CheckValues; + /// + /// Событие проверки заполненности контрола + /// + private event Func CheckValues; - /// - /// Событие получения значения из контрола - /// - private event Action GetValues; + /// + /// Событие получения значения из контрола + /// + private event Action GetValues; - private E Element - { - get { return _element; } - set - { - try - { - _element = value; - if (_element != null) - { - SetValues?.Invoke(_element); - if (tabControl.Visible) - { - foreach (TabPage page in tabControl.TabPages) - { - if (page.Name == tabPageMain.Name) - { - continue; - } - if (page.Controls[0] is IControlChildEntity cntrl) - { - cntrl.ParentId = _element.Id; - cntrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.Child }); - } - } - } - } - _haveChages = false; - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при установки значений"); - } - } - } + private E Element + { + get { return _element; } + set + { + try + { + _element = value; + if (_element != null) + { + SetValues?.Invoke(_element); + if (tabControl.Visible) + { + foreach (TabPage page in tabControl.TabPages) + { + if (page.Name == tabPageMain.Name) + { + continue; + } + if (page.Controls[0] is IControlChildEntity cntrl) + { + cntrl.ParentId = _element.Id; + cntrl.Open(new ControlOpenModel { OpenMode = ControlOpenMode.Child }); + } + } + } + } + _haveChages = false; + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при установки значений"); + } + } + } - public GenericControlEntityElement() - { - InitializeComponent(); - InitEvents(); - _businessLogic = DependencyManager.Instance.Resolve(); - _controlViewEntityElement = this; - } + public GenericControlEntityElement() + { + InitializeComponent(); + InitEvents(); + _businessLogic = DependencyManager.Instance.Resolve(); + _controlViewEntityElement = this; + } - public async void OpenControl(ControlOpenModel model) - { - if (model.CloseElement != null) - { - CloseElementEvent += model.CloseElement; - } - if (panelContainer.Controls.Count == 0) - { - try - { - Configurate(GetConfig()); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации"); - } - } - if (model.ElementId.HasValue) - { - Element = await _businessLogic.GetElementAsync(new G { Id = model.ElementId }); - if (Element == null) - { - DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении элемента"); - } - } - Dock = DockStyle.Fill; - } + public void OpenControl(ControlOpenModel model) + { + if (model.CloseElement != null) + { + CloseElementEvent += model.CloseElement; + } + if (panelContainer.Controls.Count == 0) + { + try + { + Configurate(GetConfig()); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при конфигурации"); + } + } + if (model.ElementId.HasValue) + { + Element = _businessLogic.GetElement(new G { Id = model.ElementId }); + if (Element == null) + { + DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении элемента"); + } + } + Dock = DockStyle.Fill; + } - public IControl GetInstanceControl() => _genericControlViewEntityElement?.GetInstanceGenericControl(); + public IControl GetInstanceControl() => _genericControlViewEntityElement?.GetInstanceGenericControl(); - public string SaveControlToXml() => new XElement("Control", - new XAttribute("Type", GetType().FullName), - new XAttribute("ControlId", ControlId), - new XAttribute("Title", Title)).ToString(); + public string SaveControlToXml() => new XElement("Control", + new XAttribute("Type", GetType().FullName), + new XAttribute("ControlId", ControlId), + new XAttribute("Title", Title)).ToString(); - public void LoadControlFromXml(string xml) - { - var control = XElement.Parse(xml).Element("Control"); - ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); - Title = control.Attribute("Title").Value.ToString(); - } + public void LoadControlFromXml(string xml) + { + var control = XElement.Parse(xml).Element("Control"); + ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); + Title = control.Attribute("Title").Value.ToString(); + } - private void InitEvents() - { - toolStripButtonSave.Click += async (object sender, EventArgs e) => { await SaveAsync(); }; - toolStripButtonReload.Click += (object sender, EventArgs e) => - { - if (DialogHelper.MessageQuestion("Отменить все внесенные изменения?") == DialogResult.Yes) - { - try - { - DropValues?.Invoke(); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при сбросе значений"); - } - } - }; - toolStripButtonClose.Click += async (object sender, EventArgs e) => - { - if (_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == DialogResult.Yes) - { - if (!(await SaveAsync())) - { - return; - } - } - CloseElementEvent?.Invoke(ControlId); - Dispose(); - }; - } + private void InitEvents() + { + toolStripButtonSave.Click += (object sender, EventArgs e) => { Save(); }; + toolStripButtonReload.Click += (object sender, EventArgs e) => + { + if (DialogHelper.MessageQuestion("Отменить все внесенные изменения?") == DialogResult.Yes) + { + try + { + DropValues?.Invoke(); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, $"{Title}. Ошибка при сбросе значений"); + } + } + }; + toolStripButtonClose.Click += (object sender, EventArgs e) => + { + if (_haveChages && DialogHelper.MessageQuestion("Имеется несохраненные данные, вы действительно хотите закрыть элемент?", "Закрытие элемента") == DialogResult.Yes) + { + if (!Save()) + { + return; + } + } + CloseElementEvent?.Invoke(ControlId); + Dispose(); + }; + } - private void Configurate(ControlViewEntityElementConfiguration config) - { - // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" - 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; - contextMenuStripElement.Items.Add(itemContext); - } - } - // либо скрытие пункта, если не предусмотренно подпунктов - else - { - toolStripSplitButtonActions.Visible = false; - toolStripSeparator1.Visible = false; - } - var attributeClass = typeof(E).GetCustomAttribute(); - if (attributeClass == null) - { - return; - } - tabControl.Visible = attributeClass.HaveDependenceEntities; - panelContainer.Visible = !attributeClass.HaveDependenceEntities; - Width = attributeClass.Width != 0 ? attributeClass.Width : _defaultControlWidth; + private void Configurate(ControlViewEntityElementConfiguration config) + { + // Загрузка подпунктов в контекстное меню и в пункт меню "Действие" + 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; + contextMenuStripElement.Items.Add(itemContext); + } + } + // либо скрытие пункта, если не предусмотренно подпунктов + else + { + toolStripSplitButtonActions.Visible = false; + toolStripSeparator1.Visible = false; + } + var attributeClass = typeof(E).GetCustomAttribute(); + if (attributeClass == null) + { + return; + } + tabControl.Visible = attributeClass.HaveDependenceEntities; + panelContainer.Visible = !attributeClass.HaveDependenceEntities; + Width = attributeClass.Width != 0 ? attributeClass.Width : _defaultControlWidth; - int positionY = 5; - int positionX = 5; - int interval = 15; + int positionY = 5; + int positionX = 5; + int interval = 15; - int titleWidth = 0; + int titleWidth = 0; - foreach (var property in typeof(E).GetProperties()) - { - var attribute = property.GetCustomAttribute(); - if (attribute != null) - { - AbstractBaseControl control = null; - switch (attribute.ControlType) - { - case ControlType.ControlString: - control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength); - break; - case ControlType.ControlText: - control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height); - break; - case ControlType.ControlInt: - control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue); - break; - case ControlType.ControlDecimal: - control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, - attribute.MaxValue, attribute.DecimalPlaces); - break; - case ControlType.ControlBool: - control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly); - break; - case ControlType.ControlDateTime: - control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate, - attribute.MaxDate, attribute.CustomDateFormat); - break; - case ControlType.ControlImage: - control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height); - break; - case ControlType.ControlEnum: - control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType); - break; - case ControlType.ControlGuid: - if (attribute.ControlTypeObject.IsNotEmpty() && Type.GetType(attribute.ControlTypeObject) != null) - { - control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly, - DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as IControlEntitySelectable, - property.Name == ParentPropertyName ? ParentId : null); - } - break; - } - if (control == null) - { - continue; - } + foreach (var property in typeof(E).GetProperties()) + { + var attribute = property.GetCustomAttribute(); + if (attribute != null) + { + AbstractBaseControl control = null; + switch (attribute.ControlType) + { + case ControlType.ControlString: + control = new BaseControlString(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength); + break; + case ControlType.ControlText: + control = new BaseControlText(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MaxLength, attribute.Height); + break; + case ControlType.ControlInt: + control = new BaseControlInt(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, attribute.MaxValue); + break; + case ControlType.ControlDecimal: + control = new BaseControlDecimal(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinValue, + attribute.MaxValue, attribute.DecimalPlaces); + break; + case ControlType.ControlBool: + control = new BaseControlBool(property.Name, attribute.MustHaveValue, attribute.ReadOnly); + break; + case ControlType.ControlDateTime: + control = new BaseControlDateTime(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.MinDate, + attribute.MaxDate, attribute.CustomDateFormat); + break; + case ControlType.ControlImage: + control = new BaseControlImage(property.Name, attribute.MustHaveValue, attribute.ReadOnly, attribute.Width, attribute.Height); + break; + case ControlType.ControlEnum: + control = new BaseControlEnum(property.Name, attribute.MustHaveValue, attribute.ReadOnly, property.PropertyType); + break; + case ControlType.ControlGuid: + if (attribute.ControlTypeObject.IsNotEmpty() && Type.GetType(attribute.ControlTypeObject) != null) + { + control = new BaseControlGuid(property.Name, attribute.MustHaveValue, attribute.ReadOnly, + DependencyManager.Instance.Resolve(Type.GetType(attribute.ControlTypeObject)) as IControlEntitySelectable, + property.Name == ParentPropertyName ? ParentId : null); + } + break; + } + if (control == null) + { + continue; + } - var widthTitle = control.SetTitle(attribute.DisplayName); - if (widthTitle > titleWidth) - { - titleWidth = widthTitle; - } + var widthTitle = control.SetTitle(attribute.DisplayName); + if (widthTitle > titleWidth) + { + titleWidth = widthTitle; + } - control.OnValueChangeEvent += () => { _haveChages = true; }; - SetValues += control.SetValue; - DropValues += control.DropValue; - CheckValues += control.CheckValue; - SetTitleWidth += control.SetTitleWidth; - GetValues += control.GetValue; + control.OnValueChangeEvent += () => { _haveChages = true; }; + SetValues += control.SetValue; + DropValues += control.DropValue; + CheckValues += control.CheckValue; + SetTitleWidth += control.SetTitleWidth; + GetValues += control.GetValue; - control.Location = new System.Drawing.Point(positionX, positionY); - control.Width = Width - positionX * 2 - (tabControl.Visible ? 10 : 0); - control.Anchor = AnchorStyles.Top | AnchorStyles.Left; - if (panelContainer.Visible) - { - control.Anchor |= AnchorStyles.Right; - } - positionY += control.Height + interval; + control.Location = new System.Drawing.Point(positionX, positionY); + control.Width = Width - positionX * 2 - (tabControl.Visible ? 10 : 0); + control.Anchor = AnchorStyles.Top | AnchorStyles.Left; + if (panelContainer.Visible) + { + control.Anchor |= AnchorStyles.Right; + } + positionY += control.Height + interval; - if (panelContainer.Visible) - { - panelContainer.Controls.Add(control); - } - if (tabControl.Visible) - { - tabPageMain.Controls.Add(control); - } - } - } + if (panelContainer.Visible) + { + panelContainer.Controls.Add(control); + } + if (tabControl.Visible) + { + tabPageMain.Controls.Add(control); + } + } + } - SetTitleWidth(titleWidth); - Height = attributeClass.Height != 0 ? attributeClass.Height : positionY; + SetTitleWidth(titleWidth); + Height = attributeClass.Height != 0 ? attributeClass.Height : positionY; - if (attributeClass.HaveDependenceEntities) - { - var attrDependences = typeof(E).GetCustomAttributes(); - if (attrDependences != null) - { - foreach (var attr in attrDependences) - { - if (DependencyManager.Instance.Resolve(Type.GetType(attr.ControlTypeObject)) is IControlChildEntity control) - { - var cntrl = control.GetInstance() as IControlChildEntity; - cntrl.ParentPropertyName = attr.ParentPropertyName; - //cntrl.Open(null); - var tabPage = new TabPage - { - Location = new System.Drawing.Point(4, 24), - Name = "tabPage", - Padding = new Padding(3), - Size = new System.Drawing.Size(122, 99), - TabIndex = 0, - Text = attr.Title, - UseVisualStyleBackColor = true - }; - tabPage.Controls.Add(cntrl as UserControl); + if (attributeClass.HaveDependenceEntities) + { + var attrDependences = typeof(E).GetCustomAttributes(); + if (attrDependences != null) + { + foreach (var attr in attrDependences) + { + if (DependencyManager.Instance.Resolve(Type.GetType(attr.ControlTypeObject)) is IControlChildEntity control) + { + var cntrl = control.GetInstance() as IControlChildEntity; + cntrl.ParentPropertyName = attr.ParentPropertyName; + //cntrl.Open(null); + var tabPage = new TabPage + { + Location = new System.Drawing.Point(4, 24), + Name = "tabPage", + Padding = new Padding(3), + Size = new System.Drawing.Size(122, 99), + TabIndex = 0, + Text = attr.Title, + UseVisualStyleBackColor = true + }; + tabPage.Controls.Add(cntrl as UserControl); - tabControl.TabPages.Add(tabPage); - if (attr.IsActive) - { - tabPage.Select(); - } - } - } - } - } - } + tabControl.TabPages.Add(tabPage); + if (attr.IsActive) + { + tabPage.Select(); + } + } + } + } + } + } - private async Task SaveAsync() - { - if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) - { - return false; - } - var model = Element == null ? new S() : Mapper.MapToClass(Element, true); - try - { - GetValues(model); - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); - } + private bool Save() + { + if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) + { + return false; + } + var model = Element == null ? new S() : Mapper.MapToClass(Element, true); + try + { + GetValues(model); + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); + } - if (model != null) - { - if (Element == null) - { - Element = await _businessLogic.CreateAsync(model); - } - else - { - Element = await _businessLogic.UpdateAsync(model); - } + if (model != null) + { + if (Element == null) + { + Element = _businessLogic.Create(model); + } + else + { + Element = _businessLogic.Update(model); + } - if (Element == null) - { - DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении элемента"); - return false; - } + if (Element == null) + { + DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при сохранении элемента"); + return false; + } - _haveChages = false; - DialogHelper.MessageInformation("Сохранение прошло успешно", "Сообщение"); - return true; - } + _haveChages = false; + DialogHelper.MessageInformation("Сохранение прошло успешно", "Сообщение"); + return true; + } - return false; - } + return false; + } - private ControlViewEntityElementConfiguration GetConfig() => _genericControlViewEntityElement?.GetConfigControl(); + private ControlViewEntityElementConfiguration GetConfig() => _genericControlViewEntityElement?.GetConfigControl(); - protected bool FillModel(S model) - { - if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) - { - return false; - } - try - { - GetValues(model); - return true; - } - catch (Exception ex) - { - DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); - } - return false; - } - } + protected bool FillModel(S model) + { + if (CheckValues.GetInvocationList().Select(x => (bool)x.DynamicInvoke()).ToList().Any(x => !x)) + { + return false; + } + try + { + GetValues(model); + return true; + } + catch (Exception ex) + { + DialogHelper.MessageException(ex.Message, "Ошибка при получении значений"); + } + return false; + } + } } diff --git a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs index 26a1151..288af03 100644 --- a/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs +++ b/DepartmentPortal/Common/DesktopTools/MainControls/GenericControlEntityList.cs @@ -12,13 +12,12 @@ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace DesktopTools.Controls { - public partial class GenericControlEntityList : MainControlViewEntityList, IControlViewEntityList + public partial class GenericControlEntityList : MainControlViewEntityList, IControlViewEntityList where G : GetBindingModel, new() where S : SetBindingModel, new() where L : ListViewModel @@ -68,7 +67,7 @@ namespace DesktopTools.Controls } #region IControlViewEntityList - public async void OpenControl(ControlOpenModel model) + public void OpenControl(ControlOpenModel model) { _openMode = model.OpenMode; if (model.CloseList != null) @@ -93,13 +92,13 @@ namespace DesktopTools.Controls } if (!model.LazyLoading) { - await LoadListAsync(); + LoadList(); } } public IControl GetInstanceControl() => _genericControlViewEntityList?.GetInstanceGenericControl(); - public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElementAsync(new G { Id = id }).Result?.ToString(); + public string GetTitleFromIdControl(Guid id) => _businessLogic.GetElement(new G { Id = id })?.ToString(); public string SaveControlToXml() => new XElement("Control", new XAttribute("Type", GetType().FullName), @@ -114,7 +113,7 @@ namespace DesktopTools.Controls new XElement("Value", ((toolStripComboBoxPageNames.SelectedItem as PageNamesForPaginationModel)?.Value ?? "-"))), new XElement("ParentId", ParentId?.ToString() ?? "-"))).ToString(); - public async void LoadControlFromXml(string xml) + public void LoadControlFromXml(string xml) { var control = XElement.Parse(xml); ControlId = new Guid(control.Attribute("ControlId").Value.ToString()); @@ -142,7 +141,7 @@ namespace DesktopTools.Controls { ParentId = new Guid(config.Element("ParentId").Value.ToString()); } - await LoadListAsync(); + LoadList(); } #endregion @@ -290,10 +289,10 @@ namespace DesktopTools.Controls { toolStripButtonAdd.Click += (object sender, EventArgs e) => { AddElement(); }; toolStripButtonUpd.Click += (object sender, EventArgs e) => { UpdElement(); }; - toolStripButtonDel.Click += async (object sender, EventArgs e) => { await DelElementAsync(); }; + toolStripButtonDel.Click += (object sender, EventArgs e) => { DelElement(); }; toolStripButtonSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = !panelSearch.Visible; }; - toolStripButtonRef.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; - toolStripButtonSelect.Click += async (object sender, EventArgs e) => { await SelectElement(); }; + toolStripButtonRef.Click += (object sender, EventArgs e) => { LoadList(); }; + toolStripButtonSelect.Click += (object sender, EventArgs e) => { SelectElement(); }; toolStripButtonClose.Click += (object sender, EventArgs e) => { CloseListEvent?.Invoke(ControlId); @@ -301,10 +300,10 @@ namespace DesktopTools.Controls Dispose(); }; - buttonSearch.Click += async (object sender, EventArgs e) => { await LoadListAsync(); }; - buttonCancelSearch.Click += async (object sender, EventArgs e) => { panelSearch.Visible = false; await LoadListAsync(); }; + buttonSearch.Click += (object sender, EventArgs e) => { LoadList(); }; + buttonCancelSearch.Click += (object sender, EventArgs e) => { panelSearch.Visible = false; LoadList(); }; - dataGridViewList.KeyDown += async (object sender, KeyEventArgs e) => + dataGridViewList.KeyDown += (object sender, KeyEventArgs e) => { switch (e.KeyCode) { @@ -323,41 +322,41 @@ namespace DesktopTools.Controls case Keys.Delete: if (toolStripButtonDel.Visible) { - await DelElementAsync(); + DelElement(); } break; } }; - dataGridViewList.CellDoubleClick += async (object sender, DataGridViewCellEventArgs e) => + dataGridViewList.CellDoubleClick += (object sender, DataGridViewCellEventArgs e) => { if (_openMode == ControlOpenMode.Select && dataGridViewList.SelectedRows.Count > 0) { - await SelectElement(); + SelectElement(); } UpdElement(); }; - toolStripButtonPrev.Click += async (object sender, EventArgs e) => + toolStripButtonPrev.Click += (object sender, EventArgs e) => { if (int.TryParse(toolStripTextBoxPage.Text, out int page)) { toolStripTextBoxPage.Text = (page - 1).ToString(); - await LoadListAsync(); + LoadList(); } }; - toolStripButtonNext.Click += async (object sender, EventArgs e) => + toolStripButtonNext.Click += (object sender, EventArgs e) => { if (int.TryParse(toolStripTextBoxPage.Text, out int page)) { toolStripTextBoxPage.Text = (page + 1).ToString(); - await LoadListAsync(); + LoadList(); } }; - toolStripTextBoxPage.KeyDown += async (object sender, KeyEventArgs e) => + toolStripTextBoxPage.KeyDown += (object sender, KeyEventArgs e) => { if (e.KeyData == Keys.Enter) { - await LoadListAsync(); + LoadList(); } }; @@ -369,12 +368,12 @@ namespace DesktopTools.Controls /// /// /// - private async void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => await LoadListAsync(); + private void ToolStripComboBoxPageNamesSelectedIndexChanged(object sender, EventArgs e) => LoadList(); /// /// Вызов события загрузки данных на datagrid /// - private async Task LoadListAsync() + private void LoadList() { var cursor = Cursor.Current; @@ -440,7 +439,7 @@ namespace DesktopTools.Controls } } } - data = await _businessLogic.GetListAsync(model); + data = _businessLogic.GetList(model); if (data == null && _businessLogic.Errors.Count > 0) { DialogHelper.MessageException(_businessLogic.Errors, $"{Title}. Ошибки при получении данных"); @@ -463,14 +462,14 @@ namespace DesktopTools.Controls { Cursor.Current = cursor; } - FillDataOnGridAsync(data?.List, selectedGuids); + FillDataOnGrid(data?.List, selectedGuids); } /// /// Заполнение таблицы /// /// - private void FillDataOnGridAsync(List data, List selectedGuids) + private void FillDataOnGrid(List data, List selectedGuids) { if (data == null) { @@ -513,7 +512,7 @@ namespace DesktopTools.Controls /// /// Вызов события при удалении элемента /// - private async Task DelElementAsync() + private void DelElement() { if (MessageBox.Show("Удалить выбранные записи?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { @@ -523,7 +522,7 @@ namespace DesktopTools.Controls Cursor.Current = Cursors.WaitCursor; foreach (DataGridViewRow selected in dataGridViewList.SelectedRows) { - await _businessLogic.DeleteAsync(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); + _businessLogic.Delete(new G { Id = new Guid(selected.Cells[0].Value.ToString()) }); } } catch (Exception ex) @@ -540,7 +539,7 @@ namespace DesktopTools.Controls finally { Cursor.Current = cursor; - await LoadListAsync(); + LoadList(); } } } @@ -548,12 +547,12 @@ namespace DesktopTools.Controls /// /// Вызов события при выборе элемента /// - private async Task SelectElement() + private void SelectElement() { try { SelectedId = new Guid(dataGridViewList.SelectedRows[0].Cells[0].Value.ToString()); - SelectedText = (await _businessLogic.GetElementAsync(new G { Id = SelectedId }))?.ToString(); + SelectedText = _businessLogic.GetElement(new G { Id = SelectedId })?.ToString(); CloseSelectEvent?.Invoke(true); Dispose(); } @@ -581,7 +580,10 @@ namespace DesktopTools.Controls { if (toolStripComboBoxPageNames.SelectedItem is PageNamesForPaginationModel key) { - control.ParentId = new Guid(key.Key.ToString()); + if (key.Key.GetType().Name == "Guid") + { + control.ParentId = new Guid(key.Key.ToString()); + } control.ParentPropertyName = toolStripComboBoxPageNames.Tag?.ToString(); } } @@ -596,9 +598,9 @@ namespace DesktopTools.Controls { OpenMode = ControlOpenMode.List, ElementId = id, - CloseElement = async (Guid id) => + CloseElement = (Guid id) => { - await LoadListAsync(); + LoadList(); form.Close(); } }); diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs index 83275a8..76e828b 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs @@ -3,18 +3,17 @@ using ModuleTools.Enums; using ModuleTools.Interfaces; using ModuleTools.ViewModels; using System; -using System.Threading.Tasks; namespace ModuleTools.BusinessLogics { - /// - /// Базовый класс для логики сущности - /// - /// - /// - /// - /// - public class GenericBusinessLogic : CoreBusinessLogic + /// + /// Базовый класс для логики сущности + /// + /// + /// + /// + /// + public class GenericBusinessLogic : CoreBusinessLogic where G : GetBindingModel where S : SetBindingModel where L : ListViewModel @@ -42,7 +41,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task GetListAsync(G model) + public L GetList(G model) { Errors.Clear(); try @@ -52,7 +51,7 @@ namespace ModuleTools.BusinessLogics { throw new MethodAccessException("Нет прав на получение списка"); } - var result = await Service.ReadAsync(model); + var result = Service.Read(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); @@ -73,7 +72,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task GetElementAsync(G model) + public E GetElement(G model) { Errors.Clear(); try @@ -83,7 +82,7 @@ namespace ModuleTools.BusinessLogics { throw new MethodAccessException("Нет прав на получение списка"); } - var result = await Service.ReadAsync(model); + var result = Service.Read(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); @@ -103,7 +102,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task CreateAsync(S model) + public virtual E Create(S model) { Errors.Clear(); try @@ -112,7 +111,7 @@ namespace ModuleTools.BusinessLogics { return null; } - var result = await Service.CreateAsync(model); + var result = Service.Create(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); @@ -133,7 +132,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task UpdateAsync(S model) + public virtual E Update(S model) { Errors.Clear(); try @@ -142,7 +141,7 @@ namespace ModuleTools.BusinessLogics { return null; } - var result = await Service.UpdateAsync(model); + var result = Service.Update(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); @@ -163,7 +162,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task DeleteAsync(G model) + public virtual bool Delete(G model) { Errors.Clear(); try @@ -172,7 +171,7 @@ namespace ModuleTools.BusinessLogics { return false; } - var result = await Service.DeleteAsync(model); + var result = Service.Delete(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); @@ -193,7 +192,7 @@ namespace ModuleTools.BusinessLogics /// /// /// - public async Task RestoreAsync(G model) + public virtual E Restore(G model) { Errors.Clear(); try @@ -202,7 +201,7 @@ namespace ModuleTools.BusinessLogics { return null; } - var result = await Service.RestoreAsync(model); + var result = Service.Restore(model); if (!result.IsSucceeded) { Errors.AddRange(result.Errors); diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs index f1e50f1..ac92fcb 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs @@ -1,5 +1,6 @@ using ModuleTools.Attributes; using System; +using System.Collections; using System.Reflection; namespace ModuleTools.BusinessLogics @@ -64,11 +65,16 @@ namespace ModuleTools.BusinessLogics var props = customAttribute.PropertyNameFromModel.Split('.'); foreach (var prop in props) { - if(prop == "ToString") + if (prop == "ToString") { value = value.ToString(); break; } + else if (prop == "Count") + { + value = (value as ICollection)?.Count; + break; + } var bindingProperty = value.GetType().GetProperty(prop); if (bindingProperty != null) { diff --git a/DepartmentPortal/Common/ModuleTools/Interfaces/IGenerticEntityService.cs b/DepartmentPortal/Common/ModuleTools/Interfaces/IGenerticEntityService.cs index d9bc285..c85f1c3 100644 --- a/DepartmentPortal/Common/ModuleTools/Interfaces/IGenerticEntityService.cs +++ b/DepartmentPortal/Common/ModuleTools/Interfaces/IGenerticEntityService.cs @@ -1,13 +1,12 @@ using ModuleTools.BindingModels; using ModuleTools.Models; -using System.Threading.Tasks; namespace ModuleTools.Interfaces { - /// - /// Описание логики для хранилища сущности - /// - public interface IGenerticEntityService + /// + /// Описание логики для хранилища сущности + /// + public interface IGenerticEntityService where G : GetBindingModel where S : SetBindingModel { @@ -16,34 +15,34 @@ namespace ModuleTools.Interfaces /// /// /// - Task ReadAsync(G model); + OperationResultModel Read(G model); /// /// Создание новой сущности /// /// /// - Task CreateAsync(S model); + OperationResultModel Create(S model); /// /// Изменение сущности /// /// /// - Task UpdateAsync(S model); + OperationResultModel Update(S model); /// /// Удаление сущности /// /// /// - Task DeleteAsync(G model); + OperationResultModel Delete(G model); /// /// Восстановление сущности /// /// /// - Task RestoreAsync(G model); + OperationResultModel Restore(G model); } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BindingModels/OrderStudentRecordBindingModel.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BindingModels/OrderStudentRecordBindingModel.cs index c346e69..7cb5a17 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BindingModels/OrderStudentRecordBindingModel.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BindingModels/OrderStudentRecordBindingModel.cs @@ -16,6 +16,8 @@ namespace DepartmentBusinessLogic.BindingModels public Guid? StudentId { get; set; } public Guid? StudentGroupId { get; set; } + + public OrderStudentMoveType? OrderStudentMoveType { get; set; } } /// diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderStudentRecordBusinessLogic.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderStudentRecordBusinessLogic.cs index 9626151..e4adfc7 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderStudentRecordBusinessLogic.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderStudentRecordBusinessLogic.cs @@ -1,16 +1,160 @@ using DepartmentBusinessLogic.BindingModels; +using DepartmentBusinessLogic.Enums; using DepartmentBusinessLogic.Interfaces; using DepartmentBusinessLogic.ViewModels; using ModuleTools.BusinessLogics; using ModuleTools.Enums; +using SecurityBusinessLogic.BindingModels; +using SecurityBusinessLogic.BusinessLogics; namespace DepartmentBusinessLogic.BusinessLogics { - /// - /// Логика работы с записями приказов - /// - public class OrderStudentRecordBusinessLogic : GenericBusinessLogic + /// + /// Логика работы с записями приказов + /// + public class OrderStudentRecordBusinessLogic : GenericBusinessLogic { public OrderStudentRecordBusinessLogic(IOrderStudentRecordService service) : base(service, "Приказы", AccessOperation.Приказы) { } + + public override OrderStudentRecordViewModel Create(OrderStudentRecordSetBindingModel model) + { + var result = base.Create(model); + if (result != null) + { + var studentLogic = DependencyManager.Instance.Resolve(); + var userLogic = DependencyManager.Instance.Resolve(); + var student = studentLogic.GetElement(new StudentGetBindingModel { Id = result.StudentId }); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка при получении студента", $"Не удалось получить студента")); + return null; + } + // изменять студента + var st = Mapper.MapToClass(student, true); + var studentName = student.ToString(); + if (student.StudentGroupId != result.StudentGroupToId) + { + st.StudentGroupId = result.StudentGroupToId; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить группу у студента {studentName}")); + return null; + } + } + + if (student.Description != model.Info) + { + st.Description = model.Info; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить описание у студента {studentName}")); + return null; + } + } + + if ((result.OrderStudentMoveType == OrderStudentMoveType.ЗачислитьПоПриказу || + result.OrderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводу || + result.OrderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводусДругогоВуза || + result.OrderStudentMoveType == OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры) + && student.StudentState != StudentState.Учится) + { + st.StudentState = StudentState.Учится; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + } + + if ((result.OrderStudentMoveType == OrderStudentMoveType.ОтправитьВАкадем || + result.OrderStudentMoveType == OrderStudentMoveType.ПродлитьАкадем) + && student.StudentState != StudentState.Академ) + { + st.StudentState = StudentState.Академ; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + } + + if (result.OrderStudentMoveType == OrderStudentMoveType.ВосстановитьИзАкадема && student.StudentState != StudentState.Учится) + { + st.StudentState = StudentState.Учится; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + } + + if ((result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьВСвязиСПереводом || + result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема || + result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьЗаНеуспевамость || + result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьПоСобственному || + result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению) && + student.StudentState != StudentState.Отчислен) + { + st.StudentState = result.OrderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению ? StudentState.Завершил : StudentState.Отчислен; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + var delete = studentLogic.Delete(new StudentGetBindingModel { Id = student.Id }); + if (!delete) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка удаления студента", $"Не удалось удалить студента {studentName}")); + return null; + } + delete = userLogic.Delete(new UserGetBindingModel { Id = student.UserId }); + if (!delete) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка удаления пользователя по студенту", $"Не удалось удалить пользователя по студенту {studentName}")); + return null; + } + } + + if (result.OrderStudentMoveType == OrderStudentMoveType.Восстановить && student.StudentState != StudentState.Учится) + { + st.StudentState = StudentState.Учится; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + } + + if (result.OrderStudentMoveType == OrderStudentMoveType.УбратьПоПереводу && student.StudentState != StudentState.Ушел) + { + st.StudentState = StudentState.Ушел; + student = studentLogic.Update(st); + if (student == null) + { + Errors.AddRange(studentLogic.Errors); + Errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); + return null; + } + } + } + return result; + } } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs index 4bae380..a1bc96b 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs @@ -15,14 +15,13 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; -using System.Threading.Tasks; namespace DepartmentBusinessLogic.BusinessLogics { - /// - /// Логика работы с историями синхронизации приказов - /// - public class OrderSyncHistoryBusinessLogic : GenericBusinessLogic + /// + /// Логика работы с историями синхронизации приказов + /// + public class OrderSyncHistoryBusinessLogic : GenericBusinessLogic { private OrderSyncHistoryRecordBusinessLogic _recordLogic; @@ -40,9 +39,9 @@ namespace DepartmentBusinessLogic.BusinessLogics public OrderSyncHistoryBusinessLogic(IOrderSyncHistoryService service) : base(service, "Синхронизация Приказов", AccessOperation.СинхронизацияПриказов) { } - public async Task SyncOrders() + public bool SyncOrders() { - var history = await CreateAsync(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); + var history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); if (history == null) { Errors.Add(("Ошибка создание истории", "Не удалось создать историю")); @@ -57,12 +56,12 @@ namespace DepartmentBusinessLogic.BusinessLogics _orderStudentRecordLogic = DependencyManager.Instance.Resolve(); _userLogic = DependencyManager.Instance.Resolve(); - var address = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" }))?.List?.FirstOrDefault(); + var address = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" })?.List?.FirstOrDefault(); if (address == null || address.Value.IsEmpty()) { Errors = _enviromentSettingLogic.Errors; Errors.Add(("Ошибка получения данных", "Не удалось получить адрес серверая для получения приказов по студентам")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -70,12 +69,12 @@ namespace DepartmentBusinessLogic.BusinessLogics return false; } - var username = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" }))?.List?.FirstOrDefault(); + var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault(); if (username == null || username.Value.IsEmpty()) { Errors = _enviromentSettingLogic.Errors; Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -83,12 +82,12 @@ namespace DepartmentBusinessLogic.BusinessLogics return false; } - var password = (await _enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" }))?.List?.FirstOrDefault(); + var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault(); if (password == null || password.Value.IsEmpty()) { Errors = _enviromentSettingLogic.Errors; Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -107,11 +106,11 @@ namespace DepartmentBusinessLogic.BusinessLogics // авторизация // получение списка студентов - HttpResponseMessage response = await client.GetAsync($"{address.Value}/univer_Testing/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment"); + HttpResponseMessage response = client.GetAsync($"{address.Value}/univer/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment").Result; if (!response.IsSuccessStatusCode) { Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с сервера")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -121,7 +120,7 @@ namespace DepartmentBusinessLogic.BusinessLogics var studentFromServer = JsonSerializer.Deserialize(response.Content.ReadAsStringAsync().Result); if (studentFromServer.CurrentStudentsList.Count == 0) { - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = "Полученный список студентов пустой" @@ -129,12 +128,12 @@ namespace DepartmentBusinessLogic.BusinessLogics return true; } - var groups = await _groupsLogic.GetListAsync(new StudentGroupGetBindingModel()); + var groups = _groupsLogic.GetList(new StudentGroupGetBindingModel()); if (groups == null || groups.List == null) { Errors = _groupsLogic.Errors; Errors.Add(("Ошибка получения данных", "Не удалось получить список групп")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -142,12 +141,12 @@ namespace DepartmentBusinessLogic.BusinessLogics return false; } - var students = await _studentLogic.GetListAsync(new StudentGetBindingModel()); + var students = _studentLogic.GetList(new StudentGetBindingModel()); if (students == null || students.List == null) { Errors = _studentLogic.Errors; Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -161,12 +160,12 @@ namespace DepartmentBusinessLogic.BusinessLogics // студент не найден, значит он ушел с кафедры, выясняем почему if (studentSync == null) { - await SyncStudentOrders(history, student, groups.List, client, address.Value); + SyncStudentOrders(history, student, groups.List, client, address.Value); } // не совпадение групп else if (student.StudentGroupName != studentSync.groupName) { - await SyncStudentOrders(history, student, groups.List, client, address.Value); + SyncStudentOrders(history, student, groups.List, client, address.Value); } studentFromServer.CurrentStudentsList.Remove(studentSync); @@ -174,75 +173,93 @@ namespace DepartmentBusinessLogic.BusinessLogics // новые студенты и восстановленцы foreach (var student in studentFromServer.CurrentStudentsList) { - var deletedStudent = await _studentLogic.GetElementAsync(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); + var deletedStudent = _studentLogic.GetElement(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); if (deletedStudent == null && _studentLogic.Errors.FirstOrDefault(x => x.Message == "Элемент удален") != default) { // восстановленец - deletedStudent = await _studentLogic.RestoreAsync(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); + deletedStudent = _studentLogic.Restore(new StudentGetBindingModel { NumberOfBook = student.recordBookName }); if (deletedStudent == null) { var errors = _studentLogic.Errors; errors.Add(("Ошибка при восстановлении студента", $"Не удалось восстановить студента {student.lastName} {student.firstName} {student.patronymicName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) }); continue; } - var deletedUser = await _userLogic.RestoreAsync(new UserGetBindingModel { Id = deletedStudent.UserId }); + var deletedUser = _userLogic.Restore(new UserGetBindingModel { Id = deletedStudent.UserId }); if (deletedUser == null) { var errors = _userLogic.Errors; errors.Add(("Ошибка при восстановлении пользователя студента", $"Не удалось восстановить пользователя студента {student.lastName} {student.firstName} {student.patronymicName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _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); + SyncStudentOrders(history, deletedStudent, groups.List, client, address.Value); continue; } - var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; - var result = await _userLogic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); - - var newuser = await _userLogic.CreateAsync(new UserSetBindingModel + var user = _userLogic.GetElement(new UserGetBindingModel { - Login = userName, - Password = student.recordBookName + Login = student.recordBookName }); - if (newuser == null) + if (user == null) { - var errors = _userLogic.Errors; - errors.Add(("Ошибка создания пользователя под студента", $"Не удалось создать пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + if (_userLogic.Errors.Count > 0) { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) + 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; + } + + var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; + user = _userLogic.Create(new UserSetBindingModel + { + Login = student.recordBookName, + Password = userName }); - continue; + + if (user == 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; + } } - var newStudent = await _studentLogic.CreateAsync(new StudentSetBindingModel + var newStudent = _studentLogic.Create(new StudentSetBindingModel { Iduniv = student.iduniv, NumberOfBook = student.recordBookName, - UserId = newuser.Id, + UserId = user.Id, FirstName = student.firstName, LastName = student.lastName, Patronymic = student.patronymicName, StudentState = StudentState.Неопределен, - Description = student.presenatationOfRecordBook + Description = string.Empty }); if (newStudent == null) { var errors = _studentLogic.Errors; errors.Add(("Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) @@ -250,17 +267,14 @@ namespace DepartmentBusinessLogic.BusinessLogics continue; } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = $"Добавлен студент {newStudent}" }); - await SyncStudentOrders(history, newStudent, groups.List, client, address.Value); - - studentFromServer.CurrentStudentsList.Remove(student); + SyncStudentOrders(history, newStudent, groups.List, client, address.Value); } - return true; } @@ -273,13 +287,13 @@ namespace DepartmentBusinessLogic.BusinessLogics /// /// /// - private async Task SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, List groups, HttpClient client, string address) + private void SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, List groups, HttpClient client, string address) { - HttpResponseMessage response = await client.GetAsync($"{address}/univer_Testing/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={student.Iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd"); + HttpResponseMessage response = client.GetAsync($"{address}/univer/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={student.Iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd").Result; if (!response.IsSuccessStatusCode) { Errors.Add(("Ошибка получения данных", "Не удалось получить список приказов по студенту")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) @@ -289,24 +303,58 @@ namespace DepartmentBusinessLogic.BusinessLogics var syncOrders = JsonSerializer.Deserialize(response.Content.ReadAsStringAsync().Result); foreach (var syncOrder in syncOrders.StudentOrders) { + if (syncOrder.markOfApprove.ToLower() != "true") + { + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = $"Приказ {syncOrder.clericNumber} от {syncOrder.clericDate} ({syncOrder.orderTypeName}) по студенту {student} не утврежден " + }); + continue; + } + if (syncOrder.clericNumber.IsEmpty()) + { + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = $"Приказ без номера от {syncOrder.clericDate} ({student})" + }); + continue; + } + if (syncOrder.clericDate.IsEmpty()) + { + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = $"Приказ {syncOrder.clericNumber} - неизвестная дата ({student})" + }); + continue; + } var orderType = GetOrderType(syncOrder.orderTypeName); // пропускаем приказы, которые нас не интересуют 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}" + }); continue; } // пытаемся найти приказ - var order = await _orderLogic.GetElementAsync(new OrderGetBindingModel + var order = _orderLogic.GetElement(new OrderGetBindingModel { - OrderNumber = syncOrder.clericNumber, - OrderDate = Convert.ToDateTime(syncOrder.clericDate) + OrderNumber = syncOrder.clericNumber }); if (order == null) { // если не нашли - пытаемся создать - order = await _orderLogic.CreateAsync(new OrderSetBindingModel + order = _orderLogic.Create(new OrderSetBindingModel { OrderNumber = syncOrder.clericNumber, OrderDate = Convert.ToDateTime(syncOrder.clericDate), @@ -316,7 +364,7 @@ namespace DepartmentBusinessLogic.BusinessLogics { var errors = _orderLogic.Errors; errors.Add(("Ошибка добавления приказа", $"Не удалось добавить приказ {syncOrder.clericNumber} {syncOrder.clericDate}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) @@ -325,24 +373,6 @@ namespace DepartmentBusinessLogic.BusinessLogics } } - // ищем в приказе запись по студенту - var studentOrder = await _orderStudentRecordLogic.GetElementAsync(new OrderStudentRecordGetBindingModel - { - OrderId = order.Id, - StudentId = student.Id - }); - - // если такой приказ по студенту уже есть, просто пропускаем - if (studentOrder != null) - { - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"Нерспознанный приказ {syncOrder.orderTypeName} для студента {student}" - }); - continue; - } - Guid? studentGroupFromId = null; Guid? studentGroupToId = null; string info = string.Empty; @@ -355,7 +385,8 @@ namespace DepartmentBusinessLogic.BusinessLogics studentGroupToId = groups.FirstOrDefault(x => x.ToString() == syncOrder.groupNameAfter)?.Id; } // игнорируем приказы, не связанные с нашими группами - if (!studentGroupFromId.HasValue && !studentGroupToId.HasValue) + if (!studentGroupFromId.HasValue && syncOrder.groupNameBefore.IsNotEmpty() + && !studentGroupToId.HasValue && syncOrder.groupNameAfter.IsNotEmpty()) { continue; } @@ -367,23 +398,22 @@ namespace DepartmentBusinessLogic.BusinessLogics if (syncOrder.orderSubTypeName == "Распределение по группам") { orderStudentMoveType = OrderStudentMoveType.Распределить; - info = $"Распределение студента {student} в группу {groups.First(x => x.Id == studentGroupToId)}"; + info = $"Распределение студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; } - // внутренний перевод else if (studentGroupFromId.HasValue && studentGroupToId.HasValue) { orderStudentMoveType = OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры; - info = $"Перевод студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)} в группу {groups.First(x => x.Id == studentGroupToId)}"; + 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.First(x => x.Id == studentGroupToId)}"; + info = $"Перевод студента {student} c группы {syncOrder.groupNameBefore} другой кафедры в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; } else if (studentGroupFromId.HasValue && !studentGroupToId.HasValue) { orderStudentMoveType = OrderStudentMoveType.УбратьПоПереводу; - info = $"Перевод студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)} на другую кафедру"; + info = $"Перевод студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} на другую кафедру"; } break; case "Зачисление в вуз вне приемной кампании": @@ -400,16 +430,20 @@ namespace DepartmentBusinessLogic.BusinessLogics break; case "Перевод на следующий курс": orderStudentMoveType = OrderStudentMoveType.ПеревестиНаСтаршийКурс; - info = $"Перевод студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)} на следующий курс в группу {groups.First(x => x.Id == studentGroupToId)}"; + info = $"Перевод студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} на следующий курс в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; break; //case "Завершение обучения": // уточнить приказ // orderStudentMoveType = OrderStudentMoveType.ОтчислитьПоСобственному; // info = $"Отчисление студента {student} в связи с окончанием обучения"; // break; case "Уход в академический отпуск": - // дата + DateTime? date = null; + if (syncOrder.dateEnd.IsNotEmpty()) + { + date = Convert.ToDateTime(syncOrder.dateEnd); + } orderStudentMoveType = OrderStudentMoveType.ОтправитьВАкадем; - info = $"Уход в АО студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)}"; + info = $"Уход в АО студента {student} из группы {groups.FirstOrDefault(x => x.Id == studentGroupFromId)} до {date?.ToShortDateString() ?? string.Empty}"; break; case "Продление академического отпуска": orderStudentMoveType = OrderStudentMoveType.ПродлитьАкадем; @@ -417,38 +451,56 @@ namespace DepartmentBusinessLogic.BusinessLogics break; case "Восстановление из академического отпуска": orderStudentMoveType = OrderStudentMoveType.ВосстановитьИзАкадема; - info = $"Выход из АО студента {student} в группу {groups.First(x => x.Id == studentGroupToId)}"; + info = $"Выход из АО студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; break; - //case "Отчисление по собственному": // уточнить приказ - // orderStudentMoveType = OrderStudentMoveType.ОтчислитьПоСобственному; - // info = $"Отчисление студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)} по собственному желанию"; - // break; - //case "Отчисление за неуспеваемость": // уточнить приказ - // orderStudentMoveType = OrderStudentMoveType.ОтчислитьЗаНеуспевамость; - // info = $"Отчисление студента {student} из группы {groups.First(x => x.Id == studentGroupFromId)} за неуспеваемость"; - // break; //case "Отчисление по невыходу из академа": // уточнить приказ // orderStudentMoveType = OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема; // info = $"Отчисление студента {student} по невыходу из академа"; // break; case "Отчисление": - { - + if (syncOrder.reason == "за невыполнение учебного плана") + { + 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} в группу {groups.First(x => x.Id == studentGroupToId)}"; + info = $"Восстановление отчисленного студента {student} в группу {groups.FirstOrDefault(x => x.Id == studentGroupToId)}"; break; } if (orderStudentMoveType == OrderStudentMoveType.Неопределено) + { + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = $"Неизветсный приказ {syncOrder.orderTypeName} ({syncOrder.reason}) по студенту {student}" + }); + continue; + } + + // ищем в приказе запись по студенту + var studentOrder = _orderStudentRecordLogic.GetElement(new OrderStudentRecordGetBindingModel + { + OrderId = order.Id, + StudentId = student.Id, + OrderStudentMoveType = orderStudentMoveType + }); + + // если такой приказ по студенту уже есть, просто пропускаем + if (studentOrder != null) { continue; } // создаем, если не нашли - studentOrder = await _orderStudentRecordLogic.CreateAsync(new OrderStudentRecordSetBindingModel + studentOrder = _orderStudentRecordLogic.Create(new OrderStudentRecordSetBindingModel { OrderId = order.Id, StudentId = student.Id, @@ -461,7 +513,7 @@ namespace DepartmentBusinessLogic.BusinessLogics { var errors = _orderStudentRecordLogic.Errors; errors.Add(("Ошибка добавления записи приказа по студенту", $"Не удалось добавить запись приказа {syncOrder.orderSubTypeName} по студенту {student}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) @@ -469,192 +521,7 @@ namespace DepartmentBusinessLogic.BusinessLogics continue; } - var st = Mapper.MapToClass(student, true); - var studentName = student.ToString(); - if (student.StudentGroupId != studentGroupToId) - { - st.StudentGroupId = studentGroupToId; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить группу у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменилась группа на {student.StudentGroupName}" - }); - } - - if ((orderStudentMoveType == OrderStudentMoveType.ЗачислитьПоПриказу || orderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводу - || orderStudentMoveType == OrderStudentMoveType.ПринятьПоПереводусДругогоВуза || orderStudentMoveType == OrderStudentMoveType.ПеревестиНаДругоеНаправлениеКафедры) - && student.StudentState != StudentState.Учится) - { - st.StudentState = StudentState.Учится; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {StudentState.Учится}" - }); - } - - if ((orderStudentMoveType == OrderStudentMoveType.ОтправитьВАкадем || orderStudentMoveType == OrderStudentMoveType.ПродлитьАкадем) - && student.StudentState != StudentState.Академ) - { - st.StudentState = StudentState.Академ; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {StudentState.Академ}" - }); - } - - if (orderStudentMoveType == OrderStudentMoveType.ВосстановитьИзАкадема && student.StudentState != StudentState.Учится) - { - st.StudentState = StudentState.Учится; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {StudentState.Учится}" - }); - } - - if ((orderStudentMoveType == OrderStudentMoveType.ОтчислитьВСвязиСПереводом || orderStudentMoveType == OrderStudentMoveType.ОтчислитьЗаНевыходСАкадема - || orderStudentMoveType == OrderStudentMoveType.ОтчислитьЗаНеуспевамость || orderStudentMoveType == OrderStudentMoveType.ОтчислитьПоСобственному - || orderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению) && student.StudentState != StudentState.Отчислен) - { - st.StudentState = orderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению ? StudentState.Завершил : StudentState.Отчислен; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {(orderStudentMoveType == OrderStudentMoveType.ОтчислитьПоЗавершению ? StudentState.Завершил : StudentState.Отчислен)}" - }); - var result = await _studentLogic.DeleteAsync(new StudentGetBindingModel { Id = student.Id }); - if (!result) - { - var errors = _userLogic.Errors; - errors.Add(("Ошибка удаления студента", $"Не удалось удалить студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - result = await _userLogic.DeleteAsync(new UserGetBindingModel { Id = student.UserId }); - if (!result) - { - var errors = _userLogic.Errors; - errors.Add(("Ошибка удаления пользователя по студенту", $"Не удалось удалить пользователя по студенту {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - } - - if (orderStudentMoveType == OrderStudentMoveType.Восстановить && student.StudentState != StudentState.Учится) - { - st.StudentState = StudentState.Учится; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {StudentState.Учится}" - }); - } - - if (orderStudentMoveType == OrderStudentMoveType.УбратьПоПереводу && student.StudentState != StudentState.Ушел) - { - st.StudentState = StudentState.Ушел; - student = await _studentLogic.UpdateAsync(st); - if (student == null) - { - var errors = _studentLogic.Errors; - errors.Add(("Ошибка изменения по студенту", $"Не удалось изменить статус у студента {studentName}")); - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = $"У студента {student} сменился статус на {StudentState.Ушел}" - }); - } - - await _recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel { OrderSyncHistoryId = history.Id, Information = $"Добавили запись к приказу {order.OrderNumber} по студенту {student} с формулировкой {info}" diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/HelperModels/StudentOrderSyncModel.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/HelperModels/StudentOrderSyncModel.cs index bf76472..e87ff36 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/HelperModels/StudentOrderSyncModel.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/HelperModels/StudentOrderSyncModel.cs @@ -9,6 +9,10 @@ public string clericDate { get; set; } + public string markOfDeletion { get; set; } + + public string markOfApprove { get; set; } + public string orderTypeName { get; set; } public string orderSubTypeName { get; set; } @@ -16,5 +20,11 @@ public string groupNameBefore { get; set; } public string groupNameAfter { get; set; } + + public string dateStart { get; set; } + + public string dateEnd { get; set; } + + public string reason { get; set; } } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderStudentRecordViewModel.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderStudentRecordViewModel.cs index f58f2da..ed77305 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderStudentRecordViewModel.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderStudentRecordViewModel.cs @@ -27,11 +27,11 @@ namespace DepartmentBusinessLogic.ViewModels [ViewModelControlElementProperty("Из группы", ControlType.ControlGuid, MustHaveValue = false, ReadOnly = false, ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlStudentGroupList, DepartmentWindowsDesktop")] [MapConfiguration("StudentGroupFromId")] - public Guid StudentGroupFromId { get; set; } + public Guid? StudentGroupFromId { get; set; } [ViewModelControlElementProperty("В группу", ControlType.ControlGuid, MustHaveValue = false, ReadOnly = false, ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlStudentGroupList, DepartmentWindowsDesktop")] [MapConfiguration("StudentGroupToId")] - public Guid StudentGroupToId { get; set; } + public Guid? StudentGroupToId { get; set; } [ViewModelControlElementProperty("Тип приказа", ControlType.ControlEnum, MustHaveValue = true)] [MapConfiguration("OrderStudentMoveType")] diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderSyncHistoryViewModels.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderSyncHistoryViewModels.cs index d5286db..33e55dc 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderSyncHistoryViewModels.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/OrderSyncHistoryViewModels.cs @@ -1,6 +1,7 @@ using ModuleTools.Attributes; using ModuleTools.Enums; using ModuleTools.ViewModels; +using System; namespace DepartmentBusinessLogic.ViewModels { @@ -17,14 +18,11 @@ namespace DepartmentBusinessLogic.ViewModels ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlOrderSyncHistoryRecordList, DepartmentWindowsDesktop")] public class OrderSyncHistoryViewModel : ElementViewModel { - [ViewModelControlListProperty("Дата", ColumnWidth = 100, DefaultCellStyleFormat = "dd.MM.yyyy")] [ViewModelControlElementProperty("Дата", ControlType.ControlDateTime, MustHaveValue = true, ReadOnly = true)] [MapConfiguration("SyncDate")] - public string SyncDate { get; set; } + public DateTime SyncDate { get; set; } - [ViewModelControlListProperty("События")] - [ViewModelControlElementProperty("События", ControlType.ControlText, MustHaveValue = true, ReadOnly = true, Width = 300, Height = 500)] - [MapConfiguration("History")] - public string History { get; set; } + [ViewModelControlListProperty("Дата")] + public string SyncDateTitle => $"Синхронизация данных от {SyncDate.ToString("dd.MM.yyyy HH:mm")}"; } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/StudentGroupViewModels.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/StudentGroupViewModels.cs index 235af9b..56a4e5b 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/StudentGroupViewModels.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/ViewModels/StudentGroupViewModels.cs @@ -14,11 +14,9 @@ namespace DepartmentBusinessLogic.ViewModels /// /// Элемент учебная группа /// - [ViewModelControlElementClass(HaveDependenceEntities = true, Width = 800, Height = 500)] + [ViewModelControlElementClass(HaveDependenceEntities = true, Width = 1000, Height = 900)] [ViewModelControlElementDependenceEntity(Title = "Студенты", Order = 1, ParentPropertyName = "StudentGroupId", ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlStudentList, DepartmentWindowsDesktop")] - [ViewModelControlElementDependenceEntity(Title = "Приказы", Order = 1, ParentPropertyName = "StudentGroupId", - ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlOrderStudentRecordList, DepartmentWindowsDesktop")] public class StudentGroupViewModel : ElementViewModel { [ViewModelControlElementProperty("Направление", ControlType.ControlGuid, MustHaveValue = true, ReadOnly = false, ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlEducationDirectionList, DepartmentWindowsDesktop")] @@ -51,6 +49,10 @@ namespace DepartmentBusinessLogic.ViewModels [MapConfiguration("GroupNumber")] public int GroupNumber { get; set; } + [ViewModelControlListProperty("Количество студентов")] + [MapConfiguration("Students.Count", IsDifficle = true)] + public int StudentCount { get; set; } + [ViewModelControlElementProperty("Куратор", ControlType.ControlGuid, MustHaveValue = false, ReadOnly = false, ControlTypeObject = "DepartmentWindowsDesktop.EntityControls.ControlLecturerList, DepartmentWindowsDesktop")] [MapConfiguration("LecturerId")] public Guid? LecturerId { get; set; } diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderService.cs index 9c2ac6a..78b2e6d 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderService.cs @@ -51,7 +51,7 @@ namespace DepartmentDatabaseImplementation.Implementations protected override bool AdditionalCheckForSingleGet(OrderGetBindingModel model) { - if (model.OrderDate.HasValue && model.OrderNumber.IsNotEmpty()) + if (model.OrderNumber.IsNotEmpty()) { return true; } @@ -60,9 +60,9 @@ namespace DepartmentDatabaseImplementation.Implementations protected override Order GetSingleRecord(IQueryable list, OrderGetBindingModel model) { - if (model.OrderDate.HasValue && model.OrderNumber.IsNotEmpty()) + if (model.OrderNumber.IsNotEmpty()) { - return list.FirstOrDefault(x => x.OrderDate == model.OrderDate && x.OrderNumber == model.OrderNumber); + return list.FirstOrDefault(x => x.OrderNumber == model.OrderNumber); } return base.GetSingleRecord(list, model); } diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderStudentRecordService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderStudentRecordService.cs index 421f03b..1c69733 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderStudentRecordService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderStudentRecordService.cs @@ -49,7 +49,7 @@ namespace DepartmentDatabaseImplementation.Implementations protected override bool AdditionalCheckForSingleGet(OrderStudentRecordGetBindingModel model) { - if (model.OrderId.HasValue && model.StudentId.HasValue) + if (model.OrderId.HasValue && model.StudentId.HasValue && model.OrderStudentMoveType.HasValue) { return true; } @@ -58,9 +58,9 @@ namespace DepartmentDatabaseImplementation.Implementations protected override OrderStudentRecord GetSingleRecord(IQueryable list, OrderStudentRecordGetBindingModel model) { - if (model.OrderId.HasValue && model.StudentId.HasValue) + if (model.OrderId.HasValue && model.StudentId.HasValue && model.OrderStudentMoveType.HasValue) { - return list.FirstOrDefault(x => x.OrderId == model.OrderId && x.StudentId == model.StudentId); + return list.FirstOrDefault(x => x.OrderId == model.OrderId && x.StudentId == model.StudentId && x.OrderStudentMoveType == (int)model.OrderStudentMoveType); } return base.GetSingleRecord(list, model); } diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryRecordService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryRecordService.cs index 557742c..75f5161 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryRecordService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryRecordService.cs @@ -9,26 +9,25 @@ using ModuleTools.Enums; using ModuleTools.Models; using System; using System.Linq; -using System.Threading.Tasks; namespace DepartmentDatabaseImplementation.Implementations { - /// - /// Реализация IOrderSyncHistoryRecordService - /// - public class OrderSyncHistoryRecordService : IOrderSyncHistoryRecordService + /// + /// Реализация IOrderSyncHistoryRecordService + /// + public class OrderSyncHistoryRecordService : IOrderSyncHistoryRecordService { - public async Task CreateAsync(OrderSyncHistoryRecordSetBindingModel model) + public OperationResultModel Create(OrderSyncHistoryRecordSetBindingModel model) { using var context = DatabaseManager.GetContext; var entity = Mapper.MapToClass(model, true); - await context.OrderSyncHistoryRecords.AddAsync(entity); - await context.SaveChangesAsync(); + context.OrderSyncHistoryRecords.Add(entity); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } - public async Task DeleteAsync(OrderSyncHistoryRecordGetBindingModel model) + public OperationResultModel Delete(OrderSyncHistoryRecordGetBindingModel model) { using var context = DatabaseManager.GetContext; var entity = context.OrderSyncHistoryRecords.FirstOrDefault(x => x.Id == model.Id); @@ -37,12 +36,12 @@ namespace DepartmentDatabaseImplementation.Implementations return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); } context.OrderSyncHistoryRecords.Remove(entity); - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(true); } - public async Task ReadAsync(OrderSyncHistoryRecordGetBindingModel model) + public OperationResultModel Read(OrderSyncHistoryRecordGetBindingModel model) { int countPages = 0; using var context = DatabaseManager.GetContext; @@ -69,31 +68,28 @@ namespace DepartmentDatabaseImplementation.Implementations query = query.Include(x => x.OrderSyncHistory); - return await Task.Run(() => + if (model.PageNumber.HasValue && model.PageSize.HasValue) { - if (model.PageNumber.HasValue && model.PageSize.HasValue) - { - countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); - query = query - .Skip(model.PageSize.Value * model.PageNumber.Value) - .Take(model.PageSize.Value); - } - var result = new OrderSyncHistoryRecordListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; + countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); + query = query + .Skip(model.PageSize.Value * model.PageNumber.Value) + .Take(model.PageSize.Value); + } + var result = new OrderSyncHistoryRecordListViewModel + { + MaxCount = countPages, + List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() + }; - return OperationResultModel.Success(result); - }); + return OperationResultModel.Success(result); } - public Task RestoreAsync(OrderSyncHistoryRecordGetBindingModel model) + public OperationResultModel Restore(OrderSyncHistoryRecordGetBindingModel model) { throw new NotImplementedException(); } - public async Task UpdateAsync(OrderSyncHistoryRecordSetBindingModel model) + public OperationResultModel Update(OrderSyncHistoryRecordSetBindingModel model) { using var context = DatabaseManager.GetContext; @@ -104,7 +100,7 @@ namespace DepartmentDatabaseImplementation.Implementations } entity = Mapper.MapToClass(model, entity, true); - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryService.cs index 3d9a5d3..99637f9 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/OrderSyncHistoryService.cs @@ -8,26 +8,25 @@ using ModuleTools.Enums; using ModuleTools.Models; using System; using System.Linq; -using System.Threading.Tasks; namespace DepartmentDatabaseImplementation.Implementations { - /// - /// Реализация IOrderSyncHistoryService - /// - public class OrderSyncHistoryService : IOrderSyncHistoryService + /// + /// Реализация IOrderSyncHistoryService + /// + public class OrderSyncHistoryService : IOrderSyncHistoryService { - public async Task CreateAsync(OrderSyncHistorySetBindingModel model) + public OperationResultModel Create(OrderSyncHistorySetBindingModel model) { using var context = DatabaseManager.GetContext; var entity = Mapper.MapToClass(model, true); - await context.OrderSyncHistories.AddAsync(entity); - await context.SaveChangesAsync(); + context.OrderSyncHistories.Add(entity); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } - public async Task DeleteAsync(OrderSyncHistoryGetBindingModel model) + public OperationResultModel Delete(OrderSyncHistoryGetBindingModel model) { using var context = DatabaseManager.GetContext; using var transaction = context.Database.BeginTransaction(); @@ -40,24 +39,24 @@ namespace DepartmentDatabaseImplementation.Implementations } context.OrderSyncHistories.Remove(entity); - await context.SaveChangesAsync(); + context.SaveChanges(); var records = context.OrderSyncHistoryRecords.Where(x => x.OrderSyncHistoryId == model.Id); context.OrderSyncHistoryRecords.RemoveRange(records); - await context.SaveChangesAsync(); + context.SaveChanges(); - await transaction.CommitAsync(); + transaction.Commit(); } catch (Exception) { - await transaction.RollbackAsync(); + transaction.Rollback(); throw; } return OperationResultModel.Success(true); } - public async Task ReadAsync(OrderSyncHistoryGetBindingModel model) + public OperationResultModel Read(OrderSyncHistoryGetBindingModel model) { int countPages = 0; using var context = DatabaseManager.GetContext; @@ -77,31 +76,28 @@ namespace DepartmentDatabaseImplementation.Implementations query = query.OrderByDescending(x => x.SyncDate); - return await Task.Run(() => + if (model.PageNumber.HasValue && model.PageSize.HasValue) { - if (model.PageNumber.HasValue && model.PageSize.HasValue) - { - countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); - query = query - .Skip(model.PageSize.Value * model.PageNumber.Value) - .Take(model.PageSize.Value); - } - var result = new OrderSyncHistoryListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; + countPages = (int)Math.Ceiling((double)query.Count() / model.PageSize.Value); + query = query + .Skip(model.PageSize.Value * model.PageNumber.Value) + .Take(model.PageSize.Value); + } + var result = new OrderSyncHistoryListViewModel + { + MaxCount = countPages, + List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() + }; - return OperationResultModel.Success(result); - }); + return OperationResultModel.Success(result); } - public Task RestoreAsync(OrderSyncHistoryGetBindingModel model) + public OperationResultModel Restore(OrderSyncHistoryGetBindingModel model) { throw new NotImplementedException(); } - public async Task UpdateAsync(OrderSyncHistorySetBindingModel model) + public OperationResultModel Update(OrderSyncHistorySetBindingModel model) { using var context = DatabaseManager.GetContext; @@ -112,7 +108,7 @@ namespace DepartmentDatabaseImplementation.Implementations } entity = Mapper.MapToClass(model, entity, true); - await context.SaveChangesAsync(); + context.SaveChanges(); return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } diff --git a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/StudentGroupService.cs b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/StudentGroupService.cs index 52dd8a8..b5f82b6 100644 --- a/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/StudentGroupService.cs +++ b/DepartmentPortal/Department/DepartmentDatabaseImplementation.csproj/Implementations/StudentGroupService.cs @@ -57,7 +57,7 @@ namespace DepartmentDatabaseImplementation.Implementations protected override StudentGroup GetUniqueEntity(StudentGroupSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.EducationDirectionId == model.EducationDirectionId && x.AcademicCourse == (int)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); + protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.EducationDirection).Include(x => x.Lecturer).Include(x => x.Students); protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.EducationDirection.Cipher).ThenBy(x => x.AcademicCourse).ThenBy(x => x.GroupNumber); } diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Discipline/ControlDisciplineList.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Discipline/ControlDisciplineList.cs index 40b8adc..eb7d2f8 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Discipline/ControlDisciplineList.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Discipline/ControlDisciplineList.cs @@ -12,52 +12,55 @@ using System.Linq; namespace DepartmentWindowsDesktop.EntityControls { - /// - /// Реализация контрола для списка дисциплин - /// - public partial class ControlDisciplineList : - GenericControlEntityList, - IGenericControlEntityList - { - private readonly DisciplineBlockBusinessLogic _disciplineBlockBusinessLogic; + /// + /// Реализация контрола для списка дисциплин + /// + public partial class ControlDisciplineList : + GenericControlEntityList, + IGenericControlEntityList + { + private readonly DisciplineBlockBusinessLogic _disciplineBlockBusinessLogic; - public ControlDisciplineList() - { - InitializeComponent(); - _disciplineBlockBusinessLogic = DependencyManager.Instance.Resolve(); - Title = "Дисциплины"; - ControlId = new Guid("1731f50b-b20b-44c4-aa56-b335764fae7a"); - AccessOperation = AccessOperation.Дисциплины; - ControlViewEntityElement = new ControlDisciplineElement(); - _genericControlViewEntityList = this; - FillSearchPanel(); - } + public ControlDisciplineList() + { + InitializeComponent(); + _disciplineBlockBusinessLogic = DependencyManager.Instance.Resolve(); + Title = "Дисциплины"; + ControlId = new Guid("1731f50b-b20b-44c4-aa56-b335764fae7a"); + AccessOperation = AccessOperation.Дисциплины; + ControlViewEntityElement = new ControlDisciplineElement(); + _genericControlViewEntityList = this; + FillSearchPanel(); + } - public IControl GetInstanceGenericControl() => new ControlDisciplineList() { ControlId = Guid.NewGuid() }; + public IControl GetInstanceGenericControl() => new ControlDisciplineList() { ControlId = Guid.NewGuid() }; - public ControlViewEntityListConfiguration GetConfigControl() => new() - { - PaginationOn = true, - PageNamesForPagination = _disciplineBlockBusinessLogic.GetListAsync(new DisciplineBlockGetBindingModel()).Result?.List?.Select(x => - new PageNamesForPaginationModel - { - Key = x.Id, - Value = x.Title - })?.ToList(), - ParentPropertyName = "DisciplineBlockId" - }; + public ControlViewEntityListConfiguration GetConfigControl() + { + return new ControlViewEntityListConfiguration() + { + PaginationOn = true, + PageNamesForPagination = _disciplineBlockBusinessLogic.GetList(new DisciplineBlockGetBindingModel())?.List?.Select(x => + new PageNamesForPaginationModel + { + Key = x.Id, + Value = x.Title + })?.ToList(), + ParentPropertyName = "DisciplineBlockId" + }; + } - private void FillSearchPanel() - { - var control = new BaseControlString("DisciplineNameForSearch", false, false, 0) - { - Location = new System.Drawing.Point(10, 10), - Size = new System.Drawing.Size(400, 23), - Name = "SearchDisciplineName", - TabIndex = 0 - }; - control.SetTitleWidth(control.SetTitle("Название:")); - panelSearchControls.Controls.Add(control); - } - } + private void FillSearchPanel() + { + var control = new BaseControlString("DisciplineNameForSearch", false, false, 0) + { + Location = new System.Drawing.Point(10, 10), + Size = new System.Drawing.Size(400, 23), + Name = "SearchDisciplineName", + TabIndex = 0 + }; + control.SetTitleWidth(control.SetTitle("Название:")); + panelSearchControls.Controls.Add(control); + } + } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Employee/ControlEmployeeElement.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Employee/ControlEmployeeElement.cs index d935658..772cde1 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Employee/ControlEmployeeElement.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Employee/ControlEmployeeElement.cs @@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics; using SecurityBusinessLogic.ViewModels; using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace DepartmentWindowsDesktop.EntityControls { - /// - /// Реализация контрола для сотрудника - /// - public partial class ControlEmployeeElement : + /// + /// Реализация контрола для сотрудника + /// + public partial class ControlEmployeeElement : GenericControlEntityElement, IGenericControlEntityElement { @@ -38,22 +37,22 @@ namespace DepartmentWindowsDesktop.EntityControls { ControlOnMoveElem = new Dictionary { - { "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsync(); }) }, - { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } + { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) }, + { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) } } }; /// /// Поиск пользователя под учетку, либо добавление нового, если не найдено /// - private async Task AddUserAsync() + private void AddUser() { var model = new EmployeeSetBindingModel(); if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; - var result = await logic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); + var result = logic.GetList(new UserGetBindingModel { UserNameForSearch = userName }); if (result != null) { if (result.List.Count > 1) @@ -67,7 +66,7 @@ namespace DepartmentWindowsDesktop.EntityControls } else { - var newuser = await logic.CreateAsync(new UserSetBindingModel + var newuser = logic.Create(new UserSetBindingModel { Login = userName, Password = model.DateBirth.ToShortDateString(), @@ -92,7 +91,7 @@ namespace DepartmentWindowsDesktop.EntityControls /// /// Сброс пароля пользователя /// - private async Task PasswordResetAsync() + private void PasswordReset() { if (_element == null) { @@ -102,14 +101,14 @@ namespace DepartmentWindowsDesktop.EntityControls if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); - var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); + var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId }); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); return; } user.Password = model.DateBirth.ToShortDateString(); - user = await logic.UpdateAsync(Mapper.MapToClass(user, true)); + user = logic.Update(Mapper.MapToClass(user, true)); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Lecturer/ControlLecturerElement.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Lecturer/ControlLecturerElement.cs index 13e48dc..069f0e3 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Lecturer/ControlLecturerElement.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Lecturer/ControlLecturerElement.cs @@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics; using SecurityBusinessLogic.ViewModels; using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace DepartmentWindowsDesktop.EntityControls { - /// - /// Реализация контрола для преподавателя - /// - public partial class ControlLecturerElement : + /// + /// Реализация контрола для преподавателя + /// + public partial class ControlLecturerElement : GenericControlEntityElement, IGenericControlEntityElement { @@ -38,22 +37,22 @@ namespace DepartmentWindowsDesktop.EntityControls { ControlOnMoveElem = new Dictionary { - { "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsunc(); }) }, - { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } + { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) }, + { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) } } }; /// /// Поиск пользователя под учетку, либо добавление нового, если не найдено /// - private async Task AddUserAsunc() + private void AddUser() { var model = new LecturerSetBindingModel(); if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; - var result = await logic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); + var result = logic.GetList(new UserGetBindingModel { UserNameForSearch = userName }); if (result != null) { if (result.List.Count > 1) @@ -67,7 +66,7 @@ namespace DepartmentWindowsDesktop.EntityControls } else { - var newuser = await logic.CreateAsync(new UserSetBindingModel + var newuser = logic.Create(new UserSetBindingModel { Login = userName, Password = model.DateBirth.ToShortDateString(), @@ -92,7 +91,7 @@ namespace DepartmentWindowsDesktop.EntityControls /// /// Сброс пароля пользователя /// - private async Task PasswordResetAsync() + private void PasswordReset() { if (_element == null) { @@ -102,14 +101,14 @@ namespace DepartmentWindowsDesktop.EntityControls if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); - var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); + var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId }); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); return; } user.Password = model.DateBirth.ToShortDateString(); - user = await logic.UpdateAsync(Mapper.MapToClass(user, true)); + user = logic.Update(Mapper.MapToClass(user, true)); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderStudentRecord/ControlOrderStudentRecordList.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderStudentRecord/ControlOrderStudentRecordList.cs index d2dd19e..b9edc17 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderStudentRecord/ControlOrderStudentRecordList.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderStudentRecord/ControlOrderStudentRecordList.cs @@ -22,7 +22,7 @@ namespace DepartmentWindowsDesktop.EntityControls Title = "Приказы"; ControlId = new Guid("1aa8cf1f-96b0-47aa-bd20-d1563d840534"); AccessOperation = AccessOperation.Приказы; - ControlViewEntityElement = new ControlOrderElement(); + ControlViewEntityElement = new ControlOrderStudentRecordElement(); _genericControlViewEntityList = this; } diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistory/ControlOrderSyncHistoryList.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistory/ControlOrderSyncHistoryList.cs index 09756b7..9cc2cc1 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistory/ControlOrderSyncHistoryList.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistory/ControlOrderSyncHistoryList.cs @@ -9,14 +9,13 @@ using DesktopTools.Models; using ModuleTools.Enums; using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace DepartmentWindowsDesktop.EntityControls { - /// - /// Реализация контрола для списка историй синхронизации приказов - /// - public partial class ControlOrderSyncHistoryList : + /// + /// Реализация контрола для списка историй синхронизации приказов + /// + public partial class ControlOrderSyncHistoryList : GenericControlEntityList, IGenericControlEntityList { @@ -26,7 +25,7 @@ namespace DepartmentWindowsDesktop.EntityControls Title = "Синхронизация Приказов"; ControlId = new Guid("7b857c17-405e-40fb-961f-7fe74fddf84e"); AccessOperation = AccessOperation.СинхронизацияПриказов; - ControlViewEntityElement = new ControlPostElement(); + ControlViewEntityElement = new ControlOrderSyncHistoryElement(); _genericControlViewEntityList = this; } @@ -44,7 +43,7 @@ namespace DepartmentWindowsDesktop.EntityControls }, ControlOnMoveElem = new() { - { "ToolStripMenuItemSyncOrders", ("Синхронизировать студентов", async (object sender, EventArgs e) => { await SyncOrders(); }) } + { "ToolStripMenuItemSyncOrders", ("Синхронизировать студентов", (object sender, EventArgs e) => { SyncOrders(); }) } } }; @@ -52,13 +51,17 @@ namespace DepartmentWindowsDesktop.EntityControls /// Синхронизация приказов /// /// - private async Task SyncOrders() + private void SyncOrders() { - var flag = await _businessLogic.SyncOrders(); + var flag = _businessLogic.SyncOrders(); if (!flag) { DialogHelper.MessageException(_businessLogic.Errors, "Ошибки при синхронизации"); } + else + { + DialogHelper.MessageInformation("Завершено успешно", "Синхронизация приказов"); + } } } } \ No newline at end of file diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistoryRecord/ControlOrderSyncHistoryRecordList.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistoryRecord/ControlOrderSyncHistoryRecordList.cs index 99fe91d..29ef4bb 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistoryRecord/ControlOrderSyncHistoryRecordList.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/OrderSyncHistoryRecord/ControlOrderSyncHistoryRecordList.cs @@ -24,7 +24,7 @@ namespace DepartmentWindowsDesktop.EntityControls Title = "Записи Синхронизации Приказов"; ControlId = new Guid("8d18e9fa-f056-47c8-b83d-f06f6bf553c2"); AccessOperation = AccessOperation.СинхронизацияПриказов; - ControlViewEntityElement = new ControlPostElement(); + ControlViewEntityElement = new ControlOrderSyncHistoryRecordElement(); _genericControlViewEntityList = this; } diff --git a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Student/ControlStudentElement.cs b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Student/ControlStudentElement.cs index 7e45b20..f982845 100644 --- a/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Student/ControlStudentElement.cs +++ b/DepartmentPortal/Department/DepartmentWindowsDesktop/EntityControls/Student/ControlStudentElement.cs @@ -13,14 +13,13 @@ using SecurityBusinessLogic.BusinessLogics; using SecurityBusinessLogic.ViewModels; using System; using System.Collections.Generic; -using System.Threading.Tasks; namespace DepartmentWindowsDesktop.EntityControls { - /// - /// Реализация контрола для студента - /// - public partial class ControlStudentElement : + /// + /// Реализация контрола для студента + /// + public partial class ControlStudentElement : GenericControlEntityElement, IGenericControlEntityElement { @@ -38,61 +37,54 @@ namespace DepartmentWindowsDesktop.EntityControls { ControlOnMoveElem = new Dictionary { - { "ToolStripMenuItemAddUser", ("Добавить пользователя", async (object sender, EventArgs e) => { await AddUserAsync(); }) }, - { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", async (object sender, EventArgs e) => { await PasswordResetAsync(); }) } + { "ToolStripMenuItemAddUser", ("Добавить пользователя", (object sender, EventArgs e) => { AddUser(); }) }, + { "ToolStripMenuItemPasswordReset", ("Сброс пароля пользователя", (object sender, EventArgs e) => { PasswordReset(); }) } } }; /// /// Поиск пользователя под учетку, либо добавление нового, если не найдено /// - private async Task AddUserAsync() + private void AddUser() { var model = new StudentSetBindingModel(); if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); var userName = $"{model.LastName}{(model.FirstName.IsNotEmpty() ? $" {model.FirstName[0]}." : string.Empty)}{(model.Patronymic.IsNotEmpty() ? $"{model.Patronymic[0]}." : string.Empty)}"; - var result = await logic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName }); - if (result != null) + var user = logic.GetElement(new UserGetBindingModel { Login = model.NumberOfBook }); + if (user == null) { - if (result.List.Count > 1) + if (logic.Errors.Count > 0) { - DialogHelper.MessageException("Существует несколько пользователей с такой сигнатурой", "Ошибка"); + DialogHelper.MessageException(logic.Errors, "Ошибка при создании пользователя"); return; } - if (result.List.Count == 1) + user = logic.Create(new UserSetBindingModel { - model.UserId = result.List[0].Id; - } - else + Login = model.NumberOfBook, + Password = userName, + Avatar = model.Photo + }); + if (user == null) { - var newuser = await logic.CreateAsync(new UserSetBindingModel - { - Login = userName, - Password = model.NumberOfBook, - Avatar = model.Photo - }); - if (newuser == null) - { - DialogHelper.MessageException(logic.Errors, "Ошибка при создании пользователя"); - return; - } - model.UserId = newuser.Id; - } - var controls = tabPageMain.Controls.Find($"ControlUserId", true); - if (controls != null) - { - (controls[0] as AbstractBaseControl).SetValue(model); + DialogHelper.MessageException(logic.Errors, "Ошибка при создании пользователя"); + return; } } + model.UserId = user.Id; + var controls = tabPageMain.Controls.Find($"ControlUserId", true); + if (controls != null) + { + (controls[0] as AbstractBaseControl).SetValue(model); + } } } /// /// Сброс пароля пользователя /// - private async Task PasswordResetAsync() + private void PasswordReset() { if (_element == null) { @@ -102,14 +94,14 @@ namespace DepartmentWindowsDesktop.EntityControls if (FillModel(model)) { var logic = DependencyManager.Instance.Resolve(); - var user = await logic.GetElementAsync(new UserGetBindingModel { Id = _element.UserId }); + var user = logic.GetElement(new UserGetBindingModel { Id = _element.UserId }); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); return; } user.Password = model.NumberOfBook; - user = await logic.UpdateAsync(Mapper.MapToClass(user, true)); + user = logic.Update(Mapper.MapToClass(user, true)); if (user == null) { DialogHelper.MessageException(logic.Errors, "Ошибка при получении пользователя"); diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs index 282756b..1bd921b 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/UserBindingModels.cs @@ -11,6 +11,8 @@ namespace SecurityBusinessLogic.BindingModels public class UserGetBindingModel : GetBindingModel { public string UserNameForSearch { get; set; } + + public string Login { get; set; } } /// diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs index 59bf8fa..726fb8f 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs @@ -17,7 +17,7 @@ namespace SecurityDatabaseImplementation.Implementations /// Реализация IUserService /// public class UserService : - AbstractGenerticEntityService, + AbstractGenerticEntityService, IUserService { protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, UserSetBindingModel model) @@ -74,5 +74,23 @@ namespace SecurityDatabaseImplementation.Implementations protected override IQueryable IncludingWhenReading(IQueryable query) => query; protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.UserName); + + protected override bool AdditionalCheckForSingleGet(UserGetBindingModel model) + { + if (model.Login.IsNotEmpty()) + { + return true; + } + return base.AdditionalCheckForSingleGet(model); + } + + protected override User GetSingleRecord(IQueryable list, UserGetBindingModel model) + { + if (model.Login.IsNotEmpty()) + { + return list.FirstOrDefault(x => x.UserName == model.Login); + } + return base.GetSingleRecord(list, model); + } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityWindowsDesktop/EntityControls/Access/ControlAccessList.cs b/DepartmentPortal/Security/SecurityWindowsDesktop/EntityControls/Access/ControlAccessList.cs index 3219236..b350bc7 100644 --- a/DepartmentPortal/Security/SecurityWindowsDesktop/EntityControls/Access/ControlAccessList.cs +++ b/DepartmentPortal/Security/SecurityWindowsDesktop/EntityControls/Access/ControlAccessList.cs @@ -39,7 +39,7 @@ namespace SecurityWindowsDesktop.EntityControls public ControlViewEntityListConfiguration GetConfigControl() => new() { PaginationOn = true, - PageNamesForPagination = _roleBusinessLogic.GetListAsync(new RoleGetBindingModel()).Result?.List?.Select(x => + PageNamesForPagination = _roleBusinessLogic.GetList(new RoleGetBindingModel())?.List?.Select(x => new PageNamesForPaginationModel { Key = x.Id,