Compare commits

...

51 Commits

Author SHA1 Message Date
307c81001a Update project version to 1.4.0-beta
Updated the `DigitalData.TaskFlow.API` project version from `1.3.0-beta` to `1.4.0-beta`. This includes updates to the `FileVersion` and `AssemblyVersion` from `1.3.0.0` to `1.4.0.0`, reflecting a new release with potential new features, improvements, or fixes.
2026-11-09 16:15:17 +01:00
9c5346213e Add GetAuthorizedUsersQuery and UsersController
Introduced the `GetAuthorizedUsersQuery` feature to retrieve
authorized users, including the query, result, metadata, and
handler implementation. The handler interacts with the
`IUserRepository` to fetch user data.

Added a new `UsersController` with an `[HttpGet("authorized")]`
endpoint to expose the query via a RESTful API. The endpoint
returns appropriate HTTP status codes (`200 OK`, `401
Unauthorized`, `500 Internal Server Error`) based on the
result metadata.

Included necessary `using` directives for MediatR, ASP.NET
Core, and application features.
2026-11-09 15:59:09 +01:00
6542d804f8 Add IUserRepository and implement UserRepository
Added the `IUserRepository` interface to define a method for retrieving authorized users asynchronously. Registered `IUserRepository` with its implementation `UserRepository` in the dependency injection container. Implemented `UserRepository` to execute a stored procedure and fetch authorized users using `TaskFlowDbContext`.
2026-11-09 15:15:16 +01:00
f470367d89 Add AuthorizedUser entity and DbSet to TaskFlowDbContext
A new `DbSet` property `AuthorizedUsers` was added to the
`TaskFlowDbContext` class to represent keyless results for
authorized users procedure results.

The `OnModelCreating` method was updated to configure the
`AuthorizedUser` entity as keyless, map it to a database view,
and define the `WisagId` property mapping.

Additionally, a new `AuthorizedUser` class was introduced in
the `DigitalData.TaskFlow.Domain.ProcedureResults` namespace
with an immutable `WisagId` property.
2026-11-09 15:07:13 +01:00
6ec2187361 Update project version to 1.3.0-beta
Updated the `DigitalData.TaskFlow.API` project version from `1.2.0-beta` to `1.3.0-beta`. This includes updates to the `FileVersion` and `AssemblyVersion` from `1.2.0.0` to `1.3.0.0`, reflecting a new release with potential new features, improvements, or changes.
2026-11-09 15:01:56 +01:00
8c6102d161 Refactor workflow closure logic and enhance API
Updated `CloseWorkflowCommand` to use nullable `Code` and `Message` properties for better result representation. Refactored `CloseWorkflowCommandHandler` to use a capitalized `Repo` and improved exception handling with `InvalidWorkflowPayloadException`. Enhanced `WorkflowsController` by implementing the `CloseAsync` method, which now processes `CloseWorkflowReqBody` and returns appropriate HTTP status codes. Updated XML documentation for clarity.
2026-11-04 10:07:33 +01:00
3c3744c0ce Add CloseWorkflowReqBody and CloseWorkflowReqResponse
Introduce two new classes in the DigitalData.TaskFlow.API.Models namespace to handle workflow closure requests and responses.

- CloseWorkflowReqBody.cs:
  - Added CloseWorkflowReqBody class with properties:
    - ClosingMethodId: int, mapped to "closing_method_id".
    - Comment: nullable string.
    - RejectionReasonId: nullable byte, mapped to "rejection_reason_id".

- CloseWorkflowReqResponse.cs:
  - Added CloseWorkflowReqResponse class with Meta property:
    - Meta: List of CloseWorkflowResult, initialized to an empty list.
