diff --git a/EnvelopeGenerator.Application/DocStatus/Commands/ModifyDocStatusCommandBase.cs b/EnvelopeGenerator.Application/DocStatus/Commands/ModifyDocStatusCommandBase.cs index 6591896c..73455e0e 100644 --- a/EnvelopeGenerator.Application/DocStatus/Commands/ModifyDocStatusCommandBase.cs +++ b/EnvelopeGenerator.Application/DocStatus/Commands/ModifyDocStatusCommandBase.cs @@ -5,7 +5,7 @@ namespace EnvelopeGenerator.Application.DocStatus.Commands; /// /// /// -public abstract record ModifyDocStatusCommandBase +public record ModifyDocStatusCommandBase { /// /// Gets or sets the ID of the associated envelope. diff --git a/EnvelopeGenerator.Application/DocStatus/Commands/SaveDocStatusCommand.cs b/EnvelopeGenerator.Application/DocStatus/Commands/SaveDocStatusCommand.cs new file mode 100644 index 00000000..059991fb --- /dev/null +++ b/EnvelopeGenerator.Application/DocStatus/Commands/SaveDocStatusCommand.cs @@ -0,0 +1,58 @@ +using DigitalData.Core.Abstraction.Application.Repository; +using EnvelopeGenerator.Domain.Entities; +using MediatR; +using Microsoft.EntityFrameworkCore; +using System.Linq.Expressions; + +namespace EnvelopeGenerator.Application.DocStatus.Commands; + +/// +/// Represents a command to save the status of a document, either by creating a new status or updating an existing one based on the provided envelope and receiver identifiers. +/// It returns the identifier of the saved document status. +/// +public record SaveDocStatusCommand : ModifyDocStatusCommandBase, IRequest; + +/// +/// +/// +public class SaveDocStatusCommandHandler : IRequestHandler +{ + private readonly IRepository _repo; + + /// + /// + /// + /// + public SaveDocStatusCommandHandler(IRepository repo) + { + _repo = repo; + } + + /// + /// + /// + /// + /// + /// + public async Task Handle(SaveDocStatusCommand request, CancellationToken cancel) + { + Expression> filter = ds => ds.EnvelopeId == request.EnvelopeId && ds.ReceiverId == request.ReceiverId; + + // ceck if exists + bool isExists = await _repo.ReadOnly().Where(filter).AnyAsync(cancel); + + if (isExists) + { + var uReq = request.To(); + await _repo.UpdateAsync(uReq, filter, cancel); + } + else + { + var cReq = request.To(); + await _repo.CreateAsync(cReq, cancel); + } + + var docStatus = await _repo.ReadOnly().Where(filter).FirstOrDefaultAsync(cancel); + return docStatus?.Id; + } +} \ No newline at end of file