This commit is contained in:
2021-01-30 00:53:56 +00:00
parent a8f959ce45
commit 97ad44eae1
7 changed files with 136 additions and 181 deletions

View File

@@ -10,6 +10,7 @@ using System.Threading.Tasks;
using System.Linq; using System.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using EnumsNET;
namespace AyaNova.Api.Controllers namespace AyaNova.Api.Controllers
{ {
@@ -74,7 +75,20 @@ namespace AyaNova.Api.Controllers
try try
{ {
DataListReturnData r = await DataListFetcher.GetResponseAsync(ct, tableRequest, UserRoles, log, UserId);
DataListSavedColumnViewBiz biz = DataListSavedColumnViewBiz.GetBiz(ct, HttpContext);
var SavedView = await biz.GetAsync(biz.UserId, tableRequest.DataListKey, true);
var DataList = DataListFactory.GetAyaDataList(tableRequest.DataListKey);
if (DataList == null)
return BadRequest(new ApiErrorResponse(ApiErrorCode.NOT_FOUND, "DataListKey", $"DataList \"{tableRequest.DataListKey}\" specified does not exist"));
//check rights
if (!UserRoles.HasAnyFlags(DataList.AllowedRoles))
return StatusCode(403, new ApiNotAuthorizedResponse());
//hydrate the saved view and filter
DataListTableProcessingOptions dataListTableOptions = new DataListTableProcessingOptions(tableRequest, DataList, SavedView);
DataListReturnData r = await DataListFetcher.GetResponseAsync(ct, dataListTableOptions, DataList, UserRoles, log, UserId);
return Ok(r); return Ok(r);
} }
catch (System.UnauthorizedAccessException) catch (System.UnauthorizedAccessException)

View File

@@ -35,6 +35,23 @@ namespace AyaNova.DataList
return ret; return ret;
} }
//Verify listkey
internal static bool ListKeyIsValid(string listKey)
{
System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
{
if (!ti.IsAbstract && ti.ImplementedInterfaces.Contains(typeof(IDataListProcessing)))
{
if (ti.Name == listKey)
return true;
}
}
return false;
}
}//eoc }//eoc
}//eons }//eons

View File

@@ -17,24 +17,22 @@ namespace AyaNova.DataList
// Get the data list data requested // Get the data list data requested
// //
// //
internal static async Task<DataListReturnData> GetResponseAsync(AyContext ct, DataListTableRequest dataListTableRequest, AuthorizationRoles userRoles, ILogger log, long userId) internal static async Task<DataListReturnData> GetResponseAsync(AyContext ct, DataListTableProcessingOptions dataListTableOptions,IDataListProcessing DataList, AuthorizationRoles userRoles, ILogger log, long userId)
{ {
var DataList = DataListFactory.GetAyaDataList(dataListTableRequest.DataListKey); // var DataList = DataListFactory.GetAyaDataList(dataListTableRequest.DataListKey);
//was the name not found as a list? //was the name not found as a list?
if (DataList == null) // if (DataList == null)
throw new System.ArgumentOutOfRangeException($"DataList \"{dataListTableRequest.DataListKey}\" specified does not exist"); // throw new System.ArgumentOutOfRangeException($"DataList \"{dataListTableRequest.DataListKey}\" specified does not exist");
//check rights
if (!userRoles.HasAnyFlags(DataList.AllowedRoles))
throw new System.UnauthorizedAccessException("User roles insufficient for this datalist");
//turn the DataListTableRequest into a DataListTableProcesingOptions object here //turn the DataListTableRequest into a DataListTableProcesingOptions object here
//hydrates filter and column selections etc //hydrates filter and column selections etc
DataListTableProcessingOptions dataListTableOptions = new DataListTableProcessingOptions(dataListTableRequest, DataList, ct); // = new DataListTableProcessingOptions(dataListTableRequest, DataList, ct);
//#### TODO: below block into above method to clean it up and centralize it //#### TODO: below block into above method to clean it up and centralize it
@@ -233,11 +231,8 @@ namespace AyaNova.DataList
//BUILD THE COLUMNS RETURN PROPERTY JSON FRAGMENT //BUILD THE COLUMNS RETURN PROPERTY JSON FRAGMENT
Newtonsoft.Json.Linq.JArray ColumnsJSON = null; Newtonsoft.Json.Linq.JArray ColumnsJSON = null;
ColumnsJSON = DataList.GenerateReturnListColumns(dataListTableOptions.Columns);
ColumnsJSON = DataList.GenerateReturnListColumns(dataListTableOptions.Columns);//<<<-----this next
return new DataListReturnData(rows, totalRecordCount, ColumnsJSON); return new DataListReturnData(rows, totalRecordCount, ColumnsJSON);
} }