2026-11-04 10:07:03 +01:00
46da385b92 Add CloseWorkflowCommandHandler for workflow closure
Introduce CloseWorkflowCommandHandler class to handle the
closure of workflows using the MediatR library. This class
implements IRequestHandler and processes CloseWorkflowCommand
requests, returning CloseWorkflowResult objects. It interacts
with IWorkflowRepository to execute the CloseAsync method,
validating the procedure result and throwing an exception if
the result is invalid. Necessary using directives for
DigitalData.TaskFlow.Application.Common.Interfaces and MediatR
are also added.
2026-11-03 20:57:45 +01:00
210c1f414c Add CloseAsync method to WorkflowRepository
Introduced a new asynchronous method `CloseAsync` in the
`WorkflowRepository` class to handle workflow process closing.
This method executes the `PRCUST_F19_CLOSING` stored procedure
with parameters for user ID, source, process ID, closing method
ID, comment, and rejection reason ID. It uses `FromSqlInterpolated`
for safe SQL parameterization and retrieves results with
`AsNoTracking()` and `ToListAsync(cancellationToken)`. The method
returns the first result as a `WorkflowClosing` object or `null`.
2026-11-03 20:44:08 +01:00
ca3772e2a8 Add CloseAsync method and WorkflowClosing entity
Introduced a new method `CloseAsync` in the `IWorkflowRepository`
interface to handle workflow item closure and return a procedure
result. Added a new class `WorkflowClosing` in `WorkflowClosing.cs`
as a sealed class inheriting from `ProcedureResultBase`.

Updated `TaskFlowDbContext` to include a `DbSet<WorkflowClosing>`
for keyless workflow close procedure results. Configured the
`WorkflowClosing` entity in `OnModelCreating` with specific
column mappings and a maximum length for the `Result` property.
2026-11-03 20:42:21 +01:00
a01e61aafe Add CloseWorkflowCommand with MediatR support
Introduce CloseWorkflowCommand and CloseWorkflowResult records
in CloseWorkflowCommand.cs within the DigitalData.TaskFlow
namespace. The command encapsulates data for closing a workflow,
including WisagId, Source, ProcessId, ClosingMethodId, Comment,
and RejectionReasonId. The result record provides ResultCode and
ResultMessage to convey the operation's outcome. These changes
utilize MediatR, aligning with the CQRS pattern for state
modification.
2026-11-03 20:34:34 +01:00
f3784d24bd Set API key in appsettings for all environments
Updated the `appsettings.Development.json` and `appsettings.json` files to replace the `ApiKey` value from `null` to `"jGXP7m536fnyTVCh4NROu1wgjaSOrJ5"`. This ensures that a specific API key is used in both development and production environments.
2026-10-31 22:56:32 +01:00
7d032c4a2c Update project version to 1.2.0-beta
The versioning information for the `DigitalData.TaskFlow.API` project has been updated. The `<Version>`, `<FileVersion>`, and `<AssemblyVersion>` elements have been incremented from `1.1.0-beta` to `1.2.0-beta`, and from `1.1.0.0` to `1.2.0.0` respectively. This minor version update likely includes new features or improvements that maintain backward compatibility.
2026-10-31 21:26:20 +01:00
1a6baef807 Add new endpoint and improve exception handling
Removed the `asByte` parameter from XML documentation in `DocumentController.cs`, indicating the method no longer supports byte array returns. Added a new HTTP POST endpoint `CloseAsync` in `WorkflowsController.cs`, which is currently not implemented and throws a `NotImplementedException`. Enhanced `ExceptionHandlingMiddleware.cs` to handle `NotImplementedException` by logging a warning and returning a `501 Not Implemented` response in a problem details format.
2026-10-31 21:25:49 +01:00
b35017fddc chore: update solution and remove obsolete documentation 2026-10-31 17:09:46 +01:00
893b063ae9 refactor(api): update document endpoints and middleware contracts 2026-10-31 17:09:33 +01:00
9b60f5116b refactor(infrastructure): align persistence with procedure result models 2026-10-31 17:09:21 +01:00
11ebb0567a refactor(application): update workflow queries and exception handling 2026-10-31 17:09:16 +01:00
12cb46d054 refactor(domain): replace workflow aggregates with procedure results 2026-10-31 17:09:10 +01:00
e00be89d1a Add CustDocBase64 entity and integrate into DbContext
Introduce a new entity class `CustDocBase64` mapped to the
`TBCUST_DOC_BASE64` table in the `dbo` schema. This class includes
properties for various document attributes. Update `TaskFlowDbContext`
to include a `DbSet<CustDocBase64>` for querying and interacting with
the table. Configure the entity in `OnModelCreating` to have no key
and map it to the appropriate table and schema.
2026-10-27 15:45:31 +01:00
569bf360e6 Update project version to 1.1.0
The versioning information for the DigitalData.TaskFlow.API project has been updated. The <Version>, <FileVersion>, and <AssemblyVersion> elements have been incremented from 1.0.0-beta, 1.0.0.0, and 1.0.0.0 respectively to 1.1.0-beta, 1.1.0.0, and 1.1.0.0. This indicates a minor version update, suggesting that new features or improvements have been added to the project while maintaining backward compatibility.
2026-10-26 11:46:37 +01:00
405215a8bf Enhance validation and data reading logic
Add validation in CloseWorkflowCommandHandler to reject "Contracts" as a source for closing operations. Modify ReadArray in WorkflowRepository to accept multiple property names, improving flexibility in data retrieval. Refactor database reader logic to extract JSON payloads more robustly, iterating over all fields and results.
2026-10-26 10:12:02 +01:00
232491d4ac Update development ports in launchSettings.json
Updated the `applicationUrl` property in the `https` profile of
`launchSettings.json` to use new ports:
- Changed `https://localhost:7049` to `https://localhost:7050`
- Changed `http://localhost:5298` to `http://localhost:5299`

This ensures the application runs on the updated ports during
development.
2026-10-20 11:21:46 +02:00
d07bc2418b Add API key authentication middleware support
Introduced `ApiKeyAuthOptions` for API key configuration,
including a `Key` property and `SectionName` for binding.
Updated `ApiKeyAuthMiddleware` to validate the `X-Api-Key`
header against the configured API key.

Added conditional middleware application in `Program.cs`
based on the presence of a configured API key. Bound the
`ApiKey` section in `appsettings.json` and
`appsettings.Development.json` to store the API key, with
a default value of `null`. This improves security and
centralizes API key management.
2026-10-20 11:21:18 +02:00
048456ddc7 Ignore IISProfileNet8.pubxml.user and remove its content
Updated the `.gitignore` file to exclude the `IISProfileNet8.pubxml.user` file from version control. Removed the `IISProfileNet8.pubxml.user` file entirely, which contained environment-specific configuration details such as a `History` property with timestamps and an empty `LastFailureDetails` property. This change prevents sensitive or local configuration data from being tracked in the repository.
2026-10-12 09:02:05 +02:00
b57de5a97d Add metadata and XML doc generation to project
Enhanced the project configuration by enabling XML documentation file generation with the `<GenerateDocumentationFile>` property. Added metadata properties such as `<PackageId>`, `<Authors>`, `<Company>`, `<Product>`, and versioning details to prepare the project for packaging and distribution. Configured the `<DocumentationFile>` property to specify the output path for the generated documentation.
2026-10-10 21:21:03 +02:00
2513d0f5b6 Add IIS publish profiles and update project file
Added `IISProfileNet8.pubxml` to define publish settings for the
application, including target framework `net8.0`, runtime
identifier `win-x64`, and deployment configuration for IIS.

Included `IISProfileNet8.pubxml.user` for user-specific metadata
such as publish history. Updated `DigitalData.TaskFlow.API.csproj`
to track the `.user` file under the `<None>` item group.
2026-10-10 21:18:49 +02:00
70e82567d8 Refactor workflows and improve API responses
- Added `BackToPerMethodId` constant and updated validation rules in `CloseWorkflowCommandValidator`.
- Refactored `GetWorkflowsQueryHandler` for simpler `hasListingData` logic.
- Replaced strongly-typed properties with `JsonElement` in `ContractsSourceBlock` and `FerdinandSourceBlock`.
- Updated `WorkflowListingReadModel` to use smaller data types for efficiency.
- Refactored `WorkflowRepository` to use JSON-based data retrieval and parsing.
- Introduced `MetaOnlyResponse` and `WorkflowsResponse` for consistent API responses.
- Updated `DocumentsController` and `WorkflowsController` to use new response types.
- Added `ApiKeyAuthMiddleware` for API key validation and integrated it into the middleware pipeline.
- Refactored `ExceptionHandlingMiddleware` to use `MetaOnlyResponse` for error handling.
- Performed general cleanup and modernization for improved readability and maintainability.
2026-10-10 20:47:31 +02:00
600374a6f0 feat(api): integrate Serilog bootstrap and in-app log viewer 2026-10-10 16:53:37 +02:00
1754aa64a2 chore(api): configure Serilog settings and logging packages 2026-10-10 16:53:03 +02:00
1c2c9cf3b8 Remove Microsoft.OpenApi package reference
The `Microsoft.OpenApi` package reference (version 3.10.2) was removed from the `DigitalData.TaskFlow.API.csproj` file. This change suggests that the project no longer requires this dependency, potentially due to a shift in functionality or the use of an alternative library.
2026-10-10 16:26:48 +02:00
41d49e4b89 fix(api): fail fast on unexpected null document payload 2026-10-10 16:12:56 +02:00
b6aec7a16b feat(infrastructure): add DB options and workflow close outcome evaluation 2026-10-10 16:12:17 +02:00
be41adc0f3 feat(application): enforce validation and API error mapping rules 2026-10-10 16:12:05 +02:00
f8e877ac06 feat(domain): add close workflow outcome semantics 2026-10-10 16:11:27 +02:00
c5a43ef2a0 feat(api): surface 403/404/409 responses via middleware and docs 2026-10-10 14:58:01 +02:00
315dee2f6c feat(application): map closing outcomes to API exceptions 2026-10-10 14:57:56 +02:00
3126f025be Add workflow and document APIs, middleware, and Swagger
Introduced `CloseWorkflowRequest` for closing workflows.
Added `DocumentsController` for document downloads and
`WorkflowsController` for workflow retrieval and closing.

