Files
jube-fork/Jube.App/Controllers/Session/SessionCaseSearchCompiledSqlController.cs
richard-churchman 811c938462 Improved Case Automation POST body conext and other minor issues:
* Pushed Case Workflow Display HTML rendering logic down into a controller for improved security and consistent tokenisation of the Jube token format against context. Included a migration to update the default demo entry to use proper tokenisation. Updated the repository to support fetching CaseWorkflowDisplay with appropriate security.
* Implemented improved tokenisation of the EntityAnalysisModelInstanceEntryPayload model via a common extension method on EntityAnalysisModelInstanceEntryPayload, used consistently across the system for serialisation and storage.
* Included a migration to update the tokenisation format for full CaseWorkflowDisplay support.
* Fixed an issue where CaseWorkflowFilter was incorrectly filtering on CaseWorkflowStatus.Guid instead of CaseWorkflowStatus.Name, causing the GUID to be returned rather than the display name on the template/demo model. (The remainder was fixed in GitHub issue #6.) Included a migration with a corrective SQL statement.
* Fixed an issue where tokens were not being stored alongside CaseWorkflowFilter definition configuration. It now behaves identically to CaseSearch. Note: migrating missing tokens is not feasible as it requires JS-side parsing via JQueryBuilder.
* Reduced the size of the CaseWorkflowForm invocation to include only the required fields given the new POST body context being rendered server side. Improved API serialisation by using a dictionary for form payload keys and values.
* Consolidated JSON serialisation settings into DI and updated usages throughout.
* Updated EntityAnalysisModelInstanceEntryPayload write serialisers to handle deserialisation, which is required to support tokenisation of new Case Automation POST bodies.
* Created an extension method on the EntityAnalysisModelInstanceEntryPayload to centralise tokenisation of strings across Activation and Case Automation on a consistent basis. Simplified Case Notification and Case HTTP dispatch by removing tokenisation logic from those classes.
* Removed a redundant field from the CaseWorkflowFormEntry POCO (database left unchanged for now).
* Fixed a bug in Case session SQL rebuilding where the rebuild date was not being correctly checked for null or default value, which caused a failure in the last migration.
* Made minor modifications to the Create Case process and method signature to skip serialisation when the payload object required for tokenisation is already available on the thread (e.g. during synchronous reprocessing).
* Updated Case Workflow Macro processing to fetch the archive payload for the case from the database, improving security of that invocation endpoint.
* Removed what appeared to be a duplicate EntityAnalysisModelInstanceEntryPayload model introduced during refactoring.
* Fixed a but in Case Worfkflow Display Role assigment owing to volatile Guid in its update.
2026-02-22 13:08:42 +02:00

226 lines
8.2 KiB
C#

/* Copyright (C) 2022-present Jube Holdings Limited.
*
* This file is part of Jube™ software.
*
* Jube™ is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* Jube™ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with Jube™. If not,
* see <https://www.gnu.org/licenses/>.
*/
namespace Jube.App.Controllers.Session
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Code;
using Data.Context;
using Data.Poco;
using Data.Reporting;
using Data.Repository;
using Dto;
using DynamicEnvironment;
using FluentMigrator.Runner;
using FluentValidation;
using FluentValidation.Results;
using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Validators;
[Route("api/[controller]")]
[Produces("application/json")]
[Authorize]
public class SessionCaseSearchCompiledSqlController : Controller
{
private readonly DbContext dbContext;
private readonly DynamicEnvironment dynamicEnvironment;
private readonly ILog log;
private readonly IMapper mapper;
private readonly PermissionValidation permissionValidation;
private readonly string userName;
private readonly IValidator<SessionCaseSearchCompiledSqlDto> validator;
public SessionCaseSearchCompiledSqlController(ILog log,
DynamicEnvironment dynamicEnvironment,
IHttpContextAccessor httpContextAccessor)
{
if (httpContextAccessor.HttpContext?.User.Identity != null)
{
userName = httpContextAccessor.HttpContext.User.Identity.Name;
}
this.log = log;
dbContext =
DataConnectionDbContext.GetDbContextDataConnection(dynamicEnvironment.AppSettings("ConnectionString"));
permissionValidation = new PermissionValidation(dbContext, userName);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SessionCaseSearchCompiledSql, SessionCaseSearchCompiledSqlDto>();
cfg.CreateMap<SessionCaseSearchCompiledSqlDto, SessionCaseSearchCompiledSql>();
});
mapper = new Mapper(config);
validator = new SessionCaseSearchCompiledSqlDtoValidator();
this.dynamicEnvironment = dynamicEnvironment;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
dbContext.Close();
dbContext.Dispose();
}
base.Dispose(disposing);
}
[HttpGet("ByGuid/{guid:Guid}")]
public async Task<ActionResult<List<dynamic>>> ExecuteByGuidAsync(Guid guid, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
1
}))
{
return Forbid();
}
var repository = new SessionCaseSearchCompiledSqlRepository(dbContext, userName);
var modelCompiled = repository.GetByGuid(guid);
if (modelCompiled == null)
{
return NotFound();
}
await CheckRebuildAsync(modelCompiled, token).ConfigureAwait(false);
var postgres = new Postgres(dynamicEnvironment.AppSettings("ConnectionString"));
var tokens = JsonConvert.DeserializeObject<List<object>>(modelCompiled.FilterTokens);
var sw = new StopWatch();
sw.Start();
var value = await postgres.ExecuteByOrderedParametersAsync(modelCompiled.SelectSqlSearch
+ " "
+ modelCompiled.WhereSql
+ " " + modelCompiled.OrderSql + " limit 100", tokens, token).ConfigureAwait(false);
sw.Stop();
var modelInsert = new SessionCaseSearchCompiledSqlExecution
{
SessionCaseSearchCompiledSqlId = modelCompiled.Id,
Records = value.Count,
ResponseTime = sw.ElapsedTime().Milliseconds
};
var sessionCaseSearchCompiledSqlExecutionRepository =
new SessionCaseSearchCompiledSqlExecutionRepository(dbContext, userName);
await sessionCaseSearchCompiledSqlExecutionRepository.InsertAsync(modelInsert, token);
return Ok(value);
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
private async Task<SessionCaseSearchCompiledSql> CheckRebuildAsync(SessionCaseSearchCompiledSql modelCompiled, CancellationToken token = default)
{
if (modelCompiled.Rebuild == 1 && (modelCompiled.RebuildDate != null || modelCompiled.RebuildDate == default(DateTime)))
{
return await CompileSql.CompileAsync(dbContext, modelCompiled, userName, token).ConfigureAwait(false);
}
return modelCompiled;
}
[HttpGet("ByLast")]
public async Task<ActionResult<SessionCaseSearchCompiledSqlDto>> ExecuteByLastAsync(CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
1
}))
{
return Forbid();
}
var repository = new SessionCaseSearchCompiledSqlRepository(dbContext, userName);
var modelCompiled = await repository.GetByLastAsync(token);
if (modelCompiled == null)
{
return new SessionCaseSearchCompiledSqlDto
{
NotFound = true
};
}
modelCompiled = await CheckRebuildAsync(modelCompiled, token).ConfigureAwait(false);
return Ok(mapper.Map<SessionCaseSearchCompiledSqlDto>(modelCompiled));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
[HttpPost]
[ProducesResponseType(typeof(SessionCaseSearchCompiledSqlDto), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationResult), (int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<SessionCaseSearchCompiledSqlDto>> CreateAsync(
[FromBody] SessionCaseSearchCompiledSqlDto model, CancellationToken token = default)
{
try
{
if (!permissionValidation.Validate(new[]
{
1
}))
{
return Forbid();
}
var results = await validator.ValidateAsync(model, token).ConfigureAwait(false);
if (!results.IsValid)
{
return BadRequest(results);
}
return Ok(mapper.Map<SessionCaseSearchCompiledSqlDto>(await CompileSql.CompileAsync(dbContext,
mapper.Map<SessionCaseSearchCompiledSql>(model),
userName, token).ConfigureAwait(false)));
}
catch (Exception e)
{
log.Error(e);
return StatusCode(500);
}
}
}
}