View File

@@ -1,8 +1,6 @@
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json; using Newtonsoft.Json;
using AyaNova.Util; using AyaNova.Util;
using AyaNova.Api.ControllerHelpers; using AyaNova.Api.ControllerHelpers;
@@ -44,180 +42,109 @@ namespace AyaNova.Biz
} }
////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE
//
internal async Task<DataListSavedColumnView> CreateAsync(DataListSavedColumnView newObject)
{
ValidateAsync(newObject);
if (HasErrors)
return null;
else
{
//delete the existing one in favor of this one
if (!await DeleteAsync(newObject.UserId, newObject.ListKey))
return null;
await ct.DataListSavedColumnView.AddAsync(newObject);
await ct.SaveChangesAsync();
// //////////////////////////////////////////////////////////////////////////////////////////////// return newObject;
// //CREATE }
// internal async Task<DataListSavedColumnView> CreateAsync(DataListSavedColumnView inObj) }
// {
// await ValidateAsync(inObj, true);
// if (HasErrors)
// return null;
// else
// {
// //do stuff with datafilter
// DataListSavedColumnView outObj = inObj;
// outObj.UserId = UserId;
// await ct.DataListSavedColumnView.AddAsync(outObj);
// await ct.SaveChangesAsync();
// //Handle child and associated items:
// //EVENT LOG
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, outObj.Id, BizType, AyaEvent.Created), ct);
// return outObj;
// }
// }
// ////////////////////////////////////////////////////////////////////////////////////////////////
// /// GET
// //Get one
// internal async Task<DataListSavedColumnView> GetAsync(long fetchId, bool logTheGetEvent = true)
// {
// //This is simple so nothing more here, but often will be copying to a different output object or some other ops
// var ret = await ct.DataListSavedColumnView.SingleOrDefaultAsync(z => z.Id == fetchId && (z.Public == true || z.UserId == UserId));
// if (logTheGetEvent && ret != null)
// {
// //Log
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, fetchId, BizType, AyaEvent.Retrieved), ct);
// }
// return ret;
// }
// //get ViewList (NOT PAGED)
// internal async Task<List<NameIdItem>> GetViewListAsync(string listKey)
// {
// List<NameIdItem> items = new List<NameIdItem>();
// if (!string.IsNullOrWhiteSpace(listKey))
// {
// items = await ct.DataListSavedColumnView
// .AsNoTracking()
// .Where(z => z.ListKey == listKey && (z.Public == true || z.UserId == UserId))
// .OrderBy(z => z.Name)
// .Select(z => new NameIdItem()
// {
// Id = z.Id,
// Name = z.Name
// }).ToListAsync();
// }
// return items;
// }
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
//UPDATE //GET
// //
//Internal, used by datalistfetcher via datalisttableprocessingoptions constructor
//put //can be called without full biz instantiation as it doesn't rely on UserId in biz object or other shit
internal async Task<bool> PutAsync(DataListSavedColumnView inObj) //maybe should be static?
internal async Task<DataListSavedColumnView> GetAsync(long userId, string listKey, bool createDefaultIfNecessary)
{ {
//preserve the owner ID if none was specified var ret = await ct.DataListSavedColumnView.AsNoTracking().SingleOrDefaultAsync(z => z.UserId == userId && z.ListKey == listKey);
if (inObj.UserId == 0) if(ret==null && createDefaultIfNecessary){
inObj.UserId = dbObject.UserId; if(!DataListFactory.ListKeyIsValid(listKey)){
throw new System.ArgumentOutOfRangeException($"ListKey '{listKey}' is not a valid DataListKey");
//Replace the db object with the PUT object }
CopyObject.Copy(inObj, dbObject, "Id"); ret=new DataListSavedColumnView();
//Set "original" value of concurrency token to input token ret.UserId=UserId;
//this will allow EF to check it out ret.ListKey=listKey;
ct.Entry(dbObject).OriginalValues["Concurrency"] = inObj.Concurrency; var dataList=DataListFactory.GetAyaDataList(listKey);
ret.Columns=JsonConvert.SerializeObject(dataList.DefaultColumns);
await ValidateAsync(dbObject); ret.Sort=JsonConvert.SerializeObject(dataList.DefaultSortBy);
if (HasErrors) return await CreateAsync(ret);
return false; }
await ct.SaveChangesAsync(); return ret;
//Log modification and save context
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
return true;
} }
// //////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
// //DELETE //DELETE
// // //
// internal async Task<bool> DeleteAsync(DataListSavedColumnView dbObject) internal async Task<bool> DeleteAsync(long userId, string listKey)
// { {
// //Determine if the object can be deleted, do the deletion tentatively //this is effectively the RESET route handler
// //Probably also in here deal with tags and associated search text etc //so it can be called any time even if there is no default list and it's a-ok
//because a new default will be created if needed
var dbObject = await GetAsync(userId, listKey, false);
if (dbObject != null)
{
ct.DataListSavedColumnView.Remove(dbObject);
await ct.SaveChangesAsync();
}
return true;
}
// //FUTURE POSSIBLE NEED
// //ValidateCanDelete(dbObject);
// if (HasErrors)
// return false;
// ct.DataListSavedColumnView.Remove(dbObject);
// await ct.SaveChangesAsync();
// //Delete sibling objects
// //Event log process delete
// await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.Name, ct);
// //Delete search index
// //Search.ProcessDeletedObjectKeywords(dbObject.Id, BizType);
// return true;
// }
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION //VALIDATION
// //
//Can save or update? //Can save or update?
private async Task ValidateAsync(DataListSavedColumnView inObj) private void ValidateAsync(DataListSavedColumnView inObj)
{ {
if (inObj.UserId != UserId) if (inObj.UserId != UserId)
AddError(ApiErrorCode.NOT_AUTHORIZED, "UserId", "Only own view can be modified"); AddError(ApiErrorCode.NOT_AUTHORIZED, "UserId", "Only own view can be modified");
if (string.IsNullOrWhiteSpace(inObj.ListKey)) if (string.IsNullOrWhiteSpace(inObj.ListKey))
AddError(ApiErrorCode.VALIDATION_REQUIRED, "ListKey"); AddError(ApiErrorCode.VALIDATION_REQUIRED, "ListKey");
if (!DataListFactory.ListKeyIsValid(inObj.ListKey))
//TODO TODO TODO
//THIS SHOULD USE NAME LIST INSTEAD OR BE DONE AT OBJECT ABOVE FOR DEFAULTS, SAME FOR FILTER BIZ THIS IS BASED OFF OF NO NEED TO INSTANTIATE
var DataList = DataListFactory.GetAyaDataList(inObj.ListKey);
if (DataList == null)
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "ListKey", $"ListKey \"{inObj.ListKey}\" DataListKey is not valid"); AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "ListKey", $"ListKey \"{inObj.ListKey}\" DataListKey is not valid");
}
if (inObj.ListKey.Length > 255) //Validate Sort JSON
AddError(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, "ListKey", "255 max");
//check if filter can be reconstructed into a C# filter object
try try
{ {
List<DataListFilterOption> dataListFilterOptions = JsonConvert.DeserializeObject<List<DataListFilterOption>>(inObj.Filter); JsonConvert.DeserializeObject<Dictionary<string, string>>(inObj.Sort);
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "Filter", "Filter is not valid JSON string, can't convert to List<DataListFilterOption>, error: " + ex.Message); AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "Sort", "Sort is not valid JSON string, can't convert to valid Dictionary<string, string> SortBy, error: " + ex.Message);
}
//Validate Columns JSON
try
{
JsonConvert.DeserializeObject<List<string>>(inObj.Columns);
}
catch (System.Exception ex)
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "Sort", "Sort is not valid JSON string, can't convert to valid Dictionary<string, string> SortBy, error: " + ex.Message);
} }
return; return;

