using System.Linq.Expressions; using AyCode.Core.Extensions; using AyCode.Core.Loggers; using AyCode.Core.Server.Loggers; using AyCode.Database.DbSets.Messages; using AyCode.Database.DbSets.Users; using AyCode.Models.Enums; using Microsoft.EntityFrameworkCore; using AyCode.Database.DbSets.Addresses; using AyCode.Database.DbSets.Companies; //using TIAM.Database.DataLayers.ServiceProviders; using TIAM.Database.DbContexts.Admins; using TIAM.Database.DbSets.Permissions; using TIAM.Database.DbSets.Products; using TIAM.Database.DbSets.Transfers; using TIAM.Database.DbSets.Users; using TIAM.Entities.Addresses; using TIAM.Entities.Drivers; using TIAM.Entities.Emails; using TIAM.Entities.Permissions; using TIAM.Entities.Products; using TIAM.Entities.Profiles; using TIAM.Entities.ServiceProviders; using TIAM.Entities.Transfers; using TIAM.Entities.Users; using TIAM.Models.Dtos.Products; using AyCode.Database.DbSets.Profiles; using DevExpress.Data.Filtering; using DevExpress.Data.Linq; using DevExpress.Data.Linq.Helpers; using TIAM.Database.DbSets.Drivers; using AyCode.Entities.Server.LogItems; using AyCode.Interfaces.Entities; using TIAM.Models; using TIAM.Models.Dtos.Users; using TIAM.Models.PageViewModels; using EmailMessage = TIAM.Entities.Emails.EmailMessage; namespace TIAM.Database.DataLayers.Admins { public class AdminDal : DalBase { public AdminDal() : base() { } //TODO: ezt meg a Messages-eket átbuherálni a UserDal-ra... - J. public async Task GetSiteViewModelByUserId(Guid userId) { var messages = await GetEmailMessagesByUserId(userId, true); return new SiteViewModel(messages); } #region Car public Task> GetAllCarsAsync() => SessionAsync(ctx => ctx.Cars.OrderBy(x => x.Manufacture).ThenBy(x => x.CarModel).ToList()); public Task> GetAllCarsbyProductIdAsync(Guid productId) => SessionAsync(ctx => ctx.Cars.Where(x => x.UserProductMapping.ProductId == productId).OrderBy(x => x.Manufacture).ThenBy(x => x.CarModel).ToList()); public Car? GetCarById(Guid carId) => Session(ctx => ctx.Cars.FirstOrDefault(x => x.Id == carId)); public List GetCarByUserProductMappingId(Guid userProductMappingId) => Session(ctx => ctx.Cars.Where(x => x.UserProductMappingId == userProductMappingId).ToList()); public Task> GetCarsByUserProductMappingIdAsync(Guid userProductMappingId) => SessionAsync(ctx => ctx.Cars.Where(x => x.UserProductMappingId == userProductMappingId).ToList()); public Task AddCarAsync(Car car) => TransactionAsync(ctx => ctx.Cars.Add(car).State == EntityState.Added); public Task UpdateCarAsync(Car car) => UpdateSafeAsync(car); public Task RemoveCarAsync(Car car) => TransactionAsync(ctx => ctx.Cars.Remove(car).State == EntityState.Deleted); #endregion Car #region Transfer public Task> GetTransfersByFilterAsync(CriteriaOperator criteriaOperator) => SessionAsync(ctx => (ctx.GetTransfers().AppendWhere(new CriteriaToExpressionConverter(), criteriaOperator) as IQueryable)!.OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); public Task> GetTransfersByDriverUserIdAsync(Guid driverUserId) => SessionAsync(ctx => ctx.GetTransfersByDriverUserId(driverUserId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); public Task> GetTransfersByProductIdAsync(Guid productId) => SessionAsync(ctx => ctx.GetTransfersByProductId(productId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); public Task> GetTransfersByUserProductMappingIdAsync(Guid userProductMappingId) => SessionAsync(ctx => ctx.GetTransfersByUserProductMappingId(userProductMappingId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); /// /// /// /// UserProductMappingId /// public Task GetDriverManageTransfersPageModelByDriverId(Guid driverId) => SessionAsync(ctx => { var transfers = ctx.GetTransfersByUserProductMappingId(driverId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId); var unreadMessagesCount = GetTransfersMessagesByDriverIdInnerAsync(ctx, driverId)?.Count(x => !x.IsReaded) ?? 0; return new DriverManageTransfersPageModel(transfers, unreadMessagesCount); }); public Task> GetTransfersAsync() => SessionAsync(ctx => ctx.GetTransfers().OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); public Task GetTransfersJsonAsync() => SessionAsync(ctx => ctx.GetTransfers().OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToJson()); public Task> GetTransfersByUserIdAsync(Guid userId) => SessionAsync(ctx => ctx.GetTransfersByUserId(userId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList()); public Task GetTransfersByUserIdJsonAsync(Guid userId) => SessionAsync(ctx => ctx.GetTransfersByUserId(userId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToJson()); public string GetTransfersJson() => Session(ctx => ctx.GetTransfers().OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToJson()); public Transfer? GetTransferById(Guid transferId) => Session(ctx => ctx.GetTransferById(transferId)); public Task GetTransferByIdAsync(Guid transferId) => SessionAsync(ctx => ctx.GetTransferById(transferId)); public string? GetTransferJsonById(Guid transferId) => Session(ctx => ctx.GetTransferById(transferId)?.ToJson()); public Task AddTransferAsync(Transfer transfer) => TransactionAsync(ctx => ctx.AddTransfer(transfer)); public Task UpdateTransferAsync(Transfer transfer) => UpdateSafeAsync(transfer, (ctx, safeTransfer) => ctx.UpdateTransfer(safeTransfer)); //public async Task UpdateTransferAsync(Transfer transfer) //{ // Transfer? entity = null; // var result = await TransactionAsync(ctx => // { // entity = ctx.Set().AsNoTracking().FirstOrDefault(e => e.Id == transfer.Id); // if (entity == null) return false; // ctx.Entry(entity).State = EntityState.Detached; // ctx.Entry(entity).CurrentValues.SetValues(transfer); // return ctx.UpdateTransfer(entity); // //foreach (var entityEntry in ctx.ChangeTracker.Entries()) // //{ // // if (entityEntry.Entity is not Transfer) // // entityEntry.State = EntityState.Unchanged; // //} // //var existingTransfer = ctx.Transfers.Local.SingleOrDefault(o => o.Id == transfer.Id); // //if (existingTransfer != null) // // ctx.Entry(existingTransfer).State = EntityState.Detached; // //var existingUsers = ctx.Users.Local.Where(o => transfer.TransferToDrivers.Any(x => x.UserProductMapping.UserId == o.Id)).ToList(); // //foreach (var existingUser in existingUsers) // // ctx.Entry(existingUser).State = EntityState.Detached; // //transfer.TransferToDrivers = null!; // //return ctx.UpdateTransfer(transfer); // }); // return result ? entity : null; //} public Task UpdateTransferAsync(Transfer transfer, TransferToDriver transferToDriver) => UpdateTransferAsync(transfer, [transferToDriver]); public Task UpdateTransferAsync(Transfer transfer, List transferToDrivers) => TransactionAsync(ctx => { ctx.AddRange(transferToDrivers); ctx.SaveChanges(); return ctx.UpdateTransfer(transfer); }); public Task RemoveTransferAsync(Transfer transfer) => RemoveTransferAsync(transfer.Id); public Task RemoveTransferAsync(Guid transferId) => TransactionAsync(ctx => ctx.RemoveTransfer(transferId)); #endregion Transfer #region TransferDestination public Task> GetTransferDestinationsAsync() => SessionAsync(ctx => ctx.GetTransferDestinations().ToList()); public TransferDestination? GetTransferDestinationById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId)); public Task GetTransferDestinationByIdAsync(Guid transferDestinationId) => SessionAsync(ctx => ctx.GetTransferDestinationById(transferDestinationId)); public Task> GetPublicTransferDestinationsAsync(Guid productId) => SessionAsync(ctx => ctx.GetTransferDestinations().Where(x => !x.ProductId.HasValue || x.ProductId == productId).ToList()); public Task AddTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.AddTransferDestination(transferDestination)); public Task UpdateTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.UpdateTransferDestination(transferDestination)); public Task RemoveTransferDestinationAsync(TransferDestination transferDestination, bool removeAddress) => RemoveTransferDestinationAsync(transferDestination.Id, removeAddress); public Task RemoveTransferDestinationAsync(Guid transferDestinationId, bool removeAddress) => TransactionAsync(ctx => ctx.RemoveTransferDestination(transferDestinationId, removeAddress)); #endregion TransferDestination #region TransferToDriver public Task GetTransferToDriverByIdAsync(Guid transferToDriverId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriverById(transferToDriverId, autoInclude)); public Task> GetTransferToDriversByUpmId(Guid upmId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriversByUpmId(upmId, autoInclude).ToList()); public Task> GetTransferToDriversByTransferIdAsync(Guid transferId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriversByTransferId(transferId, autoInclude).ToList()); public Task AddTransferToDriverAsync(TransferToDriver transferToDriver) => TransactionAsync(ctx => ctx.AddTransferToDriver(transferToDriver)); public Task UpdateTransferToDriverAsync(TransferToDriver transferToDriver) => UpdateSafeAsync(transferToDriver, (ctx, safeTransferToDriver) => ctx.UpdateTransferToDriver(safeTransferToDriver)); //public async Task UpdateTransferToDriverAsync(TransferToDriver transferToDriver) //{ // var transferToDriverId = transferToDriver.Id; // TransferToDriver transferToDriver2 = null!; // var result = await TransactionAsync(ctx => // { // transferToDriver2 = ctx.TransferToDrivers.FirstOrDefault(x => x.Id == transferToDriverId)!; // transferToDriver2.CarId = transferToDriver.CarId; // transferToDriver2.LicencePlate = transferToDriver.LicencePlate; // transferToDriver2.UserProductMappingId = transferToDriver.UserProductMappingId; // transferToDriver2.TransferId = transferToDriver.TransferId; // transferToDriver2.Price = transferToDriver.Price; // return ctx.TransferToDrivers.Update(transferToDriver2).State == EntityState.Modified; // }); // return result ? transferToDriver2 : null; //} public Task RemoveTransferToDriverAsync(TransferToDriver transferToDriver) => TransactionAsync(ctx => ctx.RemoveTransferToDriver(transferToDriver.Id)); #endregion TransferToDriver #region Drivers public Task> GetAllDriversAsync(bool autoInclude = true) => SessionAsync(ctx => ctx.GetAllDrivers(autoInclude).ToList()); public Task> GetAllDriversByProductIdAsync(Guid productId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetAllDriversByProductId(productId, autoInclude).ToList()); #endregion Drivers #region TransferDestinationToProduct public TransferDestinationToProduct? GetTransferDestinationToProductById(Guid transferDestinationToProductId) => Session(ctx => ctx.GetTransferDestinationToProductById(transferDestinationToProductId)); public Task GetTransferDestinationToProductByIdAsync(Guid transferDestinationToProductId) => SessionAsync(ctx => ctx.GetTransferDestinationToProductById(transferDestinationToProductId)); public string? GetTransferDestinationToProductJsonById(Guid transferDestinationToProductId) => Session(ctx => ctx.GetTransferDestinationToProductById(transferDestinationToProductId)?.ToJson()); public TransferDestinationToProduct? GetTransferDestinationToProduct(Guid productId, Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationToProduct(productId, transferDestinationId)); public Task> GetTransferDestinationToProducts() => SessionAsync(ctx => ctx.GetTransferDestinationToProducts().ToList()); public Task> GetTransferDestinationToProductsByProductId(Guid productId) => SessionAsync(ctx => ctx.GetTransferDestinationToProductsByProductId(productId).ToList()); public Task> GetTransferDestinationToProductsByTransferDestinationId(Guid transferDestinationId) => SessionAsync(ctx => ctx.GetTransferDestinationToProductsByTransferDestinationId(transferDestinationId).ToList()); public string? GetTransferDestinationToProductJson(Guid productId, Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationToProduct(productId, transferDestinationId)?.ToJson()); public Task AddTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => TransactionAsync(ctx => ctx.AddTransferDestinationToProduct(transferDestinationToProduct)); public Task UpdateTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => TransactionAsync(ctx => ctx.UpdateTransferDestinationToProduct(transferDestinationToProduct)); public Task RemoveTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => RemoveTransferDestinationToProductAsync(transferDestinationToProduct.Id); public Task RemoveTransferDestinationToProductAsync(Guid transferDestinationToProductId) => TransactionAsync(ctx => ctx.RemoveTransferDestinationToProduct(transferDestinationToProductId)); #endregion TransferDestinationToProduct public User? GetUserById(Guid userId, bool autoInclude = false) => Session(ctx => ctx.GetUserById(userId, autoInclude)); public User? GetUserByEmail(string email, bool autoInclude = false) => Session(ctx => ctx.GetUserByEmail(email, autoInclude)); public TUserModelDto? GetUserModelDtoById(Guid userId, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase => Session(ctx => ctx.GetUserModelDtoById(userId, onlyConfirmed)); public Task GetUserModelDtoByIdAsync(Guid userId, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase => SessionAsync(ctx => ctx.GetUserModelDtoById(userId, onlyConfirmed)); public TUserModelDto? GetUserModelDtoByEmail(string email, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase => Session(ctx => ctx.GetUserModelDtoByEmail(email, onlyConfirmed)); public Task GetUserModelDtoByEmailAsync(string email, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase => SessionAsync(ctx => ctx.GetUserModelDtoByEmail(email, onlyConfirmed)); public string? GetUserJsonById(Guid userId, bool onlyConfirmed) => Session(ctx => ctx.GetUserById(userId, onlyConfirmed)?.ToJson()); public string GetUsersJson() => Session(ctx => ctx.Users.ToJson()); public Task AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user)); public Task UpdateUserAsync(User? user) => UpdateSafeAsync(user); public Task RemoveUserAsync(Guid userId) => TransactionAsync(ctx => ctx.RemoveUser(userId)); #region Product public Product? GetProductById(Guid contextId, bool includeUsers = true) => Session(ctx => ctx.GetProductById(contextId, includeUsers)); public Task GetProductByIdAsync(Guid contextId, bool includeUsers = true) => SessionAsync(ctx => ctx.GetProductById(contextId, includeUsers)); public Task> GetProductModelDtoNamesAsync() => SessionAsync(ctx => ctx.Products.Select(x => new ProductModelDtoName(x)).ToList()); public string GetProductsJson(bool includeUsers = true) => Session(ctx => ctx.ProductsWithUserRelations(includeUsers).ToJson()); public List GetProductsByServiceProviderId(Guid serviceProviderId, bool includeUsers = true) => Session(ctx => ctx.GetProductsByCompanyId(serviceProviderId, includeUsers).ToList()); public string GetProductsJsonByServiceProviderId(Guid serviceProviderId, bool includeUsers = true) => Session(ctx => ctx.GetProductsByCompanyId(serviceProviderId, includeUsers).ToJson()); public Task AddProductAsync(Product product) => TransactionAsync(ctx => ctx.AddProduct(product)); public Task UpdateProductAsync(Product product) => UpdateSafeAsync(product, (ctx, safeProduct) => ctx.UpdateProduct(safeProduct)); public Task RemoveProductAsync(Product product) => RemoveProductAsync(product.Id); public Task RemoveProductAsync(Guid productId) => TransactionAsync(ctx => ctx.RemoveProduct(productId)); #endregion Product public UserProductMapping? GetUserProductMappingById(Guid userProductMappingId, bool autoInclude = true) => Session(ctx => ctx.GetUserProductMappingById(userProductMappingId, autoInclude)); public Task GetUserProductMappingByIdAsync(Guid userProductMappingId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingById(userProductMappingId, autoInclude)); public List GetUserProductMappingsByUserId(Guid userId, bool autoInclude = true) => Session(ctx => ctx.GetUserProductMappingsByUserId(userId, autoInclude).ToList()); public Task> GetUserProductMappingsByUserIdAsync(Guid userId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingsByUserId(userId, autoInclude).ToList()); public Task> GetUserProductMappingsByProductIdAsync(Guid productId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingsByProductId(productId, autoInclude).ToList()); public List GetAllUserProductMappings(bool autoInclude = true) => Session(ctx => ctx.UserProductMappings).ToList(); public Task> GetAllUserProductMappingsAsync(bool autoInclude = true) => SessionAsync(ctx => ctx.UserProductMappings.ToList()); public List GetPermissionContextsView(Guid subjectId, Guid contextId) => Session(x => x.GetPermissionContextsView(subjectId, contextId).ToList()); public List GetPermissionContextsViewBySubjectId(Guid contextId) => Session(x => x.GetPermissionContextsViewBySubjectId(contextId).ToList()); public List GetPermissionContextsViewByContextId(Guid contextId) => Session(x => x.GetPermissionContextsViewByContextId(contextId).ToList()); public Task> GetPermissionContextsViewByContextIdAsync(Guid contextId) => SessionAsync(x => x.GetPermissionContextsViewByContextId(contextId).ToList()); #region UserProductMapping public Task AddUserProductMappingAsync(UserProductMapping userProductMapping) => TransactionAsync(ctx => ctx.AddUserProductMapping(userProductMapping)); public async Task AddUserProductMappingAsync(Guid userProductMappingId, Guid userId, Guid productId, int permissions = 1, UserProductJsonDetailModel? userProductToCars = null) { UserProductMapping? userProductMapping = null; var isSucces = await TransactionAsync(ctx => { userProductMapping = ctx.AddUserProductMapping(userProductMappingId, userId, productId, permissions, userProductToCars); return userProductMapping != null; }); return isSucces ? userProductMapping : null; } public Task UpdateUserProductMappingAsync(UserProductMapping userProductMapping) => UpdateSafeAsync(userProductMapping, (ctx, safeUserProductMapping) => ctx.UpdateUserProductMapping(safeUserProductMapping)); public async Task UpdateUserProductMappingAsync(Guid userProductMappingId, int permissions = 1, UserProductJsonDetailModel? userProductToCars = null) { UserProductMapping? userProductMapping = null; var isSucces = await TransactionAsync(ctx => { userProductMapping = ctx.UpdateUserProductMapping(userProductMappingId, permissions, userProductToCars); return userProductMapping != null; }); return isSucces ? userProductMapping : null; } public Task RemoveUserProductMappingAsync(Guid userProductMappingId) => TransactionAsync(ctx => ctx.RemoveUserProductMapping(userProductMappingId)); public Task RemoveUserProductMappingAsync(Guid userId, Guid productId) => TransactionAsync(ctx => ctx.RemoveUserProductMapping(userId, productId)); #endregion UserProductMapping #region Address public Task GetAddressByIdAsync(Guid addressId) => SessionAsync(ctx => ctx.GetAddressById(addressId)); public Task UpdateAddressAsync(Address adress) => TransactionAsync(ctx => ctx.UpdateAddress(adress)); #endregion Address #region Profile public Task GetProfileByIdAsync(Guid profileId) => SessionAsync(ctx => ctx.GetProfileById(profileId)); public Task UpdateProfileAsync(Profile profile) => TransactionAsync(ctx => ctx.UpdateProfile(profile)); //public Task AddProfileAsync(Profile profile) => TransactionAsync(ctx => ctx.AddProfile(profile)); //Nem Add-olunk önmagában Profile-t! - J. //public Task RemoveProfileAsync(Guid profileId) => TransactionAsync(ctx => ctx.RemoveProfile(profileId)); //Nem törlünk Profile-t! - J. #endregion Profile #region EmailMessage public Task GetEmailMessageByIdAsync(Guid emailMessageId) => SessionAsync(ctx => ctx.GetEmailMessageById(emailMessageId)); public Task> GetEmailMessagesByContextIdAsync(Guid contextId) => SessionAsync(ctx => ctx.GetEmailMessagesByContextId(contextId).OrderByDescending(x => x.Created).ToList()); public Task> GetEmailMessagesBySenderIdAsync(Guid senderId) => SessionAsync(ctx => ctx.GetEmailMessagesBySenderId(senderId).OrderByDescending(x => x.Created).ToList()); public Task> GetEmailMessagesBySenderEmailAddressAsync(string emailAddress) => SessionAsync(ctx => ctx.GetEmailMessagesBySenderEmailAddress(emailAddress).OrderByDescending(x => x.Created).ToList()); public Task> GetEmailMessagesByUserIdOrUpmId(Guid userId, Guid userProductMappingId) => SessionAsync(ctx => ctx.GetEmailMessagesByUserIdOrUpmId(userId, userProductMappingId).OrderByDescending(x => x.Created).ToList()); public Task> GetEmailMessagesAsync(Guid contextId, Guid userId, Guid userProductMappingId) => SessionAsync(ctx => ctx.GetEmailMessages(contextId, userId, userProductMappingId).OrderByDescending(x => x.Created).ToList()); public Task> GetAllEmailMessagesAsync() => SessionAsync(ctx => ctx.GetAllEmailMessages().OrderByDescending(x => x.Created).ToList()); public Task> GetEmailMessagesByUserId(Guid userId, bool onlyUnread = false) => SessionAsync(ctx => ctx .GetEmailMessagesByIds(ctx.GetUserProductMappingsByUserId(userId).Select(x => x.Id).Concat([userId])) .Where(x => !onlyUnread || !x.IsReaded) .ToList()); /// /// /// /// UserProductMappingId /// public Task> GetTransfersMessagesByDriverIdAsync(Guid driverId) => SessionAsync(ctx => GetTransfersMessagesByDriverIdInnerAsync(ctx, driverId)?.OrderByDescending(x => x.Created).ToList() ?? []); /// /// /// /// UserProductMappingId /// public Task GetTransfersMessagesUnreadCountByDriverIdAsync(Guid driverId) => SessionAsync(ctx => GetTransfersMessagesByDriverIdInnerAsync(ctx, driverId)?.Count(x => !x.IsReaded) ?? 0); /// /// /// /// /// UserProductMappingId /// private static IQueryable? GetTransfersMessagesByDriverIdInnerAsync(AdminDbContext ctx, Guid driverId) { //TODO: Az upm.UserId elvben nem kell, csak amíg nem fix a db! semmilyen gondot nem okoz... - J. var upm = ctx.GetUserProductMappingById(driverId); if (upm == null) return default; //return ctx.GetEmailMessages(driverId) //TODO: jövőben elég lesz a driverId is és mehet vissza ez a sor! - J. return ctx.GetEmailMessagesByUserIdOrUpmId(upm.UserId, driverId) .Where(emailMessage => ctx.TransferToDrivers.Any(transferToDriver => transferToDriver.TransferId == emailMessage.ContextId && transferToDriver.UserProductMappingId == driverId)); } public Task AddEmailMessageAsync(EmailMessage emailMessage) => TransactionAsync(ctx => ctx.AddEmailMessage(emailMessage)); public Task UpdateEmailMessageAsync(EmailMessage emailMessage) => TransactionAsync(ctx => ctx.UpdateEmailMessage(emailMessage)); public Task RemoveEmailMessageAsync(Guid emailMessageId) => TransactionAsync(ctx => ctx.RemoveEmailMessage(emailMessageId)); #endregion EmailMessage #region ServiceProviders //15. (IServiceProviderDataService) Create service provider public Task AddCompanyAsync(Company serviceProvider) => TransactionAsync(ctx => ctx.AddCompany(serviceProvider)); public Task> GetCompaniesAsync() => SessionAsync(ctx => ctx.GetCompanies().ToList()); public Task GetCompaniesJsonAsync() => SessionAsync(ctx => ctx.Companies.ToJson()); public string GetCompaniesJson() => Session(ctx => ctx.Companies.ToJson()); public virtual Task GetCompanyByIdAsync(Guid id) => SessionAsync(ctx => ctx.GetCompanyById(id)); public virtual Task> GetCompaniesByOwnerIdAsync(Guid id) => SessionAsync(ctx => ctx.GetCompaniesByOwnerId(id)); //public Task CreateUserProductMappingAsync(UserProductMapping userProductMapping) //{ // Context.UserProductMappings.Add(userProductMapping); // GlobalLogger.Info($"Saving userProductMapping to db {userProductMapping.Id}, {userProductMapping.ProductId}, {userProductMapping.UserId}"); // return Context.SaveChangesAsync().ContinueWith(x => userProductMapping); //} //14. (IserviceProviderDataService) Update service provider //public Task UpdateCompanyAsync(Company company) //{ // var result = NewUpdateCompanyAsync(company); // return Task.FromResult(result.Result != null && !result.Result.Id.IsNullOrEmpty()); //} public Task UpdateCompanyAsync(Company company) => UpdateSafeAsync(company, (ctx, safeCompany) => { ctx.Entry(safeCompany.Profile).CurrentValues.SetValues(company.Profile); return ctx.UpdateCompany(safeCompany); }); //public Task UpdateCompanyAsync(Company company, Profile profile) // => TransactionAsync(ctx => // { // ctx.UpdateProfile(profile); // ctx.SaveChanges(); // return ctx.UpdateCompany(company); // }); //13. (IserviceProviderDataService) delete service provider public Task RemoveCompanyAsync(Guid companyId) => TransactionAsync(ctx => ctx.RemoveProductsByCompanyId(companyId) && ctx.RemoveCompany(companyId)); //public Task RemoveCompanyAsync(Company company) => RemoveCompanyAsync(company.Id); #endregion #region PermissionTypes //10. (IPermissionService) create permission type public Task CreatePermissionsTypeAsync(PermissionsType permissionsType) { bool result = false; using (var transaction = Context.Database.BeginTransaction()) { var existingPermission = Context.PermissionsTypes .FirstOrDefault(x => x.PermissionName == permissionsType.PermissionName)?.PermissionName; if (existingPermission == null) { //get all the permissiontypes for this context var permissionTypes = new List(); var nextBitValue = 0.0; permissionTypes = Context.PermissionsTypes .Where(x => x.ContextId == permissionsType.ContextId) .ToList(); //get the max value of the permissiontypes if (permissionTypes != null) { //next bit value is the power of two of the count of the permissiontypes nextBitValue = Math.Pow(2, permissionTypes.Count); } else { nextBitValue = Math.Pow(2, 0); } permissionsType.PermissionBit = (int)nextBitValue; Context.PermissionsTypes.Add(permissionsType); Context.SaveChanges(); transaction.Commit(); result = true; } else { result = false; } } return Task.FromResult(result); } //11. (IPermissionService) get permission types for context public Task>? GetPermissionTypesByContextIdAsync(Guid contextId) { return Context.PermissionsTypes.Where(x => x.ContextId == contextId).ToListAsync(); } public Task GetPermissionFromPermissionType(PermissionsType pType) { if (Context.PermissionsTypes.FirstOrDefault(x => x.Id == pType.Id) != null) { return Task.FromResult(pType.PermissionBit); } else { return Task.FromResult(0); } } #endregion #region PermissionMappings public Task> GetPermissionsOfUserProductMappingsAndGroupsAsyncByContextId(Guid contextId) { List result = new List(); var userProductMappings = Context.UserProductMappings.Where(x => x.ProductId == contextId).ToList(); //if (userProductMappings.Result != null) { foreach (var item in userProductMappings) { var mappingRows = Context.PermissionContextMappings.Where(x => x.SubjectId == item.Id).ToList(); if (mappingRows.Count == 0) { //user has no permission but is assigned... must be banned } else if (mappingRows.Count > 1) { //user has been assigned more than onece to same context } else { foreach (var mapping in mappingRows) { result.Add(new AssignedPermissionModel(item.ProductId, item.Id, mapping.SubjectType, item.UserId.ToString(), mapping.Permissions)); } } } } var assingedGroups = Context.PermissionGroups.Where(x => x.OwnerId == contextId).ToList(); //if (assingedGroups.Result != null) { foreach (var group in assingedGroups) { var mappingRows = Context.PermissionContextMappings.Where(x => x.SubjectId == group.Id).ToList(); if (mappingRows.Count == 0) { //group has no permission but is assigned... } else if (mappingRows.Count > 1) { //group has been assigned more than onece to same context } else { foreach (var mapping in mappingRows) { result.Add(new AssignedPermissionModel(group.OwnerId, group.Id, mapping.SubjectType, group.GroupName, mapping.Permissions)); } } } } foreach (var row in result) { GlobalLogger.Info($@"GetPermissionsOfUserProductMappingsAndGroupsAsyncByContextId: {row.ContextId}, {row.SubjectId}, {row.SubjectType}, {row.Name}, {row.PermissionsValue}"); } return Task.FromResult(result); } //12. (IPermissionService) get permission groups for context public Task> GetPermissionsForContextByContextIdAsync(Guid contextId) { List permissionContextMappings = new List(); //get all Groups where the contextId is the same var groups = Context.PermissionGroups.Where(x => x.OwnerId == contextId).Select(x => x.Id).ToHashSet(); permissionContextMappings = Context.PermissionContextMappings.Where(x => groups.Contains(x.SubjectId)).ToList(); //foreach (var item in groups.Result) //{ // //get permissioncontextmapping for the group if there is, so we know what permissions the group has // var pCm = Context.PermissionContextMappings.FirstOrDefault(x => x.SubjectId == item.Id); // permissionContextMappings.Add(pCm); //} return Task.FromResult(permissionContextMappings); } //9. (IPermissionService) add user to permission group public Task AddUserToPermissionGroupAsync(Guid permissionGroupId, Guid userId) { bool result = false; using (var transaction = Context.Database.BeginTransaction()) { //do we need to check if PermissionContextMappingId exists? var permissionGroupUserMapping = new PermissionGroupUserMapping(userId, permissionGroupId); Context.PermissionGroupUserMappings.Add(permissionGroupUserMapping); Context.SaveChanges(); transaction.Commit(); result = true; } return Task.FromResult(result); } //8. (IPermissionService) create permission group public Task CreatePermissionGroupAsync(PermissionGroup permissionGroup, Company serviceProvider) { bool result = false; using (var transaction = Context.Database.BeginTransaction()) { var existingPermissionGroup = Context.PermissionGroups.FirstOrDefault(x => x.GroupName == permissionGroup.GroupName)?.GroupName; if (existingPermissionGroup == null) { //create permission type 1 for the group var permissionType = new PermissionsType(serviceProvider.Id, "View"); Context.CreatePermissionsType(permissionType); //Create PermissionContextMapping for the group //create Id for the group Guid Id = Guid.NewGuid(); permissionGroup.Id = Id; var permissionContextMapping = new PermissionContextMapping(serviceProvider.Id, Id, PermissionContextMappingSubjectType.Group, 1, true); Context.CreatePermissionContextMapping(permissionContextMapping); Context.CreatePermissionGroup(permissionGroup); Context.SaveChanges(); transaction.Commit(); result = true; } else { //group with same name already exists result = false; } } return Task.FromResult(result); } public List GetUserProductMappingsInPermissionGroupByGroupId(Guid groupId) { return Context.GetUserProductMappingsByPermissionGroupId(groupId).ToList(); //List userProductMappings = new List(); ////let's get the permissioncontextmapping for the group //var pCm = Context.PermissionContextMappings.FirstOrDefault(x => x.SubjectId == groupId); //Guid pCmId = pCm.Id; ////let's get the permissiongroupusermappings for the permissioncontextmapping //var pGum = Context.PermissionGroupUserMappings.Where(x => x.PermissionContextMappingId == pCmId).ToList(); //if (pGum.Count > 0) //{ // foreach (var group in pGum) // { // userProductMappings.Add(Context.UserProductMappings.FirstOrDefault(x => x.Id == group.UserProductMappingId)); // } //} //return Task.FromResult(userProductMappings); } #endregion #region Products //4. (IPermissionService) AssignPermissionToUserForContextAsync public Task AssignPermissionToUserForContextAsync(UserProductMapping userProductMapping, PermissionsType permission) { var _assIgnedUser = Context.UserProductMappings.FirstOrDefault(x => x.Id == userProductMapping.Id); if (_assIgnedUser != null) { //user exists var _permissionInt = GetPermissionFromPermissionType(permission); var permissionContextMapping = Context.PermissionContextMappings.FirstOrDefault(x => x.SubjectId == userProductMapping.Id); var currentPermissions = permissionContextMapping.Permissions; var newPermissions = currentPermissions + _permissionInt.Result; permissionContextMapping.Permissions = newPermissions; return Context.SaveChangesAsync().ContinueWith(x => x.Result > 0); } else { //user does not exist, let's create it return Task.FromResult(false); } } #endregion #region UserProductMappings //24 . (IServiceProviderDataService) Remove Assigned Users By Product Id public Task RemoveUserProductMappingsByProductId(Guid productId) { using (var transaction = Context.Database.BeginTransaction()) { var userProductMappings = Context.UserProductMappings.Where(x => x.ProductId == productId).ToList(); //remove userProductMappings return Context.SaveChangesAsync().ContinueWith(x => x.Result > 0); } } //25. (IServiceProviderDataService) Remove Assigned from product by userProductMappingId public Task RemoveUserProductMappingAsync(UserProductMapping userProductMapping, bool removeFromGroups) { return TransactionAsync(ctx => { var result = false; var userProductMappingToRemove = ctx.UserProductMappings.FirstOrDefault(x => x.Id == userProductMapping.Id); //remove userProductMappings if (userProductMappingToRemove == null) return false; if (removeFromGroups) { //remove permissiongroupusermappings ctx.RemoveAssingedUserFromPermissionGroups(userProductMappingToRemove.Id); } ctx.UserProductMappings.Remove(userProductMappingToRemove); return result; }); } #endregion #region Logs public Task> GetLogItemsAsync(int takeCount, DateTime utcFromDate, DateTime utcToDate) => SessionAsync(ctx => ctx.LogItems.Where(x => x.TimeStampUtc.Date >= utcFromDate.Date && x.TimeStampUtc.Date <= utcToDate.Date).Take(takeCount).ToList()); public Task> GetLogItemsByFilterAsync(CriteriaOperator criteriaOperator, int takeCount, DateTime utcFromDate, DateTime utcToDate) => SessionAsync(ctx => (ctx.LogItems.Where(x => x.TimeStampUtc.Date >= utcFromDate.Date && x.TimeStampUtc.Date <= utcToDate.Date).AppendWhere(new CriteriaToExpressionConverter(), criteriaOperator).Take(takeCount) as IQueryable)!.ToList()); #endregion } }