using EnvelopeGenerator.Application.Contracts; using EnvelopeGenerator.Common; using System.Text; namespace EnvelopeGenerator.Web.Services { public class EnvelopeService { private readonly ReceiverModel receiverModel; private readonly EnvelopeModel envelopeModel; private readonly HistoryModel historyModel; private readonly DocumentStatusModel documentStatusModel; private readonly IConfigService _configService; private readonly ILogger _logger; public EnvelopeService(DatabaseService database, IConfigService configService, ILogger logger) { _logger = logger; if (database.Models is null) throw new ArgumentNullException("Models not loaded."); receiverModel = database.Models.receiverModel; envelopeModel = database.Models.envelopeModel; historyModel = database.Models.historyModel; documentStatusModel = database.Models.documentStatusModel; _configService = configService; } public void EnsureValidEnvelopeKey(string envelopeKey) { _logger.LogInformation("Parsing EnvelopeKey.."); if (string.IsNullOrEmpty(envelopeKey)) throw new ArgumentNullException("EnvelopeKey"); Tuple result = Helpers.DecodeEnvelopeReceiverId(envelopeKey); _logger.LogInformation("EnvelopeUUID: [{0}]", result.Item1); _logger.LogInformation("ReceiverSignature: [{0}]", result.Item2); if (string.IsNullOrEmpty(result.Item1)) throw new ArgumentNullException("EnvelopeUUID"); if (string.IsNullOrEmpty(result.Item2)) throw new ArgumentNullException("ReceiverSignature"); } public async Task LoadEnvelope(string pEnvelopeKey) { _logger.LogInformation("Loading Envelope by Key [{0}]", pEnvelopeKey); Tuple result = Helpers.DecodeEnvelopeReceiverId(pEnvelopeKey); var envelopeUuid = result.Item1; var receiverSignature = result.Item2; var receiverId = receiverModel.GetReceiverIdBySignature(receiverSignature); _logger.LogInformation("Resolved receiver signature to receiverId [{0}]", receiverId); _logger.LogInformation("Loading envelope.."); Envelope? envelope = envelopeModel.GetByUuid(envelopeUuid); if (envelope == null) { _logger.LogWarning("Envelope not found"); throw new NullReferenceException("Envelope not found"); } _logger.LogInformation("Envelope loaded"); if (envelope.Receivers == null) { _logger.LogWarning("Receivers for envelope not loaded"); throw new NullReferenceException("Receivers for envelope not loaded"); } _logger.LogInformation("Envelope receivers found: [{0}]", envelope.Receivers.Count); EnvelopeReceiver? receiver = envelope.Receivers.Where(r => r.Id == receiverId).SingleOrDefault(); if (receiver == null) { _logger.LogWarning("Receiver [{0}] not found", receiverId); throw new NullReferenceException("Receiver not found"); } _logger.LogInformation("Loading documents for receiver [{0}]", receiver.Email); // filter elements by receiver envelope.Documents = envelope.Documents.Select((document) => { document.Elements = document.Elements.Where((e) => e.ReceiverId == receiverId).ToList(); return document; }).ToList(); //if documenet_path_dmz is existing in config, replace the path with it var configResult = await _configService.ReadDefaultAsync(); if (configResult.IsSuccess && configResult.Data is not null) { var config = configResult.Data; if(config.DocumentPathDmz is not null && config.DocumentPathDmz != string.Empty) foreach(var doc in envelope.Documents) { doc.Filepath = doc.Filepath.Replace(config.DocumentPath , config.DocumentPathDmz); } } else { _logger.LogError(string.Join(". ", configResult.Messages)); throw new InvalidOperationException(String.Join(". ", configResult.Messages)); } return new() { Receiver = receiver, Envelope = envelope }; } public List LoadEnvelopes() { var receivers = receiverModel.ListReceivers(); List envelopes = new(); foreach (var receiver in receivers) { var envs = (List)envelopeModel.List(receiver.Id); envelopes.AddRange(envs); } return envelopes; } public List LoadEnvelopes(int pReceiverId) { return (List)envelopeModel.List(pReceiverId); } public bool ReceiverAlreadySigned(Envelope envelope, int receiverId) { return historyModel.HasReceiverSigned(envelope.Id, receiverId); } public async Task EnsureValidAnnotationData(HttpRequest request) { try { _logger.LogInformation("Parsing annotation data from request.."); using MemoryStream ms = new(); await request.BodyReader.CopyToAsync(ms); var bytes = ms.ToArray(); _logger.LogInformation("Annotation data parsed, size: [{0}]", bytes.Length); return Encoding.UTF8.GetString(bytes); } catch (Exception e) { _logger.LogError(e, "Inner Service Error"); throw new ArgumentNullException("AnnotationData"); } } public async Task GetDocument(int documentId, string envelopeKey) { EnvelopeResponse response = await LoadEnvelope(envelopeKey); _logger.LogInformation("Loading document for Id [{0}]", documentId); var document = response.Envelope.Documents. Where(d => d.Id == documentId). FirstOrDefault(); if (document == null) throw new ArgumentException("DocumentId"); _logger.LogInformation("Document [{0}] loaded!", documentId); return document; } public bool InsertDocumentStatus(Common.DocumentStatus documentStatus) { _logger.LogInformation("Saving annotation data.."); return documentStatusModel.InsertOrUpdate(documentStatus); } public async Task GetDocumentContents(EnvelopeDocument document) { _logger.LogInformation("Loading file [{0}]", document.Filepath); var bytes = await File.ReadAllBytesAsync(document.Filepath); _logger.LogInformation("File loaded, size: [{0}]", bytes.Length); return bytes; } } }