71 lines
2.3 KiB
C#
71 lines
2.3 KiB
C#
using Events.FilesAPI.Infrastructure.Options;
|
|
using Events.WebAPI.Handlers.EF.Data.Postgres;
|
|
using Events.WebAPI.Handlers.EF.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Events.FilesAPI.Features.RegistrationsExcel.Synchronize;
|
|
|
|
public sealed class RegistrationsExcelFileGenerator(
|
|
EventsContext context,
|
|
IHostEnvironment hostEnvironment,
|
|
IOptions<GeneratedFilesOptions> generatedFilesOptions,
|
|
ILogger<RegistrationsExcelFileGenerator> logger)
|
|
{
|
|
public async Task GenerateAsync(int eventId, CancellationToken cancellationToken)
|
|
{
|
|
var registrations = context.Set<Registration>()
|
|
.AsNoTracking()
|
|
.Where(r => r.EventId == eventId)
|
|
.OrderBy(r => r.Person.LastName)
|
|
.ThenBy(r => r.Person.FirstName)
|
|
.ThenBy(r => r.Sport.Name)
|
|
.Select(r => new EventRegistrationsExcelWriter.RowData
|
|
{
|
|
RegistrationId = r.Id,
|
|
RegisteredAt = r.RegisteredAt,
|
|
PersonId = r.PersonId,
|
|
FirstName = r.Person.FirstName,
|
|
LastName = r.Person.LastName,
|
|
FirstNameTranscription = r.Person.FirstNameTranscription,
|
|
LastNameTranscription = r.Person.LastNameTranscription,
|
|
CountryName = r.Person.CountryCodeNavigation.Name,
|
|
SportName = r.Sport.Name
|
|
});
|
|
|
|
string excelPath = GetPath(eventId);
|
|
EventRegistrationsExcelWriter.RowData? firstRow = await registrations.FirstOrDefaultAsync(cancellationToken);
|
|
if (firstRow == null)
|
|
{
|
|
DeleteFileIfExists(excelPath);
|
|
return;
|
|
}
|
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(excelPath)!);
|
|
await EventRegistrationsExcelWriter.WriteAsync(excelPath, registrations, firstRow, cancellationToken);
|
|
|
|
logger.LogInformation(
|
|
"Event registrations Excel generated for event #{EventId} at {Path}",
|
|
eventId,
|
|
excelPath);
|
|
}
|
|
|
|
private string GetPath(int eventId)
|
|
{
|
|
string rootPath = Path.IsPathRooted(generatedFilesOptions.Value.OutputPath)
|
|
? generatedFilesOptions.Value.OutputPath
|
|
: Path.GetFullPath(Path.Combine(hostEnvironment.ContentRootPath, generatedFilesOptions.Value.OutputPath));
|
|
|
|
return Path.Combine(rootPath, $"{eventId}.xlsx");
|
|
}
|
|
|
|
private void DeleteFileIfExists(string path)
|
|
{
|
|
if (!File.Exists(path))
|
|
return;
|
|
|
|
File.Delete(path);
|
|
logger.LogInformation("Event registrations Excel deleted at {Path}", path);
|
|
}
|
|
}
|