|
| 1 | +using Microsoft.Azure.Functions.Worker; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using NHS.MESH.Client.Contracts.Services; |
| 5 | +using ServiceLayer.Mesh.Configuration; |
| 6 | +using ServiceLayer.Mesh.Data; |
| 7 | +using ServiceLayer.Mesh.Messaging; |
| 8 | +using ServiceLayer.Mesh.Models; |
| 9 | + |
| 10 | +namespace ServiceLayer.Mesh.Functions |
| 11 | +{ |
| 12 | + public class FileDiscoveryFunction( |
| 13 | + ILogger<FileDiscoveryFunction> logger, |
| 14 | + IFileDiscoveryFunctionConfiguration configuration, |
| 15 | + IMeshInboxService meshInboxService, |
| 16 | + ServiceLayerDbContext serviceLayerDbContext, |
| 17 | + IFileExtractQueueClient fileExtractQueueClient) |
| 18 | + { |
| 19 | + [Function("FileDiscoveryFunction")] |
| 20 | + public async Task Run([TimerTrigger("%FileDiscoveryTimerExpression%")] TimerInfo myTimer) |
| 21 | + { |
| 22 | + logger.LogInformation("{functionName} started at: {time}", nameof(FileDiscoveryFunction), DateTime.UtcNow); |
| 23 | + |
| 24 | + var response = await meshInboxService.GetMessagesAsync(configuration.NbssMeshMailboxId); |
| 25 | + |
| 26 | + foreach (var messageId in response.Response.Messages) |
| 27 | + { |
| 28 | + await using var transaction = await serviceLayerDbContext.Database.BeginTransactionAsync(); |
| 29 | + |
| 30 | + var existing = await serviceLayerDbContext.MeshFiles |
| 31 | + .AnyAsync(f => f.FileId == messageId); |
| 32 | + |
| 33 | + if (!existing) |
| 34 | + { |
| 35 | + var file = new MeshFile |
| 36 | + { |
| 37 | + FileId = messageId, |
| 38 | + FileType = MeshFileType.NbssAppointmentEvents, |
| 39 | + MailboxId = configuration.NbssMeshMailboxId, |
| 40 | + Status = MeshFileStatus.Discovered, |
| 41 | + FirstSeenUtc = DateTime.UtcNow, |
| 42 | + LastUpdatedUtc = DateTime.UtcNow |
| 43 | + }; |
| 44 | + |
| 45 | + serviceLayerDbContext.MeshFiles.Add(file); |
| 46 | + |
| 47 | + await serviceLayerDbContext.SaveChangesAsync(); |
| 48 | + await transaction.CommitAsync(); |
| 49 | + |
| 50 | + await fileExtractQueueClient.EnqueueFileExtractAsync(file); |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + await transaction.RollbackAsync(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments