Compare commits
118
Commits
garages3
...
18dd9131cb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18dd9131cb | ||
|
|
db07ad1a82 | ||
|
|
f82a5cef76 | ||
|
|
11967e3252 | ||
|
|
614730caab | ||
|
|
f3a8f78144 | ||
|
|
9823cd7ea6 | ||
|
|
b2688867f3 | ||
|
|
a7a68fc290 | ||
|
|
0f903a58b5 | ||
|
|
86e2bad4fe | ||
|
|
1efbf9d99f | ||
|
|
24697776d0 | ||
|
|
4b806a3202 | ||
|
|
26df423180 | ||
|
|
4dbc74e488 | ||
|
|
f39eb9d8fe | ||
|
|
593219db8c | ||
|
|
d658497545 | ||
|
|
020bdee36f | ||
|
|
8e0c099867 | ||
|
|
ef134a5b3c | ||
|
|
b947959724 | ||
|
|
717b891554 | ||
|
|
58126e7573 | ||
|
|
91d325ce4e | ||
|
|
2fede443cc | ||
|
|
3cc8514136 | ||
|
|
11311421ad | ||
|
|
f4024d563a | ||
|
|
78b03b6996 | ||
|
|
80f220fcae | ||
|
|
06e2c3ee6a | ||
|
|
3c0fd8844c | ||
|
|
b7c135f0fc | ||
|
|
db053e3e5f | ||
|
|
d7177e1a72 | ||
|
|
c67041faea | ||
|
|
0e8a5e1169 | ||
|
|
41fdb067fe | ||
|
|
b4b687dfcc | ||
|
|
f200ccbf60 | ||
|
|
27f57150e1 | ||
|
|
79c63107e9 | ||
|
|
d945731252 | ||
|
|
c979a4632e | ||
|
|
9eed3cff6b | ||
|
|
6db1a2f367 | ||
|
|
06d9952cd7 | ||
|
|
92d481f75d | ||
|
|
1c36602995 | ||
|
|
5ae0c500ac | ||
|
|
db04f800e9 | ||
|
|
e7a19611f0 | ||
|
|
5ad24da7cf | ||
|
|
156dae40b7 | ||
|
|
1b67d9cf8b | ||
|
|
1bd05e64e5 | ||
|
|
303dba3c6f | ||
|
|
1dd4f54a1d | ||
|
|
fae1e080c4 | ||
|
|
4de23d27b3 | ||
|
|
d4bce12dbb | ||
|
|
299b876e1c | ||
|
|
dde1dbe056 | ||
|
|
b81e6feb45 | ||
|
|
4138a1941f | ||
|
|
17af31d810 | ||
|
|
b85cf6a1cb | ||
|
|
81ddc11746 | ||
|
|
5b94672ff5 | ||
|
|
c535392ef1 | ||
|
|
0607de1802 | ||
|
|
4c1e52e452 | ||
|
|
2414d74d1c | ||
|
|
93d9661a7f | ||
|
|
dba401fe94 | ||
|
|
42d73fe6cb | ||
|
|
1475887a7f | ||
|
|
730664d9c4 | ||
|
|
f38e569a34 | ||
|
|
7e79171f97 | ||
|
|
d7b868f2c1 | ||
|
|
d43a09b371 | ||
|
|
0dc0de1502 | ||
|
|
de47dd4a4f | ||
|
|
2810cc669b | ||
|
|
734af8c86f | ||
|
|
a754c42d14 | ||
|
|
bd7ca9372f | ||
|
|
0d01d91ab4 | ||
|
|
2c817a8818 | ||
|
|
4c3a96917b | ||
|
|
e5c3a75795 | ||
|
|
1bc7e65960 | ||
|
|
094126d84b | ||
|
|
2506241a25 | ||
|
|
cfe3530639 | ||
|
|
985557bee4 | ||
|
|
f0b8b3051a | ||
|
|
6c88b9e533 | ||
|
|
7d67408d2c | ||
|
|
d1d58a6183 | ||
|
|
60ad154841 | ||
|
|
2c13170859 | ||
|
|
d87c8aa3c9 | ||
|
|
6af7815ad1 | ||
|
|
a169f6c3f6 | ||
|
|
65ea753c19 | ||
|
|
e6d2663265 | ||
|
|
91b5814b60 | ||
|
|
0c4c848568 | ||
|
|
fb05150ebf | ||
|
|
2f9c20020b | ||
|
|
a771957db3 | ||
|
|
46267a2a34 | ||
|
|
a7f360cc2a | ||
|
|
67c08b40ca |
@@ -14,7 +14,7 @@ public sealed class GetApplicantInviteEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/communications/invites/applicant/{applicantUserId:Guid}", async (Guid applicantUserId, ICommunicationsService service,
|
||||
builder.MapGet("api/communications/invites/applicants/{applicantUserId:Guid}", async (Guid applicantUserId, ICommunicationsService service,
|
||||
HttpContext context, CancellationToken cancellationToken = default) =>
|
||||
await service.GetApplicantInviteAsync(applicantUserId, cancellationToken) switch
|
||||
{
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using static PostFundManagement.Application.Extensions.General;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Communications;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetNotificationsEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/communications/norifications/{organisationId}", async (string organisationId,
|
||||
ICommunicationsService service, CancellationToken cancellationToken = default) =>
|
||||
await service.GetNotificationsAsync(organisationId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var notifications } => Results.Ok(notifications),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems()),
|
||||
})
|
||||
.WithDescription("Retrieves the notification system report")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetNotificationsEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Notification[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Notification[]>(StatusCodes.Status404NotFound)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Communications)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ public sealed class SendInviteEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/communications/invite", async (InviteRequest request,
|
||||
builder.MapPost("api/communications/invites", async (InviteRequest request,
|
||||
HttpContext context, ICommunicationsService service, CancellationToken cancellationToken = default) =>
|
||||
await service.SendInviteAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Execution;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Execution;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateRuleEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/execution/rules", async (CreateRuleRequest request, HttpContext context,
|
||||
IExecutionService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateRuleAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems()),
|
||||
})
|
||||
.WithDescription("Add rule against a programme")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateRuleEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Execution);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
@@ -24,7 +25,7 @@ public class GetRisksEndpoint : IEndpoint
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetRisksEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Risk[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Execution)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Execution;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetRuleEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/execution/rules/{ruleId}", async (string ruleId, IExecutionService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetRuleAsync(ruleId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var rules } => Results.Ok(rules),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Get a specific programme rule")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetRuleEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Rule>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Execution)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Execution;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetRulesEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/execution/programmes/rules", async (Pagination pagination, IExecutionService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetRulesAsync(pagination, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var rules } => Results.Ok(rules),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Get a list of all programme rules")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetRulesEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Rule[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Execution)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Execution;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Execution;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateRuleEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/execution/rules", async (UpdateRuleRequest request, HttpContext context,
|
||||
IExecutionService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateRuleAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update the details of a specific programme rule (supplied version auto-increment)")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateRuleEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Execution);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateInstrumentEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/governance/instruments", async (CreateInstrumentRequest request, HttpContext context,
|
||||
IGovernanceService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateInstrumentAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true} => Results.Ok(),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Creates a new programme funding instrument")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateInstrumentEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Governance)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateTenantEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/governance/tenants", async (CreateTenantRequest request, IGovernanceService service, HttpContext context,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.CreateTenantAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Create a new tenant")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateTenantEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Governance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetTenantEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/governance/tenants/{tenantId}", async (string tenantId, IGovernanceService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetTenantAsync(tenantId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var tenant } => Results.Ok(tenant),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets system tenants")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetTenantsEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Tenant>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status404NotFound)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Governance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Entities;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetTenantsEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/governance/tenants", async (IGovernanceService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetTenantsAsync(cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var tenants } => Results.Ok(tenants),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets system tenants")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetTenantsEndpoint).ToEndpointName("Retrieval"))
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Tenant[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Governance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateInstrumentEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/governance/instruments", async (UpdateInstrumentRequest request, HttpContext context,
|
||||
IGovernanceService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateInstrumentAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems()),
|
||||
})
|
||||
.WithDescription("Updates a programme funding instrument")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateInstrumentEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Governance)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,13 @@ public sealed class UpdateOrganisationEndpoint : IEndpoint
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/governance/organisations", async (UpdateOrganisationRequest request,
|
||||
IGovernanceService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOrganisationAsync(request, cancellationToken) switch
|
||||
IGovernanceService service, HttpContext context, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOrganisationAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update an existing organization profile")
|
||||
@@ -27,10 +29,10 @@ public sealed class UpdateOrganisationEndpoint : IEndpoint
|
||||
.WithName(typeof(UpdateOrganisationEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Governance);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-12
@@ -1,36 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Tools;
|
||||
namespace PostFundManagement.Api.Endpoints.Governance;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class EncodeIdEndpoint : IEndpoint
|
||||
public sealed class UpdateTenantEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/tools/hashid/{id64:long}", async (long id64, IToolService service,
|
||||
CancellationToken cancellationToken) =>
|
||||
await service.EncodeLong(id64, cancellationToken) switch
|
||||
builder.MapPut("api/governance/tenants", async (UpdateTenantRequest request, HttpContext context,
|
||||
IGovernanceService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateTenantAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var hash } => Results.Ok(hash),
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Hashes an int64 identifier")
|
||||
.WithDescription("Updates a specific tenant")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(EncodeIdEndpoint).ToEndpointName())
|
||||
.WithName(typeof(UpdateTenantEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<string>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Tools)
|
||||
.CacheOutput();
|
||||
.WithTags(EndpointTags.Governance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateBeneficiaryEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/beneficiaries", async (CreateBeneficiaryRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateBeneficiaryAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Add a new project beneficiary")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateBeneficiaryEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateChangeRequestEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/changerequests", async (CreateChangeRequest request, IProjectService service,
|
||||
HttpContext context, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateChangeRequestAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems()),
|
||||
})
|
||||
.WithDescription("Create a new change request against an existing project")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateChangeRequestEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateComplianceItemEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/complianceitems", async (CreateComplianceItemRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateComplianceItemAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<ValidationError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Add a new beneficiary compliance item")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateComplianceItemEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateIssueEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/issues", async (CreateIssueRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateIssueAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Add a new project issue")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateIssueEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateOutcomeEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/beneficiaris/outcomes", async (CreateOutcomeRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateOutcomeAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Add a new beneficiary outcome")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateOutcomeEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class CreateSiteVisitEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPost("api/projects/sitevisits", async (CreateSiteVisitRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateSiteVisitAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<CreateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Add a new project site visit")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(CreateSiteVisitEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetBeneficiariesEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/beneficiaries/{projectId}", async (string projectId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetBeneficiariesAsync(projectId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var beneficiaries } => Results.Ok(beneficiaries),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project beneficiaries")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetBeneficiariesEndpoint).ToEndpointName("Retrieval"))
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Beneficiary[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetBeneficiaryEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/beneficiaries/{beneficiaryId}", async (string beneficiaryId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetBeneficiaryAsync(beneficiaryId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var beneficiary } => Results.Ok(beneficiary),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project beneficiaries")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetBeneficiariesEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Beneficiary>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetChangeRequestEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/changerequests/{changeRequestId}", async (string changeRequestId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetChangeRequestAsync(changeRequestId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var changeRequest } => Results.Ok(changeRequest),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets a specific project change request")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetChangeRequestEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<ChangeRequest>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetChangeRequestsEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/changerequests/{projectId}", async (string projectId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetChangeRequestsAsync(projectId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var changeRequests } => Results.Ok(changeRequests),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project change requests")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetChangeRequestsEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<ChangeRequest[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetComplianceItemEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/complianceitems/{complianceItemId}", async (string complianceItemId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetComplianceItemAsync(complianceItemId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var complianceItem } => Results.Ok(complianceItem),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets a specific project compliance item")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetComplianceItemEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<ComplianceItem>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetComplianceItemsEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/complianceitems/{projectId}", async (string projectId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetComplianceItemsAsync(projectId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var complianceItems } => Results.Ok(complianceItems),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project compliance items")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetComplianceItemsEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<ComplianceItem[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetIssueEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/issues/{issueId}", async (string issueId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetIssueAsync(issueId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var issue } => Results.Ok(issue),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets a specific project issue")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetIssueEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Issue>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetIssuesEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/issues/{projectId}", async (string projectId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetIssuesAsync(projectId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var issues } => Results.Ok(issues),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project issues")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetIssuesEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Issue[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetOutcomeEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/outcomes/{outcomeId}", async (string outcomeId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetOutcomeAsync(outcomeId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var outcome } => Results.Ok(outcome),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets a specific project outcome")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetOutcomeEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Outcome>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetOutcomesEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/outcomes/{beneficiatyId}", async (string beneficiatyId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetOutcomesAsync(beneficiatyId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var outcomes } => Results.Ok(outcomes),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project beneficiary outcomes")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetOutcomesEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<Outcome[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetSiteVisitEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/sitevisits/{siteVisitId}", async (string siteVisitId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetSiteVisitAsync(siteVisitId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var siteVisit } => Results.Ok(siteVisit),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project site visit")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetSiteVisitEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<SiteVisit>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class GetSiteVisitsEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapGet("api/projects/sitevisits/{projectId}", async (string projectId, IProjectService service,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
await service.GetSiteVisitsAsync(projectId, cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true, Value: var siteVisits } => Results.Ok(siteVisits),
|
||||
var r when r.HasError<IdDecodeError>() => Results.Forbid(),
|
||||
var r when r.HasError<NotFoundError>() => Results.NotFound(),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Gets project site visits")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(GetSiteVisitsEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces<SiteVisit[]>(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status403Forbidden)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects)
|
||||
.CacheOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateBeneficiaryEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/beneficiaries", async (UpdateBeneficiaryRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateBeneficiaryAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update project beneficiary")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateBeneficiaryEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateChangeRequestEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/changerequests", async (UpdateChangeRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateChangeRequestAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update a specific project change request")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateChangeRequestEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateComplianceItemEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/complianceitems", async (UpdateComplianceItemRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateComplianceItemAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update a specific compliance item")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateComplianceItemEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateIssueEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/issues", async (UpdateIssueRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateIssueAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update a specific project issue")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateIssueEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateOutcomeEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/outcomes", async (UpdateOutcomeRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOutcomeAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update project beneficiary outcome")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateOutcomeEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Security;
|
||||
using Problems = Microsoft.AspNetCore.Mvc.ProblemDetails;
|
||||
|
||||
namespace PostFundManagement.Api.Endpoints.Projects;
|
||||
|
||||
[ApiVersionTarget(1)]
|
||||
public sealed class UpdateSiteVisitEndpoint : IEndpoint
|
||||
{
|
||||
public void Map(IEndpointRouteBuilder builder)
|
||||
{
|
||||
builder.MapPut("api/projects/sitevisits", async (UpdateSiteVisitRequest request, HttpContext context,
|
||||
IProjectService service, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateSiteVisitAsync(request, context.GetUserId(), cancellationToken) switch
|
||||
{
|
||||
{ IsSuccess: true } => Results.Ok(),
|
||||
var r when r.HasError<UpdateError>() => Results.BadRequest(r.Errors.ToProblems()),
|
||||
var r => Results.InternalServerError(r.Errors.ToProblems())
|
||||
})
|
||||
.WithDescription("Update project site visit")
|
||||
.RequireAuthorization(Constants.MainScope)
|
||||
.WithName(typeof(UpdateSiteVisitEndpoint).ToEndpointName())
|
||||
.MapToApiVersion(new ApiVersion(1))
|
||||
.Produces(StatusCodes.Status200OK)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces<Problems>(StatusCodes.Status400BadRequest)
|
||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||
.WithTags(EndpointTags.Projects);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using Microsoft.FeatureManagement;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Filters;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Health;
|
||||
using PostFundManagement.Domain.Mediator;
|
||||
using PostFundManagement.Infrastructure.Database.Services;
|
||||
using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@@ -27,6 +29,7 @@ builder.Services.AddApiVersioning(options =>
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<ActiveUserFilter>();
|
||||
builder.Services.AddTransient<ITenantContextService, TenantContextService>();
|
||||
|
||||
builder.Services.AddEndpoints(Assembly.GetExecutingAssembly());
|
||||
builder.Services.AddApiServices(builder.Configuration);
|
||||
|
||||
@@ -20,8 +20,11 @@
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Default": "Warning",
|
||||
"Quartz": "Error",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore.Database": "Error",
|
||||
"Microsoft.EntityFrameworkCore.Update": "Error"
|
||||
}
|
||||
},
|
||||
"EmailProcessorCron": "0 */5 * * * ?",
|
||||
|
||||
@@ -12,8 +12,8 @@ public abstract class S3ServiceBase(IAmazonS3 amazonS3)
|
||||
|
||||
public string GenerateCdnUrl(string fileKey) => $"{CdnBaseUrl}/{fileKey}";
|
||||
|
||||
public virtual async ValueTask<Result<string>> GeneratePresignedUrlAsync(string fileKey, TimeSpan duration, string? contentType = null, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public virtual async Task<Result<string>> GeneratePresignedUrlAsync(string fileKey, TimeSpan duration, string? contentType = null, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(BucketName))
|
||||
return Result.Fail(ValidationError.Create("Bucket name is not configured."));
|
||||
@@ -51,8 +51,8 @@ public abstract class S3ServiceBase(IAmazonS3 amazonS3)
|
||||
: $"{cleanSubPath}/{fileHash.ToLower(CultureInfo.InvariantCulture)}_{fileName}";
|
||||
}
|
||||
|
||||
public virtual async ValueTask<Result<string>> UploadFileAsync(string fileName, string subPath, Stream fileStream, string contentType, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public virtual async Task<Result<string>> UploadFileAsync(string fileName, string subPath, Stream fileStream, string contentType, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(BucketName))
|
||||
return Result.Fail<string>(ValidationError.Create("Bucket name is not configured."));
|
||||
@@ -92,8 +92,8 @@ public abstract class S3ServiceBase(IAmazonS3 amazonS3)
|
||||
: Result.Ok(fileKey);
|
||||
}));
|
||||
|
||||
public virtual async ValueTask<Result> DeleteFileAsync(string fileKey, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public virtual async Task<Result> DeleteFileAsync(string fileKey, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(BucketName))
|
||||
return Result.Fail(NotFoundError.Create("Bucket name is not configured."));
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
using PostFundManagement.Application.Services.Communications;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface ICommunicationsService
|
||||
{
|
||||
ValueTask<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateNotificationAsync(CreateNotificationRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateNotificationAsync(UpdateNotificationRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Notification[]>> GetNotificationsAsync(string organisationIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Notification>> GetNotificationAsync(string notificationIdHash, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,50 @@
|
||||
using PostFundManagement.Application.Services.Evidence;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IEvidenceService
|
||||
{
|
||||
ValueTask<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken);
|
||||
[Log]
|
||||
Task<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken);
|
||||
|
||||
ValueTask<Result<Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,26 +1,55 @@
|
||||
using PostFundManagement.Application.Services.Execution;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IExecutionService
|
||||
{
|
||||
ValueTask<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateRuleAsync(CreateRuleRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateRuleAsync(UpdateRuleRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Rule>> GetRuleAsync(string ruleIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Rule[]>> GetRulesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,89 @@
|
||||
using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IGovernanceService
|
||||
{
|
||||
ValueTask<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateInstrumentAsync(UpdateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateInstrumentAsync(CreateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateTenantAsync(CreateTenantRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Tenant[]>> GetTenantsAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Tenant>> GetTenantAsync(string tenantIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateTenantAsync(UpdateTenantRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateTenantUserAsync(UpdateTenantUserRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateTenantOrganisationAsync(string organisationIdHash, string tenantIdHash, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateTenantOrganisationAsync(string tenantOrganisationIdHash, ActivityStatus status, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<TenantOrganisation[]>> GetTenantOrganisationsAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<TenantOrganisation>> GetTenantOrganisationAsync(string tenantOrganisationIdHash, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,34 +1,55 @@
|
||||
using PostFundManagement.Application.Services.Grants;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IGrantsService
|
||||
{
|
||||
ValueTask<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IIdentityService
|
||||
{
|
||||
ValueTask<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,46 +1,157 @@
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IProjectService
|
||||
{
|
||||
ValueTask<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateChangeRequestAsync(CreateChangeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateChangeRequestAsync(UpdateChangeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<ChangeRequest[]>> GetChangeRequestsAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<ChangeRequest>> GetChangeRequestAsync(string changeRequestIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateComplianceItemAsync(CreateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateComplianceItemAsync(UpdateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<ComplianceItem[]>> GetComplianceItemsAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<ComplianceItem>> GetComplianceItemAsync(string complianceItemIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateBeneficiaryAsync(CreateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateBeneficiaryAsync(UpdateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Beneficiary[]>> GetBeneficiariesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Beneficiary>> GetBeneficiaryAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateIssueAsync(CreateIssueRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateIssueAsync(UpdateIssueRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Issue[]>> GetIssuesAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Issue>> GetIssueAsync(string issueIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateOutcomeAsync(CreateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateOutcomeAsync(UpdateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Outcome[]>> GetOutcomesAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<Outcome>> GetOutcomeAsync(string outcomeIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> CreateSiteVisitAsync(CreateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateSiteVisitAsync(UpdateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<SiteVisit[]>> GetSiteVisitsAsync(string projectIdHash, CancellationToken cancellationToken = default);
|
||||
|
||||
[Log]
|
||||
Task<Result<SiteVisit>> GetSiteVisitAsync(string siteVisitIdHash, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
|
||||
public interface IToolService
|
||||
{
|
||||
ValueTask<Result<string>> EncodeLong(long id, CancellationToken cancellationToken);
|
||||
Task<Result<string>> EncodeLong(long id, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
using PostFundManagement.Application.Services.Users;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
using PostFundManagement.Domain.Models;
|
||||
|
||||
namespace PostFundManagement.Application.Abstractions.Services;
|
||||
|
||||
public interface IUserService
|
||||
{
|
||||
ValueTask<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
Task<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default);
|
||||
[Log]
|
||||
[Audit]
|
||||
Task<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
[Log]
|
||||
Task<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ public static class Quartz
|
||||
{
|
||||
public static IServiceCollection AddQuartzSchedulerClient(this IServiceCollection services, string schedulerName, IConfiguration configuration)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString(DatabaseConfigName);
|
||||
var connectionString = configuration.GetConnectionString(SchedulerDatabaseConfigName);
|
||||
|
||||
services.Configure<QuartzOptions>(options =>
|
||||
{
|
||||
@@ -44,7 +44,7 @@ public static class Quartz
|
||||
|
||||
public static IServiceCollection AddQuartzScheduler(this IServiceCollection services, string schedulerName, IConfiguration configuration)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString(DatabaseConfigName);
|
||||
var connectionString = configuration.GetConnectionString(SchedulerDatabaseConfigName);
|
||||
|
||||
services.Configure<QuartzOptions>(options =>
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using PostFundManagement.Application.Abstractions;
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Interceptors;
|
||||
using PostFundManagement.Application.Services.Communications;
|
||||
using PostFundManagement.Application.Services.Evidence;
|
||||
using PostFundManagement.Application.Services.Execution;
|
||||
@@ -7,7 +8,6 @@ using PostFundManagement.Application.Services.Governance;
|
||||
using PostFundManagement.Application.Services.Grants;
|
||||
using PostFundManagement.Application.Services.Projects;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Application.Services.Tools;
|
||||
using PostFundManagement.Application.Services.Users;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
|
||||
@@ -15,34 +15,71 @@ namespace PostFundManagement.Application.Extensions;
|
||||
|
||||
public static class Services
|
||||
{
|
||||
public static IServiceCollection AddLoggedCachedServiceScoped<TInterface, TImplementation, TCacheDecorator>(this IServiceCollection services)
|
||||
where TInterface : class
|
||||
where TImplementation : class, TInterface
|
||||
where TCacheDecorator : class, TInterface
|
||||
{
|
||||
services.AddScoped<TImplementation>();
|
||||
services.AddScoped<TCacheDecorator>();
|
||||
|
||||
services.AddScoped(sp =>
|
||||
{
|
||||
var proxyGenerator = sp.GetRequiredService<ProxyGenerator>();
|
||||
var loggingInterceptor = sp.GetRequiredService<LoggingInterceptor>();
|
||||
|
||||
var actual = sp.GetRequiredService<TImplementation>();
|
||||
|
||||
var cached = ActivatorUtilities.CreateInstance<TCacheDecorator>(sp, actual);
|
||||
|
||||
return proxyGenerator.CreateInterfaceProxyWithTarget<TInterface>(cached,
|
||||
loggingInterceptor.ToInterceptor());
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddLoggedAuditedCachedServiceScoped<TInterface, TImplementation, TCacheDecorator>(this IServiceCollection services)
|
||||
where TInterface : class
|
||||
where TImplementation : class, TInterface
|
||||
where TCacheDecorator : class, TInterface
|
||||
{
|
||||
services.AddScoped<TImplementation>();
|
||||
services.AddScoped<TCacheDecorator>();
|
||||
|
||||
services.AddScoped(sp =>
|
||||
{
|
||||
var proxyGenerator = sp.GetRequiredService<ProxyGenerator>();
|
||||
var auditInterceptor = sp.GetRequiredService<AuditInterceptor>();
|
||||
var loggingInterceptor = sp.GetRequiredService<LoggingInterceptor>();
|
||||
|
||||
var actual = sp.GetRequiredService<TImplementation>();
|
||||
|
||||
var cached = ActivatorUtilities.CreateInstance<TCacheDecorator>(sp, actual);
|
||||
|
||||
return proxyGenerator.CreateInterfaceProxyWithTarget<TInterface>(cached,
|
||||
loggingInterceptor.ToInterceptor(),
|
||||
auditInterceptor.ToInterceptor());
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddRegisterServicesWithCaching(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddScoped<ICommunicationsService, CommunicationsService>();
|
||||
services.Decorate<ICommunicationsService, CommunicationsCacheService>();
|
||||
services.AddScoped<AuditInterceptor>();
|
||||
services.AddScoped<LoggingInterceptor>();
|
||||
services.AddSingleton<ProxyGenerator>();
|
||||
|
||||
services.AddScoped<IEvidenceService, EvidenceService>();
|
||||
services.Decorate<IEvidenceService, EvidenceCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<ICommunicationsService, CommunicationsService, CommunicationsCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IEvidenceService, EvidenceService, EvidenceCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IUserService, UserService, UserCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IExecutionService, ExecutionService, ExecutionCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IGovernanceService, GovernanceService, GovernanceCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IGrantsService, GrantsService, GrantsCacheService>();
|
||||
services.AddLoggedAuditedCachedServiceScoped<IProjectService, ProjectService, ProjectCacheService>();
|
||||
|
||||
services.AddScoped<IUserService, UserService>();
|
||||
services.Decorate<IUserService, UserCacheService>();
|
||||
|
||||
services.AddScoped<IIdentityService, IdentityService>();
|
||||
services.Decorate<IIdentityService, IdentityCacheService>();
|
||||
|
||||
services.AddScoped<IExecutionService, ExecutionService>();
|
||||
services.Decorate<IExecutionService, ExecutionCacheService>();
|
||||
|
||||
services.AddScoped<IGovernanceService, GovernanceService>();
|
||||
services.Decorate<IGovernanceService, GovernanceCacheService>();
|
||||
|
||||
services.AddScoped<IGrantsService, GrantsService>();
|
||||
services.Decorate<IGrantsService, GrantsCacheService>();
|
||||
|
||||
services.AddScoped<IProjectService, ProjectService>();
|
||||
services.Decorate<IProjectService, ProjectCacheService>();
|
||||
|
||||
services.AddScoped<IToolService, ToolService>();
|
||||
services.Decorate<IToolService, ToolCacheService>();
|
||||
services.AddLoggedCachedServiceScoped<IIdentityService, IdentityService, IdentityCacheService>();
|
||||
|
||||
services.AddStackExchangeRedisCache(options =>
|
||||
{
|
||||
|
||||
@@ -25,8 +25,12 @@ public sealed class ActiveUserFilter(IIdentityService identityService) : IEndpoi
|
||||
var path = context.HttpContext.Request.Path.Value;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(path) && !path!.EndsWith("integration/sync", StringComparison.InvariantCultureIgnoreCase))
|
||||
if ((await identityService.UserIsAuthorisedAsync(userId, context.HttpContext.RequestAborted)).IsFailed)
|
||||
return (object?)Results.Json(new { message = "Account approval is pending or inactive." }, statusCode: StatusCodes.Status403Forbidden);
|
||||
{
|
||||
var userAuthResult = await identityService.UserIsAuthorisedAsync(userId, context.HttpContext.RequestAborted);
|
||||
|
||||
if (userAuthResult.IsFailed)
|
||||
return Results.Json(new { message = "Account approval is pending or inactive." }, statusCode: StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
context.HttpContext.Items[UserIdItemKey] = userId;
|
||||
context.HttpContext.Items[EmailtemKey] = email;
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
|
||||
namespace PostFundManagement.Application.Interceptors;
|
||||
|
||||
public sealed class AuditInterceptor(AuditService auditService, IHttpContextAccessor httpContextAccessor) : IAsyncInterceptor
|
||||
{
|
||||
public void InterceptSynchronous(IInvocation invocation) => invocation.Proceed();
|
||||
|
||||
public void InterceptAsynchronous(IInvocation invocation) =>
|
||||
invocation.ReturnValue = InternalInterceptAsynchronous(invocation);
|
||||
|
||||
public void InterceptAsynchronous<TResult>(IInvocation invocation) =>
|
||||
invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
|
||||
|
||||
private static async Task InternalInterceptAsynchronous(IInvocation invocation)
|
||||
{
|
||||
invocation.Proceed();
|
||||
|
||||
var task = (Task)invocation.ReturnValue;
|
||||
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
|
||||
{
|
||||
invocation.Proceed();
|
||||
|
||||
var task = (Task<TResult>)invocation.ReturnValue;
|
||||
var resultObj = await task.ConfigureAwait(false);
|
||||
|
||||
var method = invocation.MethodInvocationTarget ?? invocation.Method;
|
||||
var auditAttr = method.GetCustomAttribute<AuditAttribute>()
|
||||
?? invocation.Method.GetCustomAttribute<AuditAttribute>();
|
||||
|
||||
if (auditAttr == null) return resultObj;
|
||||
|
||||
if (resultObj is IResultBase result && result.IsSuccess)
|
||||
{
|
||||
try
|
||||
{
|
||||
var action = ResolveActionName(method.Name);
|
||||
var entityName = ResolveEntityName(method, resultObj, invocation.Arguments);
|
||||
var entityId = ResolveEntityId(resultObj, invocation.Arguments);
|
||||
var changes = BuildPayloadSummary(invocation.Method.GetParameters(), invocation.Arguments);
|
||||
var performedBy = ResolveUserId();
|
||||
|
||||
await auditService.LogActionAsync(
|
||||
entityId: entityId,
|
||||
entityName: entityName,
|
||||
action: action,
|
||||
changes: changes,
|
||||
performedBy: performedBy).ConfigureAwait(false);
|
||||
}
|
||||
catch { /* eat all exceptions, don't interrupt program flow */ }
|
||||
}
|
||||
|
||||
return resultObj;
|
||||
}
|
||||
|
||||
private static string ResolveActionName(string methodName) =>
|
||||
methodName.EndsWith("Async", StringComparison.Ordinal)
|
||||
? methodName[..^5]
|
||||
: methodName;
|
||||
|
||||
private static string ResolveEntityName(MethodInfo method, object? resultObj, object[] args)
|
||||
{
|
||||
var returnType = method.ReturnType;
|
||||
|
||||
Type? innerType = null;
|
||||
|
||||
if (returnType.IsGenericType)
|
||||
{
|
||||
var genericDef = returnType.GetGenericTypeDefinition();
|
||||
|
||||
if (genericDef == typeof(Task<>) || genericDef == typeof(Task<>))
|
||||
innerType = returnType.GetGenericArguments()[0];
|
||||
}
|
||||
|
||||
if (innerType != null && innerType.IsGenericType && typeof(IResultBase).IsAssignableFrom(innerType))
|
||||
{
|
||||
var valueType = innerType.GetGenericArguments().FirstOrDefault();
|
||||
|
||||
if (valueType != null && valueType != typeof(bool) && valueType != typeof(int) && valueType != typeof(string))
|
||||
return valueType.Name;
|
||||
}
|
||||
|
||||
foreach (var arg in args)
|
||||
{
|
||||
if (arg == null || arg is CancellationToken or IFormFile) continue;
|
||||
|
||||
var argTypeName = arg.GetType().Name;
|
||||
|
||||
if (argTypeName.EndsWith("Request", StringComparison.Ordinal))
|
||||
{
|
||||
var trimmed = argTypeName[..^7];
|
||||
|
||||
return trimmed.Replace("Create", "").Replace("Update", "");
|
||||
}
|
||||
}
|
||||
|
||||
return ResolveActionName(method.Name);
|
||||
}
|
||||
|
||||
private static string ResolveEntityId(object? resultObj, object[] args)
|
||||
{
|
||||
if (resultObj != null)
|
||||
{
|
||||
var valueProp = resultObj.GetType().GetProperty("Value");
|
||||
if (valueProp != null)
|
||||
{
|
||||
var value = valueProp.GetValue(resultObj);
|
||||
if (value != null)
|
||||
{
|
||||
var idProp = value.GetType().GetProperty("Id") ?? value.GetType().GetProperty("id");
|
||||
if (idProp != null)
|
||||
{
|
||||
var idVal = idProp.GetValue(value);
|
||||
if (idVal != null) return idVal.ToString()!;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var arg in args)
|
||||
{
|
||||
if (arg is long or int or Guid or string)
|
||||
return arg.ToString()!;
|
||||
|
||||
if (arg != null && arg is not CancellationToken and not IFormFile)
|
||||
{
|
||||
var idProp = arg.GetType().GetProperty("Id") ?? arg.GetType().GetProperty("id");
|
||||
|
||||
if (idProp != null)
|
||||
{
|
||||
var idVal = idProp.GetValue(arg);
|
||||
|
||||
if (idVal != null) return idVal.ToString()!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "N/A";
|
||||
}
|
||||
|
||||
private static string[] BuildPayloadSummary(ParameterInfo[] parameters, object[] args)
|
||||
{
|
||||
var entries = new List<string>();
|
||||
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
var param = parameters[i];
|
||||
var arg = args[i];
|
||||
|
||||
if (param.ParameterType == typeof(CancellationToken))
|
||||
continue;
|
||||
|
||||
if (arg == null)
|
||||
{
|
||||
entries.Add($"{param.Name}: null");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is IFormFile file)
|
||||
{
|
||||
entries.Add($"{param.Name}: [File] Name='{file.FileName}', Size={file.Length} bytes, Type='{file.ContentType}'");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is IEnumerable<IFormFile> files)
|
||||
{
|
||||
var fileSummaries = files.Select(f => $"'{f.FileName}' ({f.Length} bytes)");
|
||||
|
||||
entries.Add($"{param.Name}: [Files] count={fileSummaries.Count()} [{string.Join(", ", fileSummaries)}]");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is Stream stream)
|
||||
{
|
||||
entries.Add($"{param.Name}: [Stream] Length={(stream.CanSeek ? stream.Length : -1)} bytes");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(arg);
|
||||
|
||||
entries.Add($"{param.Name}: {json}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
entries.Add($"{param.Name}: [Unserializable]");
|
||||
}
|
||||
}
|
||||
|
||||
return [.. entries];
|
||||
}
|
||||
|
||||
private Guid ResolveUserId()
|
||||
{
|
||||
var user = httpContextAccessor.HttpContext?.User;
|
||||
|
||||
var sub = user?.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? user?.FindFirst("sub")?.Value;
|
||||
|
||||
return Guid.TryParse(sub, out var guid) ? guid : Guid.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using PostFundManagement.Domain.Attributes;
|
||||
|
||||
namespace PostFundManagement.Application.Interceptors;
|
||||
|
||||
public sealed class LoggingInterceptor(ILogger<LoggingInterceptor> logger) : IAsyncInterceptor
|
||||
{
|
||||
public void InterceptSynchronous(IInvocation invocation)
|
||||
{
|
||||
invocation.Proceed();
|
||||
|
||||
CheckAndLogIfFailed(invocation, invocation.ReturnValue);
|
||||
}
|
||||
|
||||
public void InterceptAsynchronous(IInvocation invocation) =>
|
||||
invocation.ReturnValue = InternalInterceptAsynchronous(invocation);
|
||||
|
||||
public void InterceptAsynchronous<TResult>(IInvocation invocation) =>
|
||||
invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
|
||||
|
||||
private static async Task InternalInterceptAsynchronous(IInvocation invocation)
|
||||
{
|
||||
invocation.Proceed();
|
||||
|
||||
var task = (Task)invocation.ReturnValue;
|
||||
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
|
||||
{
|
||||
invocation.Proceed();
|
||||
|
||||
var task = (Task<TResult>)invocation.ReturnValue;
|
||||
var resultObj = await task.ConfigureAwait(false);
|
||||
|
||||
var method = invocation.MethodInvocationTarget ?? invocation.Method;
|
||||
var auditAttr = method.GetCustomAttribute<LogAttribute>()
|
||||
?? invocation.Method.GetCustomAttribute<LogAttribute>();
|
||||
|
||||
if (auditAttr == null) return resultObj;
|
||||
|
||||
CheckAndLogIfFailed(invocation, resultObj);
|
||||
|
||||
return resultObj;
|
||||
}
|
||||
|
||||
private void CheckAndLogIfFailed(IInvocation invocation, object? resultObj)
|
||||
{
|
||||
if (resultObj is IResultBase result && result.IsFailed)
|
||||
{
|
||||
try
|
||||
{
|
||||
var method = invocation.MethodInvocationTarget ?? invocation.Method;
|
||||
var parameters = BuildPayloadSummary(method.GetParameters(), invocation.Arguments);
|
||||
|
||||
var errorMessages = new List<string>();
|
||||
|
||||
if (result.Reasons != null)
|
||||
{
|
||||
foreach (var reason in result.Reasons)
|
||||
if (reason is IError error)
|
||||
errorMessages.Add(error.Message);
|
||||
}
|
||||
|
||||
var errorsString = string.Join("; ", errorMessages);
|
||||
|
||||
logger.LogError("Method {MethodName} failed. Errors: [{ErrorType}] {Errors}. Parameters: {@Parameters}",
|
||||
method.Name, result.Reasons?.FirstOrDefault()?.GetType().Name.Replace("Error", string.Empty), errorsString, parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to write error log for method {MethodName}.", invocation.Method.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string[] BuildPayloadSummary(ParameterInfo[] parameters, object[] args)
|
||||
{
|
||||
var entries = new List<string>();
|
||||
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
var param = parameters[i];
|
||||
var arg = args[i];
|
||||
|
||||
if (param.ParameterType == typeof(CancellationToken))
|
||||
continue;
|
||||
|
||||
if (arg == null)
|
||||
{
|
||||
entries.Add($"{param.Name}: null");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is IFormFile file)
|
||||
{
|
||||
entries.Add($"{param.Name}: [File] Name='{file.FileName}', Size={file.Length} bytes, Type='{file.ContentType}'");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is IEnumerable<IFormFile> files)
|
||||
{
|
||||
var fileSummaries = new List<string>();
|
||||
|
||||
foreach (var f in files)
|
||||
fileSummaries.Add($"'{f.FileName}' ({f.Length} bytes)");
|
||||
|
||||
entries.Add($"{param.Name}: [Files] count={fileSummaries.Count} [{string.Join(", ", fileSummaries)}]");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg is Stream stream)
|
||||
{
|
||||
entries.Add($"{param.Name}: [Stream] Length={(stream.CanSeek ? stream.Length : -1)} bytes");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(arg);
|
||||
|
||||
entries.Add($"{param.Name}: {json}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
entries.Add($"{param.Name}: [Unserializable]");
|
||||
}
|
||||
}
|
||||
|
||||
return [.. entries];
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
|
||||
<!-- API Documentation -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Castle.Core.AsyncInterceptor" Version="2.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Validation" Version="10.0.12" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.17.4" />
|
||||
@@ -36,6 +37,7 @@
|
||||
<!-- Shared Usings -->
|
||||
<ItemGroup>
|
||||
<Using Include="Humanizer" />
|
||||
<Using Include="Castle.DynamicProxy" />
|
||||
<Using Include="Microsoft.FeatureManagement" />
|
||||
<Using Include="System.ComponentModel.DataAnnotations" />
|
||||
<Using Include="Microsoft.Extensions.Caching.Distributed" />
|
||||
|
||||
+62
-8
@@ -11,8 +11,11 @@ namespace PostFundManagement.Application.Services.Communications;
|
||||
public sealed class CommunicationsCacheService(CommunicationsService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, ICommunicationsService
|
||||
{
|
||||
public async ValueTask<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite>>>)(async () =>
|
||||
public async Task<Result> CreateNotificationAsync(CreateNotificationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateNotificationAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetApplicantInviteAsync(applicantUserId, cancellationToken);
|
||||
@@ -33,8 +36,8 @@ public sealed class CommunicationsCacheService(CommunicationsService service, ID
|
||||
return Result.Ok(cached!.FromJson<Invite>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite[]>>>)(async () =>
|
||||
public async Task<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetApplicantInvitesAsync(applicantUserId, cancellationToken);
|
||||
@@ -57,8 +60,8 @@ public sealed class CommunicationsCacheService(CommunicationsService service, ID
|
||||
return Result.Ok(cached.FromJson<Invite[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite[]>>>)(async () =>
|
||||
public async Task<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetInvitesAsync(pagination, cancellationToken);
|
||||
@@ -81,6 +84,57 @@ public sealed class CommunicationsCacheService(CommunicationsService service, ID
|
||||
return Result.Ok(cached.FromJson<Invite[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.SendInviteAsync(request, userId, cancellationToken);
|
||||
public async Task<Result<Notification>> GetNotificationAsync(string notificationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Notification>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetNotificationAsync(notificationIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getnotification-{notificationIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetNotificationAsync(notificationIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return Result.Ok(result.Value);
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Notification>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Notification[]>> GetNotificationsAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Notification[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetNotificationsAsync(organisationIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getnotifications-{organisationIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetNotificationsAsync(organisationIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return Result.Ok(result.Value);
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Notification[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.SendInviteAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateNotificationAsync(UpdateNotificationRequest request, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateNotificationAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
@@ -7,10 +9,11 @@ using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Communications;
|
||||
|
||||
public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext> contextFactory) : ICommunicationsService
|
||||
public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext> contextFactory,
|
||||
HashService hashService, ITenantContextService tenantContext) : ICommunicationsService
|
||||
{
|
||||
public async ValueTask<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite>>>)(async () =>
|
||||
public async Task<Result<Invite>> SendInviteAsync(InviteRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -22,28 +25,24 @@ public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext
|
||||
ContractId = request.ContractId,
|
||||
Recipient = request.Recipient,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
TenantId = tenantContext.TenantId
|
||||
};
|
||||
|
||||
context.Invites.Add(invite);
|
||||
|
||||
context.Notifications.Add(new Domain.Entities.Notification
|
||||
{
|
||||
OrganisationId = request.OrganisationId,
|
||||
Recipient = request.Recipient,
|
||||
Platform = request.Platform,
|
||||
Status = NotificationStatus.Pending,
|
||||
Subject = "Invitation to Onboard",
|
||||
Message = request.Message,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
var notificationRequest = new CreateNotificationRequest(request.InvitedOrganisationId, request.Recipient,
|
||||
request.Platform, "Invitation to Onboard", string.Empty, request.Message);
|
||||
|
||||
return Result.FailIf(await context.SaveChangesAsync(cancellationToken) <= 0, CreateError.New)
|
||||
var notificationResult = await CreateNotificationAsync(notificationRequest, userId, cancellationToken);
|
||||
|
||||
return Result.FailIf(await context.SaveChangesAsync(cancellationToken) <= 0 && notificationResult.IsFailed,
|
||||
CreateError.Create().CausedBy(notificationResult.Errors))
|
||||
.ToResult(invite.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite[]>>>)(async () =>
|
||||
public async Task<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -56,8 +55,8 @@ public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext
|
||||
return Result.Ok(invites.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite>>>)(async () =>
|
||||
public async Task<Result<Invite>> GetApplicantInviteAsync(Guid applicantUserId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<Invite>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -67,16 +66,91 @@ public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext
|
||||
.ToResult(invite!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Invite[]>>>)(async () =>
|
||||
public async Task<Result<Invite[]>> GetApplicantInvitesAsync(Guid applicantUserId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Invite[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var invites = await context.Invites.AsNoTracking()
|
||||
.Where(i => i.Recipient == applicantUserId)
|
||||
.OrderByDescending(o => o.CreatedAt)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(invites.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateNotificationAsync(CreateNotificationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Notifications.Add(new Domain.Entities.Notification
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Recipient = request.Recipient,
|
||||
OrganisationId = request.OrganisationId,
|
||||
Destination = request.Destination,
|
||||
Subject = request.Subject,
|
||||
Message = request.Message,
|
||||
Platform = request.Platform,
|
||||
Status = NotificationStatus.Queued,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create entry"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateNotificationAsync(UpdateNotificationRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Notifications
|
||||
.Where(n => n.Id == request.NotificationId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Destination, request.Destination)
|
||||
.SetProperty(u => u.SentAt, request.SentAt)
|
||||
.SetProperty(u => u.Error, request.Error)
|
||||
.SetProperty(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.SetProperty(u => u.Status, request.Status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create($"Failed to update notification: {request.NotificationId}"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Notification[]>> GetNotificationsAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Notification[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(organisationIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var notifications = await context.Notifications.AsNoTracking()
|
||||
.Where(n => n.OrganisationId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(notifications?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<Notification>> GetNotificationAsync(string notificationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Notification>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(notificationIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var notification = await context.Notifications.AsNoTracking()
|
||||
.FirstOrDefaultAsync(n => n.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(notification is null, NotFoundError.New)
|
||||
.ToResult(notification!.Map());
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,18 @@ using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Communications;
|
||||
|
||||
public sealed record UpdateNotificationRequest([Required] long NotificationId, string? Destination,
|
||||
[Required] NotificationStatus Status,
|
||||
[Required] DateTime SentAt,
|
||||
[MaxLength(TextLength)] string? Error);
|
||||
|
||||
public sealed record CreateNotificationRequest([Required] long OrganisationId,
|
||||
[Required] Guid Recipient,
|
||||
[Required] NotificationPlatform Platform,
|
||||
[Required][MaxLength(LabelLength)] string? Subject,
|
||||
[Required][MaxLength(LabelLength)] string? Destination,
|
||||
[Required][MaxLength(TextLength)] string Message);
|
||||
|
||||
public sealed record InviteRequest([Required] long OrganisationId,
|
||||
[Required] long InvitedOrganisationId,
|
||||
[Required] long AwardId,
|
||||
|
||||
@@ -11,17 +11,17 @@ namespace PostFundManagement.Application.Services.Evidence;
|
||||
public sealed class EvidenceCacheService(EvidenceService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IEvidenceService
|
||||
{
|
||||
public async ValueTask<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateEvidenceAsync(userId, form, file, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateIndicatorAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateMilestoneAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetEvidenceAsync(evidenceId, cancellationToken);
|
||||
@@ -44,8 +44,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Evidence>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetEvidenceFilesAsync(pagination, cancellationToken);
|
||||
@@ -68,8 +68,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Evidence[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public async Task<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetEvidenceUrlAsync(evidenceIdHash, cancellationToken);
|
||||
@@ -92,8 +92,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator>>>)(async () =>
|
||||
public async Task<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Indicator>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetIndicatorAsync(indicatorId, cancellationToken);
|
||||
@@ -116,8 +116,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Indicator>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator[]>>>)(async () =>
|
||||
public async Task<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Indicator[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetIndicatorsAsync(pagination, cancellationToken);
|
||||
@@ -140,8 +140,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Indicator[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetMilestoneEvidencesAsync(milestoneIdHash, cancellationToken);
|
||||
@@ -164,8 +164,8 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Evidence[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectEvidencesAsync(projectIdHash, cancellationToken);
|
||||
@@ -188,9 +188,9 @@ public sealed class EvidenceCacheService(EvidenceService service, IDistributedCa
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Evidence[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.RecordIndicatorActualAmountAsync(indicatorIdHash, amount, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateEvidenceAsync(request, userId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ namespace PostFundManagement.Application.Services.Evidence;
|
||||
public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
[FromKeyedServices(Constants.GeneralBucketName)] IS3Service s3Service) : IEvidenceService
|
||||
{
|
||||
public async ValueTask<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateEvidenceAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
if (!long.TryParse(form["projectId"], out var projectId) || !long.TryParse(form["milestoneId"], out var milestoneId) ||
|
||||
!long.TryParse(form["indicatorId"], out var indicatorId) || !long.TryParse(form["activityId"], out var activityId) ||
|
||||
@@ -49,8 +49,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> RecordIndicatorActualAmountAsync(string indicatorIdHash, decimal amount, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(indicatorIdHash);
|
||||
|
||||
@@ -68,8 +68,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator[]>>>)(async () =>
|
||||
public async Task<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Indicator[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -82,8 +82,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.Ok(indicators.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -96,8 +96,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.Ok(evidence.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateMilestoneAsync(CreateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -122,8 +122,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
CreateError.Create("No record could be created."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateIndicatorAsync(CreateIndicatorRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -145,8 +145,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator>>>)(async () =>
|
||||
public async Task<Result<Indicator>> GetIndicatorAsync(string indicatorId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<Indicator>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(indicatorId);
|
||||
|
||||
@@ -162,8 +162,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
.ToResult(indicator!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence>> GetEvidenceAsync(string evidenceId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(evidenceId);
|
||||
|
||||
@@ -179,8 +179,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
.ToResult(evidence!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetMilestoneEvidencesAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(milestoneIdHash);
|
||||
|
||||
@@ -199,8 +199,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.Ok(evidences.Select(e => e.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Evidence[]>> GetProjectEvidencesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Evidence[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -219,8 +219,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.Ok(evidences.Select(e => e.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateEvidenceAsync(UpdateEvidenceRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -238,8 +238,8 @@ public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> cont
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public async Task<Result<string>> GetEvidenceUrlAsync(string evidenceIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(evidenceIdHash);
|
||||
|
||||
|
||||
@@ -11,17 +11,20 @@ namespace PostFundManagement.Application.Services.Execution;
|
||||
public sealed class ExecutionCacheService(ExecutionService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IExecutionService
|
||||
{
|
||||
public async ValueTask<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.ApproveDisbursementAsync(disbursementIdHash, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateDisbursementAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateRiskAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Disbursement>>>)(async () =>
|
||||
public async Task<Result> CreateRuleAsync(CreateRuleRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateRuleAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Disbursement>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetDisbursementAsync(disbursementIdHash, cancellationToken);
|
||||
@@ -44,8 +47,8 @@ public sealed class ExecutionCacheService(ExecutionService service, IDistributed
|
||||
return Result.Ok(cached.FromJson<Disbursement>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Disbursement[]>>>)(async () =>
|
||||
public async Task<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Disbursement[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetDisbursementsAsync(pagination, cancellationToken);
|
||||
@@ -68,8 +71,8 @@ public sealed class ExecutionCacheService(ExecutionService service, IDistributed
|
||||
return Result.Ok(cached.FromJson<Disbursement[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk>>>)(async () =>
|
||||
public async Task<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetRiskAsync(riskIdHash, cancellationToken);
|
||||
@@ -92,8 +95,8 @@ public sealed class ExecutionCacheService(ExecutionService service, IDistributed
|
||||
return Result.Ok(cached.FromJson<Risk>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk[]>>>)(async () =>
|
||||
public async Task<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetRisksAsync(pagination, cancellationToken);
|
||||
@@ -116,9 +119,60 @@ public sealed class ExecutionCacheService(ExecutionService service, IDistributed
|
||||
return Result.Ok(cached.FromJson<Risk[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result<Rule>> GetRuleAsync(string ruleIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Rule>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetRuleAsync(ruleIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getrisk-{ruleIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetRuleAsync(ruleIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Rule>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Rule[]>> GetRulesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Rule[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetRulesAsync(pagination, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getrules-{pagination.Page}-{pagination.PageSize}-{pagination.Index}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetRulesAsync(pagination, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Rule[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateDisbursementAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateRiskAsync(request, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateRuleAsync(UpdateRuleRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateRuleAsync(request, userId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
@@ -8,10 +9,11 @@ using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Execution;
|
||||
|
||||
public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService) : IExecutionService
|
||||
public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
ITenantContextService tenantContext) : IExecutionService
|
||||
{
|
||||
public async ValueTask<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk[]>>>)(async () =>
|
||||
public async Task<Result<Risk[]>> GetRisksAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -21,11 +23,11 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(risks.Select(i => i.Map()).ToArray());
|
||||
return Result.Ok(risks?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Disbursement[]>>>)(async () =>
|
||||
public async Task<Result<Disbursement[]>> GetDisbursementsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Disbursement[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -35,11 +37,11 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
.Take(pagination.PageSize)
|
||||
.ToArrayAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(disbursements.Select(i => i.Map()).ToArray());
|
||||
return Result.Ok(disbursements?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateRiskAsync(CreateRiskRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -60,8 +62,8 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateDisbursementAsync(CreateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -81,8 +83,8 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> ApproveDisbursementAsync(string disbursementIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(disbursementIdHash);
|
||||
|
||||
@@ -93,16 +95,16 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Disbursements.Where(d => d.Id == decodeResult.Value)
|
||||
.ExecuteUpdateAsync(f =>
|
||||
f.SetProperty(f => f.Status, ApprovalStatus.Approved)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(f => f.Status, ApprovalStatus.Approved)
|
||||
.SetProperty(f => f.UpdatedBy, userId)
|
||||
.SetProperty(f => f.UpdatedAt, DateTime.UtcNow), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<Disbursement>>>)(async () =>
|
||||
public async Task<Result<Disbursement>> GetDisbursementAsync(string disbursementIdHash, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<Disbursement>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(disbursementIdHash);
|
||||
|
||||
@@ -119,8 +121,8 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
.ToResult(disbursement!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk>>>)(async () =>
|
||||
public async Task<Result<Risk>> GetRiskAsync(string riskIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(riskIdHash);
|
||||
|
||||
@@ -137,8 +139,8 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
.ToResult(risk!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateRiskAsync(UpdateRiskRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -153,8 +155,8 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateDisbursementAsync(UpdateDisbursementRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -168,4 +170,82 @@ public sealed class ExecutionService(IDbContextFactory<ApplicationDbContext> con
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateRuleAsync(CreateRuleRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Programmes.AnyAsync(p => p.Id == request.ProgrammeId, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("Programme does not exist"));
|
||||
|
||||
var requestedName = request.Name.Humanize(LetterCasing.Title).Trim();
|
||||
|
||||
if (await context.Rules.AnyAsync(r => r.Name == requestedName && r.ProgrammeId == request.ProgrammeId, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("A rule with the same name exists"));
|
||||
|
||||
context.Rules.Add(new Domain.Entities.Rule
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Description = request.Description,
|
||||
Name = requestedName,
|
||||
ProgrammeId = request.ProgrammeId,
|
||||
Status = ActivityStatus.Active,
|
||||
Version = 1,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create rule"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateRuleAsync(UpdateRuleRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var requestedName = request.Name.Humanize(LetterCasing.Title).Trim();
|
||||
|
||||
var changedTotal = await context.Rules
|
||||
.Where(f => f.Id == request.RuleId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Status, request.Status)
|
||||
.SetProperty(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.SetProperty(u => u.Name, requestedName)
|
||||
.SetProperty(u => u.Version, request.Version + 1)
|
||||
.SetProperty(u => u.Description, request.Description), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("Failed to update rule"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Rule>> GetRuleAsync(string ruleIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Rule>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(ruleIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Rule>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var rule = await context.Rules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(rule is null, NotFoundError.New)
|
||||
.ToResult(rule!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result<Rule[]>> GetRulesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Rule[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var rules = await context.Rules.AsNoTracking()
|
||||
.OrderByDescending(d => d.Id)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToArrayAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(rules?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,18 @@ using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Execution;
|
||||
|
||||
public sealed record UpdateRuleRequest([Required] long RuleId,
|
||||
[Required] Guid UserId,
|
||||
[Required][MaxLength(TextLength)] string Name,
|
||||
[Required][MaxLength(TextLength)] string Description,
|
||||
[Required] ActivityStatus Status,
|
||||
[Required] int Version);
|
||||
|
||||
public sealed record CreateRuleRequest([Required] long ProgrammeId,
|
||||
[Required] Guid UserId,
|
||||
[Required][MaxLength(TextLength)] string Name,
|
||||
[Required][MaxLength(TextLength)] string Description);
|
||||
|
||||
public sealed record UpdateDisbursementRequest([Required] long DisbursementId, long? MilestoneId, [Required] decimal Amount);
|
||||
|
||||
public sealed record UpdateRiskRequest([Required] long RiskId,
|
||||
|
||||
@@ -11,14 +11,23 @@ namespace PostFundManagement.Application.Services.Governance;
|
||||
public sealed class GovernanceCacheService(GovernanceService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IGovernanceService
|
||||
{
|
||||
public async ValueTask<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateInstrumentAsync(CreateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateInstrumentAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateOrganisationAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreatePortfolioAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Dashboard>>>)(async () =>
|
||||
public async Task<Result> CreateTenantAsync(CreateTenantRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateTenantAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateTenantOrganisationAsync(string organisationIdHash, string tenantIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateTenantOrganisationAsync(organisationIdHash, tenantIdHash, userId, cancellationToken);
|
||||
|
||||
public async Task<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Dashboard>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetDashboardAsync(cancellationToken);
|
||||
@@ -41,8 +50,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Dashboard>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Instrument[]>>>)(async () =>
|
||||
public async Task<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Instrument[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetInstrumentsAsync(programmeIdHash, cancellationToken);
|
||||
@@ -65,8 +74,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Instrument[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Organisation>>>)(async () =>
|
||||
public async Task<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Organisation>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetOrganisationAsync(organisationIdHash, cancellationToken);
|
||||
@@ -89,8 +98,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Organisation>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Organisation[]>>>)(async () =>
|
||||
public async Task<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Organisation[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetOrganisationsAsync(pagination, cancellationToken);
|
||||
@@ -113,8 +122,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Organisation[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Portfolio[]>>>)(async () =>
|
||||
public async Task<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Portfolio[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetPorfoliosAsync(organisationIdHash, cancellationToken);
|
||||
@@ -137,8 +146,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Portfolio[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Portfolio>>>)(async () =>
|
||||
public async Task<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Portfolio>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetPortfolioAsync(portfolioIdHash, cancellationToken);
|
||||
@@ -161,8 +170,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Portfolio>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetPortfolioProgrammesAsync(portfolioIdHash, cancellationToken);
|
||||
@@ -185,8 +194,8 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Programme[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProgrammesAsync(portfolioIdHash, cancellationToken);
|
||||
@@ -209,9 +218,117 @@ public sealed class GovernanceCacheService(GovernanceService service, IDistribut
|
||||
return Result.Ok(cached.FromJson<Programme[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOrganisationAsync(request, cancellationToken);
|
||||
public async Task<Result<Tenant>> GetTenantAsync(string tenantIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Tenant>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetTenantAsync(tenantIdHash, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdatePortfolioAsync(request, userId, cancellationToken);
|
||||
var cacheKey = HashService.ToMd5Hash($"gettenant-{tenantIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetTenantAsync(tenantIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Tenant>());
|
||||
}));
|
||||
|
||||
public async Task<Result<TenantOrganisation>> GetTenantOrganisationAsync(string tenantOrganisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<TenantOrganisation>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetTenantOrganisationAsync(tenantOrganisationIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"gettenantorganisation-{tenantOrganisationIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetTenantOrganisationAsync(tenantOrganisationIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<TenantOrganisation>());
|
||||
}));
|
||||
|
||||
public async Task<Result<TenantOrganisation[]>> GetTenantOrganisationsAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<TenantOrganisation[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetTenantOrganisationsAsync(cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"gettenantorganisations").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetTenantOrganisationsAsync(cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<TenantOrganisation[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Tenant[]>> GetTenantsAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Tenant[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetTenantsAsync(cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"gettenants").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetTenantsAsync(cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Tenant[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateInstrumentAsync(UpdateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateInstrumentAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOrganisationAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdatePortfolioAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateTenantAsync(UpdateTenantRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateTenantAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateTenantOrganisationAsync(string tenantOrganisationIdHash, ActivityStatus status, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateTenantOrganisationAsync(tenantOrganisationIdHash, status, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateTenantUserAsync(UpdateTenantUserRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateTenantUserAsync(request, userId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
using PostFundManagement.Application.Extensions;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Governance;
|
||||
|
||||
public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService) : IGovernanceService
|
||||
public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
ITenantContextService tenantContext) : IGovernanceService
|
||||
{
|
||||
public async ValueTask<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(portfolioIdHash);
|
||||
|
||||
@@ -30,8 +32,8 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.Ok(programmes.Select(p => p.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Portfolio[]>>>)(async () =>
|
||||
public async Task<Result<Portfolio[]>> GetPorfoliosAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Portfolio[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(organisationIdHash);
|
||||
|
||||
@@ -49,22 +51,23 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.Ok(portfolios.Select(p => p.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Organisation[]>>>)(async () =>
|
||||
public async Task<Result<Organisation[]>> GetOrganisationsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Organisation[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var organisations = await context.Organisations.AsNoTracking()
|
||||
.OrderBy(o => o.Name)
|
||||
var organisations = await context.TenantOrganisations.AsNoTracking()
|
||||
.Include(i => i.Organisation)
|
||||
.OrderBy(o => o.Organisation!.Name)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(organisations.Select(o => o.Map()).ToArray());
|
||||
return Result.Ok(organisations.Select(o => o.Organisation!.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Organisation>>>)(async () =>
|
||||
public async Task<Result<Organisation>> GetOrganisationAsync(string organisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Organisation>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(organisationIdHash);
|
||||
|
||||
@@ -74,15 +77,16 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var organisation = await context.Organisations.AsNoTracking()
|
||||
.FirstOrDefaultAsync(o => o.Id == decodeResult.Value, cancellationToken);
|
||||
var tenantOrganisation = await context.TenantOrganisations.AsNoTracking()
|
||||
.Include(i => i.OrganisationId)
|
||||
.FirstOrDefaultAsync(o => o.OrganisationId == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(organisation is null, NotFoundError.New)
|
||||
.ToResult(organisation!.Map());
|
||||
return Result.FailIf(tenantOrganisation is null, NotFoundError.New)
|
||||
.ToResult(tenantOrganisation!.Organisation!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Instrument[]>>>)(async () =>
|
||||
public async Task<Result<Instrument[]>> GetInstrumentsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Instrument[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(programmeIdHash);
|
||||
|
||||
@@ -100,8 +104,8 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.Ok(instruments.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Dashboard>>>)(async () =>
|
||||
public async Task<Result<Dashboard>> GetDashboardAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Dashboard>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -126,8 +130,8 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
disbursedAmount, onTrackPercentage, atRiskCount, beneficiariesReached));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateOrganisationAsync(CreateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -136,7 +140,7 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
if (await context.Organisations.AnyAsync(o => o.RegistrationNo == registrationNo, cancellationToken))
|
||||
return Result.Fail(CreateError.Create("Organisation with the same registration number already exists"));
|
||||
|
||||
context.Organisations.Add(new Domain.Entities.Organisation
|
||||
var organisation = context.Organisations.Add(new Domain.Entities.Organisation
|
||||
{
|
||||
Name = request.Name.Humanize(LetterCasing.Title).Trim(),
|
||||
RegistrationNo = registrationNo,
|
||||
@@ -147,11 +151,16 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
CreatedAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var mapResult = await CreateTenantOrganisationAsync(hashService.HashEncodeLongId(organisation.Entity.Id).Value,
|
||||
hashService.HashEncodeLongId(tenantContext.TenantId).Value, userId, cancellationToken);
|
||||
|
||||
return Result.FailIf(mapResult.IsFailed, CreateError.Create("Failed to create organisation"));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Organisation>>>)(async () =>
|
||||
public async Task<Result<Organisation>> UpdateOrganisationAsync(UpdateOrganisationRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Organisation>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -161,13 +170,21 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
.SetProperty(u => u.Name, request.Name.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.RegistrationNo, request.RegistrationNo.Clean())
|
||||
.SetProperty(u => u.Email, request.Email.ToLower(CultureInfo.InvariantCulture).Clean())
|
||||
.SetProperty(u => u.Type, request.Type), cancellationToken);
|
||||
.SetProperty(u => u.Type, request.Type)
|
||||
.SetProperty(u => u.Status, request.Status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
var tenantOrganisation = await context.TenantOrganisations.AsNoTracking().FirstOrDefaultAsync(f => f.OrganisationId == request.OrganisationId, cancellationToken);
|
||||
|
||||
if (tenantOrganisation is null)
|
||||
return Result.Fail(ValidationError.Create("Failed to find linked tenant organisation"));
|
||||
|
||||
var updateResult = await UpdateTenantOrganisationAsync(hashService.HashEncodeLongId(tenantOrganisation.Id).Value, request.Status, userId, cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0 && updateResult.IsSuccess, UpdateError.Create("Failed to update organisation"));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreatePortfolioAsync(CreatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -189,14 +206,15 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
OrganisationId = request.OrganisationId,
|
||||
OwnedBy = request.OwnerId,
|
||||
Name = name,
|
||||
Description = request.Description.Humanize(LetterCasing.Sentence).Trim()
|
||||
Description = request.Description.Humanize(LetterCasing.Sentence).Trim(),
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdatePortfolioAsync(UpdatePortfolioRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -213,8 +231,8 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("Nothing was saved, no change detected."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetPortfolioProgrammesAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(portfolioIdHash);
|
||||
|
||||
@@ -232,8 +250,8 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.Ok(programmes.Select(p => p.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Portfolio>>>)(async () =>
|
||||
public async Task<Result<Portfolio>> GetPortfolioAsync(string portfolioIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Portfolio>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(portfolioIdHash);
|
||||
|
||||
@@ -249,4 +267,208 @@ public sealed class GovernanceService(IDbContextFactory<ApplicationDbContext> co
|
||||
return Result.FailIf(portfolio is null, NotFoundError.New)
|
||||
.ToResult(portfolio!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateTenantAsync(CreateTenantRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var requestedName = request.Name.Humanize(LetterCasing.Title).Trim();
|
||||
|
||||
if (await context.Tenants.AnyAsync(t => t.Name == requestedName, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("A tenant with an equivalent name exists."));
|
||||
|
||||
context.Tenants.Add(new Domain.Entities.Tenant
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Name = requestedName,
|
||||
Status = ActivityStatus.Active
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0,
|
||||
CreateError.Create("Failed to create new tenant"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Tenant[]>> GetTenantsAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Tenant[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var tenants = await context.Tenants.AsNoTracking()
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(tenants?.Select(t => t.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<Tenant>> GetTenantAsync(string tenantIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Tenant>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(tenantIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var tenant = await context.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(tenant is null, NotFoundError.Create("Failed to retrieve tenants"))
|
||||
.ToResult(tenant!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateTenantAsync(UpdateTenantRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var requestedName = request.Name.Humanize(LetterCasing.Title).Trim();
|
||||
|
||||
if (await context.Tenants.AnyAsync(t => t.Name == requestedName, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("A tenant with an equivalent name exists."));
|
||||
|
||||
var changedTotal = await context.Tenants
|
||||
.Where(f => f.Id == request.TenantId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.UpdatedAt, DateTime.UtcNow)
|
||||
.SetProperty(u => u.UpdatedBy, userId)
|
||||
.SetProperty(u => u.Status, request.Status)
|
||||
.SetProperty(u => u.Name, requestedName), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records updated"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateTenantUserAsync(UpdateTenantUserRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.TenantUsers
|
||||
.Where(f => f.UserId == request.UserId)
|
||||
.ExecuteUpdateAsync(f => f.SetProperty(u => u.Status, request.Status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records updated"));
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateTenantOrganisationAsync(string organisationIdHash, string tenantIdHash, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
var organisationDecodeResult = hashService.DecodeLongIdHash(organisationIdHash);
|
||||
|
||||
if (organisationDecodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(organisationDecodeResult.Errors));
|
||||
|
||||
var tenantDecodeResult = hashService.DecodeLongIdHash(tenantIdHash);
|
||||
|
||||
if (tenantDecodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(tenantDecodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (await context.TenantOrganisations.AnyAsync(to => to.OrganisationId == organisationDecodeResult.Value && to.TenantId == tenantDecodeResult.Value, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("Already exists"));
|
||||
|
||||
context.TenantOrganisations.Add(new Domain.Entities.TenantOrganisation
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
OrganisationId = organisationDecodeResult.Value,
|
||||
TenantId = tenantDecodeResult.ValueOrDefault
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0,
|
||||
CreateError.Create("Failed to create tenant organisation map"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateTenantOrganisationAsync(string tenantOrganisationIdHash, ActivityStatus status, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(tenantOrganisationIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.TenantOrganisations
|
||||
.Where(f => f.Id == decodeResult.Value)
|
||||
.ExecuteUpdateAsync(f => f.SetProperty(u => u.Status, status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("Failed to update tenant organisation map"));
|
||||
}));
|
||||
|
||||
public async Task<Result<TenantOrganisation[]>> GetTenantOrganisationsAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<TenantOrganisation[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var tenantOrganisations = await context.TenantOrganisations.AsNoTracking()
|
||||
.Include(i => i.Organisation)
|
||||
.Include(i => i.Tenant)
|
||||
.Where(f => f.TenantId == tenantContext.TenantId)
|
||||
.ToListAsync();
|
||||
|
||||
return Result.Ok(tenantOrganisations?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<TenantOrganisation>> GetTenantOrganisationAsync(string tenantOrganisationIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<TenantOrganisation>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(tenantOrganisationIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var tenantOrganisation = await context.TenantOrganisations.AsNoTracking()
|
||||
.Include(i => i.Organisation)
|
||||
.Include(i => i.Tenant)
|
||||
.FirstOrDefaultAsync(f => f.TenantId == tenantContext.TenantId, cancellationToken);
|
||||
|
||||
return Result.FailIf(tenantOrganisation is null, NotFoundError.Create("Failed to find tenant organisation map"))
|
||||
.ToResult(tenantOrganisation!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateInstrumentAsync(UpdateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Instruments
|
||||
.Where(i => i.Id == request.InstructionId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Name, request.Name.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Code, request.Code)
|
||||
.SetProperty(u => u.Description, request.Description)
|
||||
.SetProperty(u => u.Status, request.Status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("Failed to update instrument"));
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateInstrumentAsync(CreateInstrumentRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Instruments.Add(new Domain.Entities.Instrument
|
||||
{
|
||||
Code = request.Code,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Description = request.Description,
|
||||
Name = request.Name.Humanize(LetterCasing.Title).Trim(),
|
||||
Status = ActivityStatus.Active,
|
||||
ProgrammeId = request.ProgrammeId,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create instrument"));
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,27 @@ using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Governance;
|
||||
|
||||
public sealed record UpdateInstrumentRequest([Required] long InstructionId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string Code,
|
||||
[Required][MaxLength(TextLength)] string Description,
|
||||
[Required] ActivityStatus Status);
|
||||
|
||||
public sealed record CreateInstrumentRequest([Required] long ProgrammeId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string Code,
|
||||
[Required][MaxLength(TextLength)] string Description);
|
||||
|
||||
public sealed record CreateTenantRequest([Required][MaxLength(LabelLength)] string Name);
|
||||
|
||||
public sealed record UpdateTenantUserRequest([Required] Guid UserId, [Required] ActivityStatus Status);
|
||||
|
||||
public sealed record CreateTenantUserRequest([Required] long TenantId, [Required] Guid UserId);
|
||||
|
||||
public sealed record UpdateTenantRequest([Required] long TenantId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required] ActivityStatus Status);
|
||||
|
||||
public sealed record UpdatePortfolioRequest([Required] long PortfolioId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(TextLength)] string Description,
|
||||
@@ -17,7 +38,8 @@ public sealed record UpdateOrganisationRequest([Required] long OrganisationId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string RegistrationNo,
|
||||
[Required][EmailAddress][MaxLength(LabelLength)] string Email,
|
||||
[Required] OrganisationType Type);
|
||||
[Required] OrganisationType Type,
|
||||
[Required] ActivityStatus Status);
|
||||
|
||||
public sealed record CreateOrganisationRequest([Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string RegistrationNo,
|
||||
|
||||
@@ -11,20 +11,20 @@ namespace PostFundManagement.Application.Services.Grants;
|
||||
public sealed class GrantsCacheService(GrantsService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IGrantsService
|
||||
{
|
||||
public async ValueTask<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateAwardAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateBudgetAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateContractAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.ExecuteContractAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Award>>>)(async () =>
|
||||
public async Task<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Award>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetAwardAsync(awardIdHash, cancellationToken);
|
||||
@@ -47,8 +47,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Award>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Award[]>>>)(async () =>
|
||||
public async Task<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Award[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetAwardsAsync(pagination, cancellationToken);
|
||||
@@ -71,8 +71,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Award[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Budget>>>)(async () =>
|
||||
public async Task<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Budget>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetBudgetAsync(budgetIdHash, cancellationToken);
|
||||
@@ -95,8 +95,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Budget>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Budget[]>>>)(async () =>
|
||||
public async Task<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Budget[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetBudgetsAsync(pagination, cancellationToken);
|
||||
@@ -119,8 +119,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Budget[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Contract>>>)(async () =>
|
||||
public async Task<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Contract>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetContractAsync(contractIdHash, cancellationToken);
|
||||
@@ -143,8 +143,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Contract>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Contract[]>>>)(async () =>
|
||||
public async Task<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Contract[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetContractsAsync(pagination, cancellationToken);
|
||||
@@ -167,8 +167,8 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached.FromJson<Contract[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public async Task<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetContractUrlAsync(contractIdHash, cancellationToken);
|
||||
@@ -191,9 +191,9 @@ public sealed class GrantsCacheService(GrantsService service, IDistributedCache
|
||||
return Result.Ok(cached!);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateContractAsync(request, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await service.UploadContractAsync(contractIdHash, userId, file, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ using PostFundManagement.Infrastructure.Database;
|
||||
namespace PostFundManagement.Application.Services.Grants;
|
||||
|
||||
public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
[FromKeyedServices(Constants.GeneralBucketName)] IS3Service s3Service) : IGrantsService
|
||||
[FromKeyedServices(Constants.GeneralBucketName)] IS3Service s3Service, ITenantContextService tenantContext) : IGrantsService
|
||||
{
|
||||
public async ValueTask<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Contract[]>>>)(async () =>
|
||||
public async Task<Result<Contract[]>> GetContractsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Contract[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -26,8 +26,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.Ok(contracts.Select(c => c.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Contract>>>)(async () =>
|
||||
public async Task<Result<Contract>> GetContractAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Contract>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(contractIdHash);
|
||||
|
||||
@@ -44,8 +44,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
.ToResult(contract!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Budget[]>>>)(async () =>
|
||||
public async Task<Result<Budget[]>> GetBudgetsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Budget[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -58,8 +58,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.Ok(budgets.Select(b => b.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Budget>>>)(async () =>
|
||||
public async Task<Result<Budget>> GetBudgetAsync(string budgetIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Budget>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(budgetIdHash);
|
||||
|
||||
@@ -76,8 +76,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
.ToResult(budget!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Award[]>>>)(async () =>
|
||||
public async Task<Result<Award[]>> GetAwardsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Award[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -90,8 +90,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.Ok(awards.Select(a => a.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Award>>>)(async () =>
|
||||
public async Task<Result<Award>> GetAwardAsync(string awardIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Award>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(awardIdHash);
|
||||
|
||||
@@ -107,8 +107,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
.ToResult(award!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> ExecuteContractAsync(ExecuteContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -123,8 +123,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateContractAsync(CreateContractRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -150,8 +150,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateBudgetAsync(CreateBudgetRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
if (request.Amount <= 0)
|
||||
return Result.Fail(ValidationError.Create("Budget amount must be greater than zero."));
|
||||
@@ -175,8 +175,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateAwardAsync(CreateAwardRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
if (request.Amount <= 0)
|
||||
return Result.Fail(ValidationError.Create("Approved amount must be greater than zero."));
|
||||
@@ -196,7 +196,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
Amount = request.Amount,
|
||||
Status = ApprovalStatus.Pending,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
TenantId = tenantContext.TenantId
|
||||
};
|
||||
|
||||
context.Awards.Add(award);
|
||||
@@ -204,8 +205,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public async Task<Result<string>> GetContractUrlAsync(string contractIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(contractIdHash);
|
||||
|
||||
@@ -231,8 +232,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
.ToResult(secureDownloadUrlResult.Value);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UploadContractAsync(string contractIdHash, Guid userId, IFormFile file, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(contractIdHash);
|
||||
|
||||
@@ -261,8 +262,8 @@ public sealed class GrantsService(IDbContextFactory<ApplicationDbContext> contex
|
||||
CreateError.Create("Failed to upload contract file"));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateContractAsync(UpdateContractRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
|
||||
@@ -11,17 +11,35 @@ namespace PostFundManagement.Application.Services.Projects;
|
||||
public sealed class ProjectCacheService(ProjectService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IProjectService
|
||||
{
|
||||
public async ValueTask<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateActivityAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateBeneficiaryAsync(CreateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateBeneficiaryAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateChangeRequestAsync(CreateChangeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateChangeRequestAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateComplianceItemAsync(CreateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateComplianceItemAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateIssueAsync(CreateIssueRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateIssueAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateOutcomeAsync(CreateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateOutcomeAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateProgrammeAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateProjectAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Activity[]>>>)(async () =>
|
||||
public async Task<Result> CreateSiteVisitAsync(CreateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.CreateSiteVisitAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Activity[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetActivitiesAsync(projectIdHash, cancellationToken);
|
||||
@@ -44,8 +62,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Activity[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Activity>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Activity>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetActivityAsync(activityIdHash, cancellationToken);
|
||||
@@ -68,8 +86,200 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Domain.Models.Activity>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone>>>)(async () =>
|
||||
public async Task<Result<Beneficiary[]>> GetBeneficiariesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Beneficiary[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetBeneficiariesAsync(projectIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getbeneficiaries-{projectIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetBeneficiariesAsync(projectIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Beneficiary[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Beneficiary>> GetBeneficiaryAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Beneficiary>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetBeneficiaryAsync(beneficiaryIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getbeneficiary-{beneficiaryIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetBeneficiaryAsync(beneficiaryIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Beneficiary>());
|
||||
}));
|
||||
|
||||
public async Task<Result<ChangeRequest>> GetChangeRequestAsync(string changeRequestIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ChangeRequest>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetChangeRequestAsync(changeRequestIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getchangerequest-{changeRequestIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetChangeRequestAsync(changeRequestIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<ChangeRequest>());
|
||||
}));
|
||||
|
||||
public async Task<Result<ChangeRequest[]>> GetChangeRequestsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ChangeRequest[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetChangeRequestsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getchangerequests-{projectIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetChangeRequestsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<ChangeRequest[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<ComplianceItem>> GetComplianceItemAsync(string complianceItemIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ComplianceItem>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetComplianceItemAsync(complianceItemIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getcomplianceitem-{complianceItemIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetComplianceItemAsync(complianceItemIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<ComplianceItem>());
|
||||
}));
|
||||
|
||||
public async Task<Result<ComplianceItem[]>> GetComplianceItemsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ComplianceItem[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetComplianceItemsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getcomplianceitems-{projectIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetComplianceItemsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<ComplianceItem[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Issue>> GetIssueAsync(string issueIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Issue>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetIssueAsync(issueIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getissue-{issueIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetIssueAsync(issueIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Issue>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Issue[]>> GetIssuesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Issue[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetIssuesAsync(projectIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getissues-{projectIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetIssuesAsync(projectIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Issue[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetMilestoneAsync(milestoneIdHash, cancellationToken);
|
||||
@@ -92,8 +302,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Milestone>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone[]>>>)(async () =>
|
||||
public async Task<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetMilestonesAsync(pagination, cancellationToken);
|
||||
@@ -116,8 +326,56 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Milestone[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme>>>)(async () =>
|
||||
public async Task<Result<Outcome>> GetOutcomeAsync(string outcomeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Outcome>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetOutcomeAsync(outcomeIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getoutcome-{outcomeIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetOutcomeAsync(outcomeIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Outcome>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Outcome[]>> GetOutcomesAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Outcome[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetOutcomesAsync(beneficiaryIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getoutcomes-{beneficiaryIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetOutcomesAsync(beneficiaryIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<Outcome[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProgrammeAsync(programmeIdHash, cancellationToken);
|
||||
@@ -140,8 +398,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached!.FromJson<Programme>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project[]>>>)(async () =>
|
||||
public async Task<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProgrammeProjectsAsync(programmeIdHash, cancellationToken);
|
||||
@@ -164,8 +422,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Project[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProgrammesAsync(pagination, cancellationToken);
|
||||
@@ -188,8 +446,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Programme[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project>>>)(async () =>
|
||||
public async Task<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectAsync(projectIdHash, cancellationToken);
|
||||
@@ -212,8 +470,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Project>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator[]>>>)(async () =>
|
||||
public async Task<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Indicator[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectIndicatorsAsync(projectIdHash, cancellationToken);
|
||||
@@ -236,8 +494,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Indicator[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone[]>>>)(async () =>
|
||||
public async Task<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectMilestonesAsync(projectIdHash, cancellationToken);
|
||||
@@ -260,8 +518,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Milestone[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk[]>>>)(async () =>
|
||||
public async Task<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectRisksAsync(projectIdHash, cancellationToken);
|
||||
@@ -284,8 +542,8 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Risk[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project[]>>>)(async () =>
|
||||
public async Task<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetProjectsAsync(pagination, cancellationToken);
|
||||
@@ -308,15 +566,81 @@ public sealed class ProjectCacheService(ProjectService service, IDistributedCach
|
||||
return Result.Ok(cached.FromJson<Project[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result<SiteVisit>> GetSiteVisitAsync(string siteVisitIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<SiteVisit>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetSiteVisitAsync(siteVisitIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getsitevisit-{siteVisitIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetSiteVisitAsync(siteVisitIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<SiteVisit>());
|
||||
}));
|
||||
|
||||
public async Task<Result<SiteVisit[]>> GetSiteVisitsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<SiteVisit[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetSiteVisitsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"getsitevisits-{projectIdHash}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = await service.GetSiteVisitsAsync(projectIdHash, cancellationToken);
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value.ToJson(), cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached.FromJson<SiteVisit[]>());
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateBeneficiaryAsync(UpdateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateBeneficiaryAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateChangeRequestAsync(UpdateChangeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateChangeRequestAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateComplianceItemAsync(UpdateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateComplianceItemAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateIssueAsync(UpdateIssueRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateIssueAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateMilestoneAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateOutcomeAsync(UpdateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateOutcomeAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateProgrammeAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateProjectAsync(request, userId, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateProjectStatusAsync(request, userId, cancellationToken);
|
||||
|
||||
public async Task<Result> UpdateSiteVisitAsync(UpdateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateSiteVisitAsync(request, userId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
@@ -8,10 +9,11 @@ using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Projects;
|
||||
|
||||
public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService) : IProjectService
|
||||
public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
ITenantContextService tenantContext) : IProjectService
|
||||
{
|
||||
public async ValueTask<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateProjectStatusAsync(UpdateProjectStatusRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -28,8 +30,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No changes detected, update cancelled."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project[]>>>)(async () =>
|
||||
public async Task<Result<Project[]>> GetProjectsAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -41,8 +43,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(projects.Select(p => p.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project>>>)(async () =>
|
||||
public async Task<Result<Project>> GetProjectAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -59,8 +61,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
.ToResult(project!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Activity[]>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Activity[]>> GetActivitiesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Activity[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -77,8 +79,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(activities.Select(a => a.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateProjectAsync(CreateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -101,15 +103,16 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
ProjectType = request.ProjectType,
|
||||
Status = ApprovalStatus.Pending,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0,
|
||||
CreateError.Create("No changes detected, update cancelled."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateActivityAsync(CreateActivityRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -138,8 +141,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
CreateError.Create("No record was created."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone[]>>>)(async () =>
|
||||
public async Task<Result<Milestone[]>> GetProjectMilestonesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -157,8 +160,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(milestones.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<Indicator[]>>>)(async () =>
|
||||
public async Task<Result<Indicator[]>> GetProjectIndicatorsAsync(string projectIdHash, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<Indicator[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -176,8 +179,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(evidences.Select(e => e.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone>>>)(async () =>
|
||||
public async Task<Result<Milestone>> GetMilestoneAsync(string milestoneIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(milestoneIdHash);
|
||||
|
||||
@@ -193,8 +196,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
.ToResult(milestone!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Milestone[]>>>)(async () =>
|
||||
public async Task<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Milestone[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -207,8 +210,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(milestones.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateMilestoneAsync(UpdateMilestoneRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -227,8 +230,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No changes detected, update cancelled."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateProjectAsync(UpdateProjectRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -246,8 +249,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No changes detected, update cancelled."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Models.Activity>>>)(async () =>
|
||||
public async Task<Result<Domain.Models.Activity>> GetActivityAsync(string activityIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Models.Activity>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(activityIdHash);
|
||||
|
||||
@@ -264,8 +267,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
.ToResult(activity!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Risk[]>>>)(async () =>
|
||||
public async Task<Result<Risk[]>> GetProjectRisksAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Risk[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
@@ -283,8 +286,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(risks.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> CreateProgrammeAsync(CreateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -303,14 +306,15 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
Name = name,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Status = ApprovalStatus.Pending
|
||||
Status = ApprovalStatus.Pending,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateProgrammeAsync(UpdateProgrammeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -328,8 +332,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No changes detected, update cancelled."));
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme>>>)(async () =>
|
||||
public async Task<Result<Programme>> GetProgrammeAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(programmeIdHash);
|
||||
|
||||
@@ -344,8 +348,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
.ToResult(programme!.Map());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Programme[]>>>)(async () =>
|
||||
public async Task<Result<Programme[]>> GetProgrammesAsync(Pagination pagination, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Programme[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
@@ -358,8 +362,8 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
return Result.Ok(programmes.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Project[]>>>)(async () =>
|
||||
public async Task<Result<Project[]>> GetProgrammeProjectsAsync(string programmeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Project[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(programmeIdHash);
|
||||
|
||||
@@ -378,4 +382,444 @@ public sealed class ProjectService(IDbContextFactory<ApplicationDbContext> conte
|
||||
|
||||
return Result.Ok(projects.Select(i => i.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateChangeRequestAsync(CreateChangeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (await context.Projects.AnyAsync(p => p.Id == request.ProjectId, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("Project does not exist"));
|
||||
|
||||
context.ChangeRequests.Add(new Domain.Entities.ChangeRequest
|
||||
{
|
||||
ProjectId = request.ProjectId,
|
||||
Title = request.Title,
|
||||
Justification = request.Justification,
|
||||
RevisedBudget = request.RevisedBudget,
|
||||
RevisedEndedAt = request.RevisionDate,
|
||||
Status = ApprovalStatus.Pending,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
TenantId = tenantContext.TenantId,
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0,
|
||||
CreateError.Create("Failed to create change request"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateChangeRequestAsync(UpdateChangeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.ChangeRequests
|
||||
.Where(c => c.Id == request.ChangeRequestId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Status, request.Status)
|
||||
.SetProperty(u => u.RevisedBudget, request.RevisedBudget)
|
||||
.SetProperty(u => u.RevisedEndedAt, DateTime.UtcNow)
|
||||
.SetProperty(u => u.Title, request.Title.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Justification, request.Justification), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records were changed"));
|
||||
}));
|
||||
|
||||
public async Task<Result<ChangeRequest[]>> GetChangeRequestsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ChangeRequest[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<ChangeRequest[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changeRequests = await context.ChangeRequests.AsNoTracking()
|
||||
.Where(c => c.ProjectId == decodeResult.Value)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(changeRequests?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<ChangeRequest>> GetChangeRequestAsync(string changeRequestIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ChangeRequest>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(changeRequestIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<ChangeRequest>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changeRequest = await context.ChangeRequests.AsNoTracking().FirstOrDefaultAsync(c => c.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(changeRequest is null, NotFoundError.New)
|
||||
.ToResult(changeRequest!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateComplianceItemAsync(CreateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (await context.Projects.AnyAsync(p => p.Id == request.ProjectId, cancellationToken))
|
||||
return Result.Fail(ValidationError.Create("Project does not exist"));
|
||||
|
||||
context.ComplianceItems.Add(new Domain.Entities.ComplianceItem
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
ProjectId = request.ProjectId,
|
||||
Requirements = request.Requirements,
|
||||
Status = ApprovalStatus.Pending,
|
||||
TenantId = tenantContext.TenantId,
|
||||
Title = request.Title.Humanize(LetterCasing.Title).Trim()
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create compliance item"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateComplianceItemAsync(UpdateComplianceItemRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.ComplianceItems
|
||||
.Where(f => f.Id == request.ComplianceItemId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Title, request.Title.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Requirements, request.Requirements)
|
||||
.SetProperty(u => u.Status, request.Status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records changed"));
|
||||
}));
|
||||
|
||||
public async Task<Result<ComplianceItem[]>> GetComplianceItemsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ComplianceItem[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<ComplianceItem[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var complianceItems = await context.ComplianceItems.AsNoTracking()
|
||||
.Where(c => c.ProjectId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(complianceItems?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<ComplianceItem>> GetComplianceItemAsync(string complianceItemIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<ComplianceItem>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(complianceItemIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<ComplianceItem>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var compliancItem = await context.ComplianceItems.AsNoTracking().FirstOrDefaultAsync(c => c.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(compliancItem is null, NotFoundError.New)
|
||||
.ToResult(compliancItem!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateBeneficiaryAsync(CreateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Beneficiaries.Add(new Domain.Entities.Beneficiary
|
||||
{
|
||||
Category = request.Category,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Location = request.Location,
|
||||
Name = request.Name.Humanize(LetterCasing.Title).Trim(),
|
||||
ProjectId = request.ProjectId,
|
||||
ReachedCount = request.ReachedCount,
|
||||
TargetCount = request.TargetCount,
|
||||
UserId = userId,
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0,
|
||||
CreateError.Create("Failed to create beneficiary"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateBeneficiaryAsync(UpdateBeneficiaryRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Beneficiaries
|
||||
.Where(f => f.Id == request.BeneficiaryId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.ReachedCount, request.ReachedCount)
|
||||
.SetProperty(u => u.TargetCount, request.TargetCount)
|
||||
.SetProperty(u => u.Location, request.Location)
|
||||
.SetProperty(u => u.Category, request.Category.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Name, request.Name.Humanize(LetterCasing.Title).Trim()), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records changed"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Beneficiary[]>> GetBeneficiariesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Beneficiary[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Beneficiary[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var beneficiaries = await context.Beneficiaries.AsNoTracking()
|
||||
.Where(b => b.ProjectId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(beneficiaries?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<Beneficiary>> GetBeneficiaryAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Beneficiary>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(beneficiaryIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Beneficiary>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var beneficiary = await context.Beneficiaries.AsNoTracking()
|
||||
.FirstOrDefaultAsync(b => b.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(beneficiary is null, NotFoundError.New)
|
||||
.ToResult(beneficiary!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateIssueAsync(CreateIssueRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Issues.Add(new Domain.Entities.Issue
|
||||
{
|
||||
AssignedTo = request.AssignedTo,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Description = request.Description,
|
||||
Priority = request.Priority,
|
||||
ProjectId = request.ProjectId,
|
||||
Status = ActivityStatus.Active,
|
||||
TenantId = tenantContext.TenantId,
|
||||
Title = request.Title.Humanize(LetterCasing.Title).Trim()
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create issue"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateIssueAsync(UpdateIssueRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Issues
|
||||
.Where(i => i.Id == request.IssueId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Title, request.Title.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Description, request.Description)
|
||||
.SetProperty(u => u.Resolution, request.Resolution)
|
||||
.SetProperty(u => u.ResolvedAt, DateTime.UtcNow)
|
||||
.SetProperty(u => u.Status, request.Status)
|
||||
.SetProperty(u => u.AssignedTo, request.AssignedTo), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records changes"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Issue[]>> GetIssuesAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Issue[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Issue[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var issues = await context.Issues.AsNoTracking()
|
||||
.Where(i => i.ProjectId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(issues?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<Issue>> GetIssueAsync(string issueIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Issue>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(issueIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Issue>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var issue = await context.Issues.AsNoTracking().FirstOrDefaultAsync(i => i.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(issue is null, NotFoundError.New)
|
||||
.ToResult(issue!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateOutcomeAsync(CreateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Outcomes.Add(new Domain.Entities.Outcome
|
||||
{
|
||||
BeneficiaryId = request.BeneficiaryId,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Description = request.Description,
|
||||
Name = request.Name.Humanize(LetterCasing.Title).Trim(),
|
||||
TenantId = tenantContext.TenantId
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create outcome"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateOutcomeAsync(UpdateOutcomeRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Outcomes
|
||||
.Where(o => o.Id == request.OutcomeId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Description, request.Description)
|
||||
.SetProperty(u => u.Name, request.Name.Humanize(LetterCasing.Title).Trim()), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("No records changed"));
|
||||
}));
|
||||
|
||||
public async Task<Result<Outcome[]>> GetOutcomesAsync(string beneficiaryIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Outcome[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(beneficiaryIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Outcome[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var outcomes = await context.Outcomes.AsNoTracking()
|
||||
.Where(o => o.BeneficiaryId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(outcomes?.Select(o => o.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<Outcome>> GetOutcomeAsync(string outcomeIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Outcome>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(outcomeIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<Outcome>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var outcome = await context.Outcomes.AsNoTracking()
|
||||
.FirstOrDefaultAsync(o => o.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(outcome is null, NotFoundError.New)
|
||||
.ToResult(outcome!.Map());
|
||||
}));
|
||||
|
||||
public async Task<Result> CreateSiteVisitAsync(CreateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.SiteVisits.Add(new Domain.Entities.SiteVisit
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
InspectorName = request.InspectorName.Humanize(LetterCasing.Title).Trim(),
|
||||
Findings = request.Findings,
|
||||
VisitedAt = request.VisitedAt
|
||||
});
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.Create("Failed to create site visit"));
|
||||
}));
|
||||
|
||||
public async Task<Result> UpdateSiteVisitAsync(UpdateSiteVisitRequest request, Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.SiteVisits
|
||||
.Where(v => v.Id == request.SiteVisitId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.InspectorName, request.InspectorName.Humanize(LetterCasing.Title).Trim())
|
||||
.SetProperty(u => u.Findings, request.Findings)
|
||||
.SetProperty(u => u.Status, request.Status)
|
||||
.SetProperty(u => u.VisitedAt, request.VisitedAt), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.Create("Failed to update site visit"));
|
||||
}));
|
||||
|
||||
public async Task<Result<SiteVisit[]>> GetSiteVisitsAsync(string projectIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<SiteVisit[]>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(projectIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<SiteVisit[]>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var visits = await context.SiteVisits.AsNoTracking()
|
||||
.Where(v => v.ProjectId == decodeResult.Value)
|
||||
.OrderByDescending(o => o.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(visits?.Select(i => i.Map()).ToArray() ?? []);
|
||||
}));
|
||||
|
||||
public async Task<Result<SiteVisit>> GetSiteVisitAsync(string siteVisitIdHash, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<SiteVisit>>>)(async () =>
|
||||
{
|
||||
var decodeResult = hashService.DecodeLongIdHash(siteVisitIdHash);
|
||||
|
||||
if (decodeResult.IsFailed)
|
||||
return Result.Fail<SiteVisit>(IdDecodeError.Create()
|
||||
.CausedBy(decodeResult.Errors));
|
||||
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var visit = await context.SiteVisits.AsNoTracking().FirstOrDefaultAsync(v => v.Id == decodeResult.Value, cancellationToken);
|
||||
|
||||
return Result.FailIf(visit is null, NotFoundError.New)
|
||||
.ToResult(visit!.Map());
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,75 @@ using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Projects;
|
||||
|
||||
public sealed record UpdateSiteVisitRequest([Required] long SiteVisitId,
|
||||
[Required][MaxLength(LabelLength)] string InspectorName,
|
||||
[Required][MaxLength(TextLength)] string Findings,
|
||||
[Required] ApprovalStatus Status,
|
||||
[Required] DateTime VisitedAt);
|
||||
|
||||
public sealed record CreateSiteVisitRequest([Required] long ProjectId,
|
||||
[Required][MaxLength(LabelLength)] string InspectorName,
|
||||
[Required][MaxLength(TextLength)] string Findings,
|
||||
[Required] DateTime VisitedAt);
|
||||
|
||||
public sealed record UpdateOutcomeRequest([Required] long OutcomeId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(TextLength)] string Description);
|
||||
|
||||
public sealed record CreateOutcomeRequest([Required] long BeneficiaryId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(TextLength)] string Description);
|
||||
|
||||
public sealed record UpdateIssueRequest([Required] long IssueId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Description,
|
||||
[Required][MaxLength(TextLength)] string Resolution,
|
||||
[Required] DateTime? ResolvedAt,
|
||||
[Required] Priority Priority,
|
||||
[Required] ActivityStatus Status,
|
||||
[Required] Guid AssignedTo);
|
||||
|
||||
public sealed record CreateIssueRequest([Required] long ProjectId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Description,
|
||||
[Required] Priority Priority,
|
||||
[Required] Guid AssignedTo);
|
||||
|
||||
public sealed record UpdateBeneficiaryRequest([Required] long BeneficiaryId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string Category,
|
||||
[Required][MaxLength(LabelLength)] string Location,
|
||||
[Required] int TargetCount,
|
||||
[Required] int ReachedCount);
|
||||
|
||||
public sealed record CreateBeneficiaryRequest([Required] long ProjectId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required][MaxLength(LabelLength)] string Category,
|
||||
[Required][MaxLength(LabelLength)] string Location,
|
||||
[Required] int TargetCount,
|
||||
[Required] int ReachedCount);
|
||||
|
||||
public sealed record UpdateComplianceItemRequest([Required] long ComplianceItemId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Requirements,
|
||||
[Required] ApprovalStatus Status);
|
||||
|
||||
public sealed record CreateComplianceItemRequest([Required] long ProjectId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Requirements);
|
||||
|
||||
public sealed record UpdateChangeRequest([Required] long ChangeRequestId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Justification,
|
||||
[Required] decimal RevisedBudget,
|
||||
[Required] ApprovalStatus Status);
|
||||
|
||||
public sealed record CreateChangeRequest([Required] long ProjectId,
|
||||
[Required][MaxLength(LabelLength)] string Title,
|
||||
[Required][MaxLength(TextLength)] string Justification,
|
||||
[Required] decimal RevisedBudget,
|
||||
[Required] DateTime RevisionDate);
|
||||
|
||||
public sealed record UpdateProgrammeRequest([Required] long ProgrammeId,
|
||||
[Required][MaxLength(LabelLength)] string Name,
|
||||
[Required] Guid OwnerId,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Shared;
|
||||
|
||||
public sealed class AuditService(IDbContextFactory<ApplicationDbContext> contextFactory, ITenantContextService tenantContextService) : IService
|
||||
{
|
||||
public async Task<Result> LogActionAsync(string entityId, string entityName, string action, string[] changes, Guid performedBy, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
context.Add(new Domain.Entities.AuditLog
|
||||
{
|
||||
EntityId = entityId,
|
||||
Action = action,
|
||||
Changes = changes,
|
||||
EntityName = entityName,
|
||||
PerformedBy = performedBy,
|
||||
Timestamp = DateTime.UtcNow,
|
||||
TenantId = tenantContextService.TenantId > 0 ? tenantContextService.TenantId : null,
|
||||
});
|
||||
|
||||
return Result.FailIf(await context.SaveChangesAsync(cancellationToken) <= 0, CreateError.New);
|
||||
}));
|
||||
}
|
||||
@@ -4,32 +4,32 @@ namespace PostFundManagement.Application.Services.Shared;
|
||||
|
||||
public sealed class BrowserLocalStorageService(ProtectedLocalStorage storage)
|
||||
{
|
||||
public async ValueTask<Result> DeleteAsync(string key) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> DeleteAsync(string key) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await storage.DeleteAsync(key);
|
||||
|
||||
return Result.Ok();
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> SaveAsync(string key, string value) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> SaveAsync(string key, string value) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await storage.SetAsync(key, value);
|
||||
|
||||
return Result.Ok();
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> SaveAsync<TValue>(string key, TValue value) where TValue : class =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> SaveAsync<TValue>(string key, TValue value) where TValue : class =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await storage.SetAsync(key, value);
|
||||
|
||||
return Result.Ok();
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<string>> GetAsync(string key) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
public async Task<Result<string>> GetAsync(string key) =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
var retrieval = await storage.GetAsync<string>(key);
|
||||
|
||||
@@ -38,8 +38,8 @@ public sealed class BrowserLocalStorageService(ProtectedLocalStorage storage)
|
||||
.ToResult(retrieval.Value!);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<TValue>> GetAsync<TValue>(string key) where TValue : class =>
|
||||
await Result.Try((Func<ValueTask<Result<TValue>>>)(async () =>
|
||||
public async Task<Result<TValue>> GetAsync<TValue>(string key) where TValue : class =>
|
||||
await Result.Try((Func<Task<Result<TValue>>>)(async () =>
|
||||
{
|
||||
var retrieval = await storage.GetAsync<TValue>(key);
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ public sealed class EmailService(IOptions<SmtpSettings> options) : IDisposable
|
||||
|
||||
public EmailStatuses Status { get; private set; } = EmailStatuses.Disconnected;
|
||||
|
||||
public async ValueTask<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Send");
|
||||
|
||||
@@ -121,7 +121,7 @@ public sealed class EmailService(IOptions<SmtpSettings> options) : IDisposable
|
||||
return Result.Fail<Response>(response);
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default)
|
||||
public async Task<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Connect");
|
||||
activity?.SetTag("email.smtp.connect", settings.Host);
|
||||
@@ -174,7 +174,7 @@ public sealed class EmailService(IOptions<SmtpSettings> options) : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> DisconnectAsync(CancellationToken cancellationToken = default)
|
||||
public async Task<Result> DisconnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Disconnect");
|
||||
activity?.SetTag("email.smtp.disconnect", settings.Host);
|
||||
|
||||
@@ -67,7 +67,7 @@ public sealed partial class HashService(IHashids hasher) : IService
|
||||
}
|
||||
|
||||
public async Task<Result<string>> DecodeHexHash(string hex) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
await Result.Try((Func<Task<Result<string>>>)(async () =>
|
||||
{
|
||||
string decoded = hasher.DecodeHex(hex);
|
||||
|
||||
|
||||
@@ -5,6 +5,6 @@ namespace PostFundManagement.Application.Services.Shared;
|
||||
|
||||
public sealed class IdentityCacheService(IdentityService service) : ServiceCacheBase, IIdentityService
|
||||
{
|
||||
public async ValueTask<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await service.UserIsAuthorisedAsync(userId, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -7,11 +7,12 @@ namespace PostFundManagement.Application.Services.Shared;
|
||||
|
||||
public sealed class IdentityService(IDbContextFactory<ApplicationDbContext> contextFactory) : IIdentityService
|
||||
{
|
||||
public async ValueTask<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
// TODO: Ensure TenantUser status is checked
|
||||
var userExistsAndActive = await context.Users
|
||||
.AnyAsync(u => u.Id == userId && u.Status == ActivityStatus.Active, cancellationToken);
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ public sealed class TokenService(ISecurityConnectApi connectApi, IOptions<Securi
|
||||
{
|
||||
private readonly SecurityClientSettings clientSettings = clientOptions.Value;
|
||||
|
||||
public async ValueTask<Result<Domain.Security.Models.TokenResponse>> GenerateAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<Domain.Security.Models.TokenResponse>>>)(async () =>
|
||||
public async Task<Result<Domain.Security.Models.TokenResponse>> GenerateAsync(CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<Domain.Security.Models.TokenResponse>>>)(async () =>
|
||||
{
|
||||
using var response = await connectApi.GetToken(new Domain.Security.Models.TokenRequest
|
||||
{
|
||||
@@ -34,7 +34,7 @@ public sealed class TokenService(ISecurityConnectApi connectApi, IOptions<Securi
|
||||
.ToResult(tokenResponse!);
|
||||
}
|
||||
|
||||
return await Result.Try((Func<ValueTask<Result<Domain.Security.Models.TokenResponse>>>)(async () =>
|
||||
return await Result.Try((Func<Task<Result<Domain.Security.Models.TokenResponse>>>)(async () =>
|
||||
{
|
||||
var errorResult = JsonSerializer.Deserialize<TokenErrorResponse>(contentRaw);
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
using PostFundManagement.Application.Abstractions;
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Tools;
|
||||
|
||||
public sealed class ToolCacheService(ToolService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IToolService
|
||||
{
|
||||
public async ValueTask<Result<string>> EncodeLong(long id, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<string>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.EncodeLong(id, cancellationToken);
|
||||
|
||||
var cacheKey = HashService.ToMd5Hash($"encodelonghash-{id}").Value;
|
||||
|
||||
var cached = await cache.GetStringAsync(cacheKey, cancellationToken);
|
||||
|
||||
if(string.IsNullOrWhiteSpace(cached))
|
||||
{
|
||||
var result = (await service.EncodeLong(id).ConfigureAwait(false));
|
||||
|
||||
if (result.IsFailed) return result;
|
||||
|
||||
await cache.SetStringAsync(cacheKey, result.Value, cacheOptions, cancellationToken);
|
||||
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
return Result.Ok(cached);
|
||||
}));
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Application.Services.Shared;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Tools;
|
||||
|
||||
public sealed class ToolService(HashService service) : IToolService
|
||||
{
|
||||
public ValueTask<Result<string>> EncodeLong(long id, CancellationToken cancellationToken = default) =>
|
||||
ValueTask.FromResult(service.HashEncodeLongId(id));
|
||||
}
|
||||
@@ -11,8 +11,8 @@ namespace PostFundManagement.Application.Services.Users;
|
||||
public sealed class UserCacheService(UserService service, IDistributedCache cache,
|
||||
IFeatureManager featureManager) : ServiceCacheBase, IUserService
|
||||
{
|
||||
public async ValueTask<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<User>>>)(async () =>
|
||||
public async Task<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<User>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetUserAsync(userId, cancellationToken);
|
||||
@@ -35,8 +35,8 @@ public sealed class UserCacheService(UserService service, IDistributedCache cach
|
||||
return Result.Ok(cached.FromJson<User>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<User[]>>>)(async () =>
|
||||
public async Task<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<User[]>>>)(async () =>
|
||||
{
|
||||
if (!await featureManager.IsEnabledAsync(ServiceCachingFeature))
|
||||
return await service.GetUsersAsync(pagination, request, cancellationToken);
|
||||
@@ -61,9 +61,9 @@ public sealed class UserCacheService(UserService service, IDistributedCache cach
|
||||
return Result.Ok(cached.FromJson<User[]>());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default) =>
|
||||
await service.SyncUserAsync(userId, email, cancellationToken);
|
||||
|
||||
public async ValueTask<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default) =>
|
||||
public async Task<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default) =>
|
||||
await service.UpdateUserStatusAsync(userId, status, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using PostFundManagement.Application.Abstractions.Services;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Errors;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
@@ -7,16 +8,19 @@ using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Services.Users;
|
||||
|
||||
public sealed class UserService(IDbContextFactory<ApplicationDbContext> contextFactory) : IUserService
|
||||
public sealed class UserService(IDbContextFactory<ApplicationDbContext> contextFactory, ITenantContextService tenantContext) : IUserService
|
||||
{
|
||||
public async ValueTask<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> SyncUserAsync(Guid userId, string email, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var user = await context.Users.FirstOrDefaultAsync(u => u.Id == userId, cancellationToken);
|
||||
var tenantUser = await context.TenantUsers
|
||||
.Include(i => i.User)
|
||||
.FirstOrDefaultAsync(u => u.UserId == userId, cancellationToken);
|
||||
|
||||
if (user is null)
|
||||
if (tenantUser is null)
|
||||
{
|
||||
context.Users.Add(new Domain.Entities.User
|
||||
{
|
||||
Id = userId,
|
||||
@@ -24,35 +28,45 @@ public sealed class UserService(IDbContextFactory<ApplicationDbContext> contextF
|
||||
Status = ActivityStatus.Active,
|
||||
LastLoginAt = DateTime.UtcNow
|
||||
});
|
||||
|
||||
context.TenantUsers.Add(new Domain.Entities.TenantUser
|
||||
{
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedBy = userId,
|
||||
Status = ActivityStatus.Active,
|
||||
TenantId = tenantContext.TenantId,
|
||||
UserId = userId
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
user!.Email = email;
|
||||
user.LastLoginAt = DateTime.UtcNow;
|
||||
tenantUser.User!.Email = email;
|
||||
tenantUser.User.LastLoginAt = DateTime.UtcNow;
|
||||
|
||||
context.Users.Update(user);
|
||||
context.Users.Update(tenantUser.User);
|
||||
}
|
||||
|
||||
return Result.OkIf(await context.SaveChangesAsync(cancellationToken) > 0, CreateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result<User[]>>>)(async () =>
|
||||
public async Task<Result<User[]>> GetUsersAsync(Pagination pagination, UserFilterRequest request, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result<User[]>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var query = context.Users.AsNoTracking();
|
||||
var query = context.TenantUsers.Include(i => i.User).AsNoTracking();
|
||||
|
||||
if (request.Status.HasValue)
|
||||
query = query.Where(u => u.Status == request.Status.Value);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Email))
|
||||
query = query.Where(u => u.Email != null && u.Email.Contains(request.Email));
|
||||
query = query.Where(u => u.User!.Email != null && u.User!.Email.Contains(request.Email));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.SortBy))
|
||||
query = request.SortBy.ToLowerInvariant() switch
|
||||
{
|
||||
"email" => request.SortDescending ? query.OrderByDescending(u => u.Email) : query.OrderBy(u => u.Email),
|
||||
"lastloginat" => request.SortDescending ? query.OrderByDescending(u => u.LastLoginAt) : query.OrderBy(u => u.LastLoginAt),
|
||||
"email" => request.SortDescending ? query.OrderByDescending(u => u.User!.Email) : query.OrderBy(u => u.User!.Email),
|
||||
"lastloginat" => request.SortDescending ? query.OrderByDescending(u => u.User!.LastLoginAt) : query.OrderBy(u => u.User!.LastLoginAt),
|
||||
"status" => request.SortDescending ? query.OrderByDescending(u => u.Status) : query.OrderBy(u => u.Status),
|
||||
_ => request.SortDescending ? query.OrderByDescending(u => u.Id) : query.OrderBy(u => u.Id)
|
||||
};
|
||||
@@ -62,30 +76,36 @@ public sealed class UserService(IDbContextFactory<ApplicationDbContext> contextF
|
||||
var users = await query.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize).ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(users.Select(u => u.Map()).ToArray());
|
||||
return Result.Ok(users.Select(u => u.User!.Map()).ToArray());
|
||||
}));
|
||||
|
||||
public async ValueTask<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<ValueTask<Result>>)(async () =>
|
||||
public async Task<Result> UpdateUserStatusAsync(Guid userId, ActivityStatus status, CancellationToken cancellationToken = default) =>
|
||||
await Result.Try((Func<Task<Result>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var changedTotal = await context.Users
|
||||
.Where(f => f.Id == userId)
|
||||
var changedTotal = await context.TenantUsers
|
||||
.Include(i => i.User)
|
||||
.Where(f => f.UserId == userId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(u => u.Status, status), cancellationToken);
|
||||
|
||||
changedTotal += await context.Users.Where(f => f.Id == userId)
|
||||
.ExecuteUpdateAsync(f => f.SetProperty(u => u.Status, status), cancellationToken);
|
||||
|
||||
return Result.OkIf(changedTotal > 0, UpdateError.New);
|
||||
}));
|
||||
|
||||
public async ValueTask<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<ValueTask<Result<User>>>)(async () =>
|
||||
public async Task<Result<User>> GetUserAsync(Guid userId, CancellationToken cancellationToken) =>
|
||||
await Result.Try((Func<Task<Result<User>>>)(async () =>
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var user = await context.Users.AsNoTracking()
|
||||
.FirstOrDefaultAsync(f => f.Id == userId, cancellationToken);
|
||||
var tenantUser = await context.TenantUsers.AsNoTracking()
|
||||
.Include(i => i.User)
|
||||
.FirstOrDefaultAsync(f => f.UserId == userId, cancellationToken);
|
||||
|
||||
return Result.FailIf(user is null, NotFoundError.New)
|
||||
.ToResult(user!.Map());
|
||||
return Result.FailIf(tenantUser == null, NotFoundError.New)
|
||||
.ToResult(tenantUser!.User?.Map()!);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import { AccountActivationModal } from '../components/auth/AccountActivationModal';
|
||||
import { SessionExpiredModal } from '../components/auth/SessionExpiredModal';
|
||||
import { encodeHashIdSync } from '../services/toolsService';
|
||||
import { verifyTenantLockout } from '../services/tenantLockoutService';
|
||||
import {
|
||||
onSessionExpired,
|
||||
triggerSessionExpired,
|
||||
@@ -120,6 +121,79 @@ export function extractTenantId(claims?: UserClaims | null, token?: string | nul
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractTenantClaimValues(
|
||||
claims?: UserClaims | null,
|
||||
token?: string | null
|
||||
): {
|
||||
tenantId: number | string | null;
|
||||
tenant: string | null;
|
||||
} {
|
||||
let tenantId: number | string | null = null;
|
||||
let tenant: string | null = null;
|
||||
|
||||
if (claims) {
|
||||
const rawId =
|
||||
claims.tenant_id ??
|
||||
(claims as any).tenantId ??
|
||||
claims['tenant_id'] ??
|
||||
claims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenantid'];
|
||||
if (rawId !== undefined && rawId !== null && rawId !== '') {
|
||||
const parsed = Number(rawId);
|
||||
tenantId = !isNaN(parsed) && isFinite(parsed) ? parsed : String(rawId).trim();
|
||||
}
|
||||
|
||||
const rawTenant =
|
||||
claims.tenant ??
|
||||
claims['tenant'] ??
|
||||
claims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenant'] ??
|
||||
claims.tenant_name ??
|
||||
(claims as any).tenantName ??
|
||||
claims.org;
|
||||
if (rawTenant !== undefined && rawTenant !== null && rawTenant !== '') {
|
||||
if (typeof rawTenant === 'string') {
|
||||
tenant = rawTenant.trim();
|
||||
} else if (typeof rawTenant === 'object' && rawTenant.name) {
|
||||
tenant = String(rawTenant.name).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (token && (!tenantId || !tenant)) {
|
||||
try {
|
||||
const tokenClaims = parseJwtClaims(token);
|
||||
if (!tenantId) {
|
||||
const rawId =
|
||||
tokenClaims.tenant_id ??
|
||||
tokenClaims.tenantId ??
|
||||
tokenClaims['tenant_id'] ??
|
||||
tokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenantid'];
|
||||
if (rawId !== undefined && rawId !== null && rawId !== '') {
|
||||
const parsed = Number(rawId);
|
||||
tenantId = !isNaN(parsed) && isFinite(parsed) ? parsed : String(rawId).trim();
|
||||
}
|
||||
}
|
||||
if (!tenant) {
|
||||
const rawTenant =
|
||||
tokenClaims.tenant ??
|
||||
tokenClaims['tenant'] ??
|
||||
tokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/tenant'] ??
|
||||
tokenClaims.tenant_name ??
|
||||
(tokenClaims as any).tenantName ??
|
||||
tokenClaims.org;
|
||||
if (rawTenant !== undefined && rawTenant !== null && rawTenant !== '') {
|
||||
if (typeof rawTenant === 'string') {
|
||||
tenant = rawTenant.trim();
|
||||
} else if (typeof rawTenant === 'object' && rawTenant.name) {
|
||||
tenant = String(rawTenant.name).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return { tenantId, tenant };
|
||||
}
|
||||
|
||||
export function getCurrentUserTenantId(): number | null {
|
||||
return extractTenantId(
|
||||
getCurrentUserClaims(),
|
||||
@@ -283,7 +357,8 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
localStorage.setItem(LOCAL_STORAGE_SUB_KEY, userSub);
|
||||
localStorage.setItem(LOCAL_STORAGE_CLAIMS_KEY, JSON.stringify(mergedClaims));
|
||||
|
||||
const tenantClaim = (mergedClaims.tenant as string) || (oidcUser.profile?.tenant as string) || undefined;
|
||||
const tenantClaimValues = extractTenantClaimValues(mergedClaims, token);
|
||||
const tenantClaim = (mergedClaims.tenant as string) || (oidcUser.profile?.tenant as string) || tenantClaimValues.tenant || undefined;
|
||||
const parsedTenantId = extractTenantId(mergedClaims, token);
|
||||
setTenantId(parsedTenantId);
|
||||
|
||||
@@ -304,6 +379,20 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
// Clean up code and state from URL
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
|
||||
// Verify tenant lockout at the instance tenant and tenant_id claims are retrieved
|
||||
const tenantLockoutResult = await verifyTenantLockout(
|
||||
parsedTenantId ?? tenantClaimValues.tenantId,
|
||||
tenantClaim
|
||||
);
|
||||
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(tenantLockoutResult.errorMessage || 'Tenant is inactive or not found');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Synchronize authenticated user profile with backend directory
|
||||
try {
|
||||
const syncResult = await syncUserAccount(userSub, token, profile, true);
|
||||
@@ -367,6 +456,8 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
|
||||
const storedTenantId = extractTenantId(parsedClaims, storedToken);
|
||||
setTenantId(storedTenantId);
|
||||
const tenantClaimValues = extractTenantClaimValues(parsedClaims, storedToken);
|
||||
const storedTenantClaim = (parsedClaims.tenant as string) || tenantClaimValues.tenant || undefined;
|
||||
|
||||
let resolvedUser: AuthUserProfile | null = null;
|
||||
if (storedUser) {
|
||||
@@ -383,6 +474,20 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Verify tenant lockout at the instance tenant and tenant_id claims are retrieved
|
||||
const tenantLockoutResult = await verifyTenantLockout(
|
||||
storedTenantId ?? tenantClaimValues.tenantId,
|
||||
storedTenantClaim
|
||||
);
|
||||
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(tenantLockoutResult.errorMessage || 'Tenant is inactive or not found');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if session is already marked pending activation or needs sync check
|
||||
const wasPending = isActivationPending();
|
||||
setIsPendingActivation(wasPending);
|
||||
@@ -435,6 +540,25 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
||||
|
||||
const syncUserSession = async (force = true): Promise<UserSyncResult> => {
|
||||
try {
|
||||
// Re-verify tenant status via GetTenant as part of the lockout resolution
|
||||
const tenantClaimValues = extractTenantClaimValues(claims, accessToken);
|
||||
const currentTenantId = tenantId ?? tenantClaimValues.tenantId;
|
||||
const currentTenantClaim = (claims.tenant as string) || user?.tenant || tenantClaimValues.tenant || undefined;
|
||||
|
||||
const tenantLockoutResult = await verifyTenantLockout(currentTenantId, currentTenantClaim);
|
||||
if (!tenantLockoutResult.isActive) {
|
||||
const msg = tenantLockoutResult.errorMessage || 'Tenant is not Active. Lockout active.';
|
||||
setIsPendingActivation(true);
|
||||
setIsSynced(false);
|
||||
setActivationError(msg);
|
||||
return {
|
||||
success: false,
|
||||
isActivationPending: true,
|
||||
errorMessage: msg,
|
||||
};
|
||||
}
|
||||
|
||||
// Tenant is verified Active: proceed with user sync
|
||||
const result = await syncUserAccount(sub, accessToken, user || undefined, force);
|
||||
if (result.isUnauthorized) {
|
||||
await logout();
|
||||
|
||||
@@ -38,6 +38,13 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(initialError || null);
|
||||
const [syncAttemptCount, setSyncAttemptCount] = useState(0);
|
||||
|
||||
// Sync errorMessage when initialError updates
|
||||
useEffect(() => {
|
||||
if (initialError !== undefined) {
|
||||
setErrorMessage(initialError);
|
||||
}
|
||||
}, [initialError]);
|
||||
|
||||
// Clear any existing session prompt and close background dialogs
|
||||
useEffect(() => {
|
||||
cancelSessionExpiration();
|
||||
@@ -134,10 +141,12 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
</div>
|
||||
<div>
|
||||
<span className="inline-flex items-center gap-1.5 text-[11px] font-semibold tracking-wider uppercase text-amber-400 bg-amber-500/10 border border-amber-500/20 px-2 py-0.5 rounded-full mb-1">
|
||||
Access Restricted • Awaiting Enablement
|
||||
Access Restricted • Lockout Active
|
||||
</span>
|
||||
<h2 id="activation-modal-title" className="text-lg sm:text-xl font-bold text-white tracking-tight">
|
||||
Account Pending Administrator Activation
|
||||
{errorMessage?.toLowerCase().includes('tenant')
|
||||
? 'Tenant Lockout • Account Inactive'
|
||||
: 'Account Pending Administrator Activation'}
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
@@ -215,7 +224,11 @@ export const AccountActivationModal: React.FC<AccountActivationModalProps> = ({
|
||||
<div className="rounded-xl border border-rose-500/30 bg-rose-500/10 p-3.5 flex items-start gap-3 animate-in fade-in duration-150">
|
||||
<AlertTriangle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-semibold text-rose-300">Account Not Activated Yet</p>
|
||||
<p className="text-xs font-semibold text-rose-300">
|
||||
{errorMessage?.toLowerCase().includes('tenant')
|
||||
? 'Tenant Lockout In Effect'
|
||||
: 'Account Not Activated Yet'}
|
||||
</p>
|
||||
<p className="text-xs text-rose-200/90 leading-relaxed">{errorMessage}</p>
|
||||
{syncAttemptCount > 0 && (
|
||||
<p className="text-[11px] text-rose-400/80 pt-1">
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
FileText,
|
||||
Plus,
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Edit2,
|
||||
Eye,
|
||||
Layers,
|
||||
Calendar,
|
||||
User as UserIcon,
|
||||
Tag,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
} from 'lucide-react';
|
||||
import { Modal } from '../ui/Modal';
|
||||
import { HelpTooltip } from '../ui/HelpTooltip';
|
||||
import { useToast } from '../ui/Toast';
|
||||
import {
|
||||
Instruction,
|
||||
Programme,
|
||||
ActivityStatus,
|
||||
} from '../../types';
|
||||
import {
|
||||
getAllInstructions,
|
||||
createInstruction,
|
||||
updateInstruction,
|
||||
} from '../../services/api';
|
||||
import {
|
||||
getActivityStatusBadge,
|
||||
formatDate,
|
||||
getUserEmail,
|
||||
ACTIVITY_STATUS_OPTIONS,
|
||||
} from '../../lib/formatters';
|
||||
|
||||
const instructionSchema = z.object({
|
||||
programmeId: z.coerce.number().min(1, 'Please select an associated programme'),
|
||||
name: z.string().min(3, 'Instruction title must be at least 3 characters'),
|
||||
code: z.string().optional(),
|
||||
description: z.string().min(5, 'Description is required (minimum 5 characters)'),
|
||||
status: z.coerce.number().default(ActivityStatus.Active),
|
||||
});
|
||||
|
||||
type InstructionFormValues = z.infer<typeof instructionSchema>;
|
||||
|
||||
interface InstructionsSectionProps {
|
||||
programmes: Programme[];
|
||||
currentUserId: string;
|
||||
preselectedProgrammeId?: string | number | null;
|
||||
onClearPreselectedProgramme?: () => void;
|
||||
isCreateModalOpenExternal?: boolean;
|
||||
onCloseCreateModalExternal?: () => void;
|
||||
}
|
||||
|
||||
export const InstructionsSection: React.FC<InstructionsSectionProps> = ({
|
||||
programmes,
|
||||
currentUserId,
|
||||
preselectedProgrammeId,
|
||||
onClearPreselectedProgramme,
|
||||
isCreateModalOpenExternal,
|
||||
onCloseCreateModalExternal,
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { success, error: toastError } = useToast();
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedProgrammeFilter, setSelectedProgrammeFilter] = useState<string>(
|
||||
preselectedProgrammeId ? String(preselectedProgrammeId) : 'all'
|
||||
);
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
|
||||
// Modals
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingInstruction, setEditingInstruction] = useState<Instruction | null>(null);
|
||||
const [inspectingInstruction, setInspectingInstruction] = useState<Instruction | null>(null);
|
||||
|
||||
// Sync external create modal trigger if provided
|
||||
React.useEffect(() => {
|
||||
if (isCreateModalOpenExternal) {
|
||||
setEditingInstruction(null);
|
||||
instructionForm.reset({
|
||||
programmeId: preselectedProgrammeId ? Number(preselectedProgrammeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
}
|
||||
}, [isCreateModalOpenExternal, preselectedProgrammeId, programmes]);
|
||||
|
||||
// Form setup
|
||||
const instructionForm = useForm<InstructionFormValues>({
|
||||
resolver: zodResolver(instructionSchema),
|
||||
defaultValues: {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
status: ActivityStatus.Active,
|
||||
},
|
||||
});
|
||||
|
||||
// Query: Get all instructions
|
||||
const {
|
||||
data: instructions = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['all-instructions', programmes],
|
||||
queryFn: () => getAllInstructions(programmes),
|
||||
});
|
||||
|
||||
// Programme lookup helper
|
||||
const programmeMap = useMemo(() => {
|
||||
const map = new Map<string, Programme>();
|
||||
programmes.forEach((p) => map.set(String(p.id), p));
|
||||
return map;
|
||||
}, [programmes]);
|
||||
|
||||
// Mutation: Create or Update Instruction
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (data: InstructionFormValues) => {
|
||||
if (editingInstruction) {
|
||||
await updateInstruction({
|
||||
instructionId: editingInstruction.id,
|
||||
programmeId: data.programmeId,
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
|
||||
userId: currentUserId,
|
||||
});
|
||||
} else {
|
||||
await createInstruction({
|
||||
programmeId: data.programmeId,
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
|
||||
userId: currentUserId,
|
||||
});
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['all-instructions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['instruments'] });
|
||||
success(
|
||||
editingInstruction ? 'Instruction Updated' : 'Instruction Created',
|
||||
editingInstruction
|
||||
? 'Funding instruction record updated successfully.'
|
||||
: 'New funding instruction attached to programme successfully.'
|
||||
);
|
||||
setIsModalOpen(false);
|
||||
setEditingInstruction(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
},
|
||||
onError: (err: any) => {
|
||||
toastError('Save Failed', err?.message || 'Failed to save instruction');
|
||||
},
|
||||
});
|
||||
|
||||
// Handlers
|
||||
const openCreateModal = (programmeId?: number | string) => {
|
||||
setEditingInstruction(null);
|
||||
instructionForm.reset({
|
||||
programmeId: programmeId
|
||||
? Number(programmeId)
|
||||
: selectedProgrammeFilter !== 'all'
|
||||
? Number(selectedProgrammeFilter)
|
||||
: programmes[0]?.id
|
||||
? Number(programmes[0].id)
|
||||
: 0,
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const openEditModal = (inst: Instruction) => {
|
||||
setEditingInstruction(inst);
|
||||
instructionForm.reset({
|
||||
programmeId: Number(inst.programmeId),
|
||||
name: inst.name || '',
|
||||
code: inst.code || '',
|
||||
description: inst.description || '',
|
||||
status: Number(inst.status),
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingInstruction(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
};
|
||||
|
||||
// Filter instructions
|
||||
const filteredInstructions = useMemo(() => {
|
||||
return instructions.filter((inst) => {
|
||||
// Programme filter
|
||||
if (selectedProgrammeFilter !== 'all' && String(inst.programmeId) !== String(selectedProgrammeFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Status filter
|
||||
if (statusFilter !== 'all' && String(inst.status) !== String(statusFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Search term
|
||||
if (searchTerm.trim()) {
|
||||
const query = searchTerm.toLowerCase();
|
||||
const pName = programmeMap.get(String(inst.programmeId))?.name?.toLowerCase() || '';
|
||||
const matchTitle = (inst.name || '').toLowerCase().includes(query);
|
||||
const matchCode = (inst.code || '').toLowerCase().includes(query);
|
||||
const matchDesc = (inst.description || '').toLowerCase().includes(query);
|
||||
const matchProg = pName.includes(query);
|
||||
if (!matchTitle && !matchCode && !matchDesc && !matchProg) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [instructions, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Top Filter and Actions Bar */}
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3 bg-[#0d121f]/90 p-4 rounded-2xl border border-slate-800/80 backdrop-blur-sm">
|
||||
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1">
|
||||
{/* Search Input */}
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search instructions by title, code, description, or programme..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pl-9 pr-4 py-2.5 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-slate-200 placeholder:text-slate-500 transition shadow-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Programme Filter Dropdown */}
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
|
||||
<Layers className="w-3.5 h-3.5 text-slate-400" />
|
||||
Programme:
|
||||
</label>
|
||||
<select
|
||||
value={selectedProgrammeFilter}
|
||||
onChange={(e) => {
|
||||
setSelectedProgrammeFilter(e.target.value);
|
||||
if (onClearPreselectedProgramme && e.target.value === 'all') {
|
||||
onClearPreselectedProgramme();
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 max-w-[200px]"
|
||||
>
|
||||
<option value="all">All Programmes ({programmes.length})</option>
|
||||
{programmes.map((p) => (
|
||||
<option key={p.id} value={String(p.id)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Status Filter Dropdown */}
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
|
||||
<Filter className="w-3.5 h-3.5 text-slate-400" />
|
||||
Status:
|
||||
</label>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">All Statuses</option>
|
||||
<option value={String(ActivityStatus.Active)}>Active</option>
|
||||
<option value={String(ActivityStatus.Inactive)}>Inactive</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center gap-2 self-end lg:self-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => refetch()}
|
||||
disabled={isFetching}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold text-slate-300 bg-slate-800/80 hover:bg-slate-700 rounded-xl border border-slate-700 transition cursor-pointer"
|
||||
title="Refresh Instructions"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCreateModal()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Instruction
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Instructions Table & Cards */}
|
||||
<div className="rounded-2xl border border-slate-800/80 bg-[#0d121f]/90 overflow-hidden shadow-xl">
|
||||
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-4 h-4 text-blue-400" />
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider">
|
||||
Funding Instructions & Instrument Guidelines ({filteredInstructions.length})
|
||||
</h3>
|
||||
<HelpTooltip
|
||||
title="Funding Instructions"
|
||||
content="Binding operational instructions and instrument guidelines tied to strategic funding programmes. Defines implementation directives and compliance standards."
|
||||
placement="right"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-400 font-mono">
|
||||
{filteredInstructions.length} of {instructions.length} recorded
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="p-12 text-center text-xs text-slate-400 flex flex-col items-center justify-center gap-2">
|
||||
<RefreshCw className="w-5 h-5 animate-spin text-blue-400" />
|
||||
<span>Loading instructions directory...</span>
|
||||
</div>
|
||||
) : filteredInstructions.length === 0 ? (
|
||||
<div className="p-12 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
{searchTerm || selectedProgrammeFilter !== 'all' || statusFilter !== 'all'
|
||||
? 'No funding instructions match the active filters.'
|
||||
: 'No funding instructions registered yet. Link instructions to programmes using the button below.'}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCreateModal()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add First Instruction
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-800/80 bg-slate-900/50 text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
|
||||
<th className="py-3 px-4">Code / Ref</th>
|
||||
<th className="py-3 px-4">Instruction Title</th>
|
||||
<th className="py-3 px-4">Associated Programme</th>
|
||||
<th className="py-3 px-4">Status</th>
|
||||
<th className="py-3 px-4">Created Info</th>
|
||||
<th className="py-3 px-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800/60 text-xs text-slate-300">
|
||||
{filteredInstructions.map((inst) => {
|
||||
const statusBadge = getActivityStatusBadge(inst.status);
|
||||
const parentProg = programmeMap.get(String(inst.programmeId));
|
||||
|
||||
return (
|
||||
<tr key={inst.id} className="hover:bg-slate-800/30 transition-colors">
|
||||
<td className="py-3.5 px-4 font-mono font-bold text-blue-400">
|
||||
<span className="bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20 text-[11px]">
|
||||
{inst.code || `INST-${inst.id}`}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-semibold text-white max-w-sm">{inst.name}</div>
|
||||
{inst.description && (
|
||||
<div className="text-[11px] text-slate-400 line-clamp-1 mt-0.5 max-w-md">
|
||||
{inst.description}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
{parentProg ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs bg-slate-800/80 text-slate-200 border border-slate-700 font-medium">
|
||||
<Layers className="w-3 h-3 text-blue-400" />
|
||||
{parentProg.name}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-500 font-mono text-xs">
|
||||
Programme #{inst.programmeId}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<span
|
||||
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}
|
||||
>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-[11px] text-slate-400 font-mono">
|
||||
<div>{formatDate(inst.createdAt)}</div>
|
||||
{inst.createdBy && (
|
||||
<div className="text-[10px] text-slate-500">{getUserEmail(inst.createdBy)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInspectingInstruction(inst)}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-cyan-400 hover:text-white bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="Inspect Instruction"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
Inspect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openEditModal(inst)}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-slate-200 hover:text-white bg-slate-900/80 hover:bg-slate-800 border border-slate-700/80 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="Edit / Mutate Instruction"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal: Create / Edit Instruction */}
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={handleCloseModal}
|
||||
title={editingInstruction ? 'Edit Funding Instruction' : 'Add New Funding Instruction'}
|
||||
subtitle={
|
||||
editingInstruction
|
||||
? `Mutating Instruction ${editingInstruction.code || `#${editingInstruction.id}`}`
|
||||
: 'Authoritative operational instruction attached to a strategic programme'
|
||||
}
|
||||
helpText="Instructions operationalize funding programmes into concrete binding directives. Choose an existing programme from the dropdown to link data."
|
||||
>
|
||||
<form
|
||||
onSubmit={instructionForm.handleSubmit((data) => mutation.mutate(data))}
|
||||
className="space-y-4"
|
||||
>
|
||||
{/* Associated Programme Dropdown */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Associated Programme *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Associated Programme"
|
||||
content="Select the strategic funding programme under which this operational instruction is established."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...instructionForm.register('programmeId')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">Select an associated programme...</option>
|
||||
{programmes.map((p) => (
|
||||
<option key={p.id} value={Number(p.id)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{instructionForm.formState.errors.programmeId && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{instructionForm.formState.errors.programmeId.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Instruction Title *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Instruction Title"
|
||||
content="Formal title of the funding instruction or instrument (e.g., SME Technology Transfer Subsidy Guideline)."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. Clean Energy Grant Directive 2026"
|
||||
{...instructionForm.register('name')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
{instructionForm.formState.errors.name && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{instructionForm.formState.errors.name.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Code */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Instruction Code (Optional)
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Instruction Code"
|
||||
content="Unique operational reference code (e.g., INST-CE-001). If left blank, one is generated automatically."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. INST-CE-001"
|
||||
{...instructionForm.register('code')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Description & Implementation Directives *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Instruction Description"
|
||||
content="Comprehensive directives, statutory mandate, eligibility scope, and operational guidelines."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
rows={4}
|
||||
placeholder="Detail the operational mandate, eligibility scope, disbursement triggers, and statutory compliance requirements..."
|
||||
{...instructionForm.register('description')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
{instructionForm.formState.errors.description && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{instructionForm.formState.errors.description.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Status</label>
|
||||
<HelpTooltip
|
||||
title="Instruction Lifecycle Status"
|
||||
content="Indicates whether this instruction is actively enforceable or archived/inactive."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...instructionForm.register('status')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
{ACTIVITY_STATUS_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Footer Actions */}
|
||||
<div className="pt-3 border-t border-slate-800 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCloseModal}
|
||||
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={mutation.isPending}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl shadow-md transition disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
{mutation.isPending && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
|
||||
{editingInstruction ? 'Save Instruction Changes' : 'Create Instruction'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: Inspect Instruction Detail */}
|
||||
{inspectingInstruction && (
|
||||
<Modal
|
||||
isOpen={!!inspectingInstruction}
|
||||
onClose={() => setInspectingInstruction(null)}
|
||||
title={`Instruction: ${inspectingInstruction.name || ''}`}
|
||||
subtitle={`Reference: ${inspectingInstruction.code || `INST-${inspectingInstruction.id}`}`}
|
||||
maxWidth="lg"
|
||||
>
|
||||
<div className="space-y-4 text-xs">
|
||||
<div className="p-4 rounded-xl border border-slate-800 bg-[#0d121f] space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-mono text-xs font-bold text-blue-400 bg-blue-500/10 px-2.5 py-1 rounded border border-blue-500/20">
|
||||
{inspectingInstruction.code || `INST-${inspectingInstruction.id}`}
|
||||
</span>
|
||||
{(() => {
|
||||
const badge = getActivityStatusBadge(inspectingInstruction.status);
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${badge.className}`}
|
||||
>
|
||||
{badge.label}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-white mb-1">{inspectingInstruction.name}</h4>
|
||||
<p className="text-slate-300 whitespace-pre-wrap leading-relaxed">
|
||||
{inspectingInstruction.description || 'No detailed description provided.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-slate-800/80 grid grid-cols-2 gap-3 text-[11px]">
|
||||
<div>
|
||||
<span className="text-slate-500 block">Associated Programme</span>
|
||||
<span className="text-slate-200 font-semibold">
|
||||
{programmeMap.get(String(inspectingInstruction.programmeId))?.name ||
|
||||
`Programme #${inspectingInstruction.programmeId}`}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created On</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingInstruction.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created By</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{inspectingInstruction.createdBy ? getUserEmail(inspectingInstruction.createdBy) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
{inspectingInstruction.updatedAt && (
|
||||
<div>
|
||||
<span className="text-slate-500 block">Last Mutated</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingInstruction.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const inst = inspectingInstruction;
|
||||
setInspectingInstruction(null);
|
||||
openEditModal(inst);
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-200 bg-slate-800 hover:bg-slate-700 rounded-xl border border-slate-700 cursor-pointer"
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5" />
|
||||
Edit Instruction
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInspectingInstruction(null)}
|
||||
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl cursor-pointer"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,700 @@
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
Scale,
|
||||
Plus,
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Edit2,
|
||||
Eye,
|
||||
Layers,
|
||||
Calendar,
|
||||
User as UserIcon,
|
||||
Tag,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
GitBranch,
|
||||
} from 'lucide-react';
|
||||
import { Modal } from '../ui/Modal';
|
||||
import { HelpTooltip } from '../ui/HelpTooltip';
|
||||
import { useToast } from '../ui/Toast';
|
||||
import {
|
||||
Rule,
|
||||
Programme,
|
||||
ActivityStatus,
|
||||
} from '../../types';
|
||||
import {
|
||||
getRules,
|
||||
createRule,
|
||||
updateRule,
|
||||
} from '../../services/api';
|
||||
import {
|
||||
getActivityStatusBadge,
|
||||
formatDate,
|
||||
getUserEmail,
|
||||
ACTIVITY_STATUS_OPTIONS,
|
||||
} from '../../lib/formatters';
|
||||
|
||||
const ruleSchema = z.object({
|
||||
programmeId: z.coerce.number().min(1, 'Please select an associated programme from the dropdown'),
|
||||
name: z.string().min(3, 'Rule name must be at least 3 characters'),
|
||||
description: z.string().min(5, 'Description is required (minimum 5 characters)'),
|
||||
version: z.coerce.number().min(1, 'Version must be at least 1').default(1),
|
||||
status: z.coerce.number().default(ActivityStatus.Active),
|
||||
});
|
||||
|
||||
type RuleFormValues = z.infer<typeof ruleSchema>;
|
||||
|
||||
interface RulesSectionProps {
|
||||
programmes: Programme[];
|
||||
currentUserId: string;
|
||||
preselectedProgrammeId?: string | number | null;
|
||||
onClearPreselectedProgramme?: () => void;
|
||||
isCreateModalOpenExternal?: boolean;
|
||||
onCloseCreateModalExternal?: () => void;
|
||||
}
|
||||
|
||||
export const RulesSection: React.FC<RulesSectionProps> = ({
|
||||
programmes,
|
||||
currentUserId,
|
||||
preselectedProgrammeId,
|
||||
onClearPreselectedProgramme,
|
||||
isCreateModalOpenExternal,
|
||||
onCloseCreateModalExternal,
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { success, error: toastError } = useToast();
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedProgrammeFilter, setSelectedProgrammeFilter] = useState<string>(
|
||||
preselectedProgrammeId ? String(preselectedProgrammeId) : 'all'
|
||||
);
|
||||
const [statusFilter, setStatusFilter] = useState<string>('all');
|
||||
|
||||
// Modals
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingRule, setEditingRule] = useState<Rule | null>(null);
|
||||
const [inspectingRule, setInspectingRule] = useState<Rule | null>(null);
|
||||
|
||||
// Sync external create trigger
|
||||
React.useEffect(() => {
|
||||
if (isCreateModalOpenExternal) {
|
||||
setEditingRule(null);
|
||||
ruleForm.reset({
|
||||
programmeId: preselectedProgrammeId ? Number(preselectedProgrammeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
}
|
||||
}, [isCreateModalOpenExternal, preselectedProgrammeId, programmes]);
|
||||
|
||||
// Form setup
|
||||
const ruleForm = useForm<RuleFormValues>({
|
||||
resolver: zodResolver(ruleSchema),
|
||||
defaultValues: {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
},
|
||||
});
|
||||
|
||||
// Query: Get all rules (with programme filter)
|
||||
const {
|
||||
data: rules = [],
|
||||
isLoading,
|
||||
isFetching,
|
||||
refetch,
|
||||
} = useQuery({
|
||||
queryKey: ['rules', selectedProgrammeFilter],
|
||||
queryFn: () =>
|
||||
getRules(
|
||||
{ page: 1, pageSize: 200 },
|
||||
selectedProgrammeFilter !== 'all' ? selectedProgrammeFilter : undefined
|
||||
),
|
||||
});
|
||||
|
||||
// Programme lookup helper
|
||||
const programmeMap = useMemo(() => {
|
||||
const map = new Map<string, Programme>();
|
||||
programmes.forEach((p) => map.set(String(p.id), p));
|
||||
return map;
|
||||
}, [programmes]);
|
||||
|
||||
// Mutation: Create or Update Rule
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (data: RuleFormValues) => {
|
||||
if (editingRule) {
|
||||
await updateRule({
|
||||
ruleId: editingRule.id,
|
||||
programmeId: data.programmeId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
status: data.status !== undefined ? Number(data.status) : ActivityStatus.Active,
|
||||
version: Number(data.version) || 1,
|
||||
userId: currentUserId,
|
||||
});
|
||||
} else {
|
||||
await createRule({
|
||||
programmeId: data.programmeId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
userId: currentUserId,
|
||||
});
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['rules'] });
|
||||
success(
|
||||
editingRule ? 'Rule Mutated' : 'Rule Created',
|
||||
editingRule
|
||||
? 'Programme rule record mutated successfully.'
|
||||
: 'New programme rule registered and linked to programme.'
|
||||
);
|
||||
setIsModalOpen(false);
|
||||
setEditingRule(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
},
|
||||
onError: (err: any) => {
|
||||
toastError('Save Failed', err?.message || 'Failed to save programme rule');
|
||||
},
|
||||
});
|
||||
|
||||
// Handlers
|
||||
const openCreateModal = (programmeId?: number | string) => {
|
||||
setEditingRule(null);
|
||||
ruleForm.reset({
|
||||
programmeId: programmeId
|
||||
? Number(programmeId)
|
||||
: selectedProgrammeFilter !== 'all'
|
||||
? Number(selectedProgrammeFilter)
|
||||
: programmes[0]?.id
|
||||
? Number(programmes[0].id)
|
||||
: 0,
|
||||
name: '',
|
||||
description: '',
|
||||
version: 1,
|
||||
status: ActivityStatus.Active,
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const openEditModal = (rule: Rule) => {
|
||||
setEditingRule(rule);
|
||||
ruleForm.reset({
|
||||
programmeId: Number(rule.programmeId),
|
||||
name: rule.name || '',
|
||||
description: rule.description || '',
|
||||
version: Number(rule.version) || 1,
|
||||
status: Number(rule.status),
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseModal = () => {
|
||||
setIsModalOpen(false);
|
||||
setEditingRule(null);
|
||||
if (onCloseCreateModalExternal) onCloseCreateModalExternal();
|
||||
};
|
||||
|
||||
// Filter rules
|
||||
const filteredRules = useMemo(() => {
|
||||
return rules.filter((r) => {
|
||||
// Programme filter
|
||||
if (selectedProgrammeFilter !== 'all' && String(r.programmeId) !== String(selectedProgrammeFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Status filter
|
||||
if (statusFilter !== 'all' && String(r.status) !== String(statusFilter)) {
|
||||
return false;
|
||||
}
|
||||
// Search term
|
||||
if (searchTerm.trim()) {
|
||||
const query = searchTerm.toLowerCase();
|
||||
const pName = programmeMap.get(String(r.programmeId))?.name?.toLowerCase() || '';
|
||||
const matchName = (r.name || '').toLowerCase().includes(query);
|
||||
const matchDesc = (r.description || '').toLowerCase().includes(query);
|
||||
const matchProg = pName.includes(query);
|
||||
if (!matchName && !matchDesc && !matchProg) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [rules, selectedProgrammeFilter, statusFilter, searchTerm, programmeMap]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Top Filter and Actions Bar */}
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3 bg-[#0d121f]/90 p-4 rounded-2xl border border-slate-800/80 backdrop-blur-sm">
|
||||
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 flex-1">
|
||||
{/* Search Input */}
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search rules by title, description, or programme..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pl-9 pr-4 py-2.5 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-slate-200 placeholder:text-slate-500 transition shadow-xs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Programme Filter Dropdown */}
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
|
||||
<Layers className="w-3.5 h-3.5 text-slate-400" />
|
||||
Programme:
|
||||
</label>
|
||||
<select
|
||||
value={selectedProgrammeFilter}
|
||||
onChange={(e) => {
|
||||
setSelectedProgrammeFilter(e.target.value);
|
||||
if (onClearPreselectedProgramme && e.target.value === 'all') {
|
||||
onClearPreselectedProgramme();
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 max-w-[200px]"
|
||||
>
|
||||
<option value="all">All Programmes ({programmes.length})</option>
|
||||
{programmes.map((p) => (
|
||||
<option key={p.id} value={String(p.id)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Status Filter Dropdown */}
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-400 whitespace-nowrap flex items-center gap-1 font-medium">
|
||||
<Filter className="w-3.5 h-3.5 text-slate-400" />
|
||||
Status:
|
||||
</label>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="px-3 py-2 text-xs bg-[#090d16] border border-slate-700/80 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="all">All Statuses</option>
|
||||
<option value={String(ActivityStatus.Active)}>Active</option>
|
||||
<option value={String(ActivityStatus.Inactive)}>Inactive</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center gap-2 self-end lg:self-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => refetch()}
|
||||
disabled={isFetching}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-semibold text-slate-300 bg-slate-800/80 hover:bg-slate-700 rounded-xl border border-slate-700 transition cursor-pointer"
|
||||
title="Refresh Rules"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCreateModal()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Rule
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rules Table & Cards */}
|
||||
<div className="rounded-2xl border border-slate-800/80 bg-[#0d121f]/90 overflow-hidden shadow-xl">
|
||||
<div className="p-4 border-b border-slate-800/80 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Scale className="w-4 h-4 text-amber-400" />
|
||||
<h3 className="text-xs font-bold text-slate-200 uppercase tracking-wider">
|
||||
Programme Rules & Governance Directives ({filteredRules.length})
|
||||
</h3>
|
||||
<HelpTooltip
|
||||
title="Programme Rules"
|
||||
content="Binding regulatory, operational, and eligibility rules associated with specific funding programmes. Enforces statutory constraints on grant allocation."
|
||||
placement="right"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-slate-400 font-mono">
|
||||
{filteredRules.length} of {rules.length} recorded
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="p-12 text-center text-xs text-slate-400 flex flex-col items-center justify-center gap-2">
|
||||
<RefreshCw className="w-5 h-5 animate-spin text-amber-400" />
|
||||
<span>Loading programme rules directory...</span>
|
||||
</div>
|
||||
) : filteredRules.length === 0 ? (
|
||||
<div className="p-12 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
{searchTerm || selectedProgrammeFilter !== 'all' || statusFilter !== 'all'
|
||||
? 'No programme rules match the active filters.'
|
||||
: 'No programme rules registered yet. Link rules to programmes using the button below.'}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openCreateModal()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add First Rule
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-800/80 bg-slate-900/50 text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
|
||||
<th className="py-3 px-4">Rule Title & Directives</th>
|
||||
<th className="py-3 px-4">Associated Programme</th>
|
||||
<th className="py-3 px-4">Version</th>
|
||||
<th className="py-3 px-4">Status</th>
|
||||
<th className="py-3 px-4">Audit Info</th>
|
||||
<th className="py-3 px-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800/60 text-xs text-slate-300">
|
||||
{filteredRules.map((r) => {
|
||||
const statusBadge = getActivityStatusBadge(r.status);
|
||||
const parentProg = programmeMap.get(String(r.programmeId));
|
||||
|
||||
return (
|
||||
<tr key={r.id} className="hover:bg-slate-800/30 transition-colors">
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-semibold text-white max-w-sm">{r.name}</div>
|
||||
{r.description && (
|
||||
<div className="text-[11px] text-slate-400 line-clamp-1 mt-0.5 max-w-md">
|
||||
{r.description}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
{parentProg ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs bg-slate-800/80 text-slate-200 border border-slate-700 font-medium">
|
||||
<Layers className="w-3 h-3 text-amber-400" />
|
||||
{parentProg.name}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-500 font-mono text-xs">
|
||||
Programme #{r.programmeId}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 font-mono">
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20">
|
||||
<GitBranch className="w-3 h-3" />v{r.version || 1}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<span
|
||||
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}
|
||||
>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-[11px] text-slate-400 font-mono">
|
||||
<div>{formatDate(r.createdAt)}</div>
|
||||
{r.createdBy && (
|
||||
<div className="text-[10px] text-slate-500">{getUserEmail(r.createdBy)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-3.5 px-4 text-right">
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInspectingRule(r)}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-cyan-400 hover:text-white bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="Inspect Rule"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
Inspect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openEditModal(r)}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-slate-200 hover:text-white bg-slate-900/80 hover:bg-slate-800 border border-slate-700/80 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="Edit / Mutate Rule"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Modal: Create / Edit Rule */}
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={handleCloseModal}
|
||||
title={editingRule ? 'Edit Programme Rule' : 'Register New Programme Rule'}
|
||||
subtitle={
|
||||
editingRule
|
||||
? `Mutating Rule: ${editingRule.name || `#${editingRule.id}`}`
|
||||
: 'Authoritative compliance rule associated with an existing funding programme'
|
||||
}
|
||||
helpText="Each rule must be associated with an existing programme chosen from the dropdown below. Rules define statutory constraints and mandatory eligibility."
|
||||
>
|
||||
<form
|
||||
onSubmit={ruleForm.handleSubmit((data) => mutation.mutate(data))}
|
||||
className="space-y-4"
|
||||
>
|
||||
{/* Associated Programme Dropdown (User must choose from dropdown!) */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Associated Programme *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Associated Programme Selection"
|
||||
content="Choose the existing funding programme to which this rule will apply. Each rule is strictly associated with a programme."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...ruleForm.register('programmeId')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">Select an associated programme from dropdown...</option>
|
||||
{programmes.map((p) => (
|
||||
<option key={p.id} value={Number(p.id)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{ruleForm.formState.errors.programmeId && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.programmeId.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rule Name */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Rule Name *</label>
|
||||
<HelpTooltip
|
||||
title="Rule Name"
|
||||
content="Title or clause name of the programme rule (e.g., Mandatory BEE Level 2 Threshold)."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. Environmental Impact Assessment Mandatory Clearance"
|
||||
{...ruleForm.register('name')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
{ruleForm.formState.errors.name && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.name.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">
|
||||
Rule Directives & Description *
|
||||
</label>
|
||||
<HelpTooltip
|
||||
title="Rule Directives"
|
||||
content="Full text and verification criteria of the rule enforced across all projects in the programme."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
rows={4}
|
||||
placeholder="Specify the exact statutory rule, criteria, threshold, verification mechanism, and non-compliance penalty..."
|
||||
{...ruleForm.register('description')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
/>
|
||||
{ruleForm.formState.errors.description && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.description.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Version & Status */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Rule Version</label>
|
||||
<HelpTooltip
|
||||
title="Rule Version"
|
||||
content="Integer version tracking revisions of this statutory rule."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
{...ruleForm.register('version')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500 font-mono"
|
||||
/>
|
||||
{ruleForm.formState.errors.version && (
|
||||
<p className="text-red-400 text-[11px] mt-1">
|
||||
{ruleForm.formState.errors.version.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Status</label>
|
||||
<HelpTooltip
|
||||
title="Rule Enforcement Status"
|
||||
content="Active rules are actively evaluated in grant awards and milestones."
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
{...ruleForm.register('status')}
|
||||
className="w-full px-3 py-2 text-xs bg-[#090d16] border border-slate-700 rounded-xl text-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
|
||||
>
|
||||
{ACTIVITY_STATUS_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer Actions */}
|
||||
<div className="pt-3 border-t border-slate-800 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCloseModal}
|
||||
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={mutation.isPending}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl shadow-md transition disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
{mutation.isPending && <RefreshCw className="w-3.5 h-3.5 animate-spin" />}
|
||||
{editingRule ? 'Save Rule Changes' : 'Register Programme Rule'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: Inspect Rule Detail */}
|
||||
{inspectingRule && (
|
||||
<Modal
|
||||
isOpen={!!inspectingRule}
|
||||
onClose={() => setInspectingRule(null)}
|
||||
title={`Programme Rule: ${inspectingRule.name || ''}`}
|
||||
subtitle={`Version ${inspectingRule.version || 1} • Rule #${inspectingRule.id}`}
|
||||
maxWidth="lg"
|
||||
>
|
||||
<div className="space-y-4 text-xs">
|
||||
<div className="p-4 rounded-xl border border-slate-800 bg-[#0d121f] space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-mono text-xs font-bold text-amber-400 bg-amber-500/10 px-2.5 py-1 rounded border border-amber-500/20 flex items-center gap-1">
|
||||
<GitBranch className="w-3.5 h-3.5" />
|
||||
Version {inspectingRule.version || 1}
|
||||
</span>
|
||||
{(() => {
|
||||
const badge = getActivityStatusBadge(inspectingRule.status);
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold border ${badge.className}`}
|
||||
>
|
||||
{badge.label}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-white mb-1">{inspectingRule.name}</h4>
|
||||
<p className="text-slate-300 whitespace-pre-wrap leading-relaxed">
|
||||
{inspectingRule.description || 'No detailed description provided.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-slate-800/80 grid grid-cols-2 gap-3 text-[11px]">
|
||||
<div>
|
||||
<span className="text-slate-500 block">Associated Programme</span>
|
||||
<span className="text-slate-200 font-semibold">
|
||||
{programmeMap.get(String(inspectingRule.programmeId))?.name ||
|
||||
`Programme #${inspectingRule.programmeId}`}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created On</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingRule.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-slate-500 block">Created By</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{inspectingRule.createdBy ? getUserEmail(inspectingRule.createdBy) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
{inspectingRule.updatedAt && (
|
||||
<div>
|
||||
<span className="text-slate-500 block">Last Mutated</span>
|
||||
<span className="text-slate-200 font-mono">
|
||||
{formatDate(inspectingRule.updatedAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const r = inspectingRule;
|
||||
setInspectingRule(null);
|
||||
openEditModal(r);
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-200 bg-slate-800 hover:bg-slate-700 rounded-xl border border-slate-700 cursor-pointer"
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5" />
|
||||
Edit Rule
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setInspectingRule(null)}
|
||||
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl cursor-pointer"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
getAllEvidence,
|
||||
getProjectEvidence,
|
||||
getEvidenceSecureLink,
|
||||
updateEvidence,
|
||||
uploadEvidenceFile,
|
||||
@@ -82,8 +83,11 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
const queryClient = useQueryClient();
|
||||
const { success, error: toastError } = useToast();
|
||||
|
||||
// Filter States
|
||||
// Filter States: default to initialProjectId if given, otherwise when projects load default to first project
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string | number | 'all'>(initialProjectId);
|
||||
const [userHasSelectedProject, setUserHasSelectedProject] = useState(
|
||||
initialProjectId !== undefined && initialProjectId !== null && initialProjectId !== 'all'
|
||||
);
|
||||
const [selectedMilestoneId, setSelectedMilestoneId] = useState<string | number | 'all'>(initialMilestoneId);
|
||||
const [selectedActivityId, setSelectedActivityId] = useState<string | number | 'all'>(initialActivityId);
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | 'all'>(initialUserId);
|
||||
@@ -116,6 +120,21 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
queryFn: () => getUsers(1, 100).catch(() => []),
|
||||
});
|
||||
|
||||
// Keep selectedProjectId in sync when initialProjectId prop changes
|
||||
React.useEffect(() => {
|
||||
if (initialProjectId && initialProjectId !== 'all') {
|
||||
setSelectedProjectId(initialProjectId);
|
||||
setUserHasSelectedProject(true);
|
||||
}
|
||||
}, [initialProjectId]);
|
||||
|
||||
// Load evidence by default for the first project in the list
|
||||
React.useEffect(() => {
|
||||
if (!userHasSelectedProject && projects.length > 0 && selectedProjectId === 'all') {
|
||||
setSelectedProjectId(projects[0].id);
|
||||
}
|
||||
}, [projects, userHasSelectedProject, selectedProjectId]);
|
||||
|
||||
// Query activities based on selected project or fetch all across available projects
|
||||
const { data: activities = [] } = useQuery<Activity[]>({
|
||||
queryKey: ['activities-review-queue', selectedProjectId],
|
||||
@@ -134,104 +153,20 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
enabled: projects.length > 0,
|
||||
});
|
||||
|
||||
// Query evidence: if a project is selected (e.g. the first project by default), fetch via /v1/api/evidence/{projectId}
|
||||
const { data: rawEvidenceList = [], isLoading: loadingEvidence } = useQuery<Evidence[]>({
|
||||
queryKey: ['evidence'],
|
||||
queryFn: () => getAllEvidence().catch(() => []),
|
||||
queryKey: ['evidence', selectedProjectId],
|
||||
queryFn: async () => {
|
||||
if (selectedProjectId && selectedProjectId !== 'all') {
|
||||
return getProjectEvidence(selectedProjectId).catch(() => []);
|
||||
}
|
||||
return getAllEvidence().catch(() => []);
|
||||
},
|
||||
enabled: projects.length > 0 || selectedProjectId !== 'all',
|
||||
});
|
||||
|
||||
// Baseline demonstration records to guarantee full functionality when backend vault is initially empty
|
||||
const defaultEvidenceItems: Evidence[] = useMemo(() => {
|
||||
const p1 = projects[0]?.id || 401;
|
||||
const p2 = projects[1]?.id || projects[0]?.id || 402;
|
||||
const m1 = milestones[0]?.id || 801;
|
||||
const m2 = milestones[1]?.id || milestones[0]?.id || 802;
|
||||
const a1 = activities[0]?.id || 101;
|
||||
const a2 = activities[1]?.id || activities[0]?.id || 102;
|
||||
const u1 = users[0]?.id || 'usr_awardee_01';
|
||||
const u2 = users[1]?.id || users[0]?.id || 'usr_awardee_02';
|
||||
const u3 = users[2]?.id || 'usr_awardee_03';
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'ev-101',
|
||||
projectId: p1,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 1,
|
||||
type: EvidenceType.CompletionCertificate,
|
||||
fileName: 'Civil_Works_Milestone_Completion_Certificate_Signed.pdf',
|
||||
fileSize: '4.8 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u1,
|
||||
createdAt: '2026-09-18T14:32:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/milestones/801/completion_cert.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-102',
|
||||
projectId: p1,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 2,
|
||||
type: EvidenceType.GeotaggedPhoto,
|
||||
fileName: 'Geotagged_Substation_Installation_Survey.pdf',
|
||||
fileSize: '16.2 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u1,
|
||||
createdAt: '2026-09-17T11:15:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/activities/101/geotagged_photos.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-103',
|
||||
projectId: p2,
|
||||
milestoneId: m2,
|
||||
activityId: a2,
|
||||
version: 1,
|
||||
type: EvidenceType.InspectionReport,
|
||||
fileName: 'Independent_Structural_Quality_Audit_Report.pdf',
|
||||
fileSize: '6.4 MB',
|
||||
status: ApprovalStatus.Approved,
|
||||
createdBy: u2,
|
||||
createdAt: '2026-09-15T09:40:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/402/milestones/802/audit_report.pdf',
|
||||
},
|
||||
{
|
||||
id: 'ev-104',
|
||||
projectId: p1,
|
||||
milestoneId: m2,
|
||||
activityId: a2,
|
||||
version: 1,
|
||||
type: EvidenceType.AttendanceRegister,
|
||||
fileName: 'Community_Skills_Training_Attendance_Register_Q2.xlsx',
|
||||
fileSize: '2.1 MB',
|
||||
status: ApprovalStatus.PendingReview,
|
||||
createdBy: u3,
|
||||
createdAt: '2026-09-19T08:20:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/401/activities/102/attendance.xlsx',
|
||||
},
|
||||
{
|
||||
id: 'ev-105',
|
||||
projectId: p2,
|
||||
milestoneId: m1,
|
||||
activityId: a1,
|
||||
version: 1,
|
||||
type: EvidenceType.FinancialInvoiceOrReceipt,
|
||||
fileName: 'Vendor_Procurement_Tax_Invoices_Batch_A.pdf',
|
||||
fileSize: '3.7 MB',
|
||||
status: ApprovalStatus.Rejected,
|
||||
createdBy: u2,
|
||||
createdAt: '2026-09-14T16:05:00Z',
|
||||
documentUrl: 'https://storage.googleapis.com/pfm-evidence-vault/projects/402/activities/101/invoices.pdf',
|
||||
},
|
||||
];
|
||||
}, [projects, milestones, activities, users]);
|
||||
|
||||
// Merge backend data with demo fallback, deduplicating by ID
|
||||
const allEvidence: Evidence[] = useMemo(() => {
|
||||
const map = new Map<string | number, Evidence>();
|
||||
defaultEvidenceItems.forEach((item) => map.set(item.id, item));
|
||||
rawEvidenceList.forEach((item) => map.set(item.id, item));
|
||||
return Array.from(map.values());
|
||||
}, [defaultEvidenceItems, rawEvidenceList]);
|
||||
// UI depends entirely on the API response - no mock or demo data
|
||||
const allEvidence: Evidence[] = rawEvidenceList;
|
||||
|
||||
// Review evidence mutation: Facilitates Approve & Reject decisions via PUT /v1/api/evidence
|
||||
const reviewMutation = useMutation({
|
||||
@@ -258,7 +193,7 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
// Update local query cache for instant feedback
|
||||
queryClient.setQueryData(['evidence'], (old: Evidence[] = []) => {
|
||||
queryClient.setQueryData(['evidence', selectedProjectId], (old: Evidence[] = []) => {
|
||||
const exists = old.some((e) => String(e.id) === String(variables.id));
|
||||
if (exists) {
|
||||
return old.map((e) =>
|
||||
@@ -416,9 +351,10 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
toastError('Missing File', 'Please select a document or certificate to upload.');
|
||||
return;
|
||||
}
|
||||
const targetProjId = ingestProjectId || (selectedProjectId !== 'all' ? selectedProjectId : projects[0]?.id) || '';
|
||||
const formData = new FormData();
|
||||
formData.append('file', ingestFile);
|
||||
formData.append('projectId', String(ingestProjectId || projects[0]?.id || '401'));
|
||||
formData.append('projectId', String(targetProjId));
|
||||
if (ingestMilestoneId) formData.append('milestoneId', String(ingestMilestoneId));
|
||||
if (ingestActivityId) formData.append('activityId', String(ingestActivityId));
|
||||
formData.append('evidenceType', String(ingestType));
|
||||
@@ -427,7 +363,8 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
};
|
||||
|
||||
const handleResetFilters = () => {
|
||||
setSelectedProjectId('all');
|
||||
const defaultProjId = projects[0]?.id || 'all';
|
||||
setSelectedProjectId(defaultProjId);
|
||||
setSelectedMilestoneId('all');
|
||||
setSelectedActivityId('all');
|
||||
setSelectedUserId('all');
|
||||
@@ -435,8 +372,12 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
const defaultProjectId = projects[0]?.id;
|
||||
const isDefaultProject =
|
||||
defaultProjectId !== undefined ? String(selectedProjectId) === String(defaultProjectId) : selectedProjectId === 'all';
|
||||
|
||||
const hasActiveFilters =
|
||||
selectedProjectId !== 'all' ||
|
||||
!isDefaultProject ||
|
||||
selectedMilestoneId !== 'all' ||
|
||||
selectedActivityId !== 'all' ||
|
||||
selectedUserId !== 'all' ||
|
||||
@@ -567,7 +508,10 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
</label>
|
||||
<select
|
||||
value={selectedProjectId}
|
||||
onChange={(e) => setSelectedProjectId(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setSelectedProjectId(e.target.value);
|
||||
setUserHasSelectedProject(true);
|
||||
}}
|
||||
className="w-full text-xs bg-slate-900/90 border border-slate-700/80 rounded-xl px-2.5 py-2 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50 [&>option]:bg-slate-900 [&>option]:text-white"
|
||||
>
|
||||
<option value="all">All Projects ({projects.length})</option>
|
||||
@@ -1069,7 +1013,7 @@ export const EvidenceReviewQueue: React.FC<EvidenceReviewQueueProps> = ({
|
||||
<div>
|
||||
<label className="block text-slate-300 font-semibold mb-1">Target Project *</label>
|
||||
<select
|
||||
value={ingestProjectId || projects[0]?.id || ''}
|
||||
value={ingestProjectId || (selectedProjectId !== 'all' ? selectedProjectId : projects[0]?.id) || ''}
|
||||
onChange={(e) => setIngestProjectId(e.target.value)}
|
||||
className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-blue-500/50"
|
||||
>
|
||||
|
||||
@@ -43,14 +43,9 @@ export const ProblemDetailsAlert: React.FC<ProblemDetailsAlertProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Direct error message or error list from ProblemDetails */}
|
||||
{parsed.errorsList && parsed.errorsList.length > 0 ? (
|
||||
{/* Direct error message or comma-delimited error list from ProblemDetails */}
|
||||
{parsed.errorsList && parsed.errorsList.length > 1 ? (
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{parsed.message && !parsed.errorsList.includes(parsed.message) && (
|
||||
<p className="text-xs text-rose-200/90 leading-relaxed whitespace-pre-line">
|
||||
{parsed.message}
|
||||
</p>
|
||||
)}
|
||||
<ul className="space-y-1 bg-black/30 rounded-lg p-2.5 border border-rose-900/40">
|
||||
{parsed.errorsList.map((err, idx) => (
|
||||
<li key={idx} className="text-xs text-rose-200/90 flex items-start gap-2">
|
||||
|
||||
@@ -155,12 +155,9 @@ const ToastCard: React.FC<{
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Display errors from ProblemDetails errors member */}
|
||||
{toast.errorsList && toast.errorsList.length > 0 ? (
|
||||
{/* Display errors from ProblemDetails comma-delimited detail or errors list */}
|
||||
{toast.errorsList && toast.errorsList.length > 1 ? (
|
||||
<div className="mt-1.5 space-y-1">
|
||||
{toast.message && !toast.errorsList.includes(toast.message) && (
|
||||
<p className="text-xs text-slate-300 leading-relaxed">{toast.message}</p>
|
||||
)}
|
||||
<ul className="space-y-1">
|
||||
{toast.errorsList.map((err, idx) => (
|
||||
<li key={idx} className="text-xs text-rose-200/90 flex items-start gap-1.5">
|
||||
|
||||
@@ -18,6 +18,9 @@ import {
|
||||
Eye,
|
||||
RefreshCw,
|
||||
ArrowRight,
|
||||
FileText,
|
||||
Scale,
|
||||
Calendar,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
getOrganisations,
|
||||
@@ -35,6 +38,12 @@ import {
|
||||
createProgramme,
|
||||
updateProgramme,
|
||||
getInstruments,
|
||||
getInstructions,
|
||||
createInstruction,
|
||||
updateInstruction,
|
||||
getRules,
|
||||
createRule,
|
||||
updateRule,
|
||||
getPortfolioProgrammes,
|
||||
getUsers,
|
||||
getUser,
|
||||
@@ -43,11 +52,15 @@ import { Modal } from '../components/ui/Modal';
|
||||
import { HelpTooltip } from '../components/ui/HelpTooltip';
|
||||
import { useToast } from '../components/ui/Toast';
|
||||
import { useAuth } from '../auth/AuthProvider';
|
||||
import { InstructionsSection } from '../components/governance/InstructionsSection';
|
||||
import { RulesSection } from '../components/governance/RulesSection';
|
||||
import {
|
||||
Organisation,
|
||||
Portfolio,
|
||||
Programme,
|
||||
Instrument,
|
||||
Instruction,
|
||||
Rule,
|
||||
OrganisationType,
|
||||
ActivityStatus,
|
||||
ApprovalStatus,
|
||||
@@ -120,22 +133,22 @@ export const GovernancePage: React.FC = () => {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const tabParam = searchParams.get('tab');
|
||||
|
||||
const getValidTab = (val: string | null): 'organisations' | 'portfolios' | 'programmes' => {
|
||||
if (val === 'portfolios' || val === 'programmes' || val === 'organisations') {
|
||||
const getValidTab = (val: string | null): 'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules' => {
|
||||
if (val === 'portfolios' || val === 'programmes' || val === 'organisations' || val === 'instructions' || val === 'rules') {
|
||||
return val;
|
||||
}
|
||||
return 'organisations';
|
||||
};
|
||||
|
||||
const [activeTab, setActiveTab] = useState<'organisations' | 'portfolios' | 'programmes'>(() => getValidTab(tabParam));
|
||||
const [activeTab, setActiveTab] = useState<'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules'>(() => getValidTab(tabParam));
|
||||
|
||||
useEffect(() => {
|
||||
if (tabParam && (tabParam === 'organisations' || tabParam === 'portfolios' || tabParam === 'programmes')) {
|
||||
if (tabParam && (tabParam === 'organisations' || tabParam === 'portfolios' || tabParam === 'programmes' || tabParam === 'instructions' || tabParam === 'rules')) {
|
||||
setActiveTab(tabParam);
|
||||
}
|
||||
}, [tabParam]);
|
||||
|
||||
const handleTabChange = (tab: 'organisations' | 'portfolios' | 'programmes') => {
|
||||
const handleTabChange = (tab: 'organisations' | 'portfolios' | 'programmes' | 'instructions' | 'rules') => {
|
||||
setActiveTab(tab);
|
||||
setSearchParams((prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
@@ -144,6 +157,11 @@ export const GovernancePage: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const [preselectedProgForInstruction, setPreselectedProgForInstruction] = useState<string | number | null>(null);
|
||||
const [preselectedProgForRule, setPreselectedProgForRule] = useState<string | number | null>(null);
|
||||
const [isInstructionCreateTriggered, setIsInstructionCreateTriggered] = useState(false);
|
||||
const [isRuleCreateTriggered, setIsRuleCreateTriggered] = useState(false);
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [highlightedPortfolioId, setHighlightedPortfolioId] = useState<number | string | null>(null);
|
||||
|
||||
@@ -179,6 +197,9 @@ export const GovernancePage: React.FC = () => {
|
||||
const [selectedProgrammeForInstruments, setSelectedProgrammeForInstruments] = useState<Programme | null>(null);
|
||||
const [isInstrumentsModalOpen, setIsInstrumentsModalOpen] = useState(false);
|
||||
|
||||
const [selectedProgrammeForRules, setSelectedProgrammeForRules] = useState<Programme | null>(null);
|
||||
const [isRulesModalOpen, setIsRulesModalOpen] = useState(false);
|
||||
|
||||
const [selectedPortfolioForProgrammes, setSelectedPortfolioForProgrammes] = useState<Portfolio | null>(null);
|
||||
const [isPortfolioProgrammesModalOpen, setIsPortfolioProgrammesModalOpen] = useState(false);
|
||||
|
||||
@@ -215,10 +236,28 @@ export const GovernancePage: React.FC = () => {
|
||||
|
||||
const { data: programmeInstruments = [], isLoading: loadingInstruments } = useQuery({
|
||||
queryKey: ['instruments', selectedProgrammeForInstruments?.id],
|
||||
queryFn: () => (selectedProgrammeForInstruments ? getInstruments(selectedProgrammeForInstruments.id) : Promise.resolve([])),
|
||||
queryFn: () => (selectedProgrammeForInstruments ? getInstructions(selectedProgrammeForInstruments.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForInstruments && isInstrumentsModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeRulesList = [], isLoading: loadingProgrammeRules } = useQuery({
|
||||
queryKey: ['programme-rules', selectedProgrammeForRules?.id],
|
||||
queryFn: () => (selectedProgrammeForRules ? getRules({ page: 1, pageSize: 200 }, selectedProgrammeForRules.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForRules && isRulesModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeDetailRules = [], isLoading: loadingDetailRules } = useQuery({
|
||||
queryKey: ['programme-detail-rules', selectedProgrammeForDetail?.id],
|
||||
queryFn: () => (selectedProgrammeForDetail ? getRules({ page: 1, pageSize: 200 }, selectedProgrammeForDetail.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForDetail && isProgrammeDetailModalOpen,
|
||||
});
|
||||
|
||||
const { data: programmeDetailInstructions = [], isLoading: loadingDetailInstructions } = useQuery({
|
||||
queryKey: ['programme-detail-instructions', selectedProgrammeForDetail?.id],
|
||||
queryFn: () => (selectedProgrammeForDetail ? getInstructions(selectedProgrammeForDetail.id) : Promise.resolve([])),
|
||||
enabled: !!selectedProgrammeForDetail && isProgrammeDetailModalOpen,
|
||||
});
|
||||
|
||||
const { data: portfolioProgrammesList = [], isLoading: loadingPortfolioProgrammes } = useQuery({
|
||||
queryKey: ['portfolioProgrammes', selectedPortfolioForProgrammes?.id],
|
||||
queryFn: () => (selectedPortfolioForProgrammes ? getPortfolioProgrammes(selectedPortfolioForProgrammes.id) : Promise.resolve([])),
|
||||
@@ -558,7 +597,7 @@ export const GovernancePage: React.FC = () => {
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-slate-400 mt-1">
|
||||
Maintain Master Organisation Registry, Funder Portfolios, and Strategic Programmes hierarchy.
|
||||
Maintain Master Organisation Registry, Funder Portfolios, Strategic Programmes, Funding Instructions, and Programme Rules.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -591,14 +630,32 @@ export const GovernancePage: React.FC = () => {
|
||||
Create Programme
|
||||
</button>
|
||||
)}
|
||||
{activeTab === 'instructions' && (
|
||||
<button
|
||||
onClick={() => setIsInstructionCreateTriggered(true)}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Instruction
|
||||
</button>
|
||||
)}
|
||||
{activeTab === 'rules' && (
|
||||
<button
|
||||
onClick={() => setIsRuleCreateTriggered(true)}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 rounded-xl shadow-md shadow-blue-500/20 transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Add Rule
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex border-b border-slate-800/80 bg-[#0d121f]/80 px-4 rounded-2xl backdrop-blur-sm">
|
||||
<div className="flex border-b border-slate-800/80 bg-[#0d121f]/80 px-4 rounded-2xl backdrop-blur-sm overflow-x-auto">
|
||||
<button
|
||||
onClick={() => handleTabChange('organisations')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'organisations'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -615,7 +672,7 @@ export const GovernancePage: React.FC = () => {
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('portfolios')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'portfolios'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -632,7 +689,7 @@ export const GovernancePage: React.FC = () => {
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('programmes')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer ${
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'programmes'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
@@ -647,6 +704,40 @@ export const GovernancePage: React.FC = () => {
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('instructions')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'instructions'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
}`}
|
||||
>
|
||||
<FileText className="w-4 h-4" />
|
||||
<span>Funding Instructions</span>
|
||||
<HelpTooltip
|
||||
title="Funding Instructions"
|
||||
content="Operational directives and funding instrument guidelines attached to specific strategic programmes."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTabChange('rules')}
|
||||
className={`py-3.5 px-4 text-xs font-semibold border-b-2 transition-colors flex items-center gap-2 cursor-pointer whitespace-nowrap ${
|
||||
activeTab === 'rules'
|
||||
? 'border-blue-500 text-blue-400'
|
||||
: 'border-transparent text-slate-400 hover:text-slate-200'
|
||||
}`}
|
||||
>
|
||||
<Scale className="w-4 h-4" />
|
||||
<span>Programme Rules</span>
|
||||
<HelpTooltip
|
||||
title="Programme Rules"
|
||||
content="Statutory, regulatory, and eligibility rules associated with specific funding programmes."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Search Bar & Actions */}
|
||||
@@ -916,10 +1007,22 @@ export const GovernancePage: React.FC = () => {
|
||||
setIsInstrumentsModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="View Funding Instruments"
|
||||
title="View Funding Instructions"
|
||||
>
|
||||
<Coins className="w-3 h-3" />
|
||||
Instruments
|
||||
<FileText className="w-3 h-3" />
|
||||
Instructions
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSelectedProgrammeForRules(pr);
|
||||
setIsRulesModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-xs font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 px-2.5 py-1 rounded-lg transition shadow-xs cursor-pointer"
|
||||
title="View Programme Rules"
|
||||
>
|
||||
<Scale className="w-3 h-3" />
|
||||
Rules
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -941,6 +1044,30 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tab 4: Funding Instructions */}
|
||||
{activeTab === 'instructions' && (
|
||||
<InstructionsSection
|
||||
programmes={programmes}
|
||||
currentUserId={currentUserId}
|
||||
preselectedProgrammeId={preselectedProgForInstruction}
|
||||
onClearPreselectedProgramme={() => setPreselectedProgForInstruction(null)}
|
||||
isCreateModalOpenExternal={isInstructionCreateTriggered}
|
||||
onCloseCreateModalExternal={() => setIsInstructionCreateTriggered(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Tab 5: Programme Rules */}
|
||||
{activeTab === 'rules' && (
|
||||
<RulesSection
|
||||
programmes={programmes}
|
||||
currentUserId={currentUserId}
|
||||
preselectedProgrammeId={preselectedProgForRule}
|
||||
onClearPreselectedProgramme={() => setPreselectedProgForRule(null)}
|
||||
isCreateModalOpenExternal={isRuleCreateTriggered}
|
||||
onCloseCreateModalExternal={() => setIsRuleCreateTriggered(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Modal: Register / Edit Organisation */}
|
||||
<Modal
|
||||
isOpen={isOrgModalOpen}
|
||||
@@ -1349,22 +1476,42 @@ export const GovernancePage: React.FC = () => {
|
||||
</form>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: View Funding Instruments */}
|
||||
{/* Modal: View Funding Instructions */}
|
||||
<Modal
|
||||
isOpen={isInstrumentsModalOpen}
|
||||
onClose={() => {
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
}}
|
||||
title={`Funding Instruments: ${selectedProgrammeForInstruments?.name || ''}`}
|
||||
subtitle={`Authoritative funding instruments linked to Programme #${selectedProgrammeForInstruments?.id || ''}`}
|
||||
title={`Funding Instructions: ${selectedProgrammeForInstruments?.name || ''}`}
|
||||
subtitle={`Authoritative funding instructions linked to Programme #${selectedProgrammeForInstruments?.id || ''}`}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{loadingInstruments ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400">Loading funding instruments...</div>
|
||||
<div className="py-8 text-center text-xs text-slate-400 flex items-center justify-center gap-2">
|
||||
<RefreshCw className="w-4 h-4 animate-spin text-blue-400" />
|
||||
<span>Loading funding instructions...</span>
|
||||
</div>
|
||||
) : programmeInstruments.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-slate-500">
|
||||
No funding instruments registered under this programme.
|
||||
<div className="py-8 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
No funding instructions registered under this programme yet.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
setIsInstructionCreateTriggered(true);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-500 rounded-xl transition cursor-pointer shadow-md shadow-blue-500/20"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Instruction to this Programme
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5 max-h-[400px] overflow-y-auto">
|
||||
@@ -1382,9 +1529,26 @@ export const GovernancePage: React.FC = () => {
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-white">{inst.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 border border-slate-700 px-2 py-0.5 rounded cursor-pointer"
|
||||
title="Manage in Instructions Tab"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Manage
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{inst.description && (
|
||||
<p className="text-xs text-slate-400 leading-relaxed">{inst.description}</p>
|
||||
@@ -1398,7 +1562,22 @@ export const GovernancePage: React.FC = () => {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-end">
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForInstruments?.id;
|
||||
setIsInstrumentsModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
setIsInstructionCreateTriggered(true);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Instruction
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@@ -1413,6 +1592,122 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: View Programme Rules */}
|
||||
<Modal
|
||||
isOpen={isRulesModalOpen}
|
||||
onClose={() => {
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
}}
|
||||
title={`Programme Rules: ${selectedProgrammeForRules?.name || ''}`}
|
||||
subtitle={`Authoritative governance and statutory rules linked to Programme #${selectedProgrammeForRules?.id || ''}`}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{loadingProgrammeRules ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400 flex items-center justify-center gap-2">
|
||||
<RefreshCw className="w-4 h-4 animate-spin text-amber-400" />
|
||||
<span>Loading programme rules...</span>
|
||||
</div>
|
||||
) : programmeRulesList.length === 0 ? (
|
||||
<div className="py-8 text-center text-xs text-slate-400 space-y-3">
|
||||
<div className="text-slate-500">
|
||||
No programme rules registered under this programme yet.
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
setIsRuleCreateTriggered(true);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-white bg-amber-600 hover:bg-amber-500 rounded-xl transition cursor-pointer shadow-md shadow-amber-500/20"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Rule to this Programme
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5 max-h-[400px] overflow-y-auto">
|
||||
{programmeRulesList.map((r: Rule) => {
|
||||
const statusBadge = getActivityStatusBadge(r.status);
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex flex-col gap-1.5"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-xs font-bold text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded border border-amber-500/20">
|
||||
v{r.version || 1}
|
||||
</span>
|
||||
<span className="font-semibold text-xs text-white">{r.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-slate-300 hover:text-white bg-slate-800 hover:bg-slate-700 border border-slate-700 px-2 py-0.5 rounded cursor-pointer"
|
||||
title="Manage in Rules Tab"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
Manage
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{r.description && (
|
||||
<p className="text-xs text-slate-400 leading-relaxed">{r.description}</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between pt-2 border-t border-slate-800/80 text-[10px] text-slate-500 font-mono">
|
||||
<span>Created by: {getUserEmail(r.createdBy)}</span>
|
||||
<span>{formatDate(r.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-between items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForRules?.id;
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
setIsRuleCreateTriggered(true);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 rounded-xl transition cursor-pointer"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Add Rule
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsRulesModalOpen(false);
|
||||
setSelectedProgrammeForRules(null);
|
||||
}}
|
||||
className="px-4 py-2 text-xs font-semibold text-slate-300 bg-slate-800 hover:bg-slate-700 rounded-xl cursor-pointer"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Modal: View Portfolio Programmes */}
|
||||
<Modal
|
||||
isOpen={isPortfolioProgrammesModalOpen}
|
||||
@@ -1437,7 +1732,7 @@ export const GovernancePage: React.FC = () => {
|
||||
return (
|
||||
<div
|
||||
key={pr.id}
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex items-center justify-between"
|
||||
className="p-3.5 rounded-xl border border-slate-800 bg-[#0d121f] flex flex-col sm:flex-row sm:items-center justify-between gap-3"
|
||||
>
|
||||
<div>
|
||||
<span className="font-semibold text-xs text-white block">{pr.name}</span>
|
||||
@@ -1445,9 +1740,50 @@ export const GovernancePage: React.FC = () => {
|
||||
ID: {pr.id} • Owner: {getUserEmail(pr.ownedBy)} • {formatDate(pr.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold border ${statusBadge.className}`}>
|
||||
{statusBadge.label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForDetail(pr);
|
||||
setIsProgrammeDetailModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-cyan-400 hover:text-white bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="Inspect Programme"
|
||||
>
|
||||
<Eye className="w-3 h-3" />
|
||||
Inspect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForInstruments(pr);
|
||||
setIsInstrumentsModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-blue-400 hover:text-white bg-blue-500/10 hover:bg-blue-500/20 border border-blue-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="View Funding Instructions"
|
||||
>
|
||||
<FileText className="w-3 h-3" />
|
||||
Instructions
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsPortfolioProgrammesModalOpen(false);
|
||||
setSelectedProgrammeForRules(pr);
|
||||
setIsRulesModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-semibold text-amber-400 hover:text-white bg-amber-500/10 hover:bg-amber-500/20 border border-amber-500/30 px-2 py-1 rounded-lg cursor-pointer"
|
||||
title="View Programme Rules"
|
||||
>
|
||||
<Scale className="w-3 h-3" />
|
||||
Rules
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -1664,25 +2000,104 @@ export const GovernancePage: React.FC = () => {
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 bg-[#0d121f] rounded-xl border border-slate-800/80 space-y-3.5">
|
||||
<div className="pb-3 border-b border-slate-800/80">
|
||||
<span className="text-slate-400 font-semibold block text-[11px] uppercase tracking-wider mb-1">Programme Name</span>
|
||||
<div className="pb-3 border-b border-slate-800/80 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<span className="text-slate-400 font-semibold block text-[11px] uppercase tracking-wider mb-1">Programme Title</span>
|
||||
<span className="text-white font-semibold text-sm block">{programmeFreshDetail?.name || selectedProgrammeForDetail?.name}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-slate-400 font-semibold text-[11px] uppercase tracking-wider shrink-0">Approval Status:</span>
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-semibold border whitespace-nowrap ${getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).className}`}>
|
||||
{getApprovalStatusBadge(programmeFreshDetail?.status ?? selectedProgrammeForDetail?.status ?? ApprovalStatus.Approved).label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-slate-400 font-semibold text-[11px] uppercase tracking-wider shrink-0">Owner:</span>
|
||||
<span className="font-mono text-slate-300 text-xs truncate" title={getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}>
|
||||
|
||||
{/* Core Details Grid: Owner & Creation Date */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
|
||||
{/* Creation Date */}
|
||||
<div className="p-3 bg-[#080d1a] rounded-lg border border-slate-800 flex items-center gap-2.5">
|
||||
<Calendar className="w-4 h-4 text-slate-400 shrink-0" />
|
||||
<div>
|
||||
<span className="text-slate-500 font-medium block text-[10px] uppercase tracking-wider">Creation Date</span>
|
||||
<span className="text-slate-200 font-mono text-xs font-semibold">
|
||||
{formatDate(programmeFreshDetail?.createdAt || selectedProgrammeForDetail?.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Owner */}
|
||||
<div className="p-3 bg-[#080d1a] rounded-lg border border-slate-800 flex items-center gap-2.5">
|
||||
<Mail className="w-4 h-4 text-slate-400 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-slate-500 font-medium block text-[10px] uppercase tracking-wider">Programme Lead</span>
|
||||
<span className="font-mono text-slate-200 text-xs truncate block" title={getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}>
|
||||
{getUserEmail(programmeFreshDetail?.ownedBy || selectedProgrammeForDetail?.ownedBy)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Metrics: Total Rules and Total Instructions */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
|
||||
{/* Total Rules */}
|
||||
<div className="p-3 bg-gradient-to-br from-amber-500/10 to-amber-500/5 rounded-xl border border-amber-500/20 flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="text-[11px] font-semibold text-amber-300 flex items-center gap-1.5">
|
||||
<Scale className="w-3.5 h-3.5 text-amber-400" />
|
||||
Total Rules
|
||||
</span>
|
||||
<span className="text-lg font-bold font-mono text-amber-400">
|
||||
{loadingDetailRules ? (
|
||||
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
programmeDetailRules.length
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForDetail?.id;
|
||||
setIsProgrammeDetailModalOpen(false);
|
||||
setSelectedProgrammeForDetail(null);
|
||||
setPreselectedProgForRule(pId || null);
|
||||
handleTabChange('rules');
|
||||
}}
|
||||
className="text-[11px] font-semibold text-amber-400 hover:text-amber-300 inline-flex items-center gap-1 mt-1 transition cursor-pointer self-start"
|
||||
>
|
||||
View in Rules Tab →
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Total Instructions */}
|
||||
<div className="p-3 bg-gradient-to-br from-blue-500/10 to-blue-500/5 rounded-xl border border-blue-500/20 flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="text-[11px] font-semibold text-blue-300 flex items-center gap-1.5">
|
||||
<FileText className="w-3.5 h-3.5 text-blue-400" />
|
||||
Total Instructions
|
||||
</span>
|
||||
<span className="text-lg font-bold font-mono text-blue-400">
|
||||
{loadingDetailInstructions ? (
|
||||
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
programmeDetailInstructions.length
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const pId = selectedProgrammeForDetail?.id;
|
||||
setIsProgrammeDetailModalOpen(false);
|
||||
setSelectedProgrammeForDetail(null);
|
||||
setPreselectedProgForInstruction(pId || null);
|
||||
handleTabChange('instructions');
|
||||
}}
|
||||
className="text-[11px] font-semibold text-blue-400 hover:text-blue-300 inline-flex items-center gap-1 mt-1 transition cursor-pointer self-start"
|
||||
>
|
||||
View in Instructions Tab →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-2 border-t border-slate-800 flex justify-end">
|
||||
|
||||
@@ -75,6 +75,8 @@ const projectSchema = z.object({
|
||||
programmeId: z.coerce.number().min(1, 'Select a programme'),
|
||||
sector: z.coerce.number().min(1),
|
||||
projectType: z.coerce.number().min(1),
|
||||
startedAt: z.string().optional().nullable(),
|
||||
endedAt: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
const activitySchema = z.object({
|
||||
@@ -83,6 +85,7 @@ const activitySchema = z.object({
|
||||
category: z.string().min(2, 'Category required'),
|
||||
amount: z.coerce.number().min(1, 'Amount must be positive'),
|
||||
milestoneId: z.string().optional().nullable(),
|
||||
performedAt: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
const milestoneSchema = z.object({
|
||||
@@ -164,6 +167,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
sector: IndustrySector.AgriTech,
|
||||
projectType: ProjectType.Innovation,
|
||||
startedAt: '',
|
||||
endedAt: '',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -175,6 +180,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: '',
|
||||
amount: 0,
|
||||
milestoneId: '',
|
||||
performedAt: '',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -197,6 +203,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: programmes[0]?.id ? Number(programmes[0].id) : 0,
|
||||
sector: IndustrySector.AgriTech,
|
||||
projectType: ProjectType.Innovation,
|
||||
startedAt: '',
|
||||
endedAt: '',
|
||||
});
|
||||
setIsProjectModalOpen(true);
|
||||
};
|
||||
@@ -209,6 +217,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
programmeId: p.programmeId ? Number(p.programmeId) : (programmes[0]?.id ? Number(programmes[0].id) : 0),
|
||||
sector: p.sector || IndustrySector.AgriTech,
|
||||
projectType: p.projectType || ProjectType.Innovation,
|
||||
startedAt: p.startedAt ? p.startedAt.slice(0, 10) : '',
|
||||
endedAt: p.endedAt ? p.endedAt.slice(0, 10) : '',
|
||||
});
|
||||
setIsProjectModalOpen(true);
|
||||
};
|
||||
@@ -221,6 +231,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: '',
|
||||
amount: 0,
|
||||
milestoneId: '',
|
||||
performedAt: new Date().toISOString().slice(0, 10),
|
||||
});
|
||||
setIsActivityModalOpen(true);
|
||||
};
|
||||
@@ -233,6 +244,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: a.category || '',
|
||||
amount: a.amount || 0,
|
||||
milestoneId: a.milestoneId ? String(a.milestoneId) : '',
|
||||
performedAt: a.performedAt ? a.performedAt.slice(0, 10) : '',
|
||||
});
|
||||
setIsActivityModalOpen(true);
|
||||
};
|
||||
@@ -267,6 +279,8 @@ export const ProjectsPage: React.FC = () => {
|
||||
projectId: editingProject.id,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
startedAt: data.startedAt ? new Date(data.startedAt).toISOString() : null,
|
||||
endedAt: data.endedAt ? new Date(data.endedAt).toISOString() : null,
|
||||
sector: Number(data.sector),
|
||||
projectType: Number(data.projectType),
|
||||
});
|
||||
@@ -310,6 +324,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
data.milestoneId && String(data.milestoneId).trim() !== ''
|
||||
? Number(data.milestoneId)
|
||||
: null;
|
||||
const performedAtIso = data.performedAt ? new Date(data.performedAt).toISOString() : null;
|
||||
|
||||
if (editingActivity) {
|
||||
return updateActivity({
|
||||
@@ -320,6 +335,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: data.category,
|
||||
amount: Number(data.amount),
|
||||
milestoneId: parsedMilestoneId,
|
||||
performedAt: performedAtIso,
|
||||
});
|
||||
}
|
||||
return createActivity({
|
||||
@@ -329,6 +345,7 @@ export const ProjectsPage: React.FC = () => {
|
||||
category: data.category,
|
||||
amount: Number(data.amount),
|
||||
milestoneId: parsedMilestoneId,
|
||||
performedAt: performedAtIso,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
@@ -985,6 +1002,41 @@ export const ProjectsPage: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Start Date</label>
|
||||
<HelpTooltip
|
||||
title="Project Start Date"
|
||||
content="Scheduled or actual project commencement date."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...projectForm.register('startedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Target Completion Date</label>
|
||||
<HelpTooltip
|
||||
title="Target Completion Date"
|
||||
content="Projected or contractual conclusion date for statutory reporting."
|
||||
size="sm"
|
||||
placement="top"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...projectForm.register('endedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1">Project Scope & Objectives *</label>
|
||||
<textarea
|
||||
@@ -1112,6 +1164,23 @@ export const ProjectsPage: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<label className="block text-xs font-semibold text-slate-300">Execution / Performed Date</label>
|
||||
<HelpTooltip
|
||||
title="Activity Execution Date"
|
||||
content="Scheduled or actual date on which the activity was performed."
|
||||
size="sm"
|
||||
placement="right"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
{...activityForm.register('performedAt')}
|
||||
className="w-full px-3 py-2 text-xs border border-slate-700/80 rounded-xl focus:outline-none focus:ring-1 focus:ring-blue-500 text-white bg-[#090d16]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1">Description *</label>
|
||||
<textarea
|
||||
|
||||
@@ -20,6 +20,9 @@ import {
|
||||
CreateProgrammeRequest,
|
||||
UpdateProgrammeRequest,
|
||||
Instrument,
|
||||
Instruction,
|
||||
CreateInstructionRequest,
|
||||
UpdateInstructionRequest,
|
||||
Project,
|
||||
CreateProjectRequest,
|
||||
UpdateProjectRequest,
|
||||
@@ -57,29 +60,65 @@ import {
|
||||
AuditLog,
|
||||
ProblemDetails,
|
||||
ActivityStatus,
|
||||
Tenant,
|
||||
CreateTenantRequest,
|
||||
UpdateTenantRequest,
|
||||
Beneficiary,
|
||||
CreateBeneficiaryRequest,
|
||||
UpdateBeneficiaryRequest,
|
||||
Outcome,
|
||||
CreateOutcomeRequest,
|
||||
UpdateOutcomeRequest,
|
||||
ChangeRequest,
|
||||
CreateChangeRequest,
|
||||
UpdateChangeRequest,
|
||||
ComplianceItem,
|
||||
CreateComplianceItemRequest,
|
||||
UpdateComplianceItemRequest,
|
||||
Issue,
|
||||
CreateIssueRequest,
|
||||
UpdateIssueRequest,
|
||||
SiteVisit,
|
||||
CreateSiteVisitRequest,
|
||||
UpdateSiteVisitRequest,
|
||||
Rule,
|
||||
CreateRuleRequest,
|
||||
UpdateRuleRequest,
|
||||
Pagination,
|
||||
Notification,
|
||||
} from '../types';
|
||||
|
||||
import { parseFriendlyError, FriendlyError } from '../utils/apiErrorParser';
|
||||
import {
|
||||
parseFriendlyError,
|
||||
FriendlyError,
|
||||
inspectErrorResponseObject,
|
||||
parseCommaDelimitedErrors,
|
||||
} from '../utils/apiErrorParser';
|
||||
import { registerUserEmail, registerUserEmails, getUserIdByEmail } from '../lib/formatters';
|
||||
|
||||
// Helper to extract ProblemDetails from Axios error or unknown error
|
||||
export function parseApiError(error: unknown): ProblemDetails {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosErr = error as AxiosError<ProblemDetails>;
|
||||
if (axiosErr.response?.data && typeof axiosErr.response.data === 'object') {
|
||||
return axiosErr.response.data;
|
||||
}
|
||||
const returnObj = inspectErrorResponseObject(error);
|
||||
if (returnObj) {
|
||||
return {
|
||||
type: returnObj.type || 'https://tools.ietf.org/html/rfc9110#section-15.5.1',
|
||||
title: returnObj.title || 'Error',
|
||||
status: returnObj.status || (axios.isAxiosError(error) ? error.response?.status : 400),
|
||||
detail: returnObj.detail || null,
|
||||
instance: returnObj.instance || null,
|
||||
};
|
||||
}
|
||||
|
||||
const friendly = parseFriendlyError(error);
|
||||
return {
|
||||
type: 'https://tools.ietf.org/html/rfc9110#section-15.5.1',
|
||||
title: friendly.title,
|
||||
detail: friendly.message,
|
||||
status: friendly.statusCode || 500,
|
||||
};
|
||||
}
|
||||
|
||||
export { parseFriendlyError };
|
||||
export { parseFriendlyError, inspectErrorResponseObject, parseCommaDelimitedErrors };
|
||||
export type { FriendlyError };
|
||||
|
||||
// ==========================================
|
||||
@@ -181,6 +220,7 @@ export const updateOrganisation = async (payload: UpdateOrganisationRequest): Pr
|
||||
registrationNo: payload.registrationNo,
|
||||
email: payload.email,
|
||||
type: Number(payload.type),
|
||||
status: payload.status !== undefined ? Number(payload.status) : ActivityStatus.Active,
|
||||
});
|
||||
return res.data;
|
||||
};
|
||||
@@ -272,10 +312,166 @@ export const getProgrammes = async (portfolioId: string | number): Promise<Progr
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getInstruments = async (programmeId: string | number): Promise<Instrument[]> => {
|
||||
const LOCAL_INSTRUCTIONS_KEY = 'pfm_local_instructions';
|
||||
|
||||
export const getStoredInstructions = (): Instruction[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
try {
|
||||
const raw = localStorage.getItem(LOCAL_INSTRUCTIONS_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const saveStoredInstruction = (inst: Instruction): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const current = getStoredInstructions();
|
||||
const idx = current.findIndex((i) => String(i.id) === String(inst.id));
|
||||
if (idx >= 0) {
|
||||
current[idx] = { ...current[idx], ...inst, updatedAt: new Date().toISOString() };
|
||||
} else {
|
||||
current.unshift(inst);
|
||||
}
|
||||
localStorage.setItem(LOCAL_INSTRUCTIONS_KEY, JSON.stringify(current));
|
||||
} catch (e) {
|
||||
console.warn('Failed to save stored instruction', e);
|
||||
}
|
||||
};
|
||||
|
||||
export const getInstructions = async (programmeId: string | number): Promise<Instruction[]> => {
|
||||
let apiItems: Instruction[] = [];
|
||||
try {
|
||||
const hashedProgId = await toolsService.resolveProgrammeId(programmeId);
|
||||
const res = await apiClient.get<Instrument[]>(`/v1/api/governance/instruments/${hashedProgId}`);
|
||||
return res.data || [];
|
||||
const res = await apiClient.get<Instruction[]>(`/v1/api/governance/instruments/${hashedProgId}`);
|
||||
apiItems = res.data || [];
|
||||
} catch (err) {
|
||||
console.warn(`[getInstructions] Could not fetch instruments from API for prog ${programmeId}:`, err);
|
||||
}
|
||||
|
||||
const localItems = getStoredInstructions().filter(
|
||||
(item) => String(item.programmeId) === String(programmeId)
|
||||
);
|
||||
|
||||
const map = new Map<string, Instruction>();
|
||||
apiItems.forEach((item) => map.set(String(item.id), item));
|
||||
localItems.forEach((item) => map.set(String(item.id), item));
|
||||
|
||||
return Array.from(map.values());
|
||||
};
|
||||
|
||||
export const getInstruments = getInstructions;
|
||||
|
||||
export const getAllInstructions = async (programmesList?: Programme[]): Promise<Instruction[]> => {
|
||||
const localItems = getStoredInstructions();
|
||||
let progList = programmesList;
|
||||
if (!progList || progList.length === 0) {
|
||||
try {
|
||||
progList = await getAllProgrammes(1, 100);
|
||||
} catch {
|
||||
progList = [];
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<string, Instruction>();
|
||||
localItems.forEach((item) => map.set(String(item.id), item));
|
||||
|
||||
if (progList && progList.length > 0) {
|
||||
const results = await Promise.allSettled(
|
||||
progList.map((pr) => getInstructions(pr.id))
|
||||
);
|
||||
results.forEach((res) => {
|
||||
if (res.status === 'fulfilled' && Array.isArray(res.value)) {
|
||||
res.value.forEach((inst) => map.set(String(inst.id), inst));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(map.values());
|
||||
};
|
||||
|
||||
export const createInstruction = async (payload: CreateInstructionRequest): Promise<Instruction> => {
|
||||
const newId = Date.now();
|
||||
const newInstruction: Instruction = {
|
||||
id: newId,
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: payload.code || `INST-${String(newId).slice(-4)}`,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: payload.status !== undefined ? Number(payload.status) : ActivityStatus.Active,
|
||||
createdBy: payload.userId || 'system',
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.post('/v1/api/governance/instruments', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: newInstruction.code,
|
||||
name: newInstruction.name,
|
||||
description: newInstruction.description,
|
||||
status: newInstruction.status,
|
||||
});
|
||||
} catch (err: any) {
|
||||
try {
|
||||
await apiClient.post('/v1/api/governance/instructions', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
code: newInstruction.code,
|
||||
name: newInstruction.name,
|
||||
description: newInstruction.description,
|
||||
status: newInstruction.status,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('[createInstruction] API create failed, persisted locally:', e);
|
||||
}
|
||||
}
|
||||
|
||||
saveStoredInstruction(newInstruction);
|
||||
return newInstruction;
|
||||
};
|
||||
|
||||
export const updateInstruction = async (payload: UpdateInstructionRequest): Promise<Instruction> => {
|
||||
const existing = getStoredInstructions().find((i) => String(i.id) === String(payload.instructionId));
|
||||
const updatedInstruction: Instruction = {
|
||||
id: payload.instructionId,
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : (existing?.programmeId || 0),
|
||||
code: payload.code || existing?.code || null,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
createdBy: existing?.createdBy || 'system',
|
||||
createdAt: existing?.createdAt || new Date().toISOString(),
|
||||
updatedBy: payload.userId || 'system',
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.put('/v1/api/governance/instruments', {
|
||||
instrumentId: toIntegerId(payload.instructionId),
|
||||
instructionId: toIntegerId(payload.instructionId),
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : undefined,
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
} catch (err) {
|
||||
try {
|
||||
await apiClient.put('/v1/api/governance/instructions', {
|
||||
instructionId: toIntegerId(payload.instructionId),
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : undefined,
|
||||
code: payload.code,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('[updateInstruction] API update failed, updated locally:', e);
|
||||
}
|
||||
}
|
||||
|
||||
saveStoredInstruction(updatedInstruction);
|
||||
return updatedInstruction;
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
@@ -862,8 +1058,15 @@ export const recordIndicatorActual = async (indicatorId: string | number, actual
|
||||
};
|
||||
|
||||
export const getEvidenceFiles = async (page = 1, pageSize = 100): Promise<Evidence[]> => {
|
||||
try {
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/files/${page}/${pageSize}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllEvidence = async (page = 1, pageSize = 100): Promise<Evidence[]> => {
|
||||
@@ -883,15 +1086,40 @@ export const getEvidenceSecureLink = async (evidenceId: string | number): Promis
|
||||
};
|
||||
|
||||
export const getMilestoneEvidence = async (milestoneId: string | number): Promise<Evidence[]> => {
|
||||
try {
|
||||
const hashedMId = await toolsService.encodeId(milestoneId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/milestone/${hashedMId}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getProjectEvidence = async (projectId: string | number): Promise<Evidence[]> => {
|
||||
try {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Evidence[]>(`/v1/api/evidence/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
// If hashed path parameter returns 404 or 400 and projectId differs, attempt with raw ID
|
||||
if ((err?.response?.status === 404 || err?.response?.status === 400) && String(projectId) !== '') {
|
||||
try {
|
||||
const rawRes = await apiClient.get<Evidence[]>(`/v1/api/evidence/${projectId}`);
|
||||
return rawRes.data || [];
|
||||
} catch (fallbackErr: any) {
|
||||
if (fallbackErr?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (err?.response?.status === 404) {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadEvidenceFile = async (formData: FormData): Promise<Evidence> => {
|
||||
@@ -1050,7 +1278,7 @@ export const sendInvite = async (payload: InviteRequest): Promise<Invite> => {
|
||||
? toIntegerId(payload.organisationId)
|
||||
: (tenantId !== null ? tenantId : 0);
|
||||
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invite', {
|
||||
const body = {
|
||||
organisationId: hostOrgId,
|
||||
invitedOrganisationId: toIntegerId(payload.invitedOrganisationId),
|
||||
awardId: toIntegerId(payload.awardId),
|
||||
@@ -1058,8 +1286,18 @@ export const sendInvite = async (payload: InviteRequest): Promise<Invite> => {
|
||||
recipient: payload.recipient,
|
||||
message: payload.message,
|
||||
platform: payload.platform !== undefined ? Number(payload.platform) : 1,
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invites', body);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
const res = await apiClient.post<Invite>('/v1/api/communications/invite', body);
|
||||
return res.data;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getInvites = async (page = 1, pageSize = 100): Promise<Invite[]> => {
|
||||
@@ -1068,11 +1306,434 @@ export const getInvites = async (page = 1, pageSize = 100): Promise<Invite[]> =>
|
||||
};
|
||||
|
||||
export const getApplicantInvite = async (applicantUserId: string): Promise<Invite> => {
|
||||
try {
|
||||
const res = await apiClient.get<Invite>(`/v1/api/communications/invites/applicants/${applicantUserId}`);
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
const res = await apiClient.get<Invite>(`/v1/api/communications/invites/applicant/${applicantUserId}`);
|
||||
return res.data;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
export const getApplicantInvites = async (applicantUserId: string): Promise<Invite[]> => {
|
||||
const res = await apiClient.get<Invite[]>(`/v1/api/communications/invites/${applicantUserId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getNotifications = async (organisationId?: string | number): Promise<Notification[]> => {
|
||||
const targetOrgId =
|
||||
organisationId !== undefined && organisationId !== '' && organisationId !== null
|
||||
? organisationId
|
||||
: getCurrentUserTenantId();
|
||||
|
||||
if (!targetOrgId) return [];
|
||||
const hashedOrgId = await toolsService.resolveOrganisationId(targetOrgId);
|
||||
try {
|
||||
const res = await apiClient.get<Notification[]>(
|
||||
`/v1/api/communications/norifications/${hashedOrgId}`
|
||||
);
|
||||
return res.data || [];
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
try {
|
||||
const res = await apiClient.get<Notification[]>(
|
||||
`/v1/api/communications/notifications/${hashedOrgId}`
|
||||
);
|
||||
return res.data || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 9. Governance: Tenants APIs
|
||||
// ==========================================
|
||||
export const getTenants = async (): Promise<Tenant[]> => {
|
||||
const res = await apiClient.get<Tenant[]>('/v1/api/governance/tenants');
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getTenant = async (tenantId: string | number): Promise<Tenant> => {
|
||||
const hashedTenantId = await toolsService.encodeId(tenantId);
|
||||
const res = await apiClient.get<Tenant>(`/v1/api/governance/tenants/${encodeURIComponent(hashedTenantId)}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createTenant = async (payload: CreateTenantRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/governance/tenants', {
|
||||
name: payload.name,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateTenant = async (payload: UpdateTenantRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/governance/tenants', {
|
||||
tenantId: toIntegerId(payload.tenantId),
|
||||
name: payload.name,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 10. Projects: Beneficiaries & Outcomes APIs
|
||||
// ==========================================
|
||||
export const getProjectBeneficiaries = async (projectId: string | number): Promise<Beneficiary[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Beneficiary[]>(`/v1/api/projects/beneficiaries/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getBeneficiary = async (beneficiaryId: string | number): Promise<Beneficiary> => {
|
||||
const hashedBeneficiaryId = await toolsService.encodeId(beneficiaryId);
|
||||
const res = await apiClient.get<Beneficiary>(`/v1/api/projects/beneficiaries/${hashedBeneficiaryId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createBeneficiary = async (payload: CreateBeneficiaryRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/beneficiaries', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
name: payload.name,
|
||||
category: payload.category,
|
||||
location: payload.location,
|
||||
targetCount: Number(payload.targetCount),
|
||||
reachedCount: Number(payload.reachedCount),
|
||||
});
|
||||
};
|
||||
|
||||
export const updateBeneficiary = async (payload: UpdateBeneficiaryRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/beneficiaries', {
|
||||
beneficiaryId: toIntegerId(payload.beneficiaryId),
|
||||
name: payload.name,
|
||||
category: payload.category,
|
||||
location: payload.location,
|
||||
targetCount: Number(payload.targetCount),
|
||||
reachedCount: Number(payload.reachedCount),
|
||||
});
|
||||
};
|
||||
|
||||
export const getOutcome = async (outcomeId: string | number): Promise<Outcome> => {
|
||||
const hashedOutcomeId = await toolsService.encodeId(outcomeId);
|
||||
const res = await apiClient.get<Outcome>(`/v1/api/projects/outcomes/${hashedOutcomeId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const getBeneficiaryOutcomes = async (beneficiaryId: string | number): Promise<Outcome[]> => {
|
||||
const hashedBeneficiaryId = await toolsService.encodeId(beneficiaryId);
|
||||
const res = await apiClient.get<Outcome[]>(`/v1/api/projects/outcomes/${hashedBeneficiaryId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const createOutcome = async (payload: CreateOutcomeRequest): Promise<void> => {
|
||||
const body = {
|
||||
beneficiaryId: toIntegerId(payload.beneficiaryId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
};
|
||||
try {
|
||||
await apiClient.post('/v1/api/projects/beneficiaris/outcomes', body);
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 404) {
|
||||
await apiClient.post('/v1/api/projects/beneficiaries/outcomes', body);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const updateOutcome = async (payload: UpdateOutcomeRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/outcomes', {
|
||||
outcomeId: toIntegerId(payload.outcomeId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 11. Projects: Change Requests APIs
|
||||
// ==========================================
|
||||
export const getProjectChangeRequests = async (projectId: string | number): Promise<ChangeRequest[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<ChangeRequest[]>(`/v1/api/projects/changerequests/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getChangeRequest = async (changeRequestId: string | number): Promise<ChangeRequest> => {
|
||||
const hashedChangeReqId = await toolsService.encodeId(changeRequestId);
|
||||
const res = await apiClient.get<ChangeRequest>(`/v1/api/projects/changerequests/${hashedChangeReqId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createChangeRequest = async (payload: CreateChangeRequest): Promise<void> => {
|
||||
const revisionDateIso = payload.revisionDate.includes('T')
|
||||
? payload.revisionDate
|
||||
: new Date(payload.revisionDate).toISOString();
|
||||
|
||||
await apiClient.post('/v1/api/projects/changerequests', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
justification: payload.justification,
|
||||
revisedBudget: Number(payload.revisedBudget),
|
||||
revisionDate: revisionDateIso,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateChangeRequest = async (payload: UpdateChangeRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/changerequests', {
|
||||
changeRequestId: toIntegerId(payload.changeRequestId),
|
||||
title: payload.title,
|
||||
justification: payload.justification,
|
||||
revisedBudget: Number(payload.revisedBudget),
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 12. Projects: Compliance Items APIs
|
||||
// ==========================================
|
||||
export const getProjectComplianceItems = async (projectId: string | number): Promise<ComplianceItem[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<ComplianceItem[]>(`/v1/api/projects/complianceitems/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getComplianceItem = async (complianceItemId: string | number): Promise<ComplianceItem> => {
|
||||
const hashedItemId = await toolsService.encodeId(complianceItemId);
|
||||
const res = await apiClient.get<ComplianceItem>(`/v1/api/projects/complianceitems/${hashedItemId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createComplianceItem = async (payload: CreateComplianceItemRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/complianceitems', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
requirements: payload.requirements,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateComplianceItem = async (payload: UpdateComplianceItemRequest): Promise<void> => {
|
||||
await apiClient.put('/v1/api/projects/complianceitems', {
|
||||
complianceItemId: toIntegerId(payload.complianceItemId),
|
||||
title: payload.title,
|
||||
requirements: payload.requirements,
|
||||
status: Number(payload.status),
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 13. Projects: Issues APIs
|
||||
// ==========================================
|
||||
export const getProjectIssues = async (projectId: string | number): Promise<Issue[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<Issue[]>(`/v1/api/projects/issues/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getIssue = async (issueId: string | number): Promise<Issue> => {
|
||||
const hashedIssueId = await toolsService.encodeId(issueId);
|
||||
const res = await apiClient.get<Issue>(`/v1/api/projects/issues/${hashedIssueId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createIssue = async (payload: CreateIssueRequest): Promise<void> => {
|
||||
await apiClient.post('/v1/api/projects/issues', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
title: payload.title,
|
||||
description: payload.description,
|
||||
priority: Number(payload.priority),
|
||||
assignedTo: payload.assignedTo,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateIssue = async (payload: UpdateIssueRequest): Promise<void> => {
|
||||
const resolvedAtIso = payload.resolvedAt
|
||||
? (payload.resolvedAt.includes('T') ? payload.resolvedAt : new Date(payload.resolvedAt).toISOString())
|
||||
: null;
|
||||
|
||||
await apiClient.put('/v1/api/projects/issues', {
|
||||
issueId: toIntegerId(payload.issueId),
|
||||
title: payload.title,
|
||||
description: payload.description,
|
||||
resolution: payload.resolution,
|
||||
resolvedAt: resolvedAtIso,
|
||||
priority: Number(payload.priority),
|
||||
status: Number(payload.status),
|
||||
assignedTo: payload.assignedTo,
|
||||
});
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 14. Projects: Site Visits APIs
|
||||
// ==========================================
|
||||
export const getProjectSiteVisits = async (projectId: string | number): Promise<SiteVisit[]> => {
|
||||
const hashedProjectId = await toolsService.resolveProjectId(projectId);
|
||||
const res = await apiClient.get<SiteVisit[]>(`/v1/api/projects/sitevisits/${hashedProjectId}`);
|
||||
return res.data || [];
|
||||
};
|
||||
|
||||
export const getSiteVisit = async (siteVisitId: string | number): Promise<SiteVisit> => {
|
||||
const hashedVisitId = await toolsService.encodeId(siteVisitId);
|
||||
const res = await apiClient.get<SiteVisit>(`/v1/api/projects/sitevisits/${hashedVisitId}`);
|
||||
return res.data;
|
||||
};
|
||||
|
||||
export const createSiteVisit = async (payload: CreateSiteVisitRequest): Promise<void> => {
|
||||
const visitedAtIso = payload.visitedAt.includes('T')
|
||||
? payload.visitedAt
|
||||
: new Date(payload.visitedAt).toISOString();
|
||||
|
||||
await apiClient.post('/v1/api/projects/sitevisits', {
|
||||
projectId: toIntegerId(payload.projectId),
|
||||
inspectorName: payload.inspectorName,
|
||||
findings: payload.findings,
|
||||
visitedAt: visitedAtIso,
|
||||
});
|
||||
};
|
||||
|
||||
export const updateSiteVisit = async (payload: UpdateSiteVisitRequest): Promise<void> => {
|
||||
const visitedAtIso = payload.visitedAt.includes('T')
|
||||
? payload.visitedAt
|
||||
: new Date(payload.visitedAt).toISOString();
|
||||
|
||||
await apiClient.put('/v1/api/projects/sitevisits', {
|
||||
siteVisitId: toIntegerId(payload.siteVisitId),
|
||||
inspectorName: payload.inspectorName,
|
||||
findings: payload.findings,
|
||||
status: Number(payload.status),
|
||||
visitedAt: visitedAtIso,
|
||||
});
|
||||
};
|
||||
|
||||
const LOCAL_RULES_KEY = 'pfm_local_rules';
|
||||
|
||||
export const getStoredRules = (): Rule[] => {
|
||||
if (typeof window === 'undefined') return [];
|
||||
try {
|
||||
const raw = localStorage.getItem(LOCAL_RULES_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const saveStoredRule = (rule: Rule): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const current = getStoredRules();
|
||||
const idx = current.findIndex((r) => String(r.id) === String(rule.id));
|
||||
if (idx >= 0) {
|
||||
current[idx] = { ...current[idx], ...rule, updatedAt: new Date().toISOString() };
|
||||
} else {
|
||||
current.unshift(rule);
|
||||
}
|
||||
localStorage.setItem(LOCAL_RULES_KEY, JSON.stringify(current));
|
||||
} catch (e) {
|
||||
console.warn('Failed to save stored rule', e);
|
||||
}
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 15. Execution: Programme Rules APIs
|
||||
// ==========================================
|
||||
export const getRule = async (ruleId: string | number): Promise<Rule> => {
|
||||
const localRule = getStoredRules().find((r) => String(r.id) === String(ruleId));
|
||||
try {
|
||||
const hashedRuleId = await toolsService.encodeId(ruleId);
|
||||
const res = await apiClient.get<Rule>(`/v1/api/execution/rules/${hashedRuleId}`);
|
||||
return res.data || localRule!;
|
||||
} catch {
|
||||
if (localRule) return localRule;
|
||||
throw new Error('Rule not found');
|
||||
}
|
||||
};
|
||||
|
||||
export const getRules = async (
|
||||
pagination: Pagination = { page: 1, pageSize: 100 },
|
||||
programmeId?: string | number
|
||||
): Promise<Rule[]> => {
|
||||
let apiRules: Rule[] = [];
|
||||
try {
|
||||
const res = await apiClient.post<Rule[]>('/v1/api/execution/programmes/rules', {
|
||||
index: pagination.index ? toIntegerId(pagination.index) : 0,
|
||||
page: pagination.page || 1,
|
||||
pageSize: pagination.pageSize || 100,
|
||||
});
|
||||
apiRules = res.data || [];
|
||||
} catch (err) {
|
||||
console.warn('[getRules] Error fetching from backend API:', err);
|
||||
}
|
||||
|
||||
const localRules = getStoredRules();
|
||||
const map = new Map<string, Rule>();
|
||||
apiRules.forEach((r) => map.set(String(r.id), r));
|
||||
localRules.forEach((r) => map.set(String(r.id), r));
|
||||
|
||||
let combined = Array.from(map.values());
|
||||
if (programmeId != null && programmeId !== '' && programmeId !== 'all') {
|
||||
combined = combined.filter((r) => String(r.programmeId) === String(programmeId));
|
||||
}
|
||||
return combined;
|
||||
};
|
||||
|
||||
export const createRule = async (payload: CreateRuleRequest): Promise<Rule> => {
|
||||
const newId = Date.now();
|
||||
const newRule: Rule = {
|
||||
id: newId,
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: ActivityStatus.Active,
|
||||
version: 1,
|
||||
createdBy: payload.userId,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await apiClient.post('/v1/api/execution/rules', {
|
||||
programmeId: toIntegerId(payload.programmeId),
|
||||
userId: payload.userId,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[createRule] API create failed, persisted locally:', err);
|
||||
}
|
||||
|
||||
saveStoredRule(newRule);
|
||||
return newRule;
|
||||
};
|
||||
|
||||
export const updateRule = async (payload: UpdateRuleRequest): Promise<void> => {
|
||||
try {
|
||||
await apiClient.put('/v1/api/execution/rules', {
|
||||
ruleId: toIntegerId(payload.ruleId),
|
||||
userId: payload.userId,
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
version: Number(payload.version),
|
||||
...(payload.programmeId ? { programmeId: toIntegerId(payload.programmeId) } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[updateRule] API update failed, updated locally:', err);
|
||||
}
|
||||
|
||||
const existing = getStoredRules().find((r) => String(r.id) === String(payload.ruleId));
|
||||
const updatedRule: Rule = {
|
||||
id: payload.ruleId,
|
||||
programmeId: payload.programmeId ? toIntegerId(payload.programmeId) : (existing?.programmeId || 0),
|
||||
name: payload.name,
|
||||
description: payload.description,
|
||||
status: Number(payload.status),
|
||||
version: Number(payload.version),
|
||||
createdBy: existing?.createdBy || payload.userId,
|
||||
createdAt: existing?.createdAt || new Date().toISOString(),
|
||||
updatedBy: payload.userId,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
saveStoredRule(updatedRule);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import axios, { InternalAxiosRequestConfig } from 'axios';
|
||||
import { getApiBaseUrl } from '../config';
|
||||
import { triggerSessionExpired, isUserSyncEndpoint } from './sessionExpiration';
|
||||
import { triggerSessionExpired, isUserSyncEndpoint, isTenantEndpoint } from './sessionExpiration';
|
||||
import { isUserSyncedInBrowser, isActivationPending, syncUserAccount } from './userSyncService';
|
||||
|
||||
export const BASE_API_URL = getApiBaseUrl();
|
||||
@@ -25,10 +25,10 @@ apiClient.interceptors.request.use(
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// User Sync Guard:
|
||||
// User Sync & Tenant Lifecycle Guard:
|
||||
// All API calls require an authenticated and enabled user in the backend system.
|
||||
const isSyncRequest = isUserSyncEndpoint(config.url);
|
||||
if (token && !isSyncRequest) {
|
||||
const isLifecycleRequest = isUserSyncEndpoint(config.url) || isTenantEndpoint(config.url);
|
||||
if (token && !isLifecycleRequest) {
|
||||
// If user account is flagged as pending administrator activation, block downstream API calls
|
||||
if (isActivationPending()) {
|
||||
return Promise.reject(new Error('User account is pending administrator activation'));
|
||||
@@ -54,10 +54,10 @@ apiClient.interceptors.response.use(
|
||||
(error) => {
|
||||
if (error?.response?.status === 401) {
|
||||
const requestUrl = error.config?.url;
|
||||
const isSyncEndpoint = isUserSyncEndpoint(requestUrl);
|
||||
const isLifecycleEndpoint = isUserSyncEndpoint(requestUrl) || isTenantEndpoint(requestUrl);
|
||||
|
||||
// Handle 401 Unauthorized errors
|
||||
if (!isSyncEndpoint) {
|
||||
if (!isLifecycleEndpoint) {
|
||||
// Working endpoint returned HTTP 401: trigger session expiration prompt
|
||||
const detailMsg =
|
||||
error?.response?.data?.detail ||
|
||||
|
||||
@@ -24,6 +24,15 @@ export function isUserSyncEndpoint(url?: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a given URL or request path targets a tenant lifecycle/governance endpoint.
|
||||
*/
|
||||
export function isTenantEndpoint(url?: string): boolean {
|
||||
if (!url) return false;
|
||||
const clean = url.toLowerCase().split('?')[0];
|
||||
return clean.includes('/governance/tenants');
|
||||
}
|
||||
|
||||
type SessionExpiredListener = (reason?: string) => void;
|
||||
|
||||
const listeners = new Set<SessionExpiredListener>();
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { getTenant } from './api';
|
||||
import { ActivityStatus, Tenant } from '../types';
|
||||
import { setActivationPending } from './userSyncService';
|
||||
|
||||
export interface TenantLockoutResult {
|
||||
isActive: boolean;
|
||||
tenant: Tenant | null;
|
||||
errorMessage?: string;
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given status value corresponds to ActivityStatus.Active (1)
|
||||
*/
|
||||
export function isStatusActive(status: any): boolean {
|
||||
if (status === undefined || status === null || status === '') {
|
||||
return false;
|
||||
}
|
||||
if (status === ActivityStatus.Active || status === 1 || status === '1') {
|
||||
return true;
|
||||
}
|
||||
if (typeof status === 'string' && status.trim().toLowerCase() === 'active') {
|
||||
return true;
|
||||
}
|
||||
if (status === true) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a human-readable status label from numeric or string status
|
||||
*/
|
||||
export function getStatusLabel(status: any): string {
|
||||
if (status === ActivityStatus.Active || status === 1 || String(status).toLowerCase() === 'active') {
|
||||
return 'Active';
|
||||
}
|
||||
if (status === ActivityStatus.Inactive || status === 2 || String(status).toLowerCase() === 'inactive') {
|
||||
return 'Inactive';
|
||||
}
|
||||
if (status === ActivityStatus.Disabled || status === 3 || String(status).toLowerCase() === 'disabled') {
|
||||
return 'Disabled';
|
||||
}
|
||||
if (String(status).toLowerCase() === 'suspended') {
|
||||
return 'Suspended';
|
||||
}
|
||||
if (status === 0 || String(status).toLowerCase() === 'pending') {
|
||||
return 'Pending';
|
||||
}
|
||||
if (status !== undefined && status !== null && status !== '') {
|
||||
return String(status);
|
||||
}
|
||||
return 'Not Specified';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls the GetTenant endpoint for the provided tenant identifier.
|
||||
*
|
||||
* Rules:
|
||||
* - If nothing is returned (empty response, 404, or failure) OR
|
||||
* - There is a response object and its Status is not Active
|
||||
* Then lockout is triggered and the existing lockout modal is shown.
|
||||
*/
|
||||
export async function verifyTenantLockout(
|
||||
tenantId?: number | string | null,
|
||||
tenantClaim?: string | null
|
||||
): Promise<TenantLockoutResult> {
|
||||
const primaryId =
|
||||
tenantId !== undefined && tenantId !== null && tenantId !== ''
|
||||
? tenantId
|
||||
: tenantClaim !== undefined && tenantClaim !== null && tenantClaim !== ''
|
||||
? tenantClaim
|
||||
: null;
|
||||
|
||||
if (primaryId === null || primaryId === undefined || primaryId === '') {
|
||||
const errorMsg =
|
||||
'Tenant identification claims (tenant / tenant_id) not found in credentials. Access is restricted.';
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: null,
|
||||
errorMessage: errorMsg,
|
||||
};
|
||||
}
|
||||
|
||||
let tenantRes: Tenant | null = null;
|
||||
let lastError: any = null;
|
||||
|
||||
try {
|
||||
tenantRes = await getTenant(primaryId);
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
tenantRes = null;
|
||||
}
|
||||
|
||||
// If primary identifier returned nothing, and tenantClaim provides a different candidate, attempt fallback
|
||||
if (!tenantRes && tenantClaim && String(tenantClaim) !== String(primaryId)) {
|
||||
try {
|
||||
tenantRes = await getTenant(tenantClaim);
|
||||
lastError = null;
|
||||
} catch (err: any) {
|
||||
lastError = err;
|
||||
tenantRes = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Condition 1: If nothing is returned
|
||||
if (!tenantRes || (typeof tenantRes === 'object' && Object.keys(tenantRes).length === 0)) {
|
||||
const serverMsg =
|
||||
lastError?.response?.data?.detail ||
|
||||
lastError?.response?.data?.message ||
|
||||
lastError?.message ||
|
||||
'No tenant record returned';
|
||||
|
||||
const errorMsg = `Tenant record could not be retrieved (${serverMsg}). Account is locked out.`;
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: null,
|
||||
errorMessage: errorMsg,
|
||||
statusCode: lastError?.response?.status,
|
||||
};
|
||||
}
|
||||
|
||||
// Handle wrapped response structures: { data: { ... } } or { result: { ... } }
|
||||
const tenantObj: Tenant = (tenantRes as any)?.data || (tenantRes as any)?.result || tenantRes;
|
||||
|
||||
// Condition 2: If there is a response object and its Status is not Active
|
||||
const rawStatus =
|
||||
(tenantObj as any)?.status ??
|
||||
(tenantObj as any)?.Status ??
|
||||
(tenantObj as any)?.activityStatus ??
|
||||
(tenantObj as any)?.ActivityStatus;
|
||||
|
||||
const active = isStatusActive(rawStatus);
|
||||
|
||||
if (!active) {
|
||||
const statusLabel = getStatusLabel(rawStatus);
|
||||
const tenantName = tenantObj?.name || String(primaryId);
|
||||
const errorMsg = `Tenant account "${tenantName}" is not Active (Status: ${statusLabel}). Account is locked out.`;
|
||||
setActivationPending(true, errorMsg);
|
||||
return {
|
||||
isActive: false,
|
||||
tenant: tenantObj,
|
||||
errorMessage: errorMsg,
|
||||
};
|
||||
}
|
||||
|
||||
// Success: Response object returned and Status is Active
|
||||
return {
|
||||
isActive: true,
|
||||
tenant: tenantObj,
|
||||
};
|
||||
}
|
||||
@@ -327,8 +327,8 @@ export async function syncUserAccount(
|
||||
// Non-401 error: Account is registered/authenticated, but administrator has not enabled it yet
|
||||
clearSuccessfulSyncRecord();
|
||||
const serverMsg =
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.detail ||
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.error ||
|
||||
err?.message ||
|
||||
'Account is not yet enabled by the administrator.';
|
||||
|
||||
@@ -320,6 +320,7 @@ export interface UpdateOrganisationRequest {
|
||||
|
||||
export interface Portfolio {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
@@ -346,6 +347,7 @@ export interface UpdatePortfolioRequest {
|
||||
export interface Programme {
|
||||
id: number | string;
|
||||
portfolioId: number | string;
|
||||
tenantId?: number | string;
|
||||
name: string | null;
|
||||
status: ApprovalStatus;
|
||||
ownedBy: string;
|
||||
@@ -372,17 +374,42 @@ export interface UpdateProgrammeRequest {
|
||||
export interface Instrument {
|
||||
id: number | string;
|
||||
programmeId: number | string;
|
||||
tenantId?: number | string;
|
||||
code: string | null;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
status: ActivityStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
updatedBy?: string | null;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export type Instruction = Instrument;
|
||||
|
||||
export interface CreateInstructionRequest {
|
||||
programmeId: number | string;
|
||||
code?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status?: ActivityStatus;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface UpdateInstructionRequest {
|
||||
instructionId: number | string;
|
||||
programmeId?: number | string;
|
||||
code?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status: ActivityStatus;
|
||||
userId?: string;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: number | string;
|
||||
programmeId: number | string;
|
||||
tenantId?: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
sector: IndustrySector;
|
||||
@@ -422,6 +449,7 @@ export interface UpdateProjectStatusRequest {
|
||||
|
||||
export interface Activity {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string | null;
|
||||
milestoneId: number | string | null;
|
||||
category: string | null;
|
||||
@@ -461,6 +489,7 @@ export interface UpdateActivityRequest {
|
||||
|
||||
export interface Milestone {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
dueAt: string;
|
||||
@@ -490,6 +519,7 @@ export interface UpdateMilestoneRequest {
|
||||
export interface Award {
|
||||
id: number | string;
|
||||
organisationId: number | string;
|
||||
tenantId?: number | string;
|
||||
programmeId: number | string;
|
||||
projectId?: number | string | null;
|
||||
amount: number;
|
||||
@@ -514,6 +544,7 @@ export interface CreateAwardRequest {
|
||||
|
||||
export interface Contract {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
awardId: number | string;
|
||||
totalValue: number;
|
||||
effectiveAt?: string | null;
|
||||
@@ -545,6 +576,7 @@ export interface ExecuteContractRequest {
|
||||
|
||||
export interface Budget {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
amount: number;
|
||||
@@ -562,6 +594,7 @@ export interface CreateBudgetRequest {
|
||||
|
||||
export interface Disbursement {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
milestoneId?: number | string | null;
|
||||
amount: number;
|
||||
@@ -588,6 +621,7 @@ export interface UpdateDisbursementRequest {
|
||||
|
||||
export interface Indicator {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
unitOfMeasure?: UnitOfMeasure | null;
|
||||
@@ -608,6 +642,7 @@ export interface CreateIndicatorRequest {
|
||||
|
||||
export interface Risk {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
@@ -638,6 +673,7 @@ export interface UpdateRiskRequest {
|
||||
|
||||
export interface Evidence {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
milestoneId?: number | string | null;
|
||||
indicatorId?: number | string | null;
|
||||
@@ -663,6 +699,7 @@ export interface UpdateEvidenceRequest {
|
||||
|
||||
export interface Invite {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
invitedOrganisationId: number | string;
|
||||
awardId: number | string;
|
||||
@@ -685,3 +722,254 @@ export interface InviteRequest {
|
||||
message: string;
|
||||
platform: NotificationPlatform;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// New OpenAPI 3.1.1 Entities & Request Models
|
||||
// ==========================================
|
||||
|
||||
export interface Tenant {
|
||||
id: number | string;
|
||||
name: string | null;
|
||||
status?: ActivityStatus;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
updatedBy?: string | null;
|
||||
updatedAt?: string | null;
|
||||
creator?: User | null;
|
||||
updator?: User | null;
|
||||
}
|
||||
|
||||
export interface CreateTenantRequest {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UpdateTenantRequest {
|
||||
tenantId: number | string;
|
||||
name: string;
|
||||
status: ActivityStatus;
|
||||
}
|
||||
|
||||
export interface Beneficiary {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
userId?: string;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
name: string | null;
|
||||
category: string | null;
|
||||
targetCount?: number;
|
||||
reachedCount?: number;
|
||||
location: string | null;
|
||||
}
|
||||
|
||||
export interface CreateBeneficiaryRequest {
|
||||
projectId: number | string;
|
||||
name: string;
|
||||
category: string;
|
||||
location: string;
|
||||
targetCount: number;
|
||||
reachedCount: number;
|
||||
}
|
||||
|
||||
export interface UpdateBeneficiaryRequest {
|
||||
beneficiaryId: number | string;
|
||||
name: string;
|
||||
category: string;
|
||||
location: string;
|
||||
targetCount: number;
|
||||
reachedCount: number;
|
||||
}
|
||||
|
||||
export interface Outcome {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
beneficiaryId: number | string;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
createdBy?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateOutcomeRequest {
|
||||
beneficiaryId: number | string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface UpdateOutcomeRequest {
|
||||
outcomeId: number | string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface ChangeRequest {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
justification: string | null;
|
||||
revisedBudget?: number | null;
|
||||
revisedEndedAt?: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
approvedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateChangeRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
justification: string;
|
||||
revisedBudget: number;
|
||||
revisionDate: string;
|
||||
}
|
||||
|
||||
export interface UpdateChangeRequest {
|
||||
changeRequestId: number | string;
|
||||
title: string;
|
||||
justification: string;
|
||||
revisedBudget: number;
|
||||
status: ApprovalStatus;
|
||||
}
|
||||
|
||||
export interface ComplianceItem {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
requirements: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
verifiedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateComplianceItemRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
requirements: string;
|
||||
}
|
||||
|
||||
export interface UpdateComplianceItemRequest {
|
||||
complianceItemId: number | string;
|
||||
title: string;
|
||||
requirements: string;
|
||||
status: ApprovalStatus;
|
||||
}
|
||||
|
||||
export interface Issue {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
title: string | null;
|
||||
description: string | null;
|
||||
priority: Priority;
|
||||
status: ActivityStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
assignedTo?: string | null;
|
||||
resolvedAt?: string | null;
|
||||
resolution?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateIssueRequest {
|
||||
projectId: number | string;
|
||||
title: string;
|
||||
description: string;
|
||||
priority: Priority;
|
||||
assignedTo: string;
|
||||
}
|
||||
|
||||
export interface UpdateIssueRequest {
|
||||
issueId: number | string;
|
||||
title: string;
|
||||
description: string;
|
||||
resolution: string;
|
||||
resolvedAt?: string | null;
|
||||
priority: Priority;
|
||||
status: ActivityStatus;
|
||||
assignedTo: string;
|
||||
}
|
||||
|
||||
export interface SiteVisit {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
projectId: number | string;
|
||||
visitedAt: string;
|
||||
inspectorName: string | null;
|
||||
findings: string | null;
|
||||
status: ApprovalStatus;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CreateSiteVisitRequest {
|
||||
projectId: number | string;
|
||||
inspectorName: string;
|
||||
findings: string;
|
||||
visitedAt: string;
|
||||
}
|
||||
|
||||
export interface UpdateSiteVisitRequest {
|
||||
siteVisitId: number | string;
|
||||
inspectorName: string;
|
||||
findings: string;
|
||||
status: ApprovalStatus;
|
||||
visitedAt: string;
|
||||
}
|
||||
|
||||
export interface Rule {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
programmeId: number | string;
|
||||
createdBy: string;
|
||||
updatedBy?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt?: string | null;
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
version?: number;
|
||||
status: ActivityStatus;
|
||||
}
|
||||
|
||||
export interface CreateRuleRequest {
|
||||
programmeId: number | string;
|
||||
userId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface UpdateRuleRequest {
|
||||
ruleId: number | string;
|
||||
userId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
status: ActivityStatus;
|
||||
version: number;
|
||||
programmeId?: number | string;
|
||||
}
|
||||
|
||||
export interface Pagination {
|
||||
index?: number | string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface Notification {
|
||||
id: number | string;
|
||||
tenantId?: number | string;
|
||||
organisationId: number | string;
|
||||
recipient: string;
|
||||
platform: NotificationPlatform;
|
||||
status: NotificationStatus;
|
||||
subject: string | null;
|
||||
message: string | null;
|
||||
destination: string | null;
|
||||
createdAt: string;
|
||||
sentAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
@@ -15,64 +15,23 @@ export interface FriendlyError {
|
||||
title: string;
|
||||
message: string;
|
||||
statusCode?: number;
|
||||
hasReturnObject: boolean;
|
||||
isProblemDetails: boolean;
|
||||
category: ErrorCategory;
|
||||
categoryLabel?: string;
|
||||
fieldErrors?: Array<{ field: string; message: string }>;
|
||||
errorsList?: string[];
|
||||
fieldErrors?: Array<{ field: string; message: string }>;
|
||||
technicalDetails?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts camelCase or PascalCase field names to human-readable titles.
|
||||
* e.g. "HashId" -> "Resource Identifier", "startDate" -> "Start Date"
|
||||
*/
|
||||
function humanizeFieldName(field: string): string {
|
||||
if (!field) return 'Field';
|
||||
|
||||
const customMappings: Record<string, string> = {
|
||||
hashid: 'Resource Identifier (HashId)',
|
||||
id: 'Record ID',
|
||||
sub: 'User Identity',
|
||||
orgid: 'Organisation',
|
||||
organisationid: 'Organisation',
|
||||
portfolioid: 'Portfolio',
|
||||
programmeid: 'Programme',
|
||||
projectid: 'Project',
|
||||
grantid: 'Award',
|
||||
awardid: 'Award',
|
||||
contractid: 'Contract',
|
||||
budgetid: 'Budget',
|
||||
disbursementid: 'Disbursement',
|
||||
indicatorid: 'Indicator',
|
||||
riskid: 'Risk',
|
||||
email: 'Email Address',
|
||||
name: 'Name',
|
||||
title: 'Title',
|
||||
code: 'Reference Code',
|
||||
startdate: 'Start Date',
|
||||
enddate: 'End Date',
|
||||
targetdate: 'Target Date',
|
||||
actualdate: 'Actual Date',
|
||||
amount: 'Amount',
|
||||
budgetamount: 'Budget Amount',
|
||||
targetvalue: 'Target Value',
|
||||
actualvalue: 'Actual Value',
|
||||
baselinevalue: 'Baseline Value',
|
||||
status: 'Status',
|
||||
governancestatus: 'Governance Status',
|
||||
contractstatus: 'Contract Status',
|
||||
disbursementstatus: 'Disbursement Status',
|
||||
};
|
||||
|
||||
const lower = field.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
if (customMappings[lower]) {
|
||||
return customMappings[lower];
|
||||
}
|
||||
|
||||
// Insert space before uppercase letters
|
||||
const spaced = field.replace(/([a-z])([A-Z])/g, '$1 $2');
|
||||
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
||||
export interface ProblemDetailsResponse {
|
||||
type?: string | null;
|
||||
title?: string | null;
|
||||
status?: number | null;
|
||||
detail?: string | null;
|
||||
instance?: string | null;
|
||||
errors?: Record<string, string[] | string> | any;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,7 +39,6 @@ function humanizeFieldName(field: string): string {
|
||||
*/
|
||||
export function isRawHttpOutput(text: string): boolean {
|
||||
if (!text || typeof text !== 'string') return false;
|
||||
// If it has multiple header-like lines or standard HTTP request/response signatures
|
||||
const headerPatterns = [
|
||||
/^(?:accept|authorization|content-type|content-length|origin|referer|user-agent|sec-ch-ua|sec-fetch|x-forwarded|x-real-ip|host):/im,
|
||||
/(?:authorization:\s*bearer|content-type:\s*application\/)/i,
|
||||
@@ -114,10 +72,9 @@ export function sanitizeTechnicalDetails(text: string): string {
|
||||
/**
|
||||
* Cleans technical jargon, stack traces, and framework namespaces from text strings.
|
||||
*/
|
||||
function cleanTechnicalJargon(text: string): string {
|
||||
export function cleanTechnicalJargon(text: string): string {
|
||||
if (!text) return '';
|
||||
|
||||
// If text is a raw HTTP dump, do not return it as clean user text
|
||||
if (isRawHttpOutput(text)) {
|
||||
return '';
|
||||
}
|
||||
@@ -132,7 +89,7 @@ function cleanTechnicalJargon(text: string): string {
|
||||
.replace(/at\s+[a-zA-Z0-9_.]+\s*\(.*?\)/g, '')
|
||||
.trim();
|
||||
|
||||
// In this system, ProblemDetails title is always "Error" — ignore trivial or generic "Error" strings
|
||||
// In this system, ProblemDetails title is typically "Error" — ignore trivial or generic "Error" strings
|
||||
if (cleaned.length < 2 || cleaned === '[object Object]' || cleaned.toLowerCase() === 'error') {
|
||||
return '';
|
||||
}
|
||||
@@ -141,7 +98,42 @@ function cleanTechnicalJargon(text: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a response object conforms to RFC 7807 / RFC 9457 ProblemDetails.
|
||||
* Safely inspects whether an error contains a valid response body object.
|
||||
* Note: not all error responses will have a return object, so this method explicitly checks.
|
||||
*/
|
||||
export function inspectErrorResponseObject(error: unknown): ProblemDetailsResponse | null {
|
||||
if (!error) return null;
|
||||
|
||||
// 1. Inspect Axios error or error with response structure
|
||||
const anyErr = error as any;
|
||||
const data = anyErr?.response?.data;
|
||||
if (data && typeof data === 'object') {
|
||||
return data as ProblemDetailsResponse;
|
||||
}
|
||||
// Check if response body is a JSON string
|
||||
if (typeof data === 'string' && data.trim().startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(data.trim());
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
return parsed as ProblemDetailsResponse;
|
||||
}
|
||||
} catch {
|
||||
// Not a JSON object
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Direct object inspection (e.g. if response.data was passed directly)
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
if ('detail' in anyErr || 'status' in anyErr || 'title' in anyErr || 'type' in anyErr) {
|
||||
return anyErr as ProblemDetailsResponse;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a response object conforms to RFC 7807 / RFC 9110 ProblemDetails.
|
||||
*/
|
||||
export function isProblemDetailsObject(data: any): data is ProblemDetails {
|
||||
if (!data || typeof data !== 'object') return false;
|
||||
@@ -151,11 +143,35 @@ export function isProblemDetailsObject(data: any): data is ProblemDetails {
|
||||
'status' in data ||
|
||||
'type' in data ||
|
||||
'errors' in data ||
|
||||
'Errors' in data ||
|
||||
'errorList' in data
|
||||
'Errors' in data
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a comma-delimited error list from the `detail` property.
|
||||
* e.g. "Failed to update organisation" -> ["Failed to update organisation"]
|
||||
* e.g. "Invalid organisation name, Budget exceeds ceiling, Target date cannot be in past"
|
||||
* -> ["Invalid organisation name", "Budget exceeds ceiling", "Target date cannot be in past"]
|
||||
*/
|
||||
export function parseCommaDelimitedErrors(detail?: string | null): string[] {
|
||||
if (!detail || typeof detail !== 'string') return [];
|
||||
const trimmed = detail.trim();
|
||||
if (!trimmed) return [];
|
||||
|
||||
// Split by comma
|
||||
const rawParts = trimmed.split(',');
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const part of rawParts) {
|
||||
const cleaned = cleanTechnicalJargon(part.trim());
|
||||
if (cleaned && cleaned.length > 0) {
|
||||
errors.push(cleaned);
|
||||
}
|
||||
}
|
||||
|
||||
return errors.length > 0 ? errors : [trimmed];
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects whether the user action context was an entity creation or an update.
|
||||
*/
|
||||
@@ -204,81 +220,46 @@ function detectOperationIntent(
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts and formats human-friendly error guidance from any error,
|
||||
* accessing the ProblemDetails `errors` array directly to display the error.
|
||||
* In this system the title field is always "Error", so no generic error testing is performed.
|
||||
* Comprehensive common error handling function across the application.
|
||||
*
|
||||
* Handles standard RFC 9110 / RFC 7807 error responses:
|
||||
* {
|
||||
* "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
|
||||
* "title": "Error",
|
||||
* "status": 400,
|
||||
* "detail": "Failed to update organisation"
|
||||
* }
|
||||
*
|
||||
* - Parses comma-delimited error list in the `detail` property.
|
||||
* - Handles authentication (401) and forbidden (403) specifically.
|
||||
* - Explicitly inspects whether a return object exists, handling responses without return objects gracefully.
|
||||
*/
|
||||
export function parseFriendlyError(
|
||||
error: unknown,
|
||||
fallbackActionTitle = 'Action Failed'
|
||||
): FriendlyError {
|
||||
let statusCode: number | undefined;
|
||||
let rawTitle: string | undefined;
|
||||
let rawDetail: string | undefined;
|
||||
let rawErrors: any = undefined;
|
||||
let isProblemDetails = false;
|
||||
let rawResponseData: any = null;
|
||||
let technicalSummary = '';
|
||||
let httpMethod = '';
|
||||
let requestUrl = '';
|
||||
|
||||
// 1. Inspect Axios error structure
|
||||
// 1. Inspect error metadata if available
|
||||
const anyErr = error as any;
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosErr = error as AxiosError<any>;
|
||||
statusCode = axiosErr.response?.status;
|
||||
rawResponseData = axiosErr.response?.data;
|
||||
httpMethod = axiosErr.config?.method?.toUpperCase() || '';
|
||||
requestUrl = axiosErr.config?.url || '';
|
||||
technicalSummary = `${httpMethod || 'HTTP'} ${requestUrl} -> ${statusCode || axiosErr.code || 'ERR'}`;
|
||||
|
||||
if (rawResponseData && typeof rawResponseData === 'object') {
|
||||
const dataObj = rawResponseData as any;
|
||||
if (isProblemDetailsObject(dataObj)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = dataObj.title || dataObj.Title || undefined;
|
||||
rawDetail = dataObj.detail || dataObj.Detail || undefined;
|
||||
statusCode = dataObj.status || dataObj.Status || statusCode;
|
||||
rawErrors = dataObj.errors ?? dataObj.Errors ?? dataObj.errorList ?? dataObj.ErrorList;
|
||||
} else if (dataObj.message || dataObj.error || dataObj.errors || dataObj.Errors) {
|
||||
rawDetail = dataObj.message || dataObj.error;
|
||||
rawErrors = dataObj.errors ?? dataObj.Errors;
|
||||
} else if (Array.isArray(dataObj)) {
|
||||
rawErrors = dataObj;
|
||||
}
|
||||
} else if (typeof rawResponseData === 'string') {
|
||||
if (isRawHttpOutput(rawResponseData)) {
|
||||
technicalSummary = sanitizeTechnicalDetails(rawResponseData);
|
||||
rawDetail = undefined;
|
||||
} else {
|
||||
// Check if response data is stringified JSON containing ProblemDetails
|
||||
try {
|
||||
const parsed = JSON.parse(rawResponseData) as any;
|
||||
if (isProblemDetailsObject(parsed)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = parsed.title || parsed.Title || undefined;
|
||||
rawDetail = parsed.detail || parsed.Detail || undefined;
|
||||
statusCode = parsed.status || parsed.Status || statusCode;
|
||||
rawErrors = parsed.errors ?? parsed.Errors ?? parsed.errorList ?? parsed.ErrorList;
|
||||
} else if (Array.isArray(parsed)) {
|
||||
rawErrors = parsed;
|
||||
} else {
|
||||
rawDetail = cleanTechnicalJargon(rawResponseData);
|
||||
}
|
||||
} catch {
|
||||
if (!rawResponseData.includes('<html')) {
|
||||
rawDetail = cleanTechnicalJargon(rawResponseData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Network disconnection or request timeout (no response received)
|
||||
// Network disconnection or request timeout (no response received at all)
|
||||
if (!axiosErr.response) {
|
||||
if (axiosErr.code === 'ECONNABORTED' || axiosErr.message.includes('timeout')) {
|
||||
return {
|
||||
title: 'Request Timed Out',
|
||||
message: 'The server took too long to respond. Please check your network and try again.',
|
||||
message: 'The server took too long to respond. Please check your network connection and try again.',
|
||||
statusCode: 408,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category: 'server',
|
||||
categoryLabel: 'Timeout',
|
||||
@@ -289,244 +270,247 @@ export function parseFriendlyError(
|
||||
title: 'Connection Unavailable',
|
||||
message: 'Unable to reach the system service. Please verify your internet connection or try again in a few moments.',
|
||||
statusCode: 0,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category: 'server',
|
||||
categoryLabel: 'Network',
|
||||
technicalDetails: technicalSummary || axiosErr.message,
|
||||
};
|
||||
}
|
||||
} else if (error && typeof error === 'object') {
|
||||
// 2. Direct ProblemDetails object or custom error object
|
||||
const obj = error as any;
|
||||
if (isProblemDetailsObject(obj)) {
|
||||
isProblemDetails = true;
|
||||
rawTitle = obj.title || obj.Title || undefined;
|
||||
rawDetail = obj.detail || obj.Detail || undefined;
|
||||
statusCode = obj.status || obj.Status || undefined;
|
||||
rawErrors = obj.errors ?? obj.Errors ?? obj.errorList ?? obj.ErrorList;
|
||||
} else if (obj.response?.data && isProblemDetailsObject(obj.response.data)) {
|
||||
isProblemDetails = true;
|
||||
const respData = obj.response.data as any;
|
||||
rawTitle = respData.title || respData.Title || undefined;
|
||||
rawDetail = respData.detail || respData.Detail || undefined;
|
||||
statusCode = obj.response.status || respData.status || respData.Status;
|
||||
rawErrors = respData.errors ?? respData.Errors ?? respData.errorList ?? respData.ErrorList;
|
||||
} else if (Array.isArray(obj)) {
|
||||
rawErrors = obj;
|
||||
} else if (obj.message) {
|
||||
rawDetail = obj.message;
|
||||
const statusMatch = obj.message.match(/status code (\d{3})/i);
|
||||
if (statusMatch) {
|
||||
statusCode = parseInt(statusMatch[1], 10);
|
||||
} else if (anyErr && typeof anyErr === 'object') {
|
||||
statusCode = anyErr.response?.status ?? anyErr.status;
|
||||
httpMethod = anyErr.config?.method?.toUpperCase() || '';
|
||||
requestUrl = anyErr.config?.url || '';
|
||||
if (statusCode) {
|
||||
technicalSummary = `HTTP ${statusCode}`;
|
||||
}
|
||||
}
|
||||
} else if (typeof error === 'string') {
|
||||
// 3. String error
|
||||
const statusMatch = error.match(/status code (\d{3})/i);
|
||||
if (statusMatch) {
|
||||
statusCode = parseInt(statusMatch[1], 10);
|
||||
}
|
||||
rawDetail = cleanTechnicalJargon(error);
|
||||
}
|
||||
|
||||
// Extract errors list directly from ProblemDetails errors array / dictionary
|
||||
const fieldErrors: Array<{ field: string; message: string }> = [];
|
||||
const errorsList: string[] = [];
|
||||
// 2. Inspect for returned response object
|
||||
const returnObject = inspectErrorResponseObject(error);
|
||||
const hasReturnObject = returnObject !== null;
|
||||
|
||||
if (rawErrors) {
|
||||
if (Array.isArray(rawErrors)) {
|
||||
rawErrors.forEach((item) => {
|
||||
if (typeof item === 'string' && item.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(item.trim());
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
} else if (item && typeof item === 'object') {
|
||||
const msg =
|
||||
item.message ||
|
||||
item.errorMessage ||
|
||||
item.detail ||
|
||||
item.error ||
|
||||
item.description ||
|
||||
JSON.stringify(item);
|
||||
const cleaned = cleanTechnicalJargon(String(msg));
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
}
|
||||
});
|
||||
} else if (typeof rawErrors === 'object') {
|
||||
for (const [key, val] of Object.entries(rawErrors)) {
|
||||
const isNumericKey = /^\d+$/.test(key);
|
||||
const fieldTitle = isNumericKey ? '' : humanizeFieldName(key);
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach((msg) => {
|
||||
if (msg) {
|
||||
const cleaned = cleanTechnicalJargon(String(msg));
|
||||
if (cleaned) {
|
||||
if (fieldTitle && !cleaned.toLowerCase().includes(fieldTitle.toLowerCase())) {
|
||||
fieldErrors.push({ field: fieldTitle, message: cleaned });
|
||||
errorsList.push(`${fieldTitle}: ${cleaned}`);
|
||||
} else {
|
||||
errorsList.push(cleaned);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (typeof val === 'string' && val.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(val.trim());
|
||||
if (cleaned) {
|
||||
if (fieldTitle && !cleaned.toLowerCase().includes(fieldTitle.toLowerCase())) {
|
||||
fieldErrors.push({ field: fieldTitle, message: cleaned });
|
||||
errorsList.push(`${fieldTitle}: ${cleaned}`);
|
||||
} else {
|
||||
errorsList.push(cleaned);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (typeof rawErrors === 'string' && rawErrors.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(rawErrors.trim());
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
if (returnObject) {
|
||||
if (returnObject.status && typeof returnObject.status === 'number') {
|
||||
statusCode = returnObject.status;
|
||||
}
|
||||
}
|
||||
|
||||
// Detect operation intent (creation, update, deletion, general)
|
||||
const operationIntent = detectOperationIntent(httpMethod, fallbackActionTitle, requestUrl);
|
||||
|
||||
let friendlyTitle = fallbackActionTitle;
|
||||
let friendlyMessage = '';
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string | undefined = undefined;
|
||||
|
||||
// 3. Special handling for Auth (401) and Forbid (403)
|
||||
if (statusCode === 401) {
|
||||
const rawDetail = returnObject?.detail || (error as any)?.message;
|
||||
const cleanDetail = cleanTechnicalJargon(rawDetail || '');
|
||||
|
||||
// In this system, ProblemDetails allows access to the errors array to display the error directly if available
|
||||
if (errorsList.length > 0) {
|
||||
category = 'validation';
|
||||
categoryLabel =
|
||||
operationIntent === 'creation'
|
||||
? 'Validation'
|
||||
: operationIntent === 'update'
|
||||
? 'Validation'
|
||||
: 'Validation';
|
||||
|
||||
// Display the error directly
|
||||
if (errorsList.length === 1) {
|
||||
friendlyMessage = errorsList[0];
|
||||
} else {
|
||||
friendlyMessage = errorsList.map((err) => `• ${err}`).join('\n');
|
||||
return {
|
||||
title: 'Authentication Required',
|
||||
message: cleanDetail || 'Your authentication session has expired or is unauthorized (HTTP 401). Please sign in again.',
|
||||
statusCode: 401,
|
||||
hasReturnObject,
|
||||
isProblemDetails: hasReturnObject,
|
||||
category: 'security',
|
||||
categoryLabel: 'Unauthorized',
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : 'HTTP 401 Unauthorized',
|
||||
};
|
||||
}
|
||||
|
||||
// If detail provides extra non-duplicate context, include it
|
||||
if (cleanDetail && !errorsList.some((e) => e.toLowerCase() === cleanDetail.toLowerCase())) {
|
||||
friendlyMessage = `${cleanDetail}\n\n${friendlyMessage}`;
|
||||
}
|
||||
} else if (cleanDetail) {
|
||||
// If no errors array, but detail is available, display detail directly
|
||||
friendlyMessage = cleanDetail;
|
||||
if (statusCode === 403) {
|
||||
category = 'security';
|
||||
categoryLabel = 'Access Denied';
|
||||
const rawDetail = returnObject?.detail || (error as any)?.message;
|
||||
const detailErrors = parseCommaDelimitedErrors(rawDetail);
|
||||
const friendlyMessage =
|
||||
detailErrors.length > 0
|
||||
? detailErrors.length === 1
|
||||
? detailErrors[0]
|
||||
: detailErrors.map((err) => `• ${err}`).join('\n')
|
||||
: 'You do not have permission to access this resource or perform this action (HTTP 403).';
|
||||
|
||||
return {
|
||||
title: fallbackActionTitle !== 'Action Failed' ? fallbackActionTitle : 'Access Forbidden',
|
||||
message: friendlyMessage,
|
||||
statusCode: 403,
|
||||
hasReturnObject,
|
||||
isProblemDetails: hasReturnObject,
|
||||
category: 'security',
|
||||
categoryLabel: 'Forbidden',
|
||||
errorsList: detailErrors.length > 0 ? detailErrors : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : 'HTTP 403 Forbidden',
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Case A: Response has a valid return object (e.g. RFC 9110 ProblemDetails)
|
||||
if (hasReturnObject && returnObject) {
|
||||
const rawDetail =
|
||||
returnObject.detail ??
|
||||
returnObject.Detail ??
|
||||
returnObject.message ??
|
||||
returnObject.error;
|
||||
|
||||
// Parse comma-delimited errors from detail property
|
||||
const errorsList = parseCommaDelimitedErrors(rawDetail);
|
||||
|
||||
// If detail was empty, check if errors array/dictionary exists
|
||||
if (errorsList.length === 0 && returnObject.errors) {
|
||||
if (Array.isArray(returnObject.errors)) {
|
||||
returnObject.errors.forEach((e: any) => {
|
||||
const cleaned = cleanTechnicalJargon(typeof e === 'string' ? e : e?.message || JSON.stringify(e));
|
||||
if (cleaned) errorsList.push(cleaned);
|
||||
});
|
||||
} else if (typeof returnObject.errors === 'object') {
|
||||
for (const [key, val] of Object.entries(returnObject.errors)) {
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach((m) => {
|
||||
const cleaned = cleanTechnicalJargon(String(m));
|
||||
if (cleaned) errorsList.push(`${key}: ${cleaned}`);
|
||||
});
|
||||
} else if (typeof val === 'string' && val.trim()) {
|
||||
const cleaned = cleanTechnicalJargon(val);
|
||||
if (cleaned) errorsList.push(`${key}: ${cleaned}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string = 'Error';
|
||||
|
||||
if (statusCode === 400) {
|
||||
if (operationIntent === 'creation') {
|
||||
category = 'creation';
|
||||
categoryLabel = 'Creation Error';
|
||||
} else if (operationIntent === 'update') {
|
||||
category = 'update';
|
||||
categoryLabel = 'Update Error';
|
||||
} else {
|
||||
category = 'validation';
|
||||
categoryLabel = 'Validation Error';
|
||||
}
|
||||
} else if (statusCode === 404) {
|
||||
category = 'notFound';
|
||||
categoryLabel = 'Not Found';
|
||||
} else if (statusCode === 409) {
|
||||
category = 'conflict';
|
||||
categoryLabel = 'Conflict';
|
||||
} else if (statusCode === 422) {
|
||||
category = 'validation';
|
||||
categoryLabel = 'Validation Error';
|
||||
} else if (statusCode && statusCode >= 500) {
|
||||
category = 'server';
|
||||
categoryLabel = 'Service Issue';
|
||||
categoryLabel = 'Server Error';
|
||||
}
|
||||
|
||||
// Format display message from errorsList
|
||||
let friendlyMessage = '';
|
||||
if (errorsList.length > 1) {
|
||||
friendlyMessage = errorsList.map((err) => `• ${err}`).join('\n');
|
||||
} else if (errorsList.length === 1) {
|
||||
friendlyMessage = errorsList[0];
|
||||
} else {
|
||||
// Fallback status-specific messaging when neither errors array nor detail is available
|
||||
switch (statusCode) {
|
||||
case 403:
|
||||
category = 'security';
|
||||
categoryLabel = 'Invalid Identifier / Forbid';
|
||||
friendlyTitle = 'Access Not Permitted or Invalid Identifier';
|
||||
// Fallback message if detail was empty string
|
||||
friendlyMessage =
|
||||
'The reference identifier (hash ID) is invalid, expired, or you do not have permission to access this item. Please verify your selection or contact your system administrator.';
|
||||
operationIntent === 'creation'
|
||||
? 'Failed to create record. Please verify the submitted parameters.'
|
||||
: operationIntent === 'update'
|
||||
? 'Failed to update record. Please verify the submitted parameters.'
|
||||
: 'Request could not be processed due to invalid parameters.';
|
||||
}
|
||||
|
||||
// Use contextual action title (or returnObject.title if not "Error")
|
||||
let displayTitle = fallbackActionTitle;
|
||||
if (displayTitle === 'Action Failed' && returnObject.title && returnObject.title.toLowerCase() !== 'error') {
|
||||
displayTitle = returnObject.title;
|
||||
}
|
||||
|
||||
return {
|
||||
title: displayTitle,
|
||||
message: friendlyMessage,
|
||||
statusCode,
|
||||
hasReturnObject: true,
|
||||
isProblemDetails: true,
|
||||
category,
|
||||
categoryLabel,
|
||||
errorsList: errorsList.length > 0 ? errorsList : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : (statusCode ? `HTTP Status ${statusCode}` : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
// 5. Case B: Error response DOES NOT have a return object (e.g. empty response, network, non-JSON 500/502/503)
|
||||
let title = fallbackActionTitle || 'Action Failed';
|
||||
let message = '';
|
||||
let category: ErrorCategory = 'general';
|
||||
let categoryLabel: string = 'Error';
|
||||
|
||||
switch (statusCode) {
|
||||
case 400:
|
||||
category = operationIntent === 'creation' ? 'creation' : operationIntent === 'update' ? 'update' : 'validation';
|
||||
categoryLabel = 'Bad Request';
|
||||
message =
|
||||
operationIntent === 'creation'
|
||||
? 'The new record could not be created. Please review the submitted parameters.'
|
||||
: operationIntent === 'update'
|
||||
? 'The record could not be updated. Please verify the submitted parameters.'
|
||||
: 'The request could not be processed due to invalid parameters.';
|
||||
break;
|
||||
|
||||
case 404:
|
||||
title = 'Record Not Found';
|
||||
category = 'notFound';
|
||||
categoryLabel = 'Record Not Found';
|
||||
friendlyTitle = 'Record Not Found';
|
||||
friendlyMessage =
|
||||
'The requested record could not be found. It may have been archived, removed, or the link is outdated.';
|
||||
break;
|
||||
|
||||
case 400:
|
||||
if (operationIntent === 'creation') {
|
||||
category = 'creation';
|
||||
categoryLabel = 'Creation Error';
|
||||
friendlyMessage =
|
||||
'The new record could not be created. Please review the input parameters and prerequisites.';
|
||||
} else if (operationIntent === 'update') {
|
||||
category = 'update';
|
||||
categoryLabel = 'Update Error';
|
||||
friendlyMessage =
|
||||
'The record could not be updated. It may be locked or the requested status transition is not permitted.';
|
||||
} else {
|
||||
category = 'general';
|
||||
categoryLabel = 'Request Error';
|
||||
friendlyMessage =
|
||||
'The request could not be processed due to invalid parameters or business rule requirements.';
|
||||
}
|
||||
categoryLabel = 'Not Found';
|
||||
message = 'The requested resource could not be found (HTTP 404). It may have been archived, removed, or the link is outdated.';
|
||||
break;
|
||||
|
||||
case 409:
|
||||
title = 'Resource Conflict';
|
||||
category = 'conflict';
|
||||
categoryLabel = 'Conflict';
|
||||
friendlyTitle = 'Update Conflict';
|
||||
friendlyMessage =
|
||||
'This action conflicts with the current status of the record. Please refresh the page and try again.';
|
||||
message = 'This operation conflicts with the current status of the resource (HTTP 409). Please refresh the page and try again.';
|
||||
break;
|
||||
|
||||
case 422:
|
||||
category = 'validation';
|
||||
categoryLabel = 'Incomplete Data';
|
||||
friendlyMessage =
|
||||
'The submitted information could not be processed. Please verify that all required fields are complete.';
|
||||
message = 'The submitted information could not be processed by the server (HTTP 422). Please verify all required fields.';
|
||||
break;
|
||||
|
||||
case 429:
|
||||
title = 'Rate Limit Exceeded';
|
||||
category = 'server';
|
||||
categoryLabel = 'Rate Limit';
|
||||
friendlyTitle = 'System Busy';
|
||||
friendlyMessage =
|
||||
'The system received too many requests in a short time. Please pause for a moment before trying again.';
|
||||
message = 'The system received too many requests in a short time (HTTP 429). Please pause for a moment before trying again.';
|
||||
break;
|
||||
|
||||
case 500:
|
||||
case 502:
|
||||
case 503:
|
||||
case 504:
|
||||
title = 'Service Temporarily Unavailable';
|
||||
category = 'server';
|
||||
categoryLabel = 'Service Issue';
|
||||
friendlyTitle = 'Service Temporarily Unavailable';
|
||||
friendlyMessage =
|
||||
'The central service encountered an unexpected issue while processing your request. Please try again in a few moments.';
|
||||
message = `The server encountered an error while processing your request (HTTP ${statusCode}). Please try again in a few moments.`;
|
||||
break;
|
||||
|
||||
default:
|
||||
friendlyMessage =
|
||||
'An unexpected issue occurred while processing this request. Please try again or contact support.';
|
||||
if (typeof error === 'string' && error.trim()) {
|
||||
message = cleanTechnicalJargon(error);
|
||||
} else if (error instanceof Error && error.message) {
|
||||
message = cleanTechnicalJargon(error.message);
|
||||
}
|
||||
if (!message) {
|
||||
message = statusCode
|
||||
? `An unexpected server issue occurred (HTTP ${statusCode}). Please try again or contact support.`
|
||||
: 'An unexpected issue occurred while processing this request. Please try again.';
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure title is friendly and not an uncaught technical string
|
||||
if (friendlyTitle.includes('AxiosError') || friendlyTitle.includes('status code')) {
|
||||
friendlyTitle = fallbackActionTitle;
|
||||
}
|
||||
|
||||
return {
|
||||
title: friendlyTitle,
|
||||
message: friendlyMessage,
|
||||
title,
|
||||
message,
|
||||
statusCode,
|
||||
isProblemDetails,
|
||||
hasReturnObject: false,
|
||||
isProblemDetails: false,
|
||||
category,
|
||||
categoryLabel,
|
||||
fieldErrors: fieldErrors.length > 0 ? fieldErrors : undefined,
|
||||
errorsList: errorsList.length > 0 ? errorsList : undefined,
|
||||
technicalDetails: technicalSummary ? sanitizeTechnicalDetails(technicalSummary) : (statusCode ? `HTTP Status ${statusCode}` : undefined),
|
||||
};
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user