Implemented `ExceptionHandlingMiddleware` for global exception
handling with structured API responses.

Enhanced Swagger configuration with metadata and production
support. Added `Scalar.AspNetCore` for API reference mapping.

Updated project dependencies and improved API documentation.
2026-10-10 13:50:26 +02:00
b44be4f9e2 Enhance workflow handling and enforce stricter exceptions
Enhanced `GetWorkflowsQueryHandler` to validate listing data
in workflow sources and return appropriate responses. Updated
`DocumentRepository.GetAsync` and `WorkflowRepository.CloseAsync`
to throw `NotSupportedException` for unimplemented functionality,
ensuring these methods cannot be used until finalized. Added
`DigitalData.TaskFlow.Domain.Enums` dependency to support new
logic in `GetWorkflowsQueryHandler`.
2026-10-10 11:34:17 +02:00
88456e7f87 feat(infrastructure): add EF Core context and repository implementations 2026-10-10 11:18:27 +02:00
1fbcc2d197 refactor(application): centralize API envelope creation and command mapping 2026-10-10 11:18:21 +02:00
b3b52a8c48 Update documentation for repo structure and DB practices
Added detailed sections to `AGENTS.md`:
- "Repo Snapshot (verified)" to describe the .NET 8 solution structure and current implementation state.
- "High-value Commands" with instructions for building and running the solution.
- "Architecture That Matters During Edits" to outline dependency direction, key libraries, and response contract.
- "Current Implementation Gaps (easy to miss)" to highlight incomplete implementations and areas needing verification.
- "Config/Security Gotcha" to warn about sensitive data in `appsettings.json`.

Updated `README.md`:
- Added "Wichtiger Hinweis zu DB-Spaltennamen" to explain DB column mapping practices and emphasize the need for final verification of stored procedure result sets.
- Clarified that DB field names are mapped only in the Infrastructure layer, not in Domain models.
2026-10-10 11:15:10 +02:00
4fa57efca4 docs: add layer readmes for architecture boundaries 2026-10-09 23:06:49 +02:00
ed06e460c3 feat(application): add workflow and document request handlers 2026-10-09 23:06:05 +02:00
4f0718a4f5 feat(application): add CQRS pipeline infrastructure and repository contracts 2026-10-09 23:06:00 +02:00
986d0aa256 feat(domain): add workflow API core models and meta codes 2026-10-09 23:05:47 +02:00
b0fd71e193 Add MediatR, FluentValidation, AutoMapper, and EF Core
Updated application and infrastructure layers to include MediatR, FluentValidation, AutoMapper, and Entity Framework Core.

