using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.Common.Query;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Dynamic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EnvelopeGenerator.Application.Annotations.Commands;
///
///
///
public record CreateAnnotationCommand : EnvelopeReceiverQueryBase, IRequest>
{
private static readonly JsonSerializerOptions SerializerOptions = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = null
};
///
///
///
[JsonIgnore]
public string PSPDFKitInstantJSON
{
set => PSPDFKitInstant = JsonSerializer.Deserialize(value, SerializerOptions) ?? new ExpandoObject();
}
///
///
///
[JsonIgnore]
public ExpandoObject PSPDFKitInstant { get; set; } = null!;
}
///
///
///
public static class CreateAnnotationCommandExtensions
{
///
///
///
///
///
///
///
public static Task> CreateAnnotation(this ISender sender, string envelopeKey, CancellationToken cancel = default)
=> sender.Send(new CreateAnnotationCommand() { Key = envelopeKey }, cancel);
}
///
///
///
public class CreateAnnotationCommandHandler : IRequestHandler>
{
///
///
///
private readonly IRepository _signRepo;
///
///
///
private readonly IRepository _annotRepo;
///
///
///
///
///
public CreateAnnotationCommandHandler(IRepository signRepo, IRepository annotRepo)
{
_signRepo = signRepo;
_annotRepo = annotRepo;
}
///
///
///
///
///
///
public async Task> Handle(CreateAnnotationCommand request, CancellationToken cancel)
{
var query = _signRepo.Query;
#region Envelope Query
if (request.Envelope.Id is int envelopeId)
query = query.Where(annot => annot.Document.EnvelopeId == envelopeId);
if (request.Envelope.Uuid is string envelopeUuid)
query = query.Where(annot => annot.Document.Envelope!.Uuid == envelopeUuid);
#endregion
// Receiver Query
query = query.Where(request.Receiver);
var elements = await query.ToListAsync(cancel);
foreach (var element in elements)
{
var annots = ParsePSPDFKitInstant(request.PSPDFKitInstant, element.Id)
.Select(annot => new Annotation()
{
ElementId = element.Id,
Name = annot.Key,
Value = annot.Value,
AddedWhen = DateTime.UtcNow
});
element.Annotations = await _annotRepo.CreateAsync(annots, cancel);
}
return elements;
}
///
///
///
///
///
///
public static Dictionary ParsePSPDFKitInstant(ExpandoObject instant, int elementId)
{
Dictionary annots = new();
// parse json here
return annots;
}
}