feat StayExport - Initial Implementation

- Created models for DB and DTOs: StayExportFile
- Added required db migrations.
- Added StayExportService and StayExportServiceFactory for stay exporting services.
- Added configuration options required for StayExport.
This commit is contained in:
2026-09-01 18:14:22 +02:00
parent 7052ec734c
commit c24faedee5
24 changed files with 892 additions and 3 deletions
@@ -0,0 +1,9 @@
namespace Somnia.GuestLog.Enums.Models;
public enum StayExportFileResult
{
OK = 0,
NoData = 1,
ExportError = 2,
UploadError = 3,
}
@@ -0,0 +1,7 @@
namespace Somnia.GuestLog.Enums.Models;
public enum StayExportFormat
{
GuestLogJson = 0,
SpainParteViajeros = 1,
}
@@ -0,0 +1,6 @@
namespace Somnia.GuestLog.Enums.Models;
public enum StayExportParamType
{
PeriodDateIn = 0,
}
@@ -5,4 +5,6 @@ public static class DbConsts
public const string DbType_Timestamptz = "timestamp with time zone"; public const string DbType_Timestamptz = "timestamp with time zone";
public const string DbType_Timestamptz_0 = "timestamp(0) with time zone"; public const string DbType_Timestamptz_0 = "timestamp(0) with time zone";
public const string DbType_Timestamptz_3 = "timestamp(3) with time zone"; public const string DbType_Timestamptz_3 = "timestamp(3) with time zone";
public const string PK_NotApply = "N/A";
} }
@@ -0,0 +1,33 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Somnia.GuestLog.Models.Entities;
namespace Somnia.GuestLog.Infrastructure.EntityConfigs;
public class StayExportFileEntityConfig : IEntityTypeConfiguration<StayExportFile>
{
public void Configure(EntityTypeBuilder<StayExportFile> builder)
{
builder.ToTable("StayExportFile");
//PK
builder.HasKey(e => e.Id);
builder.Property(e => e.Id)
.IsRequired()
.UseIdentityByDefaultColumn();
builder.ComplexProperty(e => e.ExportParams, e =>
{
e.ToJson();
});
builder.Property(e => e.ExportedPath)
.HasMaxLength(256);
builder.Property(e => e.ExportTime)
.IsRequired()
.HasColumnType(DbConsts.DbType_Timestamptz);
}
}
@@ -13,11 +13,14 @@ public partial class GuestLogContext : DbContext
public DbSet<GuestDocument> GuestDocuments { get; set; } public DbSet<GuestDocument> GuestDocuments { get; set; }
public DbSet<StayEntry> StayEntries { get; set; } public DbSet<StayEntry> StayEntries { get; set; }
public DbSet<StayExportFile> StayExportFiles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.ApplyConfiguration<GuestDocument>(new GuestDocumentEntityConfig()); modelBuilder.ApplyConfiguration<GuestDocument>(new GuestDocumentEntityConfig());
modelBuilder.ApplyConfiguration<StayEntry>(new StayEntryEntityConfig()); modelBuilder.ApplyConfiguration<StayEntry>(new StayEntryEntityConfig());
modelBuilder.ApplyConfiguration<StayExportFile>(new StayExportFileEntityConfig());
OnModelCreatingPartial(modelBuilder); OnModelCreatingPartial(modelBuilder);
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
@@ -0,0 +1,249 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Somnia.GuestLog.Infrastructure;
#nullable disable
namespace Somnia.GuestLog.Infrastructure.Migrations
{
[DbContext(typeof(GuestLogContext))]
[Migration("20260901161146_AddTable_StayExportFile")]
partial class AddTable_StayExportFile
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.7")
.HasAnnotation("Proxies:ChangeTracking", false)
.HasAnnotation("Proxies:CheckEquality", false)
.HasAnnotation("Proxies:LazyLoading", true)
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("GuestDocumentStayEntry", b =>
{
b.Property<long>("StayEntryId")
.HasColumnType("bigint");
b.Property<long>("GuestDocumentsId")
.HasColumnType("bigint");
b.Property<int>("GuestDocumentsVersion")
.HasColumnType("integer");
b.HasKey("StayEntryId", "GuestDocumentsId", "GuestDocumentsVersion");
b.HasIndex("GuestDocumentsId", "GuestDocumentsVersion");
b.ToTable("GuestDocumentStayEntry");
});
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.GuestDocument", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("Version")
.HasColumnType("integer");
b.Property<DateOnly>("BirthDate")
.HasColumnType("date");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp(3) with time zone");
b.Property<string>("DocumentNum")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("DocumentType")
.IsRequired()
.HasMaxLength(8)
.HasColumnType("character varying(8)");
b.Property<string>("EmailAddress")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("Gender")
.HasMaxLength(1)
.HasColumnType("character varying(1)");
b.Property<bool>("IsLastVersion")
.HasColumnType("boolean");
b.Property<DateOnly>("IssueDate")
.HasColumnType("date");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Nationality")
.IsRequired()
.HasMaxLength(3)
.HasColumnType("character varying(3)");
b.Property<string>("PhoneNumber")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<string>("SupportNum")
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Surname2")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTime>("UpdateTime")
.HasColumnType("timestamp(3) with time zone");
b.ComplexProperty(typeof(Dictionary<string, object>), "AddressDetails", "Somnia.GuestLog.Models.Entities.GuestDocument.AddressDetails#GuestAddress", b1 =>
{
b1.Property<string>("Address")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b1.Property<string>("AddressCity")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b1.Property<string>("AddressCountry")
.IsRequired()
.HasMaxLength(3)
.HasColumnType("character varying(3)");
b1.Property<string>("AddressProvince")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b1.Property<string>("AddressState")
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b1.Property<string>("ZipCode")
.HasMaxLength(12)
.HasColumnType("character varying(12)");
});
b.HasKey("Id", "Version");
b.ToTable("GuestDocument", (string)null);
});
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.StayEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("DateIn")
.HasColumnType("timestamp(0) with time zone");
b.Property<DateTime>("DateOut")
.HasColumnType("timestamp(0) with time zone");
b.Property<string>("PaymentMethod")
.IsRequired()
.HasMaxLength(5)
.HasColumnType("character varying(5)");
b.Property<int>("RoomCount")
.HasColumnType("integer");
b.Property<string>("RoomNumber")
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<DateTime>("UpdateTime")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("StayEntry", (string)null);
});
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.StayExportFile", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("ExportFormat")
.HasColumnType("integer");
b.Property<int>("ExportResult")
.HasColumnType("integer");
b.Property<DateTime>("ExportTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExportedPath")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.ComplexProperty(typeof(Dictionary<string, object>), "ExportParams", "Somnia.GuestLog.Models.Entities.StayExportFile.ExportParams#StayExportParams", b1 =>
{
b1.IsRequired();
b1.Property<DateTime?>("ExportPeriodEnd");
b1.Property<DateTime?>("ExportPeriodStart");
b1.Property<int>("ExportType");
b1
.ToJson("ExportParams")
.HasColumnType("jsonb");
});
b.HasKey("Id");
b.ToTable("StayExportFile", (string)null);
});
modelBuilder.Entity("GuestDocumentStayEntry", b =>
{
b.HasOne("Somnia.GuestLog.Models.Entities.StayEntry", null)
.WithMany()
.HasForeignKey("StayEntryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Somnia.GuestLog.Models.Entities.GuestDocument", null)
.WithMany()
.HasForeignKey("GuestDocumentsId", "GuestDocumentsVersion")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,40 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Somnia.GuestLog.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddTable_StayExportFile : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "StayExportFile",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ExportFormat = table.Column<int>(type: "integer", nullable: false),
ExportResult = table.Column<int>(type: "integer", nullable: false),
ExportedPath = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ExportTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
ExportParams = table.Column<string>(type: "jsonb", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StayExportFile", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "StayExportFile");
}
}
}
@@ -185,6 +185,47 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
b.ToTable("StayEntry", (string)null); b.ToTable("StayEntry", (string)null);
}); });
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.StayExportFile", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("ExportFormat")
.HasColumnType("integer");
b.Property<int>("ExportResult")
.HasColumnType("integer");
b.Property<DateTime>("ExportTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExportedPath")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.ComplexProperty(typeof(Dictionary<string, object>), "ExportParams", "Somnia.GuestLog.Models.Entities.StayExportFile.ExportParams#StayExportParams", b1 =>
{
b1.IsRequired();
b1.Property<DateTime?>("ExportPeriodEnd");
b1.Property<DateTime?>("ExportPeriodStart");
b1.Property<int>("ExportType");
b1
.ToJson("ExportParams")
.HasColumnType("jsonb");
});
b.HasKey("Id");
b.ToTable("StayExportFile", (string)null);
});
modelBuilder.Entity("GuestDocumentStayEntry", b => modelBuilder.Entity("GuestDocumentStayEntry", b =>
{ {
b.HasOne("Somnia.GuestLog.Models.Entities.StayEntry", null) b.HasOne("Somnia.GuestLog.Models.Entities.StayEntry", null)
@@ -0,0 +1,10 @@
namespace Somnia.GuestLog.Models.Configuration;
public class StayExportConfig
{
public const string SectionName = "StayExport";
public bool EnableStayExport { get; set; } = false;
public string? ExportStorageConnectionString { get; set; }
public bool UseSubdirectoryByFormat { get; set; }
}
@@ -0,0 +1,27 @@
using Somnia.GuestLog.Enums.Models;
namespace Somnia.GuestLog.Models.DTOs;
public class StayExportFileDTO
{
public long? Id { get; set; }
public StayExportFormat? ExportFormat { get; set; }
public StayExportParamsDTO? ExportParams { get; set; }
public StayExportFileResult? ExportResult { get; set; }
public string? ExportedPath { get; set; }
public DateTime? ExportTime { get; set; }
}
public class StayExportParamsDTO
{
public StayExportParamType? ExportType { get; set; }
public DateTime? ExportPeriodStart { get; set; }
public DateTime? ExportPeriodEnd { get; set; }
}
@@ -1,3 +1,5 @@
using Somnia.GuestLog.Infrastructure;
namespace Somnia.GuestLog.Models.Entities; namespace Somnia.GuestLog.Models.Entities;
public class GuestAddress : BaseEntity public class GuestAddress : BaseEntity
@@ -9,5 +11,5 @@ public class GuestAddress : BaseEntity
public required string AddressCountry { get; set; } public required string AddressCountry { get; set; }
public string? ZipCode { get; set; } public string? ZipCode { get; set; }
public override string GetFullKey() => "N/A"; public override string GetFullKey() => DbConsts.PK_NotApply;
} }
@@ -0,0 +1,28 @@
using Somnia.GuestLog.Enums.Models;
namespace Somnia.GuestLog.Models.Entities;
public class StayExportFile : BaseEntity
{
public long Id { get; set; }
public required StayExportFormat ExportFormat { get; set; }
public required StayExportParams ExportParams { get; set; }
public required StayExportFileResult ExportResult { get; set; }
/// <summary>
/// Path to exported data.
/// Should be relative to configured Storage.
/// </summary>
public string? ExportedPath { get; set; }
/// <summary>
/// Date/Time when export file was generated.
/// </summary>
public required DateTime ExportTime { get; set; }
public override string GetFullKey() => $"{Id}";
}
@@ -0,0 +1,19 @@
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Infrastructure;
namespace Somnia.GuestLog.Models.Entities;
/// <summary>
/// This class store params used on StayExport.
/// Different params apply for different export types.
/// </summary>
public class StayExportParams : BaseEntity
{
public required StayExportParamType ExportType { get; set; }
public DateTime? ExportPeriodStart { get; set; }
public DateTime? ExportPeriodEnd { get; set; }
public override string GetFullKey() => DbConsts.PK_NotApply;
}
@@ -51,4 +51,24 @@ internal static class EntityMapping
}; };
} }
public static StayExportFileDTO MapStayExportFileEntityToDTO(StayExportFile entity)
{
StayExportParamsDTO exportParamsDto = new()
{
ExportType = entity.ExportParams.ExportType,
ExportPeriodStart = entity.ExportParams.ExportPeriodStart,
ExportPeriodEnd = entity.ExportParams.ExportPeriodEnd,
};
return new()
{
Id = entity.Id,
ExportFormat = entity.ExportFormat,
ExportParams = exportParamsDto,
ExportResult = entity.ExportResult,
ExportedPath = entity.ExportedPath,
ExportTime = entity.ExportTime,
};
}
} }
+8 -1
View File
@@ -10,6 +10,7 @@ using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Services; using Somnia.GuestLog.Services;
using Somnia.GuestLog.Services.AddressQuery; using Somnia.GuestLog.Services.AddressQuery;
using Somnia.GuestLog.Services.Entity; using Somnia.GuestLog.Services.Entity;
using Somnia.GuestLog.Services.StayExport;
using Somnia.GuestLog.Utils; using Somnia.GuestLog.Utils;
using Somnia.GuestLog.Validators; using Somnia.GuestLog.Validators;
@@ -55,19 +56,25 @@ builder.Services.AddSingleton<IValidator<GuestDocumentDTO>, GuestDocumentDTOVali
builder.Services.AddSingleton<IValidator<GuestDocIdDTO>, GuestDocIdDTOValidator>(); builder.Services.AddSingleton<IValidator<GuestDocIdDTO>, GuestDocIdDTOValidator>();
builder.Services.AddSingleton<IValidator<StayEntryDTO>, StayEntryDTOValidator>(); builder.Services.AddSingleton<IValidator<StayEntryDTO>, StayEntryDTOValidator>();
// Add Services // Add Entity Services
builder.Services.AddSingleton<IGuestDocumentEntityService, GuestDocumentEntityService>(); builder.Services.AddSingleton<IGuestDocumentEntityService, GuestDocumentEntityService>();
builder.Services.AddSingleton<IStayEntryEntityService, StayEntryEntityService>(); builder.Services.AddSingleton<IStayEntryEntityService, StayEntryEntityService>();
builder.Services.AddSingleton<IStayExportFileService, StayExportFileService>();
// Add Services
builder.Services.AddSingleton<IDataListService, StaticDataListService>(); builder.Services.AddSingleton<IDataListService, StaticDataListService>();
builder.Services.AddScoped<IUserMessageService, UserMessageService>(); builder.Services.AddScoped<IUserMessageService, UserMessageService>();
// Add Factories (and it's services) // Add Factories (and it's services)
builder.Services.AddFactoryDI<IAddressQueryFactory, ConfigFileAddressQueryFactory>(); builder.Services.AddFactoryDI<IAddressQueryFactory, ConfigFileAddressQueryFactory>();
builder.Services.AddFactoryDI<IStayExportServiceFactory, ConfigFileStaytExportServiceFactory>();
// Add Options config // Add Options config
builder.Services.AddOptions<AddressQueryConfig>() builder.Services.AddOptions<AddressQueryConfig>()
.Bind(builder.Configuration.GetSection(AddressQueryConfig.SectionName)); .Bind(builder.Configuration.GetSection(AddressQueryConfig.SectionName));
builder.Services.AddOptions<StayExportConfig>()
.Bind(builder.Configuration.GetSection(StayExportConfig.SectionName));
var app = builder.Build(); var app = builder.Build();
@@ -0,0 +1,13 @@
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services;
public interface IStayExportFileService
{
public Task<Result> CreateStayExportAsync(StayExportFileDTO dto);
public Task<Result> UpdateStayExportAsync(StayExportFileDTO dto);
public Task<StayExportFileDTO?> GetDtoByIdAsync(long id);
//public Task<IEnumerable<StayExportFileDTO>> GetDtoListByFilterAsync(StayExportFileFilterDTO filter, int limit = 0);
public Task<IEnumerable<StayExportFileDTO>> GetDtoListAsync();
}
@@ -0,0 +1,30 @@
using Microsoft.Extensions.Options;
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.Configuration;
using Somnia.GuestLog.Utils.DI;
namespace Somnia.GuestLog.Services.StayExport;
public class ConfigFileStaytExportServiceFactory(
IServiceProvider serviceProvider,
IOptions<StayExportConfig> config
) : IStayExportServiceFactory, IFactoryDI
{
public static void RegisterFactoryItems(IServiceCollection services)
{
services.AddKeyedSingleton<IStayExportService, JsonStayExportService>(StayExportFormat.GuestLogJson);
services.AddKeyedSingleton<IStayExportService, SpainParteViajerosStayExportService>(StayExportFormat.SpainParteViajeros);
}
public IStayExportService GetService(StayExportFormat exportFormat)
{
if (config.Value.EnableStayExport == false)
{
throw new InvalidOperationException("StayExport is disabled. Enable and configure it first!");
}
return serviceProvider.GetKeyedService<IStayExportService>(exportFormat)
?? throw new InvalidOperationException($"StayExport service not found for ExportFormat: '{exportFormat}'");
}
}
@@ -0,0 +1,11 @@
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.StayExport;
public interface IStayExportService
{
public StayExportFormat GetFormat();
public Task<Result<StayExportFileDTO>> ExportStaysByParams(StayExportParamsDTO exportParams);
}
@@ -0,0 +1,11 @@
using Somnia.GuestLog.Enums.Models;
namespace Somnia.GuestLog.Services.StayExport;
public interface IStayExportServiceFactory
{
/// <summary>
/// Returns the StayExport service implementation given current configuration.
/// </summary>
public IStayExportService GetService(StayExportFormat exportFormat);
}
@@ -0,0 +1,192 @@
using System.Text.Json;
using FluentStorage;
using FluentStorage.Storage;
using Microsoft.Extensions.Options;
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Models.Configuration;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Models.QueryConfigs;
using Somnia.GuestLog.Services.Entity;
namespace Somnia.GuestLog.Services.StayExport;
public class JsonStayExportService(
ILogger<JsonStayExportService> logger,
IStayExportFileService stayExportEntityService,
IStayEntryEntityService stayEntityService,
IOptions<StayExportConfig> exportConfig
) : IStayExportService
{
private const string fileExtension = "json";
private static readonly StayEntryQueryConfig queryConfig =
new(IncludeGuests: true, UseSplitQueries: true, DisableTracking: true);
private readonly StayExportConfig config = exportConfig.Value;
public StayExportFormat GetFormat() => StayExportFormat.GuestLogJson;
public async Task<Result<StayExportFileDTO>> ExportStaysByParams(StayExportParamsDTO exportParams)
{
//Get data to export.
IEnumerable<StayEntryDTO>? stayList;
try
{
stayList = await GetStaysToExportByParamsAsync(exportParams);
}
catch (Exception ex)
{
logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error retriving stays to export!");
return Result<StayExportFileDTO>.Fail(ResultCode.UnknownError);
}
//Create initial StayExportFile
DateTime exportTime = DateTime.UtcNow;
StayExportFileDTO stayExport = new()
{
ExportFormat = GetFormat(),
ExportParams = exportParams,
ExportTime = exportTime,
};
//Export data.
using Stream exportedDataStream = new MemoryStream();
//Generate data to export.
StayExportFileResult? exportResult;
try
{
exportResult = await ExportDataToStream(stayList, exportedDataStream);
// "Rewind" stream so it can be read from the begining when uploading.
exportedDataStream.Seek(0, SeekOrigin.Begin);
}
catch (Exception ex)
{
logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error exporting data!");
exportResult = StayExportFileResult.ExportError;
}
//If data exported OK, save to file.
if (exportResult == StayExportFileResult.OK)
{
try
{
string exportPath = GetExportPath(exportTime);
//Store data.
using IStore exportStore = GetExportStore();
await exportStore.SetObject(objectPath: exportPath, dataStream: exportedDataStream);
//Update path in item.
stayExport.ExportedPath = exportPath;
}
catch (Exception ex)
{
logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error Uploading exported data!");
exportResult = StayExportFileResult.UploadError;
}
}
//Store StayExport in DB.
stayExport.ExportResult = exportResult;
Result? createResult = null;
try
{
createResult = await stayExportEntityService.CreateStayExportAsync(stayExport);
}
catch (Exception ex)
{
logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error storing StayExportFile entity to DB: {stayExport}", stayExport);
}
//If everything is OK, return OK.
if (createResult != null && createResult.ResultCode == ResultCode.Ok)
{
return Result<StayExportFileDTO>.Ok(stayExport);
}
//Saving export to DB failed. Delete exported file (if exported)
if (!string.IsNullOrEmpty(stayExport.ExportedPath))
{
try
{
using IStore exportStore = GetExportStore();
await exportStore.DeleteObject(objectPath: stayExport.ExportedPath);
}
catch (Exception ex)
{
logger.LogError(ex, "JsonStayExportService - ExportStaysByParams: Error deleting exported file after db saving error: {exportedPath}", stayExport.ExportedPath);
}
}
logger.LogError(
"JsonStayExportService - ExportStaysByDateIn: Error (code '{code}') storing StayExportFile entity to DB: {stayExport}",
createResult?.ResultCode, stayExport);
return Result<StayExportFileDTO>.Fail(ResultCode.UnknownError);
}
#region Internal Methods
private async Task<IEnumerable<StayEntryDTO>> GetStaysToExportByParamsAsync(StayExportParamsDTO exportParams)
{
//Todo - Improve type selection (when there are more types).
if (exportParams.ExportType == StayExportParamType.PeriodDateIn)
{
if (exportParams.ExportPeriodStart == null || exportParams.ExportPeriodEnd == null)
{
throw new InvalidOperationException($"StayExportFile - ExportType {exportParams.ExportType} require date start/end. Null dates found");
}
//Get Stays in period.
StayEntryFilterDTO filter = new()
{
DateInStart = exportParams.ExportPeriodStart,
DateInEnd = exportParams.ExportPeriodEnd
};
return await stayEntityService.GetDtoListByFilterAsync(filter, limit: 0, queryConfig: queryConfig);
}
throw new InvalidOperationException($"StayExportFile - Error getting stays using params: export type invalid: {exportParams.ExportType}");
}
private async Task<StayExportFileResult> ExportDataToStream(IEnumerable<StayEntryDTO> stayList, Stream exportStream)
{
if (!stayList.Any())
{
return StayExportFileResult.NoData;
}
// Convert to JSON.
await JsonSerializer.SerializeAsync(exportStream, stayList);
return StayExportFileResult.OK;
}
private string GetExportPath(DateTime time)
{
string formatName = GetFormatName();
string exportPathSubdir = config.UseSubdirectoryByFormat ? formatName : "";
string exportFileName = $"{formatName}_{time.ToFileTimeUtc()}.{fileExtension}";
return Path.Combine(exportPathSubdir, exportFileName);
}
private string GetFormatName()
{
return Enum.GetName(GetFormat()) ?? throw new InvalidOperationException("Can't get StayExportFormat name!");
}
private IStore GetExportStore()
{
string? storageConnString = config.ExportStorageConnectionString;
if (string.IsNullOrEmpty(storageConnString))
{
throw new InvalidOperationException("No Stay Export Storage configured. Stays can't be exported");
}
return StorageFactory.FromConnectionString(storageConnString);
}
#endregion
}
@@ -0,0 +1,17 @@
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.StayExport;
public class SpainParteViajerosStayExportService(
) : IStayExportService
{
public StayExportFormat GetFormat() => StayExportFormat.SpainParteViajeros;
public Task<Result<StayExportFileDTO>> ExportStaysByParams(StayExportParamsDTO exportParams)
{
throw new NotImplementedException();
}
}
@@ -0,0 +1,107 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using Somnia.GuestLog.Infrastructure;
using Somnia.GuestLog.Models;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Models.Entities;
namespace Somnia.GuestLog.Services;
public class StayExportFileService(
ILogger<StayExportFileService> logger,
IDbContextFactory<GuestLogContext> contextFactory
) : IStayExportFileService
{
public async Task<Result> CreateStayExportAsync(StayExportFileDTO dto)
{
ArgumentNullException.ThrowIfNull(dto, nameof(dto));
//Check for null values in the DTO.
if (dto.ExportFormat == null || dto.ExportResult == null || dto.ExportTime == null)
{
throw new InvalidOperationException("StayExportFile dto contains null fields");
}
if (dto.ExportParams == null)
{
throw new InvalidOperationException("StayExportFile dto contains null ExportParams");
}
StayExportParams exportParams = GetExportParamsFromDTO(dto.ExportParams);
StayExportFile dbItem = new()
{
ExportFormat = dto.ExportFormat.Value,
ExportParams = exportParams,
ExportResult = dto.ExportResult.Value,
ExportedPath = dto.ExportedPath,
ExportTime = dto.ExportTime?.ToUniversalTime() ?? DateTime.UtcNow,
};
try
{
using var dbContext = contextFactory.CreateDbContext();
await dbContext.AddAsync(dbItem);
await dbContext.SaveChangesAsync();
logger.LogInformation("StayExportFileService - CreateStayExportAsync: GuestDocument Created: '{id}'", dbItem.GetFullKey());
return Result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "StayExportFileService - CreateStayExportAsync: Error creating GuestDocument");
return Result.FailUnknownError();
}
}
public Task<Result> UpdateStayExportAsync(StayExportFileDTO dto)
{
throw new NotImplementedException();
}
public async Task<StayExportFileDTO?> GetDtoByIdAsync(long id)
{
using var dbContext = contextFactory.CreateDbContext();
StayExportFile? dbItem = await dbContext.StayExportFiles
.Where(e => e.Id == id)
.FirstOrDefaultAsync();
return dbItem is not null ? GetDtoFromDb(dbItem) : null;
}
public async Task<IEnumerable<StayExportFileDTO>> GetDtoListAsync()
{
using var dbContext = contextFactory.CreateDbContext();
var dbList = await dbContext.StayExportFiles
.OrderByDescending(e => e.ExportTime)
.ToListAsync();
return dbList.Select(e => GetDtoFromDb(e));
}
#region Internal Methods
private static StayExportFileDTO GetDtoFromDb(StayExportFile dbItem)
{
return EntityMapping.MapStayExportFileEntityToDTO(dbItem);
}
private static StayExportParams GetExportParamsFromDTO(StayExportParamsDTO dto)
{
if (dto.ExportType == null)
{
throw new InvalidOperationException("Dto with invalid data");
}
return new()
{
ExportType = dto.ExportType.Value,
ExportPeriodStart = dto.ExportPeriodStart?.ToUniversalTime(),
ExportPeriodEnd = dto.ExportPeriodEnd?.ToUniversalTime()
};
}
#endregion
}
+5
View File
@@ -20,5 +20,10 @@
"ApiKey": "", "ApiKey": "",
"UserAgent": "Somnia-GuestLog-Dev", "UserAgent": "Somnia-GuestLog-Dev",
"ResultLang": "es" "ResultLang": "es"
},
"StayExport": {
"EnableStayExport": true,
"ExportStorageConnectionString": "disk://path=/SomniaGuestLog/StayExportFiles",
"UseSubdirectoryByFormat": true
} }
} }