Files
EnvelopeGenerator/EnvelopeGenerator.Application/Receivers/Commands/CreateReceiverCommand.cs
TekH 75846573da Add XML docs and standardize repository access patterns
Added XML documentation to extension and handler classes for improved maintainability. Refactored repository access to use .Query instead of .ReadOnly() for consistency. Updated async extension methods for better readability and error handling.
2026-02-02 10:07:50 +01:00

97 lines
2.7 KiB
C#

using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;
namespace EnvelopeGenerator.Application.Receivers.Commands;
/// <summary>
///
/// </summary>
[ApiExplorerSettings(IgnoreApi = true)]
public record CreateReceiverCommand : IRequest<(ReceiverDto Receiver, bool AlreadyExists)>
{
/// <summary>
///
/// </summary>
[EmailAddress]
public required string EmailAddress { get; init; }
/// <summary>
///
/// </summary>
public string? TotpSecretkey { get; init; }
/// <summary>
/// var bytes_arr = Encoding.UTF8.GetBytes(EmailAddress.ToUpper());<br/>
/// var hash_arr = SHA256.HashData(bytes_arr);
/// var hexa_str = BitConverter.ToString(hash_arr);
/// return hexa_str.Replace("-", string.Empty);
/// </summary>
public string Signature
{
get
{
var bytes_arr = Encoding.UTF8.GetBytes(EmailAddress!.ToUpper());
var hash_arr = SHA256.HashData(bytes_arr);
var hexa_str = BitConverter.ToString(hash_arr);
return hexa_str.Replace("-", string.Empty);
}
}
/// <summary>
/// Default value is DateTime.Now
/// </summary>
public DateTime AddedWhen { get; } = DateTime.Now;
};
/// <summary>
///
/// </summary>
public class CreateReceiverCommandHandler : IRequestHandler<CreateReceiverCommand, (ReceiverDto Receiver, bool AlreadyExists)>
{
/// <summary>
///
/// </summary>
private readonly IRepository<Receiver> _repo;
private readonly IMapper _mapper;
/// <summary>
///
/// </summary>
/// <param name="repo"></param>
/// <param name="mapper"></param>
public CreateReceiverCommandHandler(IRepository<Receiver> repo, IMapper mapper)
{
_repo = repo;
_mapper = mapper;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="cancel"></param>
/// <returns></returns>
public async Task<(ReceiverDto Receiver, bool AlreadyExists)> Handle(CreateReceiverCommand request, CancellationToken cancel)
{
var receiver = await _repo.Query
.Where(r => r.EmailAddress == request.EmailAddress)
.SingleOrDefaultAsync(cancel);
var alreadyExists = receiver is not null;
if (!alreadyExists)
receiver = await _repo.CreateAsync(request, cancel);
var receiverDto = _mapper.Map<ReceiverDto>(receiver);
return (receiverDto, alreadyExists);
}
}