View File

@@ -252,9 +252,7 @@ namespace AyaNova.Biz
AddError(ApiErrorCode.VALIDATION_REQUIRED, "ListKey"); AddError(ApiErrorCode.VALIDATION_REQUIRED, "ListKey");
var DataList = DataListFactory.GetAyaDataList(inObj.ListKey); if (!DataListFactory.ListKeyIsValid(inObj.ListKey))
if (DataList == null)
{ {
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "ListKey", $"ListKey \"{inObj.ListKey}\" DataListKey is not valid"); AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "ListKey", $"ListKey \"{inObj.ListKey}\" DataListKey is not valid");
} }
@@ -265,7 +263,7 @@ namespace AyaNova.Biz
//check if filter can be reconstructed into a C# filter object //check if filter can be reconstructed into a C# filter object
try try
{ {
List<DataListFilterOption> dataListFilterOptions = JsonConvert.DeserializeObject<List<DataListFilterOption>>(inObj.Filter); JsonConvert.DeserializeObject<List<DataListFilterOption>>(inObj.Filter);
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {

View File

@@ -155,9 +155,7 @@ namespace AyaNova.Biz
AddError(ApiErrorCode.NOT_FOUND); AddError(ApiErrorCode.NOT_FOUND);
return false; return false;
} }
ValidateCanDelete(dbObject); ValidateCanDelete(dbObject);
if (HasErrors)
return false;
if (HasErrors) if (HasErrors)
return false; return false;
ct.Project.Remove(dbObject); ct.Project.Remove(dbObject);

View File

@@ -1,41 +1,47 @@
using System.Collections.Generic; using System.Collections.Generic;
using AyaNova.DataList; using AyaNova.DataList;
using Newtonsoft.Json;
namespace AyaNova.Models namespace AyaNova.Models
{ {
internal sealed class DataListTableProcessingOptions : DataListProcessingBase internal sealed class DataListTableProcessingOptions : DataListProcessingBase
{ {
internal List<string> Columns { get; set; } internal List<string> Columns { get; set; }
internal const int MaxPageSize = 1000; internal const int MaxPageSize = 1000;
internal const int DefaultOffset = 0; internal const int DefaultOffset = 0;
internal const int DefaultLimit = 25; internal const int DefaultLimit = 25;
internal int? Offset { get; set; } internal int? Offset { get; set; }
internal int? Limit { get; set; } internal int? Limit { get; set; }
internal DataListTableProcessingOptions( internal DataListTableProcessingOptions(
DataListTableRequest request, DataListTableRequest request,
IDataListProcessing dataList, IDataListProcessing dataList,
AyContext ct) DataListSavedColumnView savedView,
DataListSavedFilter savedFilter)
{ {
//set some values from request //set some values from request
Limit=request.Limit; Limit = request.Limit;
Offset=request.Offset; Offset = request.Offset;
base.ClientCriteria=request.ClientCriteria; base.ClientCriteria = request.ClientCriteria;
base.DataListKey=request.DataListKey; base.DataListKey = request.DataListKey;
dataList.SetListOptionDefaultsIfNecessary(this);
//populate some values from saved filter and default columnview
//SET COLUMNS
//get user default DataListProcessingBase for this list key
//SET SORTBY //SET COLUMNS
Columns = JsonConvert.DeserializeObject<List<string>>(savedView.Columns);
//SET FILTER //SET SORTBY
base.SortBy = JsonConvert.DeserializeObject<Dictionary<string, string>>(savedView.Sort);
//SERVER FILTER PROCESSING HERE CODE SEE DATALISTFETCHER //SET FILTER
if (request.FilterId != 0)
{
base.Filter = JsonConvert.DeserializeObject<List<DataListFilterOption>>(savedFilter.Filter);
}
//SERVER FILTER PROCESSING HERE CODE SEE DATALISTFETCHER