using System; using AutoMapper; using System.Linq; using xModels.Dtos; using xIds.DbContext; using System.Threading; using xCommons.Extensions; using xIds.Configurations; using xIdentityModels.Dtos; using xExceptions.Constants; using System.Threading.Tasks; using xIdentityModels.Models; using System.Linq.Expressions; using xDataService.Extensions; using xIdentityModels.Extensions; using System.Collections.Generic; using xIdentityService.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace xIds.Providers { public class XPolicyProvider : IXPolicyProvider { // private readonly string permittedRole; private readonly XIdentityDbContext dbContext; private readonly XDataServiceConfiguration configuration; private readonly Action mapperConfigurationExp; public XPolicyProvider( XIdentityDbContext dbContext, XDataServiceConfiguration configuration, string permittedRole = "admin" ) { // this.dbContext = dbContext; this.permittedRole = permittedRole; this.configuration = configuration; // // Configure Mapper Options ... mapperConfigurationExp = cfg => { // cfg.CreateMap() .ReverseMap(); // cfg.CreateMap() .ReverseMap(); // cfg.CreateMap() .ReverseMap(); }; } // #region Permission ... private bool HasPermission( XUserClaimsInfoDto userInfo = null ) { // var result = permittedRole.IsNullOrEmpty(); if (result) { return result; } // result = !userInfo.IsNullOrDefault() && userInfo.Roles .Any(ur => ur.Equals( permittedRole, StringComparison.InvariantCultureIgnoreCase)); // return result; } #endregion // #region Readers ... /// /// retrieve whole items as queryable ... /// /// a flag for Tracking behaviour /// an Expression for Filter Items ... /// an Order Builder expression for Ordering Query ... /// public virtual IQueryable AsQueryable( bool asNoTracking = true, Expression> predicate = null, Func, IOrderedQueryable> orderBuilder = null ) { // var result = dbContext.PolicyDefinitions .Where(predicate) .AsQueryable(); if (asNoTracking) { result = result.AsNoTracking(); } // return result; } /// /// retrieve an Entity by it's Id ... /// /// /// /// /// public virtual async Task GetAsync( int id, bool ignoreSoftDeleteds = true, CancellationToken cancellationToken = default ) { // // Validate ... if (!id.IsValidIntId()) { XException.InvalidArgs.Throw(); } // var result = await FindOneAsync(x => x.Id.Equals(id)); if (result.IsNullOrDefault()) { XException.NotFound.Throw(); } // return result; } /// /// retrieve all exists Entities ... /// /// /// /// /// public virtual async Task> GetAllAsync( bool ignoreSoftDeleteds = true, Func, IOrderedQueryable> orderBuilder = null, CancellationToken cancellationToken = default ) { // // Prepare Predicate ... Expression> predicator = null; if (ignoreSoftDeleteds) { predicator = x => !x.Deleted; } // var queryable = AsQueryable( asNoTracking: true, predicate: predicator, orderBuilder: orderBuilder ); // var items = await queryable .ToListAsync(cancellationToken); var result = await EnrichRangeAsync( sources: items, cancellationToken: cancellationToken ); // return result; } /// /// find an Entity by providing a Conditional Expression ... /// /// /// /// /// public virtual async Task FindOneAsync( Expression> predicate, bool ignoreSoftDeleteds = true, CancellationToken cancellationToken = default ) { // // Prepare Predicate ... Expression> predicator = null; if (ignoreSoftDeleteds) { predicator = x => !x.Deleted; } // var queryable = AsQueryable( asNoTracking: true, orderBuilder: null, predicate: predicator ); // var item = await queryable .FirstOrDefaultAsync(cancellationToken); var result = await EnrichAsync( source: item, cancellationToken: cancellationToken ); // return result; } /// /// find a collection of Entities by proving a Conditional Expression ... /// /// /// /// /// /// public virtual async Task> FindManyAsync( Expression> predicate, bool ignoreSoftDeleteds = true, Func, IOrderedQueryable> orderBuilder = null, CancellationToken cancellationToken = default ) { // // Prepare Predicate ... Expression> predicator = null; if (ignoreSoftDeleteds) { predicator = x => !x.Deleted; } // var queryable = AsQueryable( asNoTracking: true, predicate: predicator, orderBuilder: orderBuilder ); // var items = await queryable .ToListAsync(cancellationToken); var result = await EnrichRangeAsync( sources: items, cancellationToken: cancellationToken ); // return result; } /// /// count all exists Entities ... /// /// /// /// public virtual async Task CountAsync( bool ignoreSoftDeleteds = true, CancellationToken cancellationToken = default ) { // // Prepare Predicate ... Expression> predicator = null; if (ignoreSoftDeleteds) { predicator = x => !x.Deleted; } // var queryable = AsQueryable( asNoTracking: true, orderBuilder: null, predicate: predicator ); // var result = await queryable.CountAsync(); // return result; } /// /// count all exists Entities Pages by providing page size ... /// /// /// /// /// /// public virtual async Task PagesCountAsync( int pageSize, int? totalItems = null, bool ignoreSoftDeleteds = true, CancellationToken cancellationToken = default ) { // int count = totalItems.HasValue ? totalItems.Value : await CountAsync( cancellationToken: cancellationToken, ignoreSoftDeleteds: ignoreSoftDeleteds ); int pagesCount = count / pageSize; // if (count % pageSize > 0) { pagesCount++; } // return pagesCount; } /// /// Check an Entity exists or not ... /// /// /// /// /// public virtual async Task IsExistsAsync( int id, bool ignoreSoftDeleteds = true, CancellationToken cancellationToken = default ) { // var result = false; // try { // var exists = await GetAsync( id: id, cancellationToken: cancellationToken, ignoreSoftDeleteds: ignoreSoftDeleteds ); // result = !exists.IsNullOrDefault(); } catch { } // return result; } #endregion // #region Query ... /// /// retrieve Entities based on XQuery Pagination structure ... /// /// /// /// /// /// /// public virtual async Task> QueryAsync( XQuery query, bool ignoreSoftDeleteds = true, Expression> predicate = null, Func, IOrderedQueryable> orderBuilder = null, CancellationToken cancellationToken = default ) { // // Normalize Query ... query = NormalizeQuery( source: query, configuration: configuration ); // var items = await GetAllAsync( orderBuilder: orderBuilder, cancellationToken: cancellationToken, ignoreSoftDeleteds: ignoreSoftDeleteds ); var totalItemsCount = items.Count(); // // Apply Filter ... if (!query.Filter.IsNullOrEmpty()) { // items = items .ApplyFilter(query.Filter); } int filteredItemsCount = items.Count(); // // Count Pages ... var totalPagesCount = query.CountPages(totalItemsCount); var filteredPagesCount = query.CountPages(filteredItemsCount); // // Apply Paging and Sorting ... if (totalItemsCount > 0 && filteredItemsCount > 0) { // // Apply Sorting ... items = items .ToList() .ApplySorting( query.SortBy, query.IsAscending ); // // Apply Paging ... items = items .ToList() .ApplyPaging( query.Page, query.PageSize ); } // var resultItems = await EnrichRangeAsync( sources: items, cancellationToken: cancellationToken ); // // Prepare Result ... var result = new XQueryResult { Page = query.Page, Items = [.. resultItems], PageSize = query.PageSize, TotalPages = totalPagesCount, TotalItems = totalItemsCount, TotalFilteredPages = filteredPagesCount, TotalFilteredItems = filteredItemsCount }; // return result; } #endregion // #region Add/Update/Remove ... /// /// add a new Entity ... /// /// /// /// /// /// public virtual async Task AddAsync( XPolicyDefinitionDto item, bool saveChanges = true, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validate ... if (!item.IsValidForAdd()) { XException.InvalidArgs.Throw(); } // // Permission ... var hasPermission = HasPermission(userInfo); if (!hasPermission) { XException.NotAuthorized.Throw(); } // var entity = item.MapConvert(); var entry = await dbContext.PolicyDefinitions.AddAsync( entity: entity, cancellationToken: cancellationToken ); // var changes = await dbContext.SaveChangesAsync(cancellationToken); var isChanged = changes > 0 && !entry.IsNull() && !entry.Entity.IsNullOrDefault(); if (!isChanged) { XException.ActionFailed.Throw(); } // var result = await EnrichAsync( source: entry.Entity, cancellationToken: cancellationToken ); return result; } /// /// Update an Entity values ... /// /// /// /// /// /// /// public virtual async Task UpdateAsync( int id, XPolicyDefinitionDto item, bool saveChanges = true, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validate ... if (id != item.Id || !id.IsValidIntId() || !item.IsValidForAdd()) { XException.InvalidArgs.Throw(); } // // Permission ... var hasPermission = HasPermission(userInfo); if (!hasPermission) { XException.NotAuthorized.Throw(); } // // Retrieve Exists Entity ... var exists = await dbContext.PolicyDefinitions .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); if (exists.IsNullOrDefault()) { XException.NotFound.Throw(); } // // Update Data on Exists Entity ... exists = exists.UpdateData( updateWith: item, propertyWhiteList: [], propertyBlackList: [ nameof(XPolicyDefinition.Id), ] ); // var entry = dbContext.PolicyDefinitions.Attach(exists); entry.State = EntityState.Modified; // var changes = await dbContext.SaveChangesAsync(cancellationToken); var isChanged = changes > 0 && !entry.IsNull() && !entry.Entity.IsNullOrDefault(); if (!isChanged) { XException.ActionFailed.Throw(); } // var result = await EnrichAsync( source: entry.Entity, cancellationToken: cancellationToken ); return result; } /// /// remove an Entity by it's Id ... /// /// /// /// /// /// /// public virtual async Task RemoveAsync( int id, bool softDelete = true, bool saveChanges = true, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validate ... if (!id.IsValidIntId()) { XException.InvalidArgs.Throw(); } // // Permission ... var hasPermission = HasPermission(userInfo); if (!hasPermission) { XException.NotAuthorized.Throw(); } // // Retrieve Exists Entity ... var exists = await dbContext.PolicyDefinitions .FirstOrDefaultAsync(x => x.Id == id && !x.Deleted); if (exists.IsNullOrDefault()) { XException.NotFound.Throw(); } // EntityEntry entry = null; if (softDelete) { // exists.Deleted = true; entry = dbContext.PolicyDefinitions.Update(exists); } else { entry = dbContext.PolicyDefinitions.Remove(exists); } // var changes = await dbContext.SaveChangesAsync(cancellationToken); var isChanged = changes > 0 && !entry.IsNull() && !entry.Entity.IsNullOrDefault(); if (!isChanged) { XException.ActionFailed.Throw(); } // var result = await EnrichAsync( source: entry.Entity, cancellationToken: cancellationToken ); return result; } #endregion // #region Custom ... /// /// Normalize an XQuery based on Data Service Configurations ... /// /// /// /// public XQuery NormalizeQuery( XQuery source, XDataServiceConfiguration configuration // ) { // if (source.IsNull()) { source = new XQuery(); } // // Page Size Normalization ... if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize) { source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize; } if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize) { source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize; } // return source; } #endregion // #region Enrichers ... /// /// Enrich Item ... /// /// /// /// public virtual async Task EnrichAsync( XPolicyDefinition source, CancellationToken cancellationToken = default ) { // var result = source.MapConvert(); result = await EnrichAsync( source: result, cancellationToken: cancellationToken ); // return result; } /// /// Enrich Item ... /// /// /// /// public virtual async Task EnrichAsync( XPolicyDefinitionDto source, CancellationToken cancellationToken = default ) { // var result = await Task.FromResult(source); return result; } /// /// Enrich a Collection of Items(s) ... /// /// /// /// public virtual async Task> EnrichRangeAsync( IEnumerable sources, CancellationToken cancellationToken = default ) { // var tasks = sources .Select(s => EnrichAsync(s, cancellationToken)); // var result = await Task.WhenAll(tasks); // return result; } /// /// Enrich a Collection of Items(s) ... /// /// /// /// public virtual async Task> EnrichRangeAsync( IEnumerable sources, CancellationToken cancellationToken = default ) { // var tasks = sources .Select(s => EnrichAsync(s, cancellationToken)); // var result = await Task.WhenAll(tasks); // return result; } #endregion } }