TourIAm/TIAM.Database/DataLayers/Admins/AdminDal.cs

697 lines
39 KiB
C#

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.Dtos.Users;
namespace TIAM.Database.DataLayers.Admins
{
public class AdminDal : DalBase<AdminDbContext>
{
public AdminDal() : base()
{
}
#region Car
public Task<List<Car>> GetAllCarsAsync() => SessionAsync(ctx => ctx.Cars.OrderBy(x => x.Manufacture).ThenBy(x => x.CarModel).ToList());
public Task<List<Car>> 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<Car> GetCarByUserProductMappingId(Guid userProductMappingId) => Session(ctx => ctx.Cars.Where(x => x.UserProductMappingId == userProductMappingId).ToList());
public Task<List<Car>> GetCarsByUserProductMappingIdAsync(Guid userProductMappingId) => SessionAsync(ctx => ctx.Cars.Where(x => x.UserProductMappingId == userProductMappingId).ToList());
public Task<bool> AddCarAsync(Car car) => TransactionAsync(ctx => ctx.Cars.Add(car).State == EntityState.Added);
public Task<Car?> UpdateCarAsync(Car car) => UpdateSafeAsync(car);
public Task<bool> RemoveCarAsync(Car car) => TransactionAsync(ctx => ctx.Cars.Remove(car).State == EntityState.Deleted);
#endregion Car
#region Transfer
public Task<List<Transfer>> GetTransfersByFilterAsync(CriteriaOperator criteriaOperator) => SessionAsync(ctx => (ctx.GetTransfers().AppendWhere(new CriteriaToExpressionConverter(), criteriaOperator) as IQueryable<Transfer>)!.OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList());
public Task<List<Transfer>> GetTransfersByDriverUserIdAsync(Guid driverUserId) => SessionAsync(ctx => ctx.GetTransfersByDriverUserId(driverUserId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList());
public Task<List<Transfer>> GetTransfersByUserProductMappingIdAsync(Guid userProductMappingId) => SessionAsync(ctx => ctx.GetTransfersByUserProductMappingId(userProductMappingId).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList());
public Task<List<Transfer>> GetTransfersAsync() => SessionAsync(ctx => ctx.GetTransfers().OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList());
public Task<string> GetTransfersJsonAsync() => SessionAsync(ctx => ctx.GetTransfers().OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToJson());
public Task<string> 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 string? GetTransferJsonById(Guid transferId) => Session(ctx => ctx.GetTransferById(transferId)?.ToJson());
public Task<bool> AddTransferAsync(Transfer transfer) => TransactionAsync(ctx => ctx.AddTransfer(transfer));
public Task<Transfer?> UpdateTransferAsync(Transfer transfer) => UpdateSafeAsync(transfer, (ctx, safeTransfer) => ctx.UpdateTransfer(safeTransfer));
//public async Task<Transfer?> UpdateTransferAsync(Transfer transfer)
//{
// Transfer? entity = null;
// var result = await TransactionAsync(ctx =>
// {
// entity = ctx.Set<Transfer>().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<bool> UpdateTransferAsync(Transfer transfer, TransferToDriver transferToDriver) => UpdateTransferAsync(transfer, [transferToDriver]);
public Task<bool> UpdateTransferAsync(Transfer transfer, List<TransferToDriver> transferToDrivers)
=> TransactionAsync(ctx =>
{
ctx.AddRange(transferToDrivers);
ctx.SaveChanges();
return ctx.UpdateTransfer(transfer);
});
public Task<bool> RemoveTransferAsync(Transfer transfer) => RemoveTransferAsync(transfer.Id);
public Task<bool> RemoveTransferAsync(Guid transferId) => TransactionAsync(ctx => ctx.RemoveTransfer(transferId));
#endregion Transfer
#region TransferDestination
public List<TransferDestination> GetTransferDestinations() => Session(ctx => ctx.GetTransferDestinations().ToList());
public TransferDestination? GetTransferDestinationById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId));
public Task<TransferDestination?> GetTransferDestinationByIdAsync(Guid transferDestinationId) => SessionAsync(ctx => ctx.GetTransferDestinationById(transferDestinationId));
public string? GetTransferDestinationJsonById(Guid transferDestinationId) => Session(ctx => ctx.GetTransferDestinationById(transferDestinationId)?.ToJson());
public Task<bool> AddTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.AddTransferDestination(transferDestination));
public Task<bool> UpdateTransferDestinationAsync(TransferDestination transferDestination) => TransactionAsync(ctx => ctx.UpdateTransferDestination(transferDestination));
public Task<bool> RemoveTransferDestinationAsync(TransferDestination transferDestination, bool removeAddress) => RemoveTransferDestinationAsync(transferDestination.Id, removeAddress);
public Task<bool> RemoveTransferDestinationAsync(Guid transferDestinationId, bool removeAddress) => TransactionAsync(ctx => ctx.RemoveTransferDestination(transferDestinationId, removeAddress));
#endregion TransferDestination
#region TransferToDriver
public Task<TransferToDriver?> GetTransferToDriverByIdAsync(Guid transferToDriverId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriverById(transferToDriverId, autoInclude));
public Task<List<TransferToDriver>> GetTransferToDriversByUpmId(Guid upmId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriversByUpmId(upmId, autoInclude).ToList());
public Task<List<TransferToDriver>> GetTransferToDriversByTransferIdAsync(Guid transferId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetTransferToDriversByTransferId(transferId, autoInclude).ToList());
public Task<bool> AddTransferToDriverAsync(TransferToDriver transferToDriver) => TransactionAsync(ctx => ctx.AddTransferToDriver(transferToDriver));
public Task<TransferToDriver?> UpdateTransferToDriverAsync(TransferToDriver transferToDriver)
=> UpdateSafeAsync(transferToDriver, (ctx, safeTransferToDriver) => ctx.UpdateTransferToDriver(safeTransferToDriver));
//public async Task<TransferToDriver?> 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<bool> RemoveTransferToDriverAsync(TransferToDriver transferToDriver) => TransactionAsync(ctx => ctx.RemoveTransferToDriver(transferToDriver.Id));
#endregion TransferToDriver
#region Drivers
public Task<List<UserProductMapping>> GetAllDriversAsync(bool autoInclude = true) => SessionAsync(ctx => ctx.GetAllDrivers(autoInclude).ToList());
public Task<List<UserProductMapping>> 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<TransferDestinationToProduct?> 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<List<TransferDestinationToProduct>> GetTransferDestinationToProducts() => SessionAsync(ctx => ctx.GetTransferDestinationToProducts().ToList());
public Task<List<TransferDestinationToProduct>> GetTransferDestinationToProductsByProductId(Guid productId) => SessionAsync(ctx => ctx.GetTransferDestinationToProductsByProductId(productId).ToList());
public Task<List<TransferDestinationToProduct>> 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<bool> AddTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => TransactionAsync(ctx => ctx.AddTransferDestinationToProduct(transferDestinationToProduct));
public Task<bool> UpdateTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => TransactionAsync(ctx => ctx.UpdateTransferDestinationToProduct(transferDestinationToProduct));
public Task<bool> RemoveTransferDestinationToProductAsync(TransferDestinationToProduct transferDestinationToProduct) => RemoveTransferDestinationToProductAsync(transferDestinationToProduct.Id);
public Task<bool> 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<TUserModelDto>(Guid userId, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase
=> Session(ctx => ctx.GetUserModelDtoById<TUserModelDto, User>(userId, onlyConfirmed));
public Task<TUserModelDto?> GetUserModelDtoByIdAsync<TUserModelDto>(Guid userId, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase
=> SessionAsync(ctx => ctx.GetUserModelDtoById<TUserModelDto, User>(userId, onlyConfirmed));
public TUserModelDto? GetUserModelDtoByEmail<TUserModelDto>(string email, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase
=> Session(ctx => ctx.GetUserModelDtoByEmail<TUserModelDto, User>(email, onlyConfirmed));
public Task<TUserModelDto?> GetUserModelDtoByEmailAsync<TUserModelDto>(string email, bool onlyConfirmed) where TUserModelDto : class, IUserModelDtoMinBase
=> SessionAsync(ctx => ctx.GetUserModelDtoByEmail<TUserModelDto, User>(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<bool> AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user));
public Task<bool> UpdateUserAsync(User user) => TransactionAsync(ctx => ctx.UpdateUser(user));
public Task<bool> 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<Product?> GetProductByIdAsync(Guid contextId, bool includeUsers = true) => SessionAsync(ctx => ctx.GetProductById(contextId, includeUsers));
public Task<List<ProductModelDtoName>> 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<Product> 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<bool> AddProductAsync(Product product) => TransactionAsync(ctx => ctx.AddProduct(product));
public Task<Product?> UpdateProductAsync(Product product) => UpdateSafeAsync(product, (ctx, safeProduct) => ctx.UpdateProduct(safeProduct));
public Task<bool> RemoveProductAsync(Product product) => RemoveProductAsync(product.Id);
public Task<bool> 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<UserProductMapping?> GetUserProductMappingByIdAsync(Guid userProductMappingId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingById(userProductMappingId, autoInclude));
public List<UserProductMapping> GetUserProductMappingsByUserId(Guid userId, bool autoInclude = true) => Session(ctx => ctx.GetUserProductMappingsByUserId(userId, autoInclude).ToList());
public Task<List<UserProductMapping>> GetUserProductMappingsByUserIdAsync(Guid userId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingsByUserId(userId, autoInclude).ToList());
public Task<List<UserProductMapping>> GetUserProductMappingsByProductIdAsync(Guid productId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingsByProductId(productId, autoInclude).ToList());
public List<UserProductMapping> GetAllUserProductMappings(bool autoInclude = true) => Session(ctx => ctx.UserProductMappings).ToList();
public Task<List<UserProductMapping>> GetAllUserProductMappingsAsync(bool autoInclude = true) => SessionAsync(ctx => ctx.UserProductMappings.ToList());
public List<PermissionContextMapping> GetPermissionContextsView(Guid subjectId, Guid contextId)
=> Session(x => x.GetPermissionContextsView(subjectId, contextId).ToList());
public List<PermissionContextMapping> GetPermissionContextsViewBySubjectId(Guid contextId)
=> Session(x => x.GetPermissionContextsViewBySubjectId(contextId).ToList());
public List<PermissionContextMapping> GetPermissionContextsViewByContextId(Guid contextId)
=> Session(x => x.GetPermissionContextsViewByContextId(contextId).ToList());
public Task<List<PermissionContextMapping>> GetPermissionContextsViewByContextIdAsync(Guid contextId)
=> SessionAsync(x => x.GetPermissionContextsViewByContextId(contextId).ToList());
#region UserProductMapping
public Task<bool> AddUserProductMappingAsync(UserProductMapping userProductMapping) => TransactionAsync(ctx => ctx.AddUserProductMapping(userProductMapping));
public async Task<UserProductMapping?> 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<UserProductMapping?> UpdateUserProductMappingAsync(UserProductMapping userProductMapping) => UpdateSafeAsync(userProductMapping, (ctx, safeUserProductMapping) => ctx.UpdateUserProductMapping(safeUserProductMapping));
public async Task<UserProductMapping?> 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<bool> RemoveUserProductMappingAsync(Guid userProductMappingId) => TransactionAsync(ctx => ctx.RemoveUserProductMapping(userProductMappingId));
public Task<bool> RemoveUserProductMappingAsync(Guid userId, Guid productId) => TransactionAsync(ctx => ctx.RemoveUserProductMapping(userId, productId));
#endregion UserProductMapping
#region Address
public Task<Address?> GetAddressByIdAsync(Guid addressId) => SessionAsync(ctx => ctx.GetAddressById(addressId));
public Task<bool> UpdateAddressAsync(Address adress) => TransactionAsync(ctx => ctx.UpdateAddress(adress));
#endregion Address
#region Profile
public Task<Profile?> GetProfileByIdAsync(Guid profileId) => SessionAsync(ctx => ctx.GetProfileById(profileId));
public Task<bool> UpdateProfileAsync(Profile profile) => TransactionAsync(ctx => ctx.UpdateProfile(profile));
//public Task<bool> AddProfileAsync(Profile profile) => TransactionAsync(ctx => ctx.AddProfile(profile)); //Nem Add-olunk önmagában Profile-t! - J.
//public Task<bool> RemoveProfileAsync(Guid profileId) => TransactionAsync(ctx => ctx.RemoveProfile(profileId)); //Nem törlünk Profile-t! - J.
#endregion Profile
#region EmailMessage
public Task<EmailMessage?> GetEmailMessageByIdAsync(Guid emailMessageId) => SessionAsync(ctx => ctx.GetEmailMessageById(emailMessageId));
public Task<List<EmailMessage>> GetEmailMessagesByContextIdAsync(Guid contextId) => SessionAsync(ctx => ctx.GetEmailMessagesByContextId(contextId).OrderByDescending(x => x.Created).ToList());
public Task<List<EmailMessage>> GetEmailMessagesBySenderIdAsync(Guid senderId) => SessionAsync(ctx => ctx.GetEmailMessagesBySenderId(senderId).OrderByDescending(x => x.Created).ToList());
public Task<List<EmailMessage>> GetEmailMessagesBySenderEmailAddressAsync(string emailAddress) => SessionAsync(ctx => ctx.GetEmailMessagesBySenderEmailAddress(emailAddress).OrderByDescending(x => x.Created).ToList());
public Task<List<EmailMessage>> GetEmailMessagesAsync(Guid userId, Guid userProductMappingId) => SessionAsync(ctx => ctx.GetEmailMessages<EmailMessage, EmailRecipient>(userId, userProductMappingId).OrderByDescending(x => x.Created).ToList());
public Task<List<EmailMessage>> GetEmailMessagesAsync(Guid contextId, Guid userId, Guid userProductMappingId) => SessionAsync(ctx => ctx.GetEmailMessages<EmailMessage, EmailRecipient>(contextId, userId, userProductMappingId).OrderByDescending(x => x.Created).ToList());
public Task<List<EmailMessage>> GetAllEmailMessagesAsync() => SessionAsync(ctx => ctx.GetAllEmailMessages<EmailMessage, EmailRecipient>().OrderByDescending(x => x.Created).ToList());
public Task<bool> AddEmailMessageAsync(EmailMessage emailMessage)
=> TransactionAsync(ctx => ctx.AddEmailMessage(emailMessage));
public Task<bool> UpdateEmailMessageAsync(EmailMessage emailMessage)
=> TransactionAsync(ctx => ctx.UpdateEmailMessage(emailMessage));
public Task<bool> RemoveEmailMessageAsync(Guid emailMessageId)
=> TransactionAsync(ctx => ctx.RemoveEmailMessage(emailMessageId));
#endregion EmailMessage
#region ServiceProviders
//15. (IServiceProviderDataService) Create service provider
public Task<bool> AddCompanyAsync(Company serviceProvider) => TransactionAsync(ctx => ctx.AddCompany<Company, Profile, Address>(serviceProvider));
public Task<List<Company>> GetCompaniesAsync() => SessionAsync(ctx => ctx.GetCompanies().ToList());
public Task<string> GetCompaniesJsonAsync() => SessionAsync(ctx => ctx.Companies.ToJson());
public string GetCompaniesJson() => Session(ctx => ctx.Companies.ToJson());
public virtual Task<Company?> GetCompanyByIdAsync(Guid id) => SessionAsync(ctx => ctx.GetCompanyById(id));
public virtual Task<List<Company>> GetCompaniesByOwnerIdAsync(Guid id) => SessionAsync(ctx => ctx.GetCompaniesByOwnerId(id));
//public Task<UserProductMapping> 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<bool> UpdateCompanyAsync(Company company)
//{
// var result = NewUpdateCompanyAsync(company);
// return Task.FromResult(result.Result != null && !result.Result.Id.IsNullOrEmpty());
//}
public Task<Company?> UpdateCompanyAsync(Company company) => UpdateSafeAsync(company, (ctx, safeCompany) =>
{
ctx.Entry(safeCompany.Profile).CurrentValues.SetValues(company.Profile);
return ctx.UpdateCompany(safeCompany);
});
//public Task<bool> UpdateCompanyAsync(Company company, Profile profile)
// => TransactionAsync(ctx =>
// {
// ctx.UpdateProfile(profile);
// ctx.SaveChanges();
// return ctx.UpdateCompany(company);
// });
//13. (IserviceProviderDataService) delete service provider
public Task<bool> RemoveCompanyAsync(Guid companyId) => TransactionAsync(ctx => ctx.RemoveProductsByCompanyId(companyId) && ctx.RemoveCompany(companyId));
//public Task<bool> RemoveCompanyAsync(Company company) => RemoveCompanyAsync(company.Id);
#endregion
#region PermissionTypes
//10. (IPermissionService) create permission type
public Task<bool> 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<PermissionsType>();
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<List<PermissionsType>>? GetPermissionTypesByContextIdAsync(Guid contextId)
{
return Context.PermissionsTypes.Where(x => x.ContextId == contextId).ToListAsync();
}
public Task<int> 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<List<AssignedPermissionModel>> GetPermissionsOfUserProductMappingsAndGroupsAsyncByContextId(Guid contextId)
{
List<AssignedPermissionModel> result = new List<AssignedPermissionModel>();
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<List<PermissionContextMapping>> GetPermissionsForContextByContextIdAsync(Guid contextId)
{
List<PermissionContextMapping> permissionContextMappings = new List<PermissionContextMapping>();
//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<bool> 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<bool> 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<UserProductMapping> GetUserProductMappingsInPermissionGroupByGroupId(Guid groupId)
{
return Context.GetUserProductMappingsByPermissionGroupId(groupId).ToList();
//List<UserProductMapping> userProductMappings = new List<UserProductMapping>();
////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<bool> 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<bool> 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<List<AcLogItem>> 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<List<AcLogItem>> 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<AcLogItem>)!.ToList());
#endregion
}
}