Refactored Communications and Evidence endpoints
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Communications;
|
||||
|
||||
public sealed class CommunicationsService(IDbContextFactory<ApplicationDbContext> contextFactory) : IService
|
||||
{
|
||||
public async ValueTask<Result<Invite>> SendInviteAsync(InviteRequest request, ClaimsPrincipal principal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
|
||||
|
||||
if (!Guid.TryParse(sidClaim, out var currentUserId))
|
||||
return Result.Fail("Missing or invalid 'sid' claim.");
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var invite = new Domain.Entities.Invite
|
||||
{
|
||||
OrganisationId = request.OrganisationId,
|
||||
InvitedOrganisationId = request.InvitedOrganisationId,
|
||||
AwardId = request.AwardId,
|
||||
ContractId = request.ContractId,
|
||||
Recipient = request.Recipient,
|
||||
CreatedBy = currentUserId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
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
|
||||
});
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok(invite.Map())
|
||||
: Result.Fail("Failed to complete the insite distribution");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Invite[]>> GetInvitesAsync(Pagination pagination, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var envites = await context.Invites.AsNoTracking()
|
||||
.OrderByDescending(i => i.CreatedAt)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(envites.Select(i => i.Map()).ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using PostFundManagement.Domain.Events.Communications;
|
||||
|
||||
namespace PostFundManagement.Application.Communications.Events;
|
||||
|
||||
public class SyncUserEventHandler(ILogger<SyncUserEvent> logger) : INotificationHandler<SyncUserEvent>
|
||||
{
|
||||
public ValueTask Handle(SyncUserEvent notification, CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation("Integration Sync executed. Correlation ID: {CorrelationId}", notification.CorrelationId);
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
using PostFundManagement.Domain;
|
||||
|
||||
namespace PostFundManagement.Application.Communications;
|
||||
|
||||
public record InviteRequest(long OrganisationId, long InvitedOrganisationId, long AwardId, long ContractId, Guid Recipient, string Message, NotificationPlatform Platform);
|
||||
@@ -0,0 +1,251 @@
|
||||
using PostFundManagement.Application.Shared;
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Application.Evidence;
|
||||
|
||||
public sealed class EvidenceService(IDbContextFactory<ApplicationDbContext> contextFactory, HashService hashService,
|
||||
[FromKeyedServices(Constants.EvidenceS3SettingsSection)] IS3Service s3Service) : IService
|
||||
{
|
||||
public async ValueTask<Result> UploadEvidenceFileAsync(Guid userId, IFormCollection form, IFormFile file, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
_ = 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);
|
||||
_ = Enum.TryParse<EvidenceType>(form["type"], out var type);
|
||||
|
||||
using var stream = file.OpenReadStream();
|
||||
|
||||
var uploadResult = await s3Service.UploadFileAsync(file.FileName, stream, file.ContentType, cancellationToken);
|
||||
|
||||
if (uploadResult.IsFailed)
|
||||
return Result.Fail(uploadResult.Errors.FirstOrDefault()?.Message ?? "File upload failed.");
|
||||
|
||||
var documentUrl = uploadResult.Value;
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var evidence = new Domain.Entities.Evidence
|
||||
{
|
||||
ProjectId = projectId,
|
||||
MilestoneId = milestoneId,
|
||||
IndicatorId = indicatorId,
|
||||
ActivityId = activityId,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Version = 1,
|
||||
Type = type,
|
||||
DocumentUrl = documentUrl,
|
||||
Status = ApprovalStatus.Pending
|
||||
};
|
||||
|
||||
context.Evidences.Add(evidence);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail("Evidence upload failed");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> RecordIndicatorActualAmountAsync(string hash, decimal amount, ClaimsPrincipal principal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
|
||||
|
||||
if (!Guid.TryParse(sidClaim, out var userId))
|
||||
return Result.Fail("Missing or invalid 'sid' claim.");
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var hashResult = hashService.DecodeLongIdHash(hash);
|
||||
long indicatorId = 0;
|
||||
|
||||
if (hashResult.IsFailed)
|
||||
return Result.Fail(hashResult.Errors);
|
||||
|
||||
var totalUpdated = await context.Indicators.Where(i => i.Id == indicatorId)
|
||||
.ExecuteUpdateAsync(f => f
|
||||
.SetProperty(f => f.ActualAmount, amount)
|
||||
.SetProperty(f => f.CreatedBy, userId), cancellationToken);
|
||||
|
||||
return totalUpdated > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail("Failed to record actual amount");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetMilestonesByProjectIdAsync(long projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var milestones = await context.Milestones.AsNoTracking()
|
||||
.Where(m => m.ProjectId == projectId)
|
||||
.OrderBy(m => m.DueAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Ok(milestones.Select(m => m.Map()).ToArray());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Milestone[]>> GetMilestonesAsync(Pagination pagination, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var milestones = await context.Milestones.AsNoTracking()
|
||||
.OrderByDescending(m => m.CreatedAt)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return milestones?.Count > 0
|
||||
? Result.Ok(milestones.Select(i => i.Map()).ToArray())
|
||||
: Result.Ok<Milestone[]>([]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Indicator[]>> GetIndicatorsAsync(Pagination pagination, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var indicators = await context.Indicators.AsNoTracking()
|
||||
.OrderByDescending(i => i.CreatedAt)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return indicators?.Count > 0
|
||||
? Result.Ok(indicators.Select(i => i.Map()).ToArray())
|
||||
: Result.Ok<Indicator[]>([]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Domain.Models.Evidence[]>> GetEvidenceFilesAsync(Pagination pagination, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
var evidence = await context.Evidences.AsNoTracking()
|
||||
.OrderByDescending(e => e.CreatedAt)
|
||||
.Skip((pagination.Page - 1) * pagination.PageSize)
|
||||
.Take(pagination.PageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return evidence?.Count > 0
|
||||
? Result.Ok(evidence.Select(e => e.Map()).ToArray())
|
||||
: Result.Ok<Domain.Models.Evidence[]>([]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<(string Id, Milestone Milestone)>> CreateMilestoneAsync(CreateMilestoneRequest request, ClaimsPrincipal principal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
|
||||
|
||||
if (!Guid.TryParse(sidClaim, out var userId))
|
||||
return Result.Fail("Missing or invalid 'sid' claim.");
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Projects.AnyAsync(p => p.Id == request.ProjectId, cancellationToken))
|
||||
return Result.Fail($"Project with ID {request.ProjectId} does not exist.");
|
||||
|
||||
var milestone = new Domain.Entities.Milestone
|
||||
{
|
||||
ProjectId = request.ProjectId,
|
||||
DueAt = request.DueAt,
|
||||
Name = request.Name,
|
||||
Priority = request.Priority,
|
||||
Status = ApprovalStatus.Pending,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
context.Milestones.Add(milestone);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok((hashService.HashEncodeLongId(milestone.Id).Value, milestone.Map()))
|
||||
: Result.Fail("Failed to create the milestone");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<(string Id, Indicator Indicator)>> CreateIndicatorAsync(CreateIndicatorRequest request, ClaimsPrincipal principal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
|
||||
|
||||
if (!Guid.TryParse(sidClaim, out var userId))
|
||||
return Result.Fail("Missing or invalid 'sid' claim.");
|
||||
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Projects.AnyAsync(p => p.Id == request.ProjectId, cancellationToken))
|
||||
return Result.Fail($"Project with ID {request.ProjectId} does not exist.");
|
||||
|
||||
var indicator = new Domain.Entities.Indicator
|
||||
{
|
||||
ProjectId = request.ProjectId,
|
||||
Name = request.Name,
|
||||
UnitOfMeasure = request.UnitOfMeasure,
|
||||
BaselineAmount = request.BaselineAmount,
|
||||
TargetAmount = request.TargetAmount,
|
||||
ActualAmount = request.BaselineAmount,
|
||||
CreatedBy = userId,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
context.Indicators.Add(indicator);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok((hashService.HashEncodeLongId(indicator.Id).Value, indicator.Map()))
|
||||
: Result.Fail("Failed to create the invite");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using PostFundManagement.Domain;
|
||||
|
||||
namespace PostFundManagement.Application.Evidence;
|
||||
|
||||
public record RecordActualRequest(decimal ActualAmount);
|
||||
|
||||
public record CreateMilestoneRequest(long ProjectId, DateTime DueAt, string Name, Priority Priority);
|
||||
|
||||
public record CreateIndicatorRequest(long ProjectId, string Name, UnitOfMeasure UnitOfMeasure, decimal BaselineAmount, decimal TargetAmount);
|
||||
@@ -0,0 +1,67 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyOriginatorKeyFile>..\PostFundManagement.snk</AssemblyOriginatorKeyFile>
|
||||
<SignAssembly>True</SignAssembly>
|
||||
<PackageLicenseFile>..\LICENSE</PackageLicenseFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PostFundManagement.Domain\PostFundManagement.Domain.csproj" />
|
||||
<ProjectReference Include="..\PostFundManagement.Infrastructure\PostFundManagement.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Shared Usings -->
|
||||
<ItemGroup>
|
||||
<Using Include="System.Security.Claims" />
|
||||
<Using Include="System.Diagnostics" />
|
||||
<Using Include="MimeKit" />
|
||||
<Using Include="MailKit.Net.Smtp" />
|
||||
<Using Include="Quartz" />
|
||||
<Using Include="Refit" />
|
||||
<Using Include="AccessTokenClient" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.Cookies" />
|
||||
<Using Include="IdentityModel.AspNetCore.OAuth2Introspection" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<Using Include="Microsoft.Extensions.Configuration" />
|
||||
<Using Include="Amazon.S3" />
|
||||
<Using Include="Amazon.S3.Model" />
|
||||
<Using Include="Amazon.Runtime" />
|
||||
<Using Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" />
|
||||
<Using Include="Microsoft.EntityFrameworkCore" />
|
||||
<Using Include="Microsoft.EntityFrameworkCore.Design" />
|
||||
<Using Include="Microsoft.EntityFrameworkCore.Metadata.Builders" />
|
||||
<Using Include="Mediator" />
|
||||
<Using Include="FluentResults" />
|
||||
<Using Include="Microsoft.AspNetCore.DataProtection" />
|
||||
<Using Include="System.Security.Cryptography.X509Certificates" />
|
||||
<Using Include="Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage" />
|
||||
<Using Include="System.Text.Json.Serialization" />
|
||||
<Using Include="System.Reflection" />
|
||||
<Using Include="Microsoft.Extensions.DependencyInjection.Extensions" />
|
||||
<Using Include="Microsoft.AspNetCore.Routing" />
|
||||
<Using Include="System.Web" />
|
||||
<Using Include="Microsoft.IdentityModel.Tokens" />
|
||||
<Using Include="Microsoft.AspNetCore.Http" />
|
||||
<Using Include="HashidsNet" />
|
||||
<Using Include="System.Net" />
|
||||
<Using Include="System.Text.RegularExpressions" />
|
||||
<Using Include="System.Globalization" />
|
||||
<Using Include="Microsoft.AspNetCore.Builder" />
|
||||
<Using Include="Microsoft.Extensions.Hosting" />
|
||||
<Using Include="System.Text" />
|
||||
<Using Include="System.Text.Json" />
|
||||
<Using Include="System.Threading.Channels" />
|
||||
<Using Include="System.Collections.ObjectModel" />
|
||||
<Using Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<Using Include="System.Security.Cryptography" />
|
||||
<Using Include="Microsoft.Extensions.Options" />
|
||||
<Using Include="Microsoft.Extensions.Logging" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,78 @@
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class BrowserLocalStorageService(ProtectedLocalStorage storage)
|
||||
{
|
||||
public async ValueTask<Result> DeleteAsync(string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
await storage.DeleteAsync(key);
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> SaveAsync(string key, string value)
|
||||
{
|
||||
try
|
||||
{
|
||||
await storage.SetAsync(key, value);
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> SaveAsync<TValue>(string key, TValue value) where TValue : class
|
||||
{
|
||||
try
|
||||
{
|
||||
await storage.SetAsync(key, value);
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<string>> GetAsync(string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
var retrieval = await storage.GetAsync<string>(key);
|
||||
|
||||
return retrieval.Success && !string.IsNullOrWhiteSpace(retrieval.Value)
|
||||
? Result.Ok(retrieval.Value)
|
||||
: Result.Fail($"Could not find object by key {key}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result<TValue>> GetAsync<TValue>(string key) where TValue : class
|
||||
{
|
||||
try
|
||||
{
|
||||
var retrieval = await storage.GetAsync<TValue>(key);
|
||||
|
||||
return retrieval.Success && retrieval.Value is not null
|
||||
? Result.Ok(retrieval.Value)
|
||||
: Result.Fail($"Could not find object by key {key}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class ContractS3Service(IConfiguration configuration, [FromKeyedServices(ContractBucketName)] IAmazonS3 amazonS3) :
|
||||
S3ServiceBase(amazonS3), IS3Service
|
||||
{
|
||||
protected override string BucketName => configuration.GetSection($"{ContractS3SettingsSection}:BucketName").Value ?? "";
|
||||
protected override string CdnBaseUrl => configuration.GetSection($"{ContractS3SettingsSection}:CdnBaseUrl").Value ?? "";
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using PostFundManagement.Domain;
|
||||
using PostFundManagement.Domain.Configuration.Email;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Models.Email;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class EmailService(IOptions<SmtpSettings> options) : IDisposable
|
||||
{
|
||||
private readonly SmtpSettings settings = options.Value;
|
||||
|
||||
private readonly SmtpClient client = new();
|
||||
|
||||
private readonly int sendMaxCount = 10;
|
||||
|
||||
private int sendCount = 0;
|
||||
|
||||
public EmailStatuses Status { get; private set; } = EmailStatuses.Disconnected;
|
||||
|
||||
public async ValueTask<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Send");
|
||||
|
||||
activity?.SetTag("email.recipient", message.Recipient?.Address);
|
||||
|
||||
try
|
||||
{
|
||||
if (Status != EmailStatuses.Connected)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, "Disconnected");
|
||||
|
||||
return Result.Fail<Response>("Smtp service is disconnected.");
|
||||
}
|
||||
|
||||
var email = ConstructEmail(message, cancellationToken);
|
||||
|
||||
var response = await client.SendAsync(email, cancellationToken);
|
||||
|
||||
bool emailSent = response.Contains("OK", StringComparison.InvariantCultureIgnoreCase);
|
||||
|
||||
message.Dispose();
|
||||
|
||||
Interlocked.Increment(ref sendCount);
|
||||
|
||||
if (sendCount % sendMaxCount == 0)
|
||||
{
|
||||
using var delayActivity = EmailTelemetry.Source.StartActivity("Rate Limit Pause");
|
||||
|
||||
sendCount = 0;
|
||||
|
||||
await Task.Delay(1000, cancellationToken);
|
||||
}
|
||||
|
||||
if (emailSent)
|
||||
{
|
||||
EmailTelemetry.EmailsSent.Add(1, new TagList { { "host", settings.Host } });
|
||||
|
||||
return Result.Ok(Response.Create(EmailStatuses.Success));
|
||||
}
|
||||
|
||||
await DisconnectAsync(cancellationToken);
|
||||
|
||||
var failCheckResult = HandleNegativeResponse(response);
|
||||
|
||||
if (failCheckResult.IsFailed) return failCheckResult;
|
||||
|
||||
Status = EmailStatuses.Disconnected;
|
||||
|
||||
return Result.Fail<Response>("General error, disconnected");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
|
||||
activity?.AddException(ex);
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "exception", ex.GetType().Name } });
|
||||
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
private static MimeMessage ConstructEmail(Message message, CancellationToken cancellationToken)
|
||||
{
|
||||
var email = new MimeMessage();
|
||||
email.From.Add(new MailboxAddress(message.Sender!.Name, message.Sender.Address!));
|
||||
email.To.Add(new MailboxAddress(message.Recipient!.Name, message.Recipient!.Address!));
|
||||
email.Subject = message.Subject!;
|
||||
|
||||
var bodyBuilder = new BodyBuilder();
|
||||
|
||||
if (message.Body!.Properties.HasAttachments)
|
||||
foreach (var attachment in message.Body?.Attachments!)
|
||||
bodyBuilder.Attachments.Add(attachment.Name!, attachment.FileStream!, cancellationToken);
|
||||
|
||||
if (!message.Body.Properties.IsHtml) bodyBuilder.TextBody = message.Body.Message;
|
||||
if (message.Body.Properties.IsHtml) bodyBuilder.HtmlBody = message.Body.Message;
|
||||
|
||||
email.Body = bodyBuilder.ToMessageBody();
|
||||
|
||||
return email;
|
||||
}
|
||||
|
||||
private Result<Response> HandleNegativeResponse(string response)
|
||||
{
|
||||
if (response.Contains("421", StringComparison.Ordinal))
|
||||
{
|
||||
Status = EmailStatuses.TooManyConnections;
|
||||
|
||||
return Result.Fail<Response>(response);
|
||||
}
|
||||
|
||||
if (response.Contains("451", StringComparison.Ordinal))
|
||||
{
|
||||
Status = EmailStatuses.ConnectionAborted;
|
||||
|
||||
return Result.Fail<Response>(response);
|
||||
}
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "error_message", response } });
|
||||
|
||||
return Result.Fail<Response>(response);
|
||||
}
|
||||
|
||||
public async ValueTask<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Connect");
|
||||
activity?.SetTag("email.smtp.connect", settings.Host);
|
||||
|
||||
try
|
||||
{
|
||||
if (Status is EmailStatuses.Connected) return Result.Ok(Response.Create(Status));
|
||||
|
||||
await client.ConnectAsync(settings.Host!, settings.Port, settings.UseSsl, cancellationToken);
|
||||
await client.AuthenticateAsync(settings.Credentials!.Username!, settings.Credentials.Password!, cancellationToken);
|
||||
|
||||
Status = EmailStatuses.Connected;
|
||||
|
||||
activity?.SetStatus(ActivityStatusCode.Ok, "Connected");
|
||||
|
||||
return Result.Ok(Response.Create(Status));
|
||||
}
|
||||
catch (MailKit.ProtocolException ex)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
|
||||
activity?.AddException(ex);
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "exception", ex.GetType().Name } });
|
||||
|
||||
Status = EmailStatuses.ProtocolError;
|
||||
|
||||
return Result.Fail<Response>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
catch (Exception ex) when (ex is MailKit.Security.SslHandshakeException || ex is MailKit.Security.AuthenticationException)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
|
||||
activity?.AddException(ex);
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "exception", ex.GetType().Name } });
|
||||
|
||||
Status = EmailStatuses.AuthenticationError;
|
||||
|
||||
return Result.Fail<Response>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
|
||||
activity?.AddException(ex);
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "exception", ex.GetType().Name } });
|
||||
|
||||
Status = EmailStatuses.GeneralError;
|
||||
|
||||
return Result.Fail<Response>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<Result> DisconnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var activity = EmailTelemetry.Source.StartActivity("Email Disconnect");
|
||||
activity?.SetTag("email.smtp.disconnect", settings.Host);
|
||||
|
||||
try
|
||||
{
|
||||
if (Status is EmailStatuses.Disconnected) return Result.Ok();
|
||||
|
||||
await client.DisconnectAsync(true, cancellationToken);
|
||||
|
||||
activity?.SetStatus(ActivityStatusCode.Ok, "Disconnected");
|
||||
|
||||
Status = EmailStatuses.Disconnected;
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
|
||||
activity?.AddException(ex);
|
||||
|
||||
EmailTelemetry.EmailsFailed.Add(1, new TagList { { "exception", ex.GetType().Name } });
|
||||
|
||||
Status = EmailStatuses.GeneralError;
|
||||
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
client.Dispose();
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class EvidenceS3Service(IConfiguration configuration, [FromKeyedServices(EvidenceBucketName)] IAmazonS3 amazonS3) :
|
||||
S3ServiceBase(amazonS3), IS3Service
|
||||
{
|
||||
protected override string BucketName => configuration.GetSection($"{EvidenceS3SettingsSection}:BucketName").Value ?? "";
|
||||
protected override string CdnBaseUrl => configuration.GetSection($"{EvidenceS3SettingsSection}:CdnBaseUrl").Value ?? "";
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using static PostFundManagement.Domain.Extensions.Constants;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class GeneralS3Service(IConfiguration configuration, [FromKeyedServices(GeneralBucketName)] IAmazonS3 amazonS3) :
|
||||
S3ServiceBase(amazonS3), IS3Service
|
||||
{
|
||||
protected override string BucketName => configuration.GetSection($"{GeneralS3SettingsSection}:BucketName").Value ?? "";
|
||||
protected override string CdnBaseUrl => configuration.GetSection($"{GeneralS3SettingsSection}:CdnBaseUrl").Value ?? "";
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed partial class HashService(IHashids hasher) : IService
|
||||
{
|
||||
[GeneratedRegex(@"\A\b[0-9a-fA-F]+\b\Z", RegexOptions.None, matchTimeoutMilliseconds: 100)]
|
||||
private static partial Regex HexHashRegex { get; }
|
||||
|
||||
[GeneratedRegex(@"\A[0-9a-fA-F]{32}\Z", RegexOptions.None, matchTimeoutMilliseconds: 100)]
|
||||
private static partial Regex Md5Regex { get; }
|
||||
|
||||
[GeneratedRegex(@"\A[0-9a-fA-F]{64}\Z", RegexOptions.None, matchTimeoutMilliseconds: 100)]
|
||||
private static partial Regex Sha256Regex { get; }
|
||||
|
||||
public static bool IsMd5Hash(string? value) =>
|
||||
!string.IsNullOrWhiteSpace(value) && Md5Regex.IsMatch(value);
|
||||
|
||||
public static bool IsSha256Hash(string? value) =>
|
||||
!string.IsNullOrWhiteSpace(value) && Sha256Regex.IsMatch(value);
|
||||
|
||||
public static string? StringToSha256Hash(string? input) =>
|
||||
string.IsNullOrEmpty(input) ? null : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input)));
|
||||
|
||||
public static string? StreamToSha256Hash(Stream stream) =>
|
||||
stream is null ? null : Convert.ToHexString(SHA256.HashData(stream));
|
||||
|
||||
public static string? BytesToSha256Hash(byte[] bytes) =>
|
||||
bytes is null ? null : Convert.ToHexString(SHA256.HashData(bytes));
|
||||
|
||||
public static Result<string> ToMd5Hash(string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
return Result.Fail<string>("Input content cannot be null or empty for MD5 processing.");
|
||||
|
||||
byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(input));
|
||||
return Result.Ok(Convert.ToHexString(bytes).ToLowerInvariant());
|
||||
}
|
||||
|
||||
public Result<string> HashEncodeHex(string input) => string.IsNullOrWhiteSpace(input) || !HexHashRegex.IsMatch(input)
|
||||
? Result.Fail<string>("Input must be a valid hexadecimal string.")
|
||||
: Result.Ok(hasher.EncodeHex(input));
|
||||
|
||||
public Result<string> HashEncodeIntId(int id) => id < 0
|
||||
? Result.Fail<string>("Id cannot be negative.")
|
||||
: Result.Ok(hasher.Encode(id));
|
||||
|
||||
public Result<string> HashEncodeLongId(long id) => id < 0
|
||||
? Result.Fail<string>("Id cannot be negative.")
|
||||
: Result.Ok(hasher.EncodeLong(id));
|
||||
|
||||
public Result<int> DecodeIntIdHash(string hash)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(hash)) return Result.Fail<int>("Invalid token layout.");
|
||||
|
||||
int[] decoded = hasher.Decode(hash);
|
||||
|
||||
return decoded.Length == 1 ? Result.Ok(decoded[0]) : Result.Fail<int>("Invalid or modified Int hash token.");
|
||||
}
|
||||
|
||||
public Result<long> DecodeLongIdHash(string hash)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(hash)) return Result.Fail<long>("Invalid token layout.");
|
||||
|
||||
long[] decoded = hasher.DecodeLong(hash);
|
||||
|
||||
return decoded.Length == 1 ? Result.Ok(decoded[0]) : Result.Fail<long>("Invalid or modified Long hash token.");
|
||||
}
|
||||
|
||||
public Result<string> DecodeHexHash(string hex)
|
||||
{
|
||||
try
|
||||
{
|
||||
string decoded = hasher.DecodeHex(hex);
|
||||
|
||||
return string.IsNullOrEmpty(decoded)
|
||||
? Result.Fail<string>("Invalid or corrupted hex hash.")
|
||||
: Result.Ok(decoded);
|
||||
}
|
||||
catch (FormatException fex)
|
||||
{
|
||||
return Result.Fail<string>(new Error("Invalid hash structure.").CausedBy(fex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail<string>(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using PostFundManagement.Domain.Api.Configuration;
|
||||
using PostFundManagement.Domain.Api.Models;
|
||||
using PostFundManagement.Domain.Sdk;
|
||||
|
||||
namespace PostFundManagement.Application.Shared;
|
||||
|
||||
public sealed class TokenService(ISecurityConnectApi connectApi, IOptions<SecurityClientSettings> clientOptions)
|
||||
{
|
||||
private readonly SecurityClientSettings clientSettings = clientOptions.Value;
|
||||
|
||||
public async Task<Result<Domain.Api.Models.TokenResponse>> GenerateAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new Domain.Api.Models.TokenRequest
|
||||
{
|
||||
ClientId = clientSettings.ClientId,
|
||||
ClientSecret = clientSettings.ClientSecret,
|
||||
GrantType = clientSettings.GrantType,
|
||||
Scope = clientSettings.Scope,
|
||||
};
|
||||
|
||||
using var response = await connectApi.GetToken(request, cancellationToken);
|
||||
|
||||
var contentRaw = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(contentRaw))
|
||||
return Result.Fail(new Error($"The authentication endpoint returned an empty payload. Status code: {response.StatusCode}"));
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var tokenResponse = JsonSerializer.Deserialize<Domain.Api.Models.TokenResponse>(contentRaw);
|
||||
|
||||
return !string.IsNullOrWhiteSpace(tokenResponse?.AccessToken)
|
||||
? Result.Ok(tokenResponse)
|
||||
: Result.Fail<Domain.Api.Models.TokenResponse>(new Error("Authentication succeeded, but no access token was found in the response payload."));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var errorResult = JsonSerializer.Deserialize<TokenErrorResponse>(contentRaw);
|
||||
|
||||
if (errorResult != null)
|
||||
{
|
||||
string summary = $"{errorResult.Error}: {errorResult.ErrorDescription}";
|
||||
|
||||
return Result.Fail(new Error(summary));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Result.Fail(new Error($"Authentication failed: {contentRaw}"));
|
||||
}
|
||||
|
||||
return Result.Fail(new Error($"Authentication failed with status code: {response.StatusCode}"));
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
return Result.Fail(new Error("The token generation request was canceled.").CausedBy(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user