Files
sockeye/server/biz/DashboardViewBiz.cs
2022-12-16 06:01:23 +00:00

123 lines
3.8 KiB
C#

using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Sockeye.Util;
using Sockeye.Api.ControllerHelpers;
using Sockeye.Models;
namespace Sockeye.Biz
{
//Only one dashboard view per user and there is always one so no delete method, not create method
internal class DashboardViewBiz : BizObject
{
internal DashboardViewBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
{
ct = dbcontext;
UserId = currentUserId;
UserTranslationId = userTranslationId;
CurrentUserRoles = UserRoles;
BizType = SockType.DashboardView;
}
internal static DashboardViewBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
{
if (httpContext != null)
return new DashboardViewBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
else
return new DashboardViewBiz(ct, 1, ServerBootConfig.SOCKEYE_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdmin);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//EXISTS
internal async Task<bool> ExistsAsync()
{
return await ct.DashboardView.AnyAsync(z => z.UserId == UserId);
}
////////////////////////////////////////////////////////////////////////////////////////////////
/// GET
//Get one - will create if there isn't one to get
internal async Task<DashboardView> GetAsync()
{
//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.DashboardView.SingleOrDefaultAsync(z => z.UserId == UserId);
if (ret == null)
{
ret = new DashboardView();
ret.UserId = UserId;
ct.DashboardView.Add(ret);
await ct.SaveChangesAsync();
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//UPDATE
//
//put
internal async Task<bool> PutAsync(DashboardView dbObject, string theView)
{
//todo: check this, is it correct to not be using the standard PUT methodology
dbObject.View = theView;
Validate(dbObject, false);
if (HasErrors)
return false;
await ct.SaveChangesAsync();
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION
//
//Can save or update?
private void Validate(DashboardView inObj, bool isNew)
{
//Filter json must parse
//this is all automated normally so not going to do too much parsing here
//just ensure it's basically there
if (!string.IsNullOrWhiteSpace(inObj.View))
{
try
{
var v = JArray.Parse(inObj.View);
}
catch (Newtonsoft.Json.JsonReaderException ex)
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "DashboardView", "DashboardView is not valid JSON string: " + ex.Message);
}
}
return;
}
/////////////////////////////////////////////////////////////////////
}//eoc
}//eons