|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | + |
| 3 | +namespace Nhs.Appointments.Core.BulkImport; |
| 4 | +public class SiteStatusDataImportHandler(ISiteService siteService) : ISiteStatusDataImportHandler |
| 5 | +{ |
| 6 | + public async Task<IEnumerable<ReportItem>> ProcessFile(IFormFile inputFile) |
| 7 | + { |
| 8 | + var siteRows = new List<SiteStatusImportRow>(); |
| 9 | + var processor = new CsvProcessor<SiteStatusImportRow, SiteStatusImportRowMap>( |
| 10 | + sr => Task.Run(() => siteRows.Add(sr)), |
| 11 | + sr => sr.Id, |
| 12 | + () => new SiteStatusImportRowMap() |
| 13 | + ); |
| 14 | + using TextReader fileReader = new StreamReader(inputFile.OpenReadStream()); |
| 15 | + var report = (await processor.ProcessFile(fileReader)).ToList(); |
| 16 | + |
| 17 | + var sites = await siteService.GetAllSites(includeDeleted: true); |
| 18 | + |
| 19 | + var missingSites = FindMissingSites(siteRows, sites); |
| 20 | + if (missingSites.Count > 0) |
| 21 | + { |
| 22 | + report.AddRange(missingSites.Select(ms => new ReportItem(-1, ms.Name, false, $"Could not find existing site with name {ms.Name} and ID: {ms.Id}"))); |
| 23 | + } |
| 24 | + |
| 25 | + if (report.Any(r => !r.Success)) |
| 26 | + { |
| 27 | + return report.Where(r => !r.Success); |
| 28 | + } |
| 29 | + |
| 30 | + foreach (var row in siteRows) |
| 31 | + { |
| 32 | + try |
| 33 | + { |
| 34 | + var result = await siteService.ToggleSiteSoftDeletionAsync(row.Id); |
| 35 | + if (!result.Success) |
| 36 | + { |
| 37 | + report.Add(new ReportItem(-1, row.Name, false, $"Failed to update the soft deletion status of site with name: {row.Name} and ID: {row.Id}")); |
| 38 | + continue; |
| 39 | + } |
| 40 | + } |
| 41 | + catch (Exception ex) |
| 42 | + { |
| 43 | + report.Add(new ReportItem(-1, row.Name, false, ex.Message)); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return report; |
| 48 | + } |
| 49 | + |
| 50 | + public static List<SiteStatusImportRow> FindMissingSites(List<SiteStatusImportRow> siteRows, IEnumerable<Site> sites) |
| 51 | + { |
| 52 | + return [.. siteRows.Where(sr => !sites.Any(s => s.Id == sr.Id && s.Name.Equals(sr.Name, StringComparison.CurrentCultureIgnoreCase)))]; |
| 53 | + } |
| 54 | + |
| 55 | + public class SiteStatusImportRow |
| 56 | + { |
| 57 | + public string Id { get; set; } |
| 58 | + public string Name { get; set; } |
| 59 | + } |
| 60 | +} |
0 commit comments