diff --git a/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs b/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs new file mode 100644 index 0000000..ed691a6 --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/AbstractGenerticEntityService.cs @@ -0,0 +1,225 @@ +using DatabaseCore.Models; +using Microsoft.EntityFrameworkCore; +using ModuleTools.BindingModels; +using ModuleTools.BusinessLogics; +using ModuleTools.Enums; +using ModuleTools.Interfaces; +using ModuleTools.Models; +using ModuleTools.ViewModels; +using System; +using System.Linq; + +namespace DatabaseCore +{ + public abstract class AbstractGenerticEntityService : IGenerticEntityService + where G : GetBindingModel + where S : SetBindingModel + where T : BaseEntity + where L : ListViewModel, new() + where E : ElementViewModel + { + public OperationResultModel Create(S model) + { + using var context = DatabaseManager.GetContext; + + var result = AdditionalCheckingWhenAdding(context, model); + if (!result.IsSucceeded) + { + return result; + } + + var exsistEntity = GetUniqueEntity(model, context); + if (exsistEntity == null) + { + var entity = Mapper.MapToClass(model, true); + context.Set().Add(entity); + context.SaveChanges(); + return OperationResultModel.Success(Mapper.MapToClass(entity, true)); + } + else + { + if (exsistEntity.IsDeleted) + { + exsistEntity = Mapper.MapToClass(model, exsistEntity, true); + exsistEntity.IsDeleted = false; + context.SaveChanges(); + return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); + } + else + { + return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); + } + } + } + + public OperationResultModel Delete(G model) + { + using var context = DatabaseManager.GetContext; + using var transaction = context.Database.BeginTransaction(); + try + { + var entity = context.Set().FirstOrDefault(x => x.Id == model.Id); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + else if (entity.IsDeleted) + { + return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); + } + + var result = AdditionalCheckingWhenDeleting(context, model); + if (!result.IsSucceeded) + { + return result; + } + + entity.IsDeleted = true; + entity.DateDelete = DateTime.Now; + + context.SaveChanges(); + + AdditionalDeleting(context, model); + + transaction.Commit(); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + + return OperationResultModel.Success(true); + } + + public OperationResultModel Read(G model) + { + int countPages = 0; + using var context = DatabaseManager.GetContext; + + // для одной записи + if (model.Id.HasValue) + { + var entity = context.Set().FirstOrDefault(x => x.Id == model.Id.Value); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); + } + + var query = context.Set().Where(x => !x.IsDeleted).AsQueryable(); + + query = AdditionalCheckingWhenReadingList(query, model); + + query = OrderingWhenReading(query); + + 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); + } + + query = IncludingWhenReading(query); + + var result = new L + { + MaxCount = countPages, + List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() + }; + + return OperationResultModel.Success(result); + } + + public OperationResultModel Update(S model) + { + using var context = DatabaseManager.GetContext; + + var result = AdditionalCheckingWhenUpdateing(context, model); + if (!result.IsSucceeded) + { + return result; + } + + var exsistEntity = GetUniqueEntity(model, context); + if (exsistEntity != null) + { + return OperationResultModel.Error("Error:", "Существует запись с такими значениями", ResultServiceStatusCode.ExsistItem); + } + + var entity = context.Set().FirstOrDefault(x => x.Id == model.Id); + if (entity == null) + { + return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + } + else if (entity.IsDeleted) + { + return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); + } + entity = Mapper.MapToClass(model, entity, true); + + context.SaveChanges(); + + return OperationResultModel.Success(Mapper.MapToClass(entity, true)); + } + + /// + /// Поиск записи с уникальными значениями + /// + /// + /// + protected abstract T GetUniqueEntity(S model, DbContext context); + + /// + /// Возможные дополнительные проверки при добавлении + /// + /// + /// + /// + protected abstract OperationResultModel AdditionalCheckingWhenAdding(DbContext context, S model); + + /// + /// Возможные дополнительные проверки при удалении + /// + /// + /// + /// + protected abstract OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, G model); + + /// + /// Добавление дополнительных фильтров + /// + /// + /// + /// + protected abstract IQueryable AdditionalCheckingWhenReadingList(IQueryable query, G model); + + /// + /// Возможные дополнительные проверки модели при изменении + /// + /// + protected abstract OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, S model); + + /// + /// Дополнительные удаления зависимых сущностей + /// + /// + protected abstract void AdditionalDeleting(DbContext context, G model); + + /// + /// Установка сортировок + /// + /// + /// + protected abstract IQueryable OrderingWhenReading(IQueryable query); + + /// + /// Добавление Include + /// + /// + /// + protected abstract IQueryable IncludingWhenReading(IQueryable query); + } +} \ No newline at end of file diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.Designer.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.Designer.cs new file mode 100644 index 0000000..4fa0c15 --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.Designer.cs @@ -0,0 +1,854 @@ +// +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("20210405060128_AddEnviromentSettingsFields")] + partial class AddEnviromentSettingsFields + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Relational:MaxIdentifierLength", 128) + .HasAnnotation("ProductVersion", "5.0.4") + .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); + + 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") + .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() + .HasFilter("[Number] IS NOT NULL"); + + 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.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.EmployeeEmployeePost", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EmployeeId") + .HasColumnType("uniqueidentifier"); + + b.Property("EmployeePostId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsExternalCombination") + .HasColumnType("bit"); + + b.Property("IsInternalCombination") + .HasColumnType("bit"); + + b.Property("Rate") + .HasColumnType("decimal(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("EmployeeId"); + + b.HasIndex("EmployeePostId"); + + b.ToTable("EmployeeEmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EmployeePostName") + .HasColumnType("nvarchar(450)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Order") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("EmployeePostName") + .IsUnique() + .HasFilter("[EmployeePostName] IS NOT NULL"); + + 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("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("LecturerPostId") + .HasColumnType("uniqueidentifier"); + + b.Property("LecturerPostRate") + .HasColumnType("decimal(18,2)"); + + 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("LecturerPostId"); + + 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.LecturerEmployeePost", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateDelete") + .HasColumnType("datetime2"); + + b.Property("EmployeePostId") + .HasColumnType("uniqueidentifier"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsExternalCombination") + .HasColumnType("bit"); + + b.Property("IsInternalCombination") + .HasColumnType("bit"); + + b.Property("LecturerId") + .HasColumnType("uniqueidentifier"); + + b.Property("Rate") + .HasColumnType("decimal(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("EmployeePostId"); + + b.HasIndex("LecturerId"); + + b.ToTable("LecturerEmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerPost", 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("LecturerPostName") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Order") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("LecturerPostName") + .IsUnique(); + + b.ToTable("LecturerPosts"); + }); + + 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.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.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.EmployeeEmployeePost", b => + { + b.HasOne("DatabaseCore.Models.Department.Employee", "Employee") + .WithMany("EmployeeEmployeePosts") + .HasForeignKey("EmployeeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.EmployeePost", "EmployeePost") + .WithMany("EmployeeEmployeePosts") + .HasForeignKey("EmployeePostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Employee"); + + b.Navigation("EmployeePost"); + }); + + 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.Department.LecturerPost", "LecturerPost") + .WithMany("Lecturers") + .HasForeignKey("LecturerPostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Security.User", "User") + .WithMany("Lecturers") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LecturerAcademicDegree"); + + b.Navigation("LecturerAcademicRank"); + + b.Navigation("LecturerPost"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.LecturerEmployeePost", b => + { + b.HasOne("DatabaseCore.Models.Department.EmployeePost", "EmployeePost") + .WithMany("LecturerEmployeePosts") + .HasForeignKey("EmployeePostId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("DatabaseCore.Models.Department.Lecturer", "Lecturer") + .WithMany("LecturerEmployeePosts") + .HasForeignKey("LecturerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EmployeePost"); + + b.Navigation("Lecturer"); + }); + + 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.DisciplineBlock", b => + { + b.Navigation("Disciplines"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Employee", b => + { + b.Navigation("Classrooms"); + + b.Navigation("EmployeeEmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.EmployeePost", b => + { + b.Navigation("EmployeeEmployeePosts"); + + b.Navigation("LecturerEmployeePosts"); + }); + + modelBuilder.Entity("DatabaseCore.Models.Department.Lecturer", b => + { + b.Navigation("LecturerEmployeePosts"); + }); + + 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.LecturerPost", b => + { + b.Navigation("Lecturers"); + }); + + 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("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.cs new file mode 100644 index 0000000..8feb278 --- /dev/null +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/20210405060128_AddEnviromentSettingsFields.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace DatabaseCore.Migrations +{ + public partial class AddEnviromentSettingsFields : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "DateCreate", + table: "EnviromentSettings", + type: "datetime2", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + migrationBuilder.AddColumn( + name: "DateDelete", + table: "EnviromentSettings", + type: "datetime2", + nullable: true); + + migrationBuilder.AddColumn( + name: "IsDeleted", + table: "EnviromentSettings", + type: "bit", + nullable: false, + defaultValue: false); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "DateCreate", + table: "EnviromentSettings"); + + migrationBuilder.DropColumn( + name: "DateDelete", + table: "EnviromentSettings"); + + migrationBuilder.DropColumn( + name: "IsDeleted", + table: "EnviromentSettings"); + } + } +} diff --git a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs index df4cbbd..2ba3e92 100644 --- a/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs +++ b/DepartmentPortal/Common/DatabaseCore/Migrations/DatabaseContextModelSnapshot.cs @@ -530,9 +530,18 @@ namespace DatabaseCore.Migrations 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)"); diff --git a/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs b/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs index 3f77425..de9a9e6 100644 --- a/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs +++ b/DepartmentPortal/Common/DatabaseCore/Models/Security/EnviromentSetting.cs @@ -10,7 +10,7 @@ namespace DatabaseCore.Models.Security /// [DataContract] [EntityDescription("EnviromentSetting", "Общие настройки системы")] - public class EnviromentSetting : IdEntity, IEntitySecurityExtenstion + public class EnviromentSetting : BaseEntity, IEntitySecurityExtenstion { [DataMember] [Required] diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/CoreBusinessLogic.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/CoreBusinessLogic.cs index 8080e8b..65433d0 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/CoreBusinessLogic.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/CoreBusinessLogic.cs @@ -1,4 +1,7 @@ -using ModuleTools.Interfaces; +using ModuleTools.BindingModels; +using ModuleTools.Enums; +using ModuleTools.Interfaces; +using ModuleTools.Models; using System.Collections.Generic; namespace ModuleTools.BusinessLogics @@ -13,6 +16,16 @@ namespace ModuleTools.BusinessLogics /// protected readonly ISecurityManager _security; + /// + /// Тип операции, скоторым работает логика + /// + protected AccessOperation _serviceOperation; + + /// + /// Название сущности + /// + protected string _entity; + /// /// Перечень ошибок при выполнении операции /// @@ -27,5 +40,21 @@ namespace ModuleTools.BusinessLogics _security = DependencyManager.Instance.Resolve(); Errors = new(); } + + /// + /// Проверка доступности операции для пользователя + /// + /// + /// + /// + protected bool NoAccess(AccessBindingModel model, AccessType type) + { + if (_security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity))) + { + return false; + } + Errors.Add(("Ошибка безопасности", _security.ErrorMessage)); + return true; + } } } \ No newline at end of file diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs index 5bea787..9b175bf 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/GenericBusinessLogic.cs @@ -1,7 +1,6 @@ using ModuleTools.BindingModels; using ModuleTools.Enums; using ModuleTools.Interfaces; -using ModuleTools.Models; using ModuleTools.ViewModels; using System; @@ -25,16 +24,6 @@ namespace ModuleTools.BusinessLogics /// protected IGenerticEntityService Service { get; set; } - /// - /// Тип операции, скоторым работает логика - /// - protected readonly AccessOperation _serviceOperation; - - /// - /// Название сущности - /// - protected readonly string _entity; - /// /// Возможен ли просмотр без авторизации /// @@ -47,22 +36,6 @@ namespace ModuleTools.BusinessLogics _serviceOperation = serviceOperation; } - /// - /// Проверка доступности операции для пользователя - /// - /// - /// - /// - protected bool NoAccess(AccessBindingModel model, AccessType type) - { - if (_security.CheckAccess(new SecurityManagerCheckAccessModel(model, _serviceOperation, type, _entity))) - { - return false; - } - Errors.Add(("Ошибка безопасности", _security.ErrorMessage)); - return true; - } - /// /// Получение списка записей /// diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/BackupBusinessLogic.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/BackupBusinessLogic.cs index f6a0fc5..d21690e 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/BackupBusinessLogic.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/BackupBusinessLogic.cs @@ -1,7 +1,6 @@ using ModuleTools.BusinessLogics; using ModuleTools.Enums; using ModuleTools.Extensions; -using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; using System; @@ -23,7 +22,12 @@ namespace SecurityBusinessLogic.BusinessLogics /// Логика работы с бекапом /// /// - public BackupBusinessLogic(IBackupService service) => _service = service; + public BackupBusinessLogic(IBackupService service) + { + _service = service; + _serviceOperation = AccessOperation.РаботасБекапом; + _entity = "Работа с Бекапом"; + } /// /// Создание бекапа с данными @@ -39,7 +43,7 @@ namespace SecurityBusinessLogic.BusinessLogics } try { - if (NoAccess()) + if (NoAccess(null, AccessType.Delete)) { return false; } @@ -82,7 +86,7 @@ namespace SecurityBusinessLogic.BusinessLogics } try { - if (NoAccess()) + if (NoAccess(null, AccessType.Delete)) { return false; } @@ -100,19 +104,5 @@ namespace SecurityBusinessLogic.BusinessLogics return false; } } - - /// - /// Проверка доступности операции для пользователя - /// - /// - private bool NoAccess() - { - if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.РаботасБекапом, AccessType.Delete, "бекап"))) - { - return false; - } - Errors.Add(("Ошибка безопасности", _security.ErrorMessage)); - return true; - } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/SynchronizationBusinessLogic.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/SynchronizationBusinessLogic.cs index 977618e..d268e4b 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/SynchronizationBusinessLogic.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BusinessLogics/SynchronizationBusinessLogic.cs @@ -1,6 +1,5 @@ using ModuleTools.BusinessLogics; using ModuleTools.Enums; -using ModuleTools.Models; using SecurityBusinessLogic.Interfaces; using System; @@ -20,7 +19,12 @@ namespace SecurityBusinessLogic.BusinessLogics /// Логика работы с бекапом /// /// - public SynchronizationBusinessLogic(ISynchronizationService service) => _service = service; + public SynchronizationBusinessLogic(ISynchronizationService service) + { + _service = service; + _serviceOperation = AccessOperation.Синхронизация; + _entity = "Синхронизация"; + } /// /// Запуск синхронизации @@ -31,7 +35,7 @@ namespace SecurityBusinessLogic.BusinessLogics { try { - if (NoAccess()) + if (NoAccess(null, AccessType.Delete)) { return false; } @@ -49,19 +53,5 @@ namespace SecurityBusinessLogic.BusinessLogics return false; } } - - /// - /// Проверка доступности операции для пользователя - /// - /// - private bool NoAccess() - { - if (_security.CheckAccess(new SecurityManagerCheckAccessModel(null, AccessOperation.Синхронизация, AccessType.Delete, "Синхронизация"))) - { - return false; - } - Errors.Add(("Ошибка безопасности", _security.ErrorMessage)); - return true; - } } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs index 7d7ebdc..772fc3b 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/AccessService.cs @@ -1,14 +1,10 @@ using DatabaseCore; using DatabaseCore.Models.Security; using Microsoft.EntityFrameworkCore; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using ModuleTools.Extensions; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.ViewModels; -using System; using System.Linq; namespace SecurityDatabaseImplementation.Implementations @@ -16,118 +12,33 @@ namespace SecurityDatabaseImplementation.Implementations /// /// Реализация IAccessService /// - public class AccessService : IAccessService + public class AccessService : + AbstractGenerticEntityService, + IAccessService { - public OperationResultModel Create(AccessSetBindingModel model) + protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, AccessSetBindingModel model) => OperationResultModel.Success(null); + + protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, AccessGetBindingModel model) { return OperationResultModel.Success(null); } + + protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, AccessGetBindingModel model) { - using var context = DatabaseManager.GetContext; - - var exsistEntity = context.Accesses.FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType); - if (exsistEntity == null) - { - var entity = Mapper.MapToClass(model, true); - context.Accesses.Add(entity); - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } - else - { - if (exsistEntity.IsDeleted) - { - exsistEntity = Mapper.MapToClass(model, exsistEntity, true); - exsistEntity.IsDeleted = false; - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); - } - else - { - return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); - } - } - } - - public OperationResultModel Delete(AccessGetBindingModel model) - { - using var context = DatabaseManager.GetContext; - - var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - entity.IsDeleted = true; - entity.DateDelete = DateTime.Now; - - context.SaveChanges(); - - return OperationResultModel.Success(true); - } - - public OperationResultModel Read(AccessGetBindingModel model) - { - int countPages = 0; - using var context = DatabaseManager.GetContext; - - // для одной записи - if(model.Id.HasValue) - { - var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id.Value); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - var query = context.Accesses.Where(x => !x.IsDeleted).AsQueryable(); if (model.RoleId.HasValue) { query = query.Where(x => x.RoleId == model.RoleId); } - - query = query.OrderBy(x => x.Role.RoleName).ThenBy(x => x.AccessOperation).ThenBy(x => x.AccessType); - - 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); - } - - query = query.Include(x => x.Role); - - var result = new AccessListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); + return query; } - public OperationResultModel Update(AccessSetBindingModel model) - { - using var context = DatabaseManager.GetContext; + protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, AccessSetBindingModel model) => OperationResultModel.Success(null); - var entity = context.Accesses.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - entity = Mapper.MapToClass(model, entity, true); + protected override void AdditionalDeleting(DbContext context, AccessGetBindingModel model) { } - context.SaveChanges(); + protected override Access GetUniqueEntity(AccessSetBindingModel model, DbContext context) => + context.Set().FirstOrDefault(x => x.AccessOperation == model.AccessOperation && x.RoleId == model.RoleId && x.AccessType == model.AccessType && x.Id != model.Id); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } + protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Role); + + protected override IQueryable OrderingWhenReading(IQueryable query) => + query.OrderBy(x => x.Role.RoleName).ThenBy(x => x.AccessOperation).ThenBy(x => x.AccessType); } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs index d0cbcb6..5a5185c 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/EnviromentSettingService.cs @@ -1,13 +1,10 @@ using DatabaseCore; using DatabaseCore.Models.Security; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; -using ModuleTools.Extensions; +using Microsoft.EntityFrameworkCore; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.ViewModels; -using System; using System.Linq; namespace SecurityDatabaseImplementation.Implementations @@ -15,100 +12,24 @@ namespace SecurityDatabaseImplementation.Implementations /// /// Реализация IEnviromentSettingService /// - public class EnviromentSettingService : IEnviromentSettingService + public class EnviromentSettingService : + AbstractGenerticEntityService, + IEnviromentSettingService { - public OperationResultModel Create(EnviromentSettingSetBindingModel model) - { - using var context = DatabaseManager.GetContext; + protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, EnviromentSettingSetBindingModel model) => OperationResultModel.Success(null); - var exsistEntity = context.EnviromentSettings.FirstOrDefault(x => x.Key == model.Key); - if (exsistEntity == null) - { - var entity = Mapper.MapToClass(model, true); - context.EnviromentSettings.Add(entity); - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } - return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); - } + protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, EnviromentSettingGetBindingModel model) => OperationResultModel.Success(null); - public OperationResultModel Delete(EnviromentSettingGetBindingModel model) - { - using var context = DatabaseManager.GetContext; + protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, EnviromentSettingGetBindingModel model) => query; - var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } + protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, EnviromentSettingSetBindingModel model) => OperationResultModel.Success(null); - context.EnviromentSettings.Remove(entity); - context.SaveChanges(); + protected override void AdditionalDeleting(DbContext context, EnviromentSettingGetBindingModel model) { } - return OperationResultModel.Success(true); - } + protected override EnviromentSetting GetUniqueEntity(EnviromentSettingSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.Key == model.Key && x.Id != model.Id); - public OperationResultModel Read(EnviromentSettingGetBindingModel model) - { - int countPages = 0; - using var context = DatabaseManager.GetContext; + protected override IQueryable IncludingWhenReading(IQueryable query) => query; - // для одной записи - if (model.Id.HasValue) - { - var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id.Value); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - if (model.Key.IsNotEmpty()) - { - var entity = context.EnviromentSettings.FirstOrDefault(x => x.Key == model.Key); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - var query = context.EnviromentSettings.AsQueryable(); - - query = query.OrderBy(x => x.Key); - - 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 EnviromentSettingListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); - } - - public OperationResultModel Update(EnviromentSettingSetBindingModel model) - { - using var context = DatabaseManager.GetContext; - - var entity = context.EnviromentSettings.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - entity = Mapper.MapToClass(model, entity, true); - - context.SaveChanges(); - - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } + protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.Key); } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs index a6a6367..5049f9f 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs @@ -1,6 +1,6 @@ using DatabaseCore; using DatabaseCore.Models.Security; -using ModuleTools.BusinessLogics; +using Microsoft.EntityFrameworkCore; using ModuleTools.Enums; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; @@ -14,135 +14,40 @@ namespace SecurityDatabaseImplementation.Implementations /// /// Реализация IRoleService /// - public class RoleService : IRoleService + public class RoleService : + AbstractGenerticEntityService, + IRoleService { - public OperationResultModel Create(RoleSetBindingModel model) - { - using var context = DatabaseManager.GetContext; + protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, RoleSetBindingModel model) => OperationResultModel.Success(null); - var exsistEntity = context.Roles.FirstOrDefault(x => x.RoleName == model.RoleName); - if (exsistEntity == null) + protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, RoleGetBindingModel model) + { + if (context.Set().Any(x => x.RoleId == model.Id && !x.IsDeleted)) { - var entity = Mapper.MapToClass(model, true); - context.Roles.Add(entity); - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } - else - { - if (exsistEntity.IsDeleted) - { - exsistEntity = Mapper.MapToClass(model, exsistEntity, true); - exsistEntity.IsDeleted = false; - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); - } - else - { - return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); - } + return OperationResultModel.Error("Error:", "Существуют пользователи, у которых есть эта роль", ResultServiceStatusCode.ExsistItem); } + return OperationResultModel.Success(null); } - public OperationResultModel Delete(RoleGetBindingModel model) + protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, RoleGetBindingModel model) => query; + + protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, RoleSetBindingModel model) => OperationResultModel.Success(null); + + protected override void AdditionalDeleting(DbContext context, RoleGetBindingModel model) { - using var context = DatabaseManager.GetContext; - using var transaction = context.Database.BeginTransaction(); - try + var access = context.Set().Where(x => x.RoleId == model.Id); + foreach (var ac in access) { - var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - if(context.UserRoles.Any(x => x.RoleId == model.Id && !x.IsDeleted)) - { - return OperationResultModel.Error("Error:", "Существуют пользователи, у которых есть эта роль", ResultServiceStatusCode.ExsistItem); - } - - entity.IsDeleted = true; - entity.DateDelete = DateTime.Now; - - context.SaveChanges(); - - var access = context.Accesses.Where(x => x.RoleId == model.Id); - foreach(var ac in access) - { - ac.IsDeleted = true; - ac.DateDelete = DateTime.Now; - } - context.SaveChanges(); - - transaction.Commit(); + ac.IsDeleted = true; + ac.DateDelete = DateTime.Now; } - catch(Exception) - { - transaction.Rollback(); - throw; - } - - return OperationResultModel.Success(true); - } - - public OperationResultModel Read(RoleGetBindingModel model) - { - int countPages = 0; - using var context = DatabaseManager.GetContext; - - // для одной записи - if (model.Id.HasValue) - { - var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id.Value); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - var query = context.Roles.Where(x => !x.IsDeleted).AsQueryable(); - - query = query.OrderBy(x => x.RoleName); - - 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 RoleListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); - } - - public OperationResultModel Update(RoleSetBindingModel model) - { - using var context = DatabaseManager.GetContext; - - var entity = context.Roles.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - entity = Mapper.MapToClass(model, entity, true); - context.SaveChanges(); - - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } + + protected override Role GetUniqueEntity(RoleSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.RoleName == model.RoleName && x.Id != model.Id); + + protected override IQueryable IncludingWhenReading(IQueryable query) => query; + + protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.RoleName); } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs index 390135d..8bddd47 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserRoleService.cs @@ -1,13 +1,10 @@ using DatabaseCore; using DatabaseCore.Models.Security; using Microsoft.EntityFrameworkCore; -using ModuleTools.BusinessLogics; -using ModuleTools.Enums; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; using SecurityBusinessLogic.ViewModels; -using System; using System.Linq; namespace SecurityDatabaseImplementation.Implementations @@ -15,74 +12,16 @@ namespace SecurityDatabaseImplementation.Implementations /// /// Реализация IUserRoleService /// - public class UserRoleService : IUserRoleService + public class UserRoleService : + AbstractGenerticEntityService, + IUserRoleService { - public OperationResultModel Create(UserRoleSetBindingModel model) + protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, UserRoleSetBindingModel model) => OperationResultModel.Success(null); + + protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, UserRoleGetBindingModel model) => OperationResultModel.Success(null); + + protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, UserRoleGetBindingModel model) { - using var context = DatabaseManager.GetContext; - - var exsistEntity = context.UserRoles.FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId); - if (exsistEntity == null) - { - var entity = Mapper.MapToClass(model, true); - context.UserRoles.Add(entity); - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } - else - { - if (exsistEntity.IsDeleted) - { - exsistEntity = Mapper.MapToClass(model, exsistEntity, true); - exsistEntity.IsDeleted = false; - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); - } - else - { - return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); - } - } - } - - public OperationResultModel Delete(UserRoleGetBindingModel model) - { - using var context = DatabaseManager.GetContext; - - var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - entity.IsDeleted = true; - entity.DateDelete = DateTime.Now; - - context.SaveChanges(); - - return OperationResultModel.Success(true); - } - - public OperationResultModel Read(UserRoleGetBindingModel model) - { - int countPages = 0; - using var context = DatabaseManager.GetContext; - - // для одной записи - if (model.Id.HasValue) - { - var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id.Value); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - var query = context.UserRoles.Where(x => !x.IsDeleted).AsQueryable(); if (model.RoleId.HasValue) { query = query.Where(x => x.RoleId == model.RoleId); @@ -91,46 +30,17 @@ namespace SecurityDatabaseImplementation.Implementations { query = query.Where(x => x.UserId == model.UserId); } - - query = query.OrderBy(x => x.User.UserName); - - 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); - } - - query = query.Include(x => x.Role).Include(x => x.User); - - var result = new UserRoleListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); + return query; } - public OperationResultModel Update(UserRoleSetBindingModel model) - { - using var context = DatabaseManager.GetContext; + protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, UserRoleSetBindingModel model) => OperationResultModel.Success(null); - var entity = context.UserRoles.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - entity = Mapper.MapToClass(model, entity, true); + protected override void AdditionalDeleting(DbContext context, UserRoleGetBindingModel model) { } - context.SaveChanges(); + protected override UserRole GetUniqueEntity(UserRoleSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.UserId == model.UserId && x.RoleId == model.RoleId && x.Id != model.Id); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } + protected override IQueryable IncludingWhenReading(IQueryable query) => query.Include(x => x.Role).Include(x => x.User); + + protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.User.UserName); } } \ No newline at end of file diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs index 4e42e28..b731942 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/UserService.cs @@ -1,6 +1,7 @@ using DatabaseCore; +using DatabaseCore.Models.Department; using DatabaseCore.Models.Security; -using ModuleTools.BusinessLogics; +using Microsoft.EntityFrameworkCore; using ModuleTools.Enums; using ModuleTools.Extensions; using ModuleTools.Models; @@ -15,156 +16,59 @@ namespace SecurityDatabaseImplementation.Implementations /// /// Реализация IUserService /// - public class UserService : IUserService + public class UserService : + AbstractGenerticEntityService, + IUserService { - public OperationResultModel Create(UserSetBindingModel model) + protected override OperationResultModel AdditionalCheckingWhenAdding(DbContext context, UserSetBindingModel model) { - using var context = DatabaseManager.GetContext; - if (model.Password.IsEmpty()) { model.Password = "qwerty"; } model.Password = SecurityManager.GetPasswordHash(model.Password); - - var exsistEntity = context.Users.FirstOrDefault(x => x.UserName == model.Login); - if (exsistEntity == null) - { - var entity = Mapper.MapToClass(model, true); - context.Users.Add(entity); - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); - } - else - { - if (exsistEntity.IsDeleted) - { - exsistEntity = Mapper.MapToClass(model, exsistEntity, true); - exsistEntity.IsDeleted = false; - context.SaveChanges(); - return OperationResultModel.Success(Mapper.MapToClass(exsistEntity, true)); - } - else - { - return OperationResultModel.Error("Error:", "Элемент уже существует", ResultServiceStatusCode.ExsistItem); - } - } + return OperationResultModel.Success(null); } - public OperationResultModel Delete(UserGetBindingModel model) + protected override OperationResultModel AdditionalCheckingWhenDeleting(DbContext context, UserGetBindingModel model) { - using var context = DatabaseManager.GetContext; - using var transaction = context.Database.BeginTransaction(); - try + if (context.Set().Any(x => x.UserId == model.Id && !x.IsDeleted)) { - var entity = context.Users.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - - if (context.Employees.Any(x => x.UserId == model.Id && !x.IsDeleted)) - { - return OperationResultModel.Error("Error:", "Имеется сотрудник, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem); - } - if (context.Lecturers.Any(x => x.UserId == model.Id && !x.IsDeleted)) - { - return OperationResultModel.Error("Error:", "Имеется преподаватель, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem); - } - - entity.IsDeleted = true; - entity.DateDelete = DateTime.Now; - - context.SaveChanges(); - - var users = context.UserRoles.Where(x => x.UserId == model.Id); - foreach (var u in users) - { - u.IsDeleted = true; - u.DateDelete = DateTime.Now; - } - context.SaveChanges(); - - transaction.Commit(); + return OperationResultModel.Error("Error:", "Имеется сотрудник, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem); } - catch (Exception) + if (context.Set().Any(x => x.UserId == model.Id && !x.IsDeleted)) { - transaction.Rollback(); - throw; + return OperationResultModel.Error("Error:", "Имеется преподаватель, приязанный к этой учетке", ResultServiceStatusCode.ExsistItem); } - - return OperationResultModel.Success(true); + return OperationResultModel.Success(null); } - public OperationResultModel Read(UserGetBindingModel model) + protected override IQueryable AdditionalCheckingWhenReadingList(IQueryable query, UserGetBindingModel model) { - int countPages = 0; - using var context = DatabaseManager.GetContext; - - // для одной записи - if (model.Id.HasValue) - { - var entity = context.Users.FirstOrDefault(x => x.Id == model.Id.Value); - if (entity == null) - { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); - } - return OperationResultModel.Success(Mapper.MapToClass(entity, model.HaveRight)); - } - - var query = context.Users.Where(x => !x.IsDeleted).AsQueryable(); - - if(model.UserNameForSearch.IsNotEmpty()) + if (model.UserNameForSearch.IsNotEmpty()) { query = query.Where(x => x.UserName.Contains(model.UserNameForSearch)); } - - query = query.OrderBy(x => x.UserName); - - 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 UserListViewModel - { - MaxCount = countPages, - List = query.Select(x => Mapper.MapToClass(x, model.HaveRight)).ToList() - }; - - return OperationResultModel.Success(result); + return query; } - public OperationResultModel Update(UserSetBindingModel model) + protected override OperationResultModel AdditionalCheckingWhenUpdateing(DbContext context, UserSetBindingModel model) => OperationResultModel.Success(null); + + protected override void AdditionalDeleting(DbContext context, UserGetBindingModel model) { - using var context = DatabaseManager.GetContext; - - var entity = context.Users.FirstOrDefault(x => x.Id == model.Id); - if (entity == null) + var users = context.Set().Where(x => x.UserId == model.Id); + foreach (var u in users) { - return OperationResultModel.Error("Error:", "Элемент не найден", ResultServiceStatusCode.NotFound); + u.IsDeleted = true; + u.DateDelete = DateTime.Now; } - else if (entity.IsDeleted) - { - return OperationResultModel.Error("Error:", "Элемент был удален", ResultServiceStatusCode.WasDelete); - } - if(entity.IsBanned && !model.IsBanned) - { - model.DateBanned = null; - model.CountAttempt = 0; - } - entity = Mapper.MapToClass(model, entity, true); - context.SaveChanges(); - - return OperationResultModel.Success(Mapper.MapToClass(entity, true)); } + + protected override User GetUniqueEntity(UserSetBindingModel model, DbContext context) => context.Set().FirstOrDefault(x => x.UserName == model.Login && x.Id != model.Id); + + protected override IQueryable IncludingWhenReading(IQueryable query) => query; + + protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.UserName); } } \ No newline at end of file