- Added new dependencies to `DigitalData.TaskFlow.Application.csproj` and `DigitalData.TaskFlow.Infrastructure.csproj` for MediatR, FluentValidation, AutoMapper, and EF Core.
- Configured MediatR with options and license key support.
- Registered validators and AutoMapper profiles in the application layer.
- Introduced `MediatROptions` and `SwaggerOptions` for configuration.
- Updated `appsettings.json` with connection strings and configuration sections for MediatR and Swagger.
- Replaced placeholder comments in `DependencyInjection` classes with actual service registrations.
- Upgraded `Swashbuckle.AspNetCore` and added `FluentValidation.AspNetCore` for API validation.
2026-10-09 16:29:58 +02:00
ee107d74c4 Add DI setup for modular architecture
Introduced `DependencyInjection.cs` in Application and Infrastructure layers to centralize service registration. Updated project files to include necessary package references (`Microsoft.Extensions.Configuration.Abstractions` and `Microsoft.Extensions.DependencyInjection.Abstractions`) and project dependencies between layers. Integrated service registration in `Program.cs` to enable modular architecture for the API.
2026-10-09 15:24:17 +02:00
41a395af99 Add Domain, Application, and Infrastructure projects
Added three new projects: `DigitalData.TaskFlow.Domain`,
`DigitalData.TaskFlow.Application`, and
`DigitalData.TaskFlow.Infrastructure` to the solution.
Updated the solution file to include their paths, GUIDs,
build configurations, and nested structure.

Each project targets `.NET 8.0`, uses `Microsoft.NET.Sdk`,
and enables implicit usings and nullable reference types.
Introduced an `ExtensibilityGlobals` section with a
`SolutionGuid` for better solution management.
2026-10-09 15:18:32 +02:00
3c6d1b14de Add initial ASP.NET Core project structure
This commit introduces the initial setup for the DigitalData.TaskFlow solution:
- Added `DigitalData.TaskFlow.sln` to organize the project structure into `src`, `presentation`, `core`, and `infrastructure` folders.
- Created `DigitalData.TaskFlow.API` project targeting .NET 8.0 with nullable reference types and Swagger/OpenAPI support.
- Added `Program.cs` to configure the ASP.NET Core application with services, middleware, and Swagger UI.
- Added `launchSettings.json` for development profiles and environment variables.
- Added `appsettings.json` and `appsettings.Development.json` for logging and configuration.
2026-10-09 15:14:33 +02:00
1428d989aa Update .gitignore to exclude specific files and patterns
Added `FodyWeavers.xsd` to the `.gitignore` file to prevent it
from being tracked by version control. Also added a new `/ignore`
entry to exclude files or directories matching this pattern.
These changes help avoid committing unnecessary or sensitive files.
2026-10-09 15:13:01 +02:00
43 changed files with 1330 additions and 2 deletions

2
.gitignore vendored
View File

@@ -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
View 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

View File

@@ -1,2 +0,0 @@
# DigitalData.TaskFlow

View File

@@ -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);
}
}

View File

@@ -0,0 +1,5 @@
namespace DigitalData.TaskFlow.Application.Common.Exceptions;
public sealed class InvalidWorkflowPayloadException(string message) : Exception(message)
{
}

View File

@@ -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);
}

View File

@@ -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
{
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -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>

View File

@@ -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.");
}
}

View File

@@ -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));
}
}

View File

@@ -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);

View File

@@ -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);
}
}

View File

@@ -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.");
}
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,6 @@
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
public class AuthorizedUser
{
public int WisagId { get; init; }
}

View File

@@ -0,0 +1,5 @@
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
public class Document : ProcedureResultBase
{
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,5 @@
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
public class Workflow : ProcedureResultBase
{
}

View File

@@ -0,0 +1,5 @@
namespace DigitalData.TaskFlow.Domain.ProcedureResults;
public sealed class WorkflowClosing : ProcedureResultBase
{
}

View File

@@ -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;
}
}

View File

@@ -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>

View File

@@ -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");
});
}
}

View File

@@ -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();
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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));
}
}

View File

@@ -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)
};
}
}

View File

@@ -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)
};
}
}

View File

@@ -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>

View File

@@ -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));
}
}

View File

@@ -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));
}
}
}

View File

@@ -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; }
}

View File

@@ -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; } = [];
}

View File

@@ -0,0 +1,8 @@
namespace DigitalData.TaskFlow.API.Options;
public sealed class ApiKeyAuthOptions
{
public const string SectionName = "ApiKey";
public string? Key { get; init; }
}

View File

@@ -0,0 +1,8 @@
namespace DigitalData.TaskFlow.API.Options;
public sealed class SwaggerOptions
{
public const string SectionName = "Swagger";
public bool EnabledInProduction { get; init; }
}

View 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();
}

View File

@@ -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&amp;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>

View File

@@ -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"
}
}
}
}

View File

@@ -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"
}
}
}

View 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": "*"
}