Compare commits
51 Commits
4eece52eaf
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 307c81001a | |||
| 9c5346213e | |||
| 6542d804f8 | |||
| f470367d89 | |||
| 6ec2187361 | |||
| 8c6102d161 | |||
| 3c3744c0ce | |||
| 46da385b92 | |||
| 210c1f414c | |||
| ca3772e2a8 | |||
| a01e61aafe | |||
| f3784d24bd | |||
| 7d032c4a2c | |||
| 1a6baef807 | |||
| b35017fddc | |||
| 893b063ae9 | |||
| 9b60f5116b | |||
| 11ebb0567a | |||
| 12cb46d054 | |||
| e00be89d1a | |||
| 569bf360e6 | |||
| 405215a8bf | |||
| 232491d4ac | |||
| d07bc2418b | |||
| 048456ddc7 | |||
| b57de5a97d | |||
| 2513d0f5b6 | |||
| 70e82567d8 | |||
| 600374a6f0 | |||
| 1754aa64a2 | |||
| 1c2c9cf3b8 | |||
| 41d49e4b89 | |||
| b6aec7a16b | |||
| be41adc0f3 | |||
| f8e877ac06 | |||
| c5a43ef2a0 | |||
| 315dee2f6c | |||
| 3126f025be | |||
| b44be4f9e2 | |||
| 88456e7f87 | |||
| 1fbcc2d197 | |||
| b3b52a8c48 | |||
| 4fa57efca4 | |||
| ed06e460c3 | |||
| 4f0718a4f5 | |||
| 986d0aa256 | |||
| b0fd71e193 | |||
| ee107d74c4 | |||
| 41a395af99 | |||
| 3c6d1b14de | |||
| 1428d989aa |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -414,3 +414,5 @@ FodyWeavers.xsd
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
/ignore
|
||||
/src/presentation/DigitalData.TaskFlow.API/Properties/PublishProfiles/IISProfileNet8.pubxml.user
|
||||
|
||||
65
DigitalData.TaskFlow.sln
Normal file
65
DigitalData.TaskFlow.sln
Normal file
@@ -0,0 +1,65 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.14.36717.8
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.TaskFlow.API", "src\presentation\DigitalData.TaskFlow.API\DigitalData.TaskFlow.API.csproj", "{C0F3BD78-47FF-4320-A139-99D42648BA6B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "presentation", "presentation", "{4F1A8452-FAEC-4EE4-87A3-DB0AF05B780F}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
.gitignore = .gitignore
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "core", "core", "{C3F5466A-4F6B-4DF3-B594-2B4FE943AC1E}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.TaskFlow.Domain", "src\core\DigitalData.TaskFlow.Domain\DigitalData.TaskFlow.Domain.csproj", "{42B3A931-DDB1-4648-9EFA-9812354C6982}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "infrastructure", "infrastructure", "{9C44DE52-84B0-4441-9419-E810762D195D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.TaskFlow.Infrastructure", "src\infrastructure\DigitalData.TaskFlow.Infrastructure\DigitalData.TaskFlow.Infrastructure.csproj", "{D414DF56-EBE6-4972-B76C-4004F1CEA812}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.TaskFlow.Application", "src\core\DigitalData.TaskFlow.Application\DigitalData.TaskFlow.Application.csproj", "{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{C0F3BD78-47FF-4320-A139-99D42648BA6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C0F3BD78-47FF-4320-A139-99D42648BA6B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C0F3BD78-47FF-4320-A139-99D42648BA6B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C0F3BD78-47FF-4320-A139-99D42648BA6B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{42B3A931-DDB1-4648-9EFA-9812354C6982}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{42B3A931-DDB1-4648-9EFA-9812354C6982}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{42B3A931-DDB1-4648-9EFA-9812354C6982}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{42B3A931-DDB1-4648-9EFA-9812354C6982}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D414DF56-EBE6-4972-B76C-4004F1CEA812}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D414DF56-EBE6-4972-B76C-4004F1CEA812}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D414DF56-EBE6-4972-B76C-4004F1CEA812}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D414DF56-EBE6-4972-B76C-4004F1CEA812}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{C0F3BD78-47FF-4320-A139-99D42648BA6B} = {4F1A8452-FAEC-4EE4-87A3-DB0AF05B780F}
|
||||
{4F1A8452-FAEC-4EE4-87A3-DB0AF05B780F} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{C3F5466A-4F6B-4DF3-B594-2B4FE943AC1E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{42B3A931-DDB1-4648-9EFA-9812354C6982} = {C3F5466A-4F6B-4DF3-B594-2B4FE943AC1E}
|
||||
{9C44DE52-84B0-4441-9419-E810762D195D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{D414DF56-EBE6-4972-B76C-4004F1CEA812} = {9C44DE52-84B0-4441-9419-E810762D195D}
|
||||
{FAC8E4F4-C0B2-4582-A5CE-A8BC76A135B8} = {C3F5466A-4F6B-4DF3-B594-2B4FE943AC1E}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {9CDB06DD-EB59-4309-8B48-B34F488F9D2F}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,48 @@
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Common.Behaviors;
|
||||
|
||||
/// <summary>
|
||||
/// Runs FluentValidation validators before a MediatR request reaches its handler.
|
||||
/// </summary>
|
||||
/// <typeparam name="TRequest">Request type.</typeparam>
|
||||
/// <typeparam name="TResponse">Response type.</typeparam>
|
||||
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
|
||||
: IPipelineBehavior<TRequest, TResponse>
|
||||
where TRequest : notnull
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the request and continues the pipeline when validation succeeds.
|
||||
/// </summary>
|
||||
/// <param name="request">Current request instance.</param>
|
||||
/// <param name="next">Next pipeline delegate.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Handler response when validation passes.</returns>
|
||||
/// <exception cref="ValidationException">Thrown when one or more validation errors are found.</exception>
|
||||
public async Task<TResponse> Handle(
|
||||
TRequest request,
|
||||
RequestHandlerDelegate<TResponse> next,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!validators.Any())
|
||||
{
|
||||
return await next(cancellationToken);
|
||||
}
|
||||
|
||||
var context = new ValidationContext<TRequest>(request);
|
||||
var validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken)));
|
||||
|
||||
var failures = validationResults
|
||||
.SelectMany(r => r.Errors)
|
||||
.Where(f => f is not null)
|
||||
.ToList();
|
||||
|
||||
if (failures.Count != 0)
|
||||
{
|
||||
throw new ValidationException(failures);
|
||||
}
|
||||
|
||||
return await next(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
|
||||
public sealed class InvalidWorkflowPayloadException(string message) : Exception(message)
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
|
||||
public interface IDocumentRepository
|
||||
{
|
||||
Task<Document?> GetAsync(int userId, long processId, long docId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a marker contract for repository abstractions in the application layer.
|
||||
/// </summary>
|
||||
public interface IRepository
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
|
||||
public interface IUserRepository : IRepository
|
||||
{
|
||||
Task<IEnumerable<AuthorizedUser>> GetAuthorizedAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Defines workflow-specific data access operations for reading and closing workflow items.
|
||||
/// </summary>
|
||||
public interface IWorkflowRepository : IRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets grouped workflow data for the given WISAG user identifier.
|
||||
/// </summary>
|
||||
/// <param name="wisagId">WISAG user identifier.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Workflow data grouped by source.</returns>
|
||||
Task<Workflow?> GetByWisagIdAsync(int wisagId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Closes a workflow item and returns procedure result code/message.
|
||||
/// </summary>
|
||||
/// <param name="userId">Internal user identifier expected by the procedure.</param>
|
||||
/// <param name="source">Source system identifier.</param>
|
||||
/// <param name="processId">Process identifier.</param>
|
||||
/// <param name="closingMethodId">Closing method identifier.</param>
|
||||
/// <param name="comment">Optional comment.</param>
|
||||
/// <param name="rejectionReasonId">Optional rejection reason identifier.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Close operation result.</returns>
|
||||
Task<WorkflowClosing?> CloseAsync(
|
||||
int userId,
|
||||
string source,
|
||||
long processId,
|
||||
int closingMethodId,
|
||||
string? comment,
|
||||
byte? rejectionReasonId,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using FluentValidation;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Reflection;
|
||||
using DigitalData.TaskFlow.Application.Common.Behaviors;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public const string LuckyPennySoftLicenseKeySection = "LuckyPennySoftLicenseKey";
|
||||
|
||||
public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var lpSoftLicenseKey = configuration[LuckyPennySoftLicenseKeySection];
|
||||
var hasLpSoftLicenseKey = !string.IsNullOrWhiteSpace(lpSoftLicenseKey);
|
||||
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
|
||||
services.AddMediatR(config =>
|
||||
{
|
||||
config.RegisterServicesFromAssembly(assembly);
|
||||
|
||||
if (hasLpSoftLicenseKey)
|
||||
config.LicenseKey = lpSoftLicenseKey;
|
||||
});
|
||||
|
||||
services.AddValidatorsFromAssembly(assembly);
|
||||
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
|
||||
services.AddAutoMapper(config =>
|
||||
{
|
||||
if (hasLpSoftLicenseKey)
|
||||
config.LicenseKey = lpSoftLicenseKey;
|
||||
}, assembly);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="16.2.0" />
|
||||
<PackageReference Include="FluentValidation" Version="12.1.1" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
|
||||
<PackageReference Include="MediatR" Version="14.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="11.0.0-rc.1.26425.128" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="11.0.0-rc.1.26425.128" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0-rc.1.26425.128" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DigitalData.TaskFlow.Domain\DigitalData.TaskFlow.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,37 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using MediatR;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Features.Documents.Queries;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="UserId"></param>
|
||||
/// <param name="ProcessId"></param>
|
||||
/// <param name="Id"></param>
|
||||
public sealed record GetDocumentQuery(int UserId, long ProcessId, long Id) : IRequest<JsonElement>;
|
||||
|
||||
public sealed class GetDocumentQueryHandler(IDocumentRepository Repo) : IRequestHandler<GetDocumentQuery, JsonElement>
|
||||
{
|
||||
public async Task<JsonElement> Handle(GetDocumentQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var document = await Repo.GetAsync(userId: request.UserId, processId: request.ProcessId, docId: request.Id, cancellationToken);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(document?.Result))
|
||||
{
|
||||
using var doc = JsonDocument.Parse(document.Result);
|
||||
var root = doc.RootElement;
|
||||
|
||||
if (root.ValueKind == JsonValueKind.Object &&
|
||||
root.TryGetProperty("response", out var response))
|
||||
{
|
||||
return response.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidWorkflowPayloadException(
|
||||
"Stored procedure returned an invalid payload. Expected a JSON object with a 'response' property.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using MediatR;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Features.Users.Queries;
|
||||
|
||||
public sealed record GetAuthorizedUsersQuery : IRequest<GetAuthorizedUsersResult>;
|
||||
|
||||
public sealed record GetAuthorizedUsersResult(IEnumerable<GetAuthorizedUsersMeta> Meta, IEnumerable<int> Wisagids);
|
||||
|
||||
public sealed record GetAuthorizedUsersMeta(int? Code, string Message);
|
||||
|
||||
public sealed class GetAuthorizedUsersQueryHandler(IUserRepository repo) : IRequestHandler<GetAuthorizedUsersQuery, GetAuthorizedUsersResult>
|
||||
{
|
||||
public async Task<GetAuthorizedUsersResult> Handle(GetAuthorizedUsersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var users = await repo.GetAuthorizedAsync(cancellationToken);
|
||||
|
||||
return new GetAuthorizedUsersResult(
|
||||
Meta: [new GetAuthorizedUsersMeta(Code: 0, Message: "OK")],
|
||||
Wisagids: users.Select(x => x.WisagId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using MediatR;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Features.Workflows.Commands;
|
||||
|
||||
public sealed record CloseWorkflowCommand(
|
||||
int WisagId,
|
||||
string Source,
|
||||
long ProcessId,
|
||||
int ClosingMethodId,
|
||||
string? Comment,
|
||||
byte? RejectionReasonId) : IRequest<CloseWorkflowResult>;
|
||||
|
||||
public sealed record CloseWorkflowResult(
|
||||
int? Code,
|
||||
string Message);
|
||||
@@ -0,0 +1,26 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using MediatR;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Features.Workflows.Commands;
|
||||
|
||||
public sealed class CloseWorkflowCommandHandler(IWorkflowRepository Repo) : IRequestHandler<CloseWorkflowCommand, CloseWorkflowResult>
|
||||
{
|
||||
public async Task<CloseWorkflowResult> Handle(CloseWorkflowCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var procedureResult = await Repo.CloseAsync(
|
||||
userId: request.WisagId,
|
||||
source: request.Source,
|
||||
processId: request.ProcessId,
|
||||
closingMethodId: request.ClosingMethodId,
|
||||
comment: request.Comment,
|
||||
rejectionReasonId: request.RejectionReasonId,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
return procedureResult is null
|
||||
? throw new InvalidWorkflowPayloadException("Close workflow closing procedure returned no result.")
|
||||
: new CloseWorkflowResult(
|
||||
Code: procedureResult.Code,
|
||||
Message: procedureResult.Result ?? string.Empty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using MediatR;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.Application.Features.Workflows.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to fetch grouped workflow data for a WISAG user.
|
||||
/// </summary>
|
||||
/// <param name="WisagId">WISAG user identifier.</param>
|
||||
public sealed record GetWorkflowsQuery(int WisagId) : IRequest<JsonElement>;
|
||||
|
||||
public sealed class GetWorkflowsQueryHandler(IWorkflowRepository Repo) : IRequestHandler<GetWorkflowsQuery, JsonElement>
|
||||
{
|
||||
public async Task<JsonElement> Handle(GetWorkflowsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var workflow = await Repo.GetByWisagIdAsync(request.WisagId, cancellationToken);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(workflow?.Result))
|
||||
{
|
||||
using var document = JsonDocument.Parse(workflow.Result);
|
||||
var root = document.RootElement;
|
||||
|
||||
if (root.ValueKind == JsonValueKind.Object &&
|
||||
root.TryGetProperty("response", out var response))
|
||||
{
|
||||
return response.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidWorkflowPayloadException(
|
||||
"Stored procedure returned an invalid payload. Expected a JSON object with a 'response' property.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
public class AuthorizedUser
|
||||
{
|
||||
public int WisagId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
public class Document : ProcedureResultBase
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
public abstract class ProcedureResultBase
|
||||
{
|
||||
public virtual int? Code { get; init; }
|
||||
|
||||
public virtual string? Result { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
public class Workflow : ProcedureResultBase
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
|
||||
public sealed class WorkflowClosing : ProcedureResultBase
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using DigitalData.TaskFlow.Infrastructure.Persistence;
|
||||
using DigitalData.TaskFlow.Infrastructure.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace DigitalData.TaskFlow.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("TaskFlowDb");
|
||||
if (string.IsNullOrWhiteSpace(connectionString))
|
||||
throw new InvalidOperationException("Connection string 'TaskFlowDb' is not configured.");
|
||||
|
||||
services.AddDbContext<TaskFlowDbContext>(options =>
|
||||
{
|
||||
options.UseSqlServer(connectionString);
|
||||
});
|
||||
|
||||
services.AddScoped<IWorkflowRepository, WorkflowRepository>();
|
||||
services.AddScoped<IDocumentRepository, DocumentRepository>();
|
||||
services.AddScoped<IUserRepository, UserRepository>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="11.0.0-rc.1.26425.128" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="11.0.0-rc.1.26425.128" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0-rc.1.26425.128" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\core\DigitalData.TaskFlow.Application\DigitalData.TaskFlow.Application.csproj" />
|
||||
<ProjectReference Include="..\..\core\DigitalData.TaskFlow.Domain\DigitalData.TaskFlow.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,66 @@
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DigitalData.TaskFlow.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// EF Core DbContext for TaskFlow infrastructure data access.
|
||||
/// </summary>
|
||||
public sealed class TaskFlowDbContext(DbContextOptions<TaskFlowDbContext> options) : DbContext(options)
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the keyless result model used for workflow procedure reads.
|
||||
/// </summary>
|
||||
public DbSet<Workflow> Workflows => Set<Workflow>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the keyless result model used for document procedure reads.
|
||||
/// </summary>
|
||||
public DbSet<Document> Documents => Set<Document>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the keyless result model used for workflow close procedure results.
|
||||
/// </summary>
|
||||
public DbSet<WorkflowClosing> WorkflowClosings => Set<WorkflowClosing>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the keyless result model used for authorized users procedure results.
|
||||
/// </summary>
|
||||
public DbSet<AuthorizedUser> AuthorizedUsers => Set<AuthorizedUser>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<Workflow>(entity =>
|
||||
{
|
||||
entity.HasNoKey();
|
||||
entity.ToView(null);
|
||||
entity.Property(x => x.Code).HasColumnName("CODE").HasColumnType("int");
|
||||
entity.Property(x => x.Result).HasColumnName("RESULT").HasColumnType("nvarchar(max)");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Document>(entity =>
|
||||
{
|
||||
entity.HasNoKey();
|
||||
entity.ToView(null);
|
||||
entity.Property(x => x.Code).HasColumnName("CODE").HasColumnType("int");
|
||||
entity.Property(x => x.Result).HasColumnName("RESULT").HasColumnType("nvarchar(max)");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<WorkflowClosing>(entity =>
|
||||
{
|
||||
entity.HasNoKey();
|
||||
entity.ToView(null);
|
||||
entity.Property(x => x.Code).HasColumnName("CODE").HasColumnType("int");
|
||||
entity.Property(x => x.Result).HasColumnName("RESULT").HasColumnType("nvarchar(400)");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AuthorizedUser>(entity =>
|
||||
{
|
||||
entity.HasNoKey();
|
||||
entity.ToView(null);
|
||||
entity.Property(x => x.WisagId).HasColumnName("wisagid").HasColumnType("int");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
using DigitalData.TaskFlow.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DigitalData.TaskFlow.Infrastructure.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// Document repository implementation for reading document listing data and applying close operations.
|
||||
/// </summary>
|
||||
public sealed class DocumentRepository(TaskFlowDbContext context) : IDocumentRepository
|
||||
{
|
||||
public async Task<Document?> GetAsync(int userId, long processId, long docId, CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await context.Documents
|
||||
.FromSqlInterpolated(@$"EXEC [PRCUST_F19_GET_DOCUMENT] @pRESULT_TYPE = 'json', @pOBJECT_TYPE = 'Ferdinand', @pUSER_ID = {userId}, @pPROCESS_ID = {processId}, @pDOC_ID = {docId}")
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return rows.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
using DigitalData.TaskFlow.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DigitalData.TaskFlow.Infrastructure.Repositories;
|
||||
|
||||
public sealed class UserRepository(TaskFlowDbContext context) : IUserRepository
|
||||
{
|
||||
public async Task<IEnumerable<AuthorizedUser>> GetAuthorizedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await context.AuthorizedUsers
|
||||
.FromSqlInterpolated($"EXEC [dbo].[PRCUST_F19_GET_AUTHORIZED_USERS]")
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Interfaces;
|
||||
using DigitalData.TaskFlow.Domain.ProcedureResults;
|
||||
using DigitalData.TaskFlow.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DigitalData.TaskFlow.Infrastructure.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// Workflow repository implementation for reading workflow listing data and applying close operations.
|
||||
/// </summary>
|
||||
public sealed class WorkflowRepository(TaskFlowDbContext context) : IWorkflowRepository
|
||||
{
|
||||
public async Task<Workflow?> GetByWisagIdAsync(int wisagId, CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await context.Workflows
|
||||
.FromSqlInterpolated(@$"EXEC [PRCUST_F19_GET_LISTING_DATA] @pUSER_ID = {wisagId}, @pRESULT_TYPE = 'json', @pOBJECT_TYPE = 'Ferdinand'")
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return rows.FirstOrDefault();
|
||||
}
|
||||
|
||||
public async Task<WorkflowClosing?> CloseAsync(
|
||||
int userId,
|
||||
string source,
|
||||
long processId,
|
||||
int closingMethodId,
|
||||
string? comment,
|
||||
byte? rejectionReasonId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await context.WorkflowClosings
|
||||
.FromSqlInterpolated($@"
|
||||
DECLARE @ResultCode INT;
|
||||
DECLARE @ResultMessage NVARCHAR(400);
|
||||
|
||||
EXEC dbo.PRCUST_F19_CLOSING
|
||||
@UserID = {userId},
|
||||
@Source = {source},
|
||||
@ProcessID = {processId},
|
||||
@ClosingMethodID = {closingMethodId},
|
||||
@Comment = {comment},
|
||||
@RejectionReasonID = {rejectionReasonId},
|
||||
@ResultCode = @ResultCode OUTPUT,
|
||||
@ResultMessage = @ResultMessage OUTPUT;
|
||||
|
||||
SELECT @ResultCode AS CODE, @ResultMessage AS RESULT;")
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return rows.FirstOrDefault();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using DigitalData.TaskFlow.Application.Features.Documents.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Provides workflow read and close endpoints.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/documents")]
|
||||
public sealed class DocumentController(ISender sender) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns open documents for a WISAG user identifier.
|
||||
/// </summary>
|
||||
/// <param name="id">Document identifier.</param>
|
||||
/// <param name="userId">User identifier.</param>
|
||||
/// <param name="processId">Process identifier.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Document response envelope grouped by source.</returns>
|
||||
[HttpGet("{id:int}")]
|
||||
[ProducesResponseType(typeof(JsonElement), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status502BadGateway)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<ActionResult<JsonElement>> GetAsync([FromRoute] int id, [FromQuery] int userId, [FromQuery] long processId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return Ok(await sender.Send(new GetDocumentQuery(Id: id, UserId: userId, ProcessId: processId), cancellationToken));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using DigitalData.TaskFlow.Application.Features.Users.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
public sealed class UsersController(ISender sender) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("authorized")]
|
||||
[ProducesResponseType(typeof(GetAuthorizedUsersResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(GetAuthorizedUsersResult), StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(typeof(GetAuthorizedUsersResult), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetAuthorizedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(new GetAuthorizedUsersQuery(), cancellationToken);
|
||||
var code = result.Meta.FirstOrDefault()?.Code;
|
||||
|
||||
return code switch
|
||||
{
|
||||
0 => Ok(result),
|
||||
4 => Unauthorized(result),
|
||||
_ => StatusCode(StatusCodes.Status500InternalServerError, result)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using DigitalData.TaskFlow.API.Models;
|
||||
using DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
using DigitalData.TaskFlow.Application.Features.Workflows.Commands;
|
||||
using DigitalData.TaskFlow.Application.Features.Workflows.Queries;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Provides workflow read and close endpoints.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/workflows")]
|
||||
public sealed class WorkflowsController(ISender sender) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns open workflows for a WISAG user identifier.
|
||||
/// </summary>
|
||||
/// <param name="wisagId">WISAG user identifier.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Workflow response envelope grouped by source.</returns>
|
||||
[HttpGet("{wisagId:int}")]
|
||||
[ProducesResponseType(typeof(JsonElement), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status502BadGateway)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<ActionResult<JsonElement>> GetAsync([FromRoute] int wisagId, CancellationToken cancellationToken)
|
||||
{
|
||||
return Ok(await sender.Send(new GetWorkflowsQuery(wisagId), cancellationToken));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes a workflow for a WISAG user identifier, source, and process identifier.
|
||||
/// </summary>
|
||||
/// <param name="wisagId"></param>
|
||||
/// <param name="processId"></param>
|
||||
/// <param name="body"></param>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("{wisagId:int}/{source}/{processId:long}/closing")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> CloseAsync(
|
||||
[FromRoute] int wisagId,
|
||||
[FromRoute] long processId,
|
||||
[FromBody] CloseWorkflowReqBody body,
|
||||
[FromRoute] string source = "Ferdinand",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = await sender.Send(
|
||||
new CloseWorkflowCommand(
|
||||
WisagId: wisagId,
|
||||
Source: source,
|
||||
ProcessId: processId,
|
||||
ClosingMethodId: body.ClosingMethodId,
|
||||
Comment: body.Comment,
|
||||
RejectionReasonId: body.RejectionReasonId),
|
||||
cancellationToken);
|
||||
|
||||
var metaResult = new CloseWorkflowReqResponse() { Meta = [result] };
|
||||
return result.Code switch
|
||||
{
|
||||
0 => Ok(metaResult),
|
||||
4 => BadRequest(metaResult),
|
||||
6 => NotFound(metaResult),
|
||||
7 => Conflict(metaResult),
|
||||
_ => StatusCode(StatusCodes.Status500InternalServerError, metaResult)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<PackageId>DigitalData.TaskFlow.API</PackageId>
|
||||
<Title></Title>
|
||||
<Authors>Digital Data GmbH</Authors>
|
||||
<Company>Digital Data GmbH</Company>
|
||||
<Product>DigitalData.TaskFlow.API</Product>
|
||||
<Version>1.4.0-beta</Version>
|
||||
<FileVersion>1.4.0.0</FileVersion>
|
||||
<AssemblyVersion>1.4.0.0</AssemblyVersion>
|
||||
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
|
||||
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.SQLite" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.UI" Version="3.2.0" />
|
||||
<PackageReference Include="Serilog.UI.SqliteProvider" Version="1.1.0" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.17.14" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="Properties\PublishProfiles\IISProfileNet8.pubxml.user" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\core\DigitalData.TaskFlow.Application\DigitalData.TaskFlow.Application.csproj" />
|
||||
<ProjectReference Include="..\..\infrastructure\DigitalData.TaskFlow.Infrastructure\DigitalData.TaskFlow.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,55 @@
|
||||
using DigitalData.TaskFlow.API.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Enforces API key authentication for all requests under the /api path prefix.
|
||||
/// Expects the key to be supplied via the <c>X-Api-Key</c> request header.
|
||||
/// </summary>
|
||||
public sealed class ApiKeyAuthMiddleware(RequestDelegate next, IOptions<ApiKeyAuthOptions> options)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
// Snapshot at startup; options are not expected to change at runtime.
|
||||
private readonly string? _configuredKey = options.Value.Key;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
// Only guard /api/** routes; let non-API paths pass through (e.g. health, swagger).
|
||||
if (!context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// Treat a missing or empty configured key as a misconfiguration — deny all traffic.
|
||||
if (!string.IsNullOrWhiteSpace(_configuredKey)
|
||||
&& context.Request.Headers.TryGetValue("X-Api-Key", out var provided)
|
||||
&& string.Equals(provided, _configuredKey, StringComparison.Ordinal))
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
await WriteUnauthorizedAsync(context);
|
||||
}
|
||||
|
||||
private static Task WriteUnauthorizedAsync(HttpContext context)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
|
||||
var body = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7807",
|
||||
title = "Unauthorized",
|
||||
status = StatusCodes.Status401Unauthorized,
|
||||
detail = "A valid API key must be supplied via the X-Api-Key header."
|
||||
};
|
||||
|
||||
return context.Response.WriteAsync(JsonSerializer.Serialize(body, JsonOptions));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using DigitalData.TaskFlow.Application.Common.Exceptions;
|
||||
using FluentValidation;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Handles exceptions globally and returns RFC 7807 (Problem Details) compatible API envelopes.
|
||||
/// </summary>
|
||||
public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Validation failed for {Method} {Path}",
|
||||
context.Request.Method, context.Request.Path);
|
||||
|
||||
var errors = ex.Errors
|
||||
.GroupBy(e => e.PropertyName)
|
||||
.ToDictionary(
|
||||
g => g.Key,
|
||||
g => g.Select(e => e.ErrorMessage).ToArray()
|
||||
);
|
||||
|
||||
var response = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7807",
|
||||
title = "Validation Error",
|
||||
status = StatusCodes.Status400BadRequest,
|
||||
errors
|
||||
};
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(response, JsonOptions));
|
||||
}
|
||||
catch (InvalidWorkflowPayloadException ex)
|
||||
{
|
||||
logger.LogError(ex, "Invalid upstream payload for {Method} {Path}",
|
||||
context.Request.Method, context.Request.Path);
|
||||
|
||||
var response = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7807",
|
||||
title = "Bad Gateway",
|
||||
status = StatusCodes.Status502BadGateway,
|
||||
detail = ex.Message
|
||||
};
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status502BadGateway;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(response, JsonOptions));
|
||||
}
|
||||
catch (NotImplementedException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Not implemented: {Method} {Path}",
|
||||
context.Request.Method, context.Request.Path);
|
||||
|
||||
var response = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7807",
|
||||
title = "Not Implemented",
|
||||
status = StatusCodes.Status501NotImplemented
|
||||
};
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status501NotImplemented;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(response, JsonOptions));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled exception for {Method} {Path}",
|
||||
context.Request.Method, context.Request.Path);
|
||||
|
||||
var response = new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7807",
|
||||
title = "Internal Server Error",
|
||||
status = StatusCodes.Status500InternalServerError
|
||||
};
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(response, JsonOptions));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Models;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class CloseWorkflowReqBody
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonPropertyName("closing_method_id")]
|
||||
public int ClosingMethodId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string? Comment { get; init; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[JsonPropertyName("rejection_reason_id")]
|
||||
public byte? RejectionReasonId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using DigitalData.TaskFlow.Application.Features.Workflows.Commands;
|
||||
|
||||
namespace DigitalData.TaskFlow.API.Models;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class CloseWorkflowReqResponse
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<CloseWorkflowResult> Meta { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.TaskFlow.API.Options;
|
||||
|
||||
public sealed class ApiKeyAuthOptions
|
||||
{
|
||||
public const string SectionName = "ApiKey";
|
||||
|
||||
public string? Key { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.TaskFlow.API.Options;
|
||||
|
||||
public sealed class SwaggerOptions
|
||||
{
|
||||
public const string SectionName = "Swagger";
|
||||
|
||||
public bool EnabledInProduction { get; init; }
|
||||
}
|
||||
186
src/presentation/DigitalData.TaskFlow.API/Program.cs
Normal file
186
src/presentation/DigitalData.TaskFlow.API/Program.cs
Normal file
@@ -0,0 +1,186 @@
|
||||
using DigitalData.TaskFlow.Application;
|
||||
using DigitalData.TaskFlow.API.Middleware;
|
||||
using DigitalData.TaskFlow.API.Options;
|
||||
using DigitalData.TaskFlow.Infrastructure;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Scalar.AspNetCore;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using Serilog.Ui.Core.Extensions;
|
||||
using Serilog.Ui.SqliteDataProvider.Extensions;
|
||||
using Serilog.Ui.Web.Extensions;
|
||||
|
||||
var tempConfig = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
|
||||
.Build();
|
||||
|
||||
var logDirectoryRaw = tempConfig.GetValue<string>("Application:LogDirectory") ?? "logs";
|
||||
var logDirectory = Path.IsPathRooted(logDirectoryRaw)
|
||||
? logDirectoryRaw
|
||||
: Path.Combine(AppContext.BaseDirectory, logDirectoryRaw);
|
||||
Directory.CreateDirectory(logDirectory);
|
||||
var sqliteDbPath = Path.Combine(logDirectory, "logs.db");
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.MinimumLevel.Information()
|
||||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("System", LogEventLevel.Warning)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.File(
|
||||
path: Path.Combine(logDirectory, "taskflow-.log"),
|
||||
rollingInterval: RollingInterval.Day,
|
||||
retainedFileCountLimit: 30,
|
||||
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true)
|
||||
.CreateBootstrapLogger();
|
||||
|
||||
try
|
||||
{
|
||||
Log.Information("Starting TaskFlow API");
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var config = builder.Configuration;
|
||||
|
||||
builder.Host.UseSerilog((context, services, loggerConfiguration) =>
|
||||
{
|
||||
loggerConfiguration
|
||||
.ReadFrom.Configuration(context.Configuration)
|
||||
.ReadFrom.Services(services)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.File(
|
||||
path: Path.Combine(logDirectory, "taskflow-.log"),
|
||||
rollingInterval: RollingInterval.Day,
|
||||
retainedFileCountLimit: 30,
|
||||
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true);
|
||||
|
||||
if (context.HostingEnvironment.IsDevelopment())
|
||||
{
|
||||
loggerConfiguration.WriteTo.Console(
|
||||
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
}
|
||||
});
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddApplicationServices(config);
|
||||
builder.Services.AddInfrastructureServices(config);
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
var apiKeyConfigured = !string.IsNullOrWhiteSpace(config[$"{ApiKeyAuthOptions.SectionName}:Key"]);
|
||||
|
||||
builder.Services.AddSwaggerGen(options =>
|
||||
{
|
||||
options.SwaggerDoc("v1", new OpenApiInfo
|
||||
{
|
||||
Title = "DigitalData TaskFlow API",
|
||||
Version = "v1",
|
||||
Description = """
|
||||
Integrations-API für taskFLOW Workflow- und Dokumentenoperationen.
|
||||
|
||||
---
|
||||
|
||||
- [Serilog Protokoll-Viewer](/serilog-ui)
|
||||
""",
|
||||
Contact = new OpenApiContact
|
||||
{
|
||||
Name = "Digital Data GmbH",
|
||||
Url = new Uri("https://digitaldata.works/"),
|
||||
Email = "info-flow@digitaldata.works"
|
||||
}
|
||||
});
|
||||
|
||||
if (apiKeyConfigured)
|
||||
{
|
||||
options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
In = ParameterLocation.Header,
|
||||
Name = "X-Api-Key",
|
||||
Description = "Optionaler API-Schlüssel. Leer lassen, falls nicht erforderlich."
|
||||
});
|
||||
|
||||
options.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{
|
||||
Type = ReferenceType.SecurityScheme,
|
||||
Id = "ApiKey"
|
||||
}
|
||||
},
|
||||
[]
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
builder.Services
|
||||
.AddOptions<SwaggerOptions>()
|
||||
.Bind(config.GetSection(SwaggerOptions.SectionName));
|
||||
|
||||
builder.Services
|
||||
.AddOptions<ApiKeyAuthOptions>()
|
||||
.Bind(config.GetSection(ApiKeyAuthOptions.SectionName));
|
||||
|
||||
builder.Services.AddSerilogUi(options =>
|
||||
{
|
||||
options.UseSqliteServer(databaseOptions =>
|
||||
{
|
||||
databaseOptions.WithConnectionString($"Data Source={sqliteDbPath}");
|
||||
databaseOptions.WithTable("Logs");
|
||||
});
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
var swaggerOptions = app.Services
|
||||
.GetRequiredService<Microsoft.Extensions.Options.IOptions<SwaggerOptions>>()
|
||||
.Value;
|
||||
var apiKeyOptions = app.Services
|
||||
.GetRequiredService<Microsoft.Extensions.Options.IOptions<ApiKeyAuthOptions>>()
|
||||
.Value;
|
||||
|
||||
var enableSwagger = app.Environment.IsDevelopment() || swaggerOptions.EnabledInProduction;
|
||||
var enforceApiKey = !string.IsNullOrWhiteSpace(apiKeyOptions.Key);
|
||||
|
||||
app.UseMiddleware<ExceptionHandlingMiddleware>();
|
||||
if (enforceApiKey)
|
||||
{
|
||||
app.UseMiddleware<ApiKeyAuthMiddleware>();
|
||||
}
|
||||
app.UseSerilogRequestLogging();
|
||||
|
||||
if (enableSwagger)
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
app.MapScalarApiReference(options =>
|
||||
{
|
||||
options.Title = "DigitalData TaskFlow API";
|
||||
options.Theme = ScalarTheme.BluePlanet;
|
||||
});
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseSerilogUi();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
|
||||
Log.Information("TaskFlow API started successfully");
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Log.Fatal(exception, "TaskFlow API failed to start");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<WebPublishMethod>Package</WebPublishMethod>
|
||||
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
|
||||
<LastUsedPlatform>Any CPU</LastUsedPlatform>
|
||||
<SiteUrlToLaunchAfterPublish />
|
||||
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
|
||||
<ExcludeApp_Data>false</ExcludeApp_Data>
|
||||
<ProjectGuid>5e0e17c0-ff5a-4246-bf87-1add85376a27</ProjectGuid>
|
||||
<DesktopBuildPackageLocation>M:\App&Service\0 DD - Funktionsmodule\TaskFlow\PreRelease\API\net8\$(Version)\DigitalData.TaskFlow.API.zip</DesktopBuildPackageLocation>
|
||||
<PackageAsSingleFile>true</PackageAsSingleFile>
|
||||
<DeployIisAppPath>EnvelopeGenerator</DeployIisAppPath>
|
||||
<_TargetId>IISWebDeployPackage</_TargetId>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<SelfContained>true</SelfContained>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<EnvironmentName>Production</EnvironmentName>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:63206",
|
||||
"sslPort": 44315
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5062",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7131;http://localhost:5062",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning",
|
||||
"System": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ApiKey": {
|
||||
"Key": "jGXP7m536fnyTVCh4NROu1wgjaSOrJ5"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
33
src/presentation/DigitalData.TaskFlow.API/appsettings.json
Normal file
33
src/presentation/DigitalData.TaskFlow.API/appsettings.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning",
|
||||
"System": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"TaskFlowDb": "Server=SDD-VHP04-SQL19\\DD_TESTING01;Database=DD_ECM;User Id=sa;Password=123456789dD!;Encrypt=false;TrustServerCertificate=True;"
|
||||
},
|
||||
"ApiKey": {
|
||||
"Key": "jGXP7m536fnyTVCh4NROu1wgjaSOrJ5"
|
||||
},
|
||||
"LuckyPennySoftLicenseKey": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODE2MTI4MDAwIiwiaWF0IjoiMTc4NDYyNDU1NyIsImFjY291bnRfaWQiOiIwMTk4M2M1OWU0YjM3MjhlYmZkMzEwM2MyYTQ4NmU4NSIsImN1c3RvbWVyX2lkIjoiMDE5ODNjNTllNGIzNzI4ZWJmZDMxMDNjMmE0ODZlODUiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiJ9.IUUO926m9crYGYxMjjKD_n9BnUm-EDyjFIn0YmMUCo7C-QTwvB8WhXP8veTSFsBq-leIIDJ4jyl7Pgc_7ciwg1XhUSIs4mkQroEUaSFCGOxw7Pi41WM8MK5YFSaqLTYYXec9zxgiJbGzABbh3CHTSup3okGnVm_CMoPEs91l2c0A6N1JyZy74urd_tF0KGVKf0MOvzdlQIWLQ8o73S4pTv2N-F6UlzI0fdMtTHMLNNQyr0NdWdnuBk_jMBXO-gy5RE_oCRfMTTYRX2n3XLK6pTfXE0Ct338o9F5sH8Ph2lTXSu56cpdsfZOQZGqCH0LoFp1Dd7RJgIgNmBiTGfvDnA",
|
||||
"Swagger": {
|
||||
"EnabledInProduction": false
|
||||
},
|
||||
"Application": {
|
||||
"LogDirectory": "logs"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user