/// <summary> /// Adds a document to the queue. /// </summary> /// <param name="queueDocumentData">Queue document data.</param> /// <returns>Created document entity.</returns> public async Task <DocumentEntity> AddDocumentToQueue(QueueDocumentData queueDocumentData) { // Validate the document await _queueDocumentDataValidator.ValidateAndThrowAsync(queueDocumentData); if (Log.IsEnabled(LogEventLevel.Verbose)) { Log.Information("Queue document data {@queueDocumentData}", JsonConvert.SerializeObject(queueDocumentData)); } // Get the metadata from the package CdaPackageData cdaPackageData = _cdaPackageService.ExtractPackageData(queueDocumentData.CdaPackage); // Check if the document already exists with the same ID DocumentEntity documentEntity = await _dataStore.GetDocument(cdaPackageData.DocumentId); if (documentEntity != null) { throw new ArgumentException($"Document with ID '{cdaPackageData.DocumentId}' already exists in the queue with the '{documentEntity.Status.ToString()}' state"); } // Validate the replace if (!string.IsNullOrEmpty(queueDocumentData.DocumentIdToReplace)) { // Check if the document to replace exists var documentToReplace = await _dataStore.GetDocument(queueDocumentData.DocumentIdToReplace); if (documentToReplace == null) { throw new ArgumentException($"Document to replace with ID '{queueDocumentData.DocumentIdToReplace}' does not exist in the queue"); } // Check the replace document status if (documentToReplace.Status == DocumentStatus.RetryLimitReached || documentToReplace.Status == DocumentStatus.Removed) { throw new ArgumentException($"Document to replace cannot have a status of '{DocumentStatus.RetryLimitReached.ToString()}' or '{DocumentStatus.Removed.ToString()}' and is '{documentToReplace.Status.ToString()}'"); } } DateTime addedDateTime = DateTime.Now; // Create the document DocumentEntity documentToQueue = new DocumentEntity { QueueDate = addedDateTime, Status = DocumentStatus.Pending, DocumentId = cdaPackageData.DocumentId, DocumentIdToReplace = queueDocumentData.DocumentIdToReplace, FormatCodeName = queueDocumentData.FormatCodeName, FormatCode = queueDocumentData.FormatCode, DocumentData = queueDocumentData.CdaPackage, Ihi = cdaPackageData.Ihi }; // Add the create event documentToQueue.AddEvent(new EventEntity { Type = EventType.Created, EventDate = addedDateTime }); await _dataStore.AddDocument(documentToQueue); return(documentToQueue); }