Compare commits

..
11 Commits
Author SHA256 Message Date
Daniel-Garmig 9ec87d56da feat StayExport - Added ExportDetails for StayExports
Store a new field ('ExportDetails') with export details. This is a JSON field in DB that can store information about the export depending on the format provider used.

Changes:
- Updated models and created required migrations.
- Show field in StayExport list.
2026-09-08 19:58:47 +02:00
Daniel-Garmig 7b8020879b feat StayExport - StayExportProvider SpainParteViejeros - Initial implementation
- Added initial implementation to export stays in "SpainParteViajeros" format.
- Added required configurations.
2026-09-08 14:31:00 +02:00
Daniel-Garmig dc5293bdf7 feat StayExport - Added service SpainCodigoMunicipio
- This service gets the "municipio" code of INE using Catastro API services.
2026-09-08 13:27:17 +02:00
Daniel-Garmig 4b72e3b3d3 feat StayExport - Added delete for StayExports. 2026-09-06 22:24:25 +02:00
Daniel-Garmig 6fe5a5e5a3 feat StayExport - Refactor Export Services.
- Created new service: IStayExportService" for common export operations.
- Updated older services to be "IStayExportFormatProvider". This services will only implement the export format.
- Renamed "IStayExportServiceFactory" to "IStayExportFormatProviderFactory" as this factory now is used to get the format providers for the given format.
2026-09-04 22:33:01 +02:00
Daniel-Garmig 058352b7f3 feat StayExport - Added common Interface "IResult" for Result so both (generic and non-generic one) can be used easier. 2026-09-04 20:50:38 +02:00
Daniel-Garmig 313a714a99 feat StayExport - Stay Export Pages - Initial implementation 2026-09-04 20:38:00 +02:00
Daniel-Garmig cf31cbc414 feat StayExport - Added LocalizerService
- Added new "LocalizerService" to get localization for enum values (and other dynamic/db values in the future).
2026-09-02 13:15:10 +02:00
Daniel-Garmig b318f2415c feat StayExport - Moved Entity Services. 2026-09-01 18:14:27 +02:00
Daniel-Garmig c24faedee5 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.
2026-09-01 18:14:22 +02:00
Daniel-Garmig 7052ec734c feat StayExport - Added lib FluentStorage 2026-09-01 15:23:23 +02:00
49 changed files with 2412 additions and 35 deletions
+2
View File
@@ -6,6 +6,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageVersion Include="Extensions.MudBlazor.StaticInput" Version="4.1.0" /> <PackageVersion Include="Extensions.MudBlazor.StaticInput" Version="4.1.0" />
<PackageVersion Include="FluentStorage" Version="8.0.16" />
<PackageVersion Include="FluentStorage.AWS" Version="8.0.10" />
<PackageVersion Include="FluentValidation" Version="12.1.1" /> <PackageVersion Include="FluentValidation" Version="12.1.1" />
<PackageVersion Include="Grpc.AspNetCore" Version="2.64.0" /> <PackageVersion Include="Grpc.AspNetCore" Version="2.64.0" />
<PackageVersion Include="Microsoft.Extensions.Localization" Version="10.0.9" /> <PackageVersion Include="Microsoft.Extensions.Localization" Version="10.0.9" />
+1
View File
@@ -23,6 +23,7 @@
<ReconnectModal /> <ReconnectModal />
<script src="@Assets["_framework/blazor.web.js"]"></script> <script src="@Assets["_framework/blazor.web.js"]"></script>
<script src="@Assets["_content/MudBlazor/MudBlazor.min.js"]"></script> <script src="@Assets["_content/MudBlazor/MudBlazor.min.js"]"></script>
<script src="js/App.js"></script>
</body> </body>
</html> </html>
@@ -13,4 +13,7 @@
<MudNavLink Href="@GuestConsts.Page_StayEntry_List" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Book"> <MudNavLink Href="@GuestConsts.Page_StayEntry_List" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.Book">
@LanguageLocale.navMenu_StayEntryList @LanguageLocale.navMenu_StayEntryList
</MudNavLink> </MudNavLink>
<MudNavLink Href="@GuestConsts.Page_StayExport_List" Match="NavLinkMatch.Prefix" Icon="@Icons.Material.Filled.ImportExport">
@LanguageLocale.navMenu_StayExport
</MudNavLink>
</MudNavMenu> </MudNavMenu>
@@ -0,0 +1,197 @@
@attribute [Route($"{GuestConsts.Page_StayExport_List}")]
@using System.Text.Json;
@using Somnia.GuestLog.Models.DTOs;
@using Somnia.GuestLog.Services;
@using Somnia.GuestLog.Services.StayExport;
@inject IStayExportFileEntityService stayExportEntityService
@inject NavigationManager Navigation
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject IDataListService dataListService;
@inject ILocalizerService Localizer;
@inject IStayExportService ExportService;
@inject IJSRuntime JS
<PageTitle>Somnia - Stay Export Files</PageTitle>
<MudStack Row="true" Class="my-4">
<MudText Typo="Typo.h4" GutterBottom="true">@LanguageLocale.page_StayExportList_pageTitle</MudText>
<MudSpacer />
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small"
StartIcon="@Icons.Material.Filled.Search" OnClick="() => BtnSearchDataAsync()">
@LanguageLocale.general_btnSearch
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small" StartIcon="@Icons.Material.Filled.Add"
OnClick="() => BtnNewExport()">
@LanguageLocale.page_StayExportList_btnNewExport
</MudButton>
</MudStack>
@* <MudPaper Class="pa-4 my-4" Elevation="2" Height="100%">
FILTER
</MudPaper> *@
<MudDataGrid @ref="_dataGrid" T="StayExportFileDTO" Items="@stayExportList" Loading="@_dataLoading" ReadOnly="true"
Elevation="2">
<ToolBarContent>
<MudText Typo="Typo.subtitle1">@LanguageLocale.page_StayExportList_exportList</MudText>
</ToolBarContent>
<Columns>
<PropertyColumn Property="x => x.Id" Hideable="false" Title="@LanguageLocale.dto_StayExportFile_Id" />
<PropertyColumn Property="x => Localizer.GetEnumValue(x.ExportFormat)"
Title="@LanguageLocale.dto_StayExportFile_ExportFormat" />
<TemplateColumn Title="@LanguageLocale.dto_StayExportFile_ExportParams">
<CellTemplate>
<MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Info"
OnClick="() => ShowExportParams(context.Item)" />
</CellTemplate>
</TemplateColumn>
<PropertyColumn Property="x => Localizer.GetEnumValue(x.ExportResult)"
Title="@LanguageLocale.dto_StayExportFile_ExportResult" />
<PropertyColumn Property="x => x.ExportTime" Title="@LanguageLocale.dto_StayExportFile_ExportTime" />
<TemplateColumn Title="@LanguageLocale.dto_StayExportFile_ExportDetails">
<CellTemplate>
<MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Info"
OnClick="() => ShowExportDetails(context.Item)" />
</CellTemplate>
</TemplateColumn>
<TemplateColumn CellClass="d-flex justify-between" Title="Options" StickyRight Hideable="false"
ShowColumnOptions="false">
<CellTemplate>
<MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Download"
OnClick="() => BtnDownloadFile(context.Item)" />
<MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Delete"
OnClick="() => BtnDeleteItem(context.Item)" />
</CellTemplate>
</TemplateColumn>
</Columns>
<PagerContent>
<MudDataGridPager T="StayExportFileDTO" />
</PagerContent>
</MudDataGrid>
<ConfirmDeleteMsgBox @ref="_confirmDeleteMsgBox" />
@code {
private bool _dataLoading = true;
private const int resultLimit = 200;
private IEnumerable<StayExportFileDTO> stayExportList = [];
private MudDataGrid<StayExportFileDTO> _dataGrid = null!;
private ConfirmDeleteMsgBox _confirmDeleteMsgBox = null!;
protected override async Task OnInitializedAsync()
{
await LoadDataAsync(showMsg: false);
}
private async Task LoadDataAsync(bool showMsg = true)
{
_dataLoading = true;
stayExportList = await stayExportEntityService.GetDtoListAsync(limit: resultLimit);
if (showMsg)
{
userMessage.ShowMessage("Data loaded from DB", MessageKind.Info);
}
_dataLoading = false;
}
#region Event Handlers
private async Task BtnSearchDataAsync()
{
await LoadDataAsync();
}
private void BtnNewExport()
{
Navigation.NavigateTo(GuestConsts.Page_StayExport_New);
}
private async Task ShowExportParams(StayExportFileDTO dto)
{
string jsonParams = JsonSerializer.Serialize(dto.ExportParams, options: new() { WriteIndented = true });
await DialogService.ShowMessageBoxAsync("Details", (MarkupString)$"<pre>{jsonParams}</pre>");
}
private async Task ShowExportDetails(StayExportFileDTO dto)
{
if (string.IsNullOrEmpty(dto.ExportDetails))
{
userMessage.ShowMessage("This ExportFile doesn't have any export details", MessageKind.Info);
return;
}
using var jDoc = JsonDocument.Parse(dto.ExportDetails);
string jsonDetails = JsonSerializer.Serialize(jDoc, new JsonSerializerOptions { WriteIndented = true });
await DialogService.ShowMessageBoxAsync("Details", (MarkupString)$"<pre>{jsonDetails}</pre>");
}
private async Task BtnDownloadFile(StayExportFileDTO item)
{
if (item.ExportResult == Enums.Models.StayExportFileResult.NoData)
{
userMessage.ShowMessage("A Export without data can't be downloaded!", MessageKind.Warning);
return;
}
if (string.IsNullOrEmpty(item.ExportedPath))
{
userMessage.ShowMessage("File can't be downloaded: no path found!", MessageKind.Warning);
return;
}
using Stream objectStream = new MemoryStream();
Result loadResult = await ExportService.GetExportedFileAsync(item, objectStream);
if (!loadResult.IsSuccess)
{
userMessage.ShowResultWithMessage(loadResult, "Exported File can't be downloaded");
return;
}
objectStream.Seek(0, SeekOrigin.Begin);
using var streamRef = new DotNetStreamReference(stream: objectStream);
var fileName = Path.GetFileName(item.ExportedPath);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
userMessage.ShowMessage("Exported File downloaded!", MessageKind.Success);
}
private async Task BtnDeleteItem(StayExportFileDTO item)
{
bool? confirmDelete = await _confirmDeleteMsgBox.MsgBox.ShowAsync();
if (confirmDelete is null || confirmDelete.Value == false)
{
return;
}
Result deleteResult = await ExportService.DeleteExportedFileAsync(item);
if (!deleteResult.IsSuccess)
{
string errorMsg = $"Error deleting Export file {item.Id}";
userMessage.ShowResultWithMessage(deleteResult, errorMsg);
return;
}
userMessage.ShowMessage($"Export file {item.Id} deleted!", MessageKind.Success);
await LoadDataAsync();
}
#endregion
}
@@ -0,0 +1,162 @@
@attribute [Route($"{GuestConsts.Page_StayExport_New}")]
@using FluentValidation;
@using Somnia.GuestLog.Models.DTOs;
@using Somnia.GuestLog.Enums.Models;
@using Somnia.GuestLog.Services;
@using Somnia.GuestLog.Validators;
@using Somnia.GuestLog.Services.StayExport;
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject NavigationManager Navigation
@inject IValidator<StayExportParamsDTO> ExportParamsValidator;
@inject ILocalizerService Localizer;
@inject IStayExportService ExportService;
@inject IJSRuntime JS
<PageTitle>Somnia - Stay Export - New</PageTitle>
<MudStack Row="true" Class="my-4">
<MudText Typo="Typo.h4" GutterBottom="true">
@LanguageLocale.page_StayExportNew_pageTitle
</MudText>
<MudSpacer />
<MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small" StartIcon="@Icons.Material.Filled.Add"
OnClick="() => BtnCreateExport()" Disabled="@_isExported">
@LanguageLocale.general_btnCreate
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Default" Size="Size.Small"
StartIcon="@Icons.Material.Filled.ArrowBack" OnClick="() => BtnReturn()">
@LanguageLocale.general_btnReturn
</MudButton>
</MudStack>
<MudForm @ref="@_form" Model="@exportParams"
Validation="@((ExportParamsValidator as StayExportParamsDTOValidator)!.ValidateValue)" ReadOnly="@_isExported">
<MudPaper Class="pa-4 my-4" Elevation="3" Height="100%">
<MudStack Row style="margin-block: 0.2em;">
<MudSelect @bind-Value="exportFormat" Label="@LanguageLocale.dto_StayExportFile_ExportFormat" FullWidth
Clearable>
@foreach (StayExportFormat option in Enum.GetValues<StayExportFormat>())
{
<MudSelectItem Value="new Nullable<StayExportFormat>(option)">
@Localizer.GetEnumValue(option)
</MudSelectItem>
}
</MudSelect>
<MudSelect @bind-Value="exportParams.ExportType" For="@(() => exportParams.ExportType)"
Label="@LanguageLocale.dto_StayExportParams_ExportType" FullWidth Clearable>
@foreach (StayExportParamType option in Enum.GetValues<StayExportParamType>())
{
<MudSelectItem Value="new Nullable<StayExportParamType>(option)">
@Localizer.GetEnumValue(option)
</MudSelectItem>
}
</MudSelect>
</MudStack>
</MudPaper>
@if (_showPeriodFields)
{
<MudPaper Class="pa-4" Elevation="3" Height="100%">
<MudStack Row>
<MudDatePicker @bind-Date="exportParams.ExportPeriodStart" For="@(() => exportParams.ExportPeriodStart)"
Label="@LanguageLocale.dto_StayExportParams_ExportPeriodStart" Clearable OpenTo="OpenTo.Date" Editable
AutoClose="true" />
<MudDatePicker @bind-Date="exportParams.ExportPeriodEnd" For="@(() => exportParams.ExportPeriodEnd)"
Label="@LanguageLocale.dto_StayExportParams_ExportPeriodEnd" Clearable OpenTo="OpenTo.Date" Editable
AutoClose="true" />
</MudStack>
</MudPaper>
}
</MudForm>
@if (_isExported && exportedFile != null)
{
<MudPaper Class="pa-4 my-6" Elevation="3" Height="100%">
<MudStack>
<MudText Typo="Typo.h4">File Exported!</MudText>
<MudTextField Value="@Localizer.GetEnumValue(exportedFile.ExportResult)"
Label="@LanguageLocale.dto_StayExportFile_ExportResult" FullWidth ReadOnly="true" />
<MudTextField Value="@Localizer.GetEnumValue(exportedFile.ExportFormat)"
Label="@LanguageLocale.dto_StayExportFile_ExportFormat" FullWidth ReadOnly="true" />
<MudButton OnClick="BtnDownloadExportedFile">Download Exported File</MudButton>
</MudStack>
</MudPaper>
}
@code {
MudForm _form = null!;
StayExportFormat? exportFormat = null;
StayExportParamsDTO exportParams = new();
StayExportFileDTO? exportedFile = null;
bool _showPeriodFields => exportParams.ExportType == StayExportParamType.PeriodDateIn;
bool _isExported => exportedFile != null;
private void BtnReturn()
{
Navigation.NavigateTo(GuestConsts.Page_StayExport_List);
}
private async Task BtnCreateExport()
{
await _form.ValidateAsync();
if (!_form.IsValid || exportFormat == null)
{
userMessage.ShowMessage("Invalid Form!", MessageKind.Warning);
return;
}
var loadingDialog = await DialogService.ShowAsync<LoadingDialog>();
var exportResult = await ExportService.ExportStaysByParamsAsync(exportFormat.Value, exportParams);
exportedFile = exportResult.Value;
loadingDialog.Close();
if (!exportResult.IsSuccess)
{
userMessage.ShowResultWithMessage(exportResult, $"Error exporting stays");
return;
}
userMessage.ShowMessage(
$"Stay exported: {exportResult.ResultCode} with export result: {exportedFile?.ExportResult}",
MessageKind.Success);
}
private async Task BtnDownloadExportedFile()
{
Debug.Assert(exportedFile != null);
if (string.IsNullOrEmpty(exportedFile.ExportedPath))
{
userMessage.ShowMessage("Exported File can't be downloaded as no file was saved", MessageKind.Warning);
return;
}
using Stream dataStream = new MemoryStream();
Result loadResult = await ExportService.GetExportedFileAsync(exportedFile, dataStream);
if (!loadResult.IsSuccess)
{
userMessage.ShowResultWithMessage(loadResult, "Exported File can't be downloaded");
return;
}
dataStream.Seek(0, SeekOrigin.Begin);
using var streamRef = new DotNetStreamReference(stream: dataStream);
var fileName = Path.GetFileName(exportedFile.ExportedPath);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
userMessage.ShowMessage("Exported File downloaded!", MessageKind.Success);
}
}
@@ -1,2 +1,3 @@
@using Somnia.GuestLog.Components.Controls @using Somnia.GuestLog.Components.Controls
@using Somnia.GuestLog.Services.Entity; @using Somnia.GuestLog.Services.Entity;
@using System.Diagnostics;
@@ -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,
}
@@ -7,6 +7,7 @@ public enum ResultCode
UnknownError, UnknownError,
FailedValidation, FailedValidation,
NotFound, NotFound,
FileStorageError,
//Specific Codes //Specific Codes
GuestInStay, GuestInStay,
+10
View File
@@ -13,6 +13,9 @@ public static class GuestConsts
public const string Page_StayEntry_Detail = $"/stayEntries/d/{Page_StayEntry_Detail_Param_Id}"; public const string Page_StayEntry_Detail = $"/stayEntries/d/{Page_StayEntry_Detail_Param_Id}";
public const string Page_StayEntry_Detail_Param_Id = "{StayId:long}"; public const string Page_StayEntry_Detail_Param_Id = "{StayId:long}";
public const string Page_StayExport_List = "/stayExport";
public const string Page_StayExport_New = "/stayExport/new";
public const string QueryParam_ReturnUrl = "returnUrl"; public const string QueryParam_ReturnUrl = "returnUrl";
@@ -29,5 +32,12 @@ public static class GuestConsts
public const string DocumentType_NIE = "NIE"; public const string DocumentType_NIE = "NIE";
public const string DocumentType_PASSPORT = "PASSPORT"; public const string DocumentType_PASSPORT = "PASSPORT";
public const string GenderOptions_MALE = "M";
public const string GenderOptions_FEMALE = "F";
public const string GenderOptions_OTHER = "O";
public const int GuestDocument_FirstVersion = 1; public const int GuestDocument_FirstVersion = 1;
public const string EmptyField = "-";
} }
@@ -5,4 +5,8 @@ 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 DbType_jsonb = "jsonb";
public const string PK_NotApply = "N/A";
} }
@@ -0,0 +1,36 @@
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.ExportDetails)
.HasColumnType(DbConsts.DbType_jsonb);
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");
}
}
}
@@ -0,0 +1,252 @@
// <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("20260908172441_StayExportFile_AddColumn_ExportDetails")]
partial class StayExportFile_AddColumn_ExportDetails
{
/// <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<string>("ExportDetails")
.HasColumnType("jsonb");
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,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Somnia.GuestLog.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class StayExportFile_AddColumn_ExportDetails : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ExportDetails",
table: "StayExportFile",
type: "jsonb",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ExportDetails",
table: "StayExportFile");
}
}
}
@@ -185,6 +185,50 @@ 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<string>("ExportDetails")
.HasColumnType("jsonb");
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,9 @@
namespace Somnia.GuestLog.Models.Configuration;
public class StayExportSpainParteViajerosConfig
{
public const string SectionName = "StayExportSpainParteViajeros";
public bool InternetAvailable { get; set; } = false;
public string? CodigoEstablecimiento { get; set; }
}
+18 -2
View File
@@ -2,7 +2,18 @@ using Somnia.GuestLog.Enums.Services;
namespace Somnia.GuestLog.Models.DTOs; namespace Somnia.GuestLog.Models.DTOs;
public sealed record Result(bool IsSuccess, ResultCode ResultCode, params object[]? Context) public interface IResult
{
bool IsSuccess { get; }
ResultCode ResultCode { get; }
object[]? Context { get; }
}
public sealed record Result(
bool IsSuccess,
ResultCode ResultCode,
params object[]? Context
) : IResult
{ {
public static Result Ok() => new(IsSuccess: true, ResultCode: ResultCode.Ok, Context: null); public static Result Ok() => new(IsSuccess: true, ResultCode: ResultCode.Ok, Context: null);
@@ -15,7 +26,12 @@ public sealed record Result(bool IsSuccess, ResultCode ResultCode, params object
public bool IsUnknownError => !IsSuccess && ResultCode == ResultCode.UnknownError; public bool IsUnknownError => !IsSuccess && ResultCode == ResultCode.UnknownError;
} }
public sealed record Result<T>(bool IsSuccess, T? Value, ResultCode ResultCode, params object[]? Context) public sealed record Result<T>(
bool IsSuccess,
T? Value,
ResultCode ResultCode,
params object[]? Context
) : IResult
{ {
public static Result<T> Ok(T value) => new(IsSuccess: true, value, ResultCode: ResultCode.Ok, Context: null); public static Result<T> Ok(T value) => new(IsSuccess: true, value, ResultCode: ResultCode.Ok, Context: null);
public static Result<T> Fail(ResultCode resultCode) => new(IsSuccess: false, Value: default, resultCode, Context: null); public static Result<T> Fail(ResultCode resultCode) => new(IsSuccess: false, Value: default, resultCode, Context: null);
@@ -0,0 +1,29 @@
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 string? ExportDetails { 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,33 @@
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>
/// A JSON column to store details about the exported file.
/// This details can contain information about errors, which stays where included, etc.
/// </summary>
public string? ExportDetails { 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,25 @@ 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,
ExportDetails = entity.ExportDetails,
ExportTime = entity.ExportTime,
};
}
} }
+19 -2
View File
@@ -1,3 +1,4 @@
using FluentStorage;
using FluentValidation; using FluentValidation;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -10,6 +11,8 @@ 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.SpainCodigoMunicipio;
using Somnia.GuestLog.Services.StayExport;
using Somnia.GuestLog.Utils; using Somnia.GuestLog.Utils;
using Somnia.GuestLog.Validators; using Somnia.GuestLog.Validators;
@@ -54,20 +57,31 @@ builder.Services.AddHttpClient();
builder.Services.AddSingleton<IValidator<GuestDocumentDTO>, GuestDocumentDTOValidator>(); builder.Services.AddSingleton<IValidator<GuestDocumentDTO>, GuestDocumentDTOValidator>();
builder.Services.AddSingleton<IValidator<GuestDocIdDTO>, GuestDocIdDTOValidator>(); builder.Services.AddSingleton<IValidator<GuestDocIdDTO>, GuestDocIdDTOValidator>();
builder.Services.AddSingleton<IValidator<StayEntryDTO>, StayEntryDTOValidator>(); builder.Services.AddSingleton<IValidator<StayEntryDTO>, StayEntryDTOValidator>();
builder.Services.AddSingleton<IValidator<StayExportParamsDTO>, StayExportParamsDTOValidator>();
// 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<IDataListService, StaticDataListService>(); builder.Services.AddSingleton<IStayExportFileEntityService, StayExportFileEntityService>();
// Add Services
builder.Services.AddSingleton<IDataListService, StaticDataListService>();
builder.Services.AddScoped<IUserMessageService, UserMessageService>(); builder.Services.AddScoped<IUserMessageService, UserMessageService>();
builder.Services.AddSingleton<ILocalizerService, LocalizerService>();
builder.Services.AddSingleton<IStayExportService, StayExportService>();
builder.Services.AddSingleton<ISpainCodigoMunicipioService, SpainCodigoMunicipioCatastroService>();
// 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<IStayExportFormatProviderFactory, StayExportFormatProviderFactory>();
// 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));
builder.Services.AddOptions<StayExportSpainParteViajerosConfig>()
.Bind(builder.Configuration.GetSection(StayExportSpainParteViajerosConfig.SectionName));
var app = builder.Build(); var app = builder.Build();
@@ -102,4 +116,7 @@ app.MapStaticAssets();
app.MapRazorComponents<App>() app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode(); .AddInteractiveServerRenderMode();
//Activate S3 storage.
AwsS3Storage.Use();
app.Run(); app.Run();
@@ -149,6 +149,18 @@
<data name="dto.StayEntry.CreateTime" xml:space="preserve"><value>Creation Time</value></data> <data name="dto.StayEntry.CreateTime" xml:space="preserve"><value>Creation Time</value></data>
<data name="dto.StayEntry.UpdateTime" xml:space="preserve"><value>Update Time</value></data> <data name="dto.StayEntry.UpdateTime" xml:space="preserve"><value>Update Time</value></data>
<data name="dto.StayExportFile.Id" xml:space="preserve"><value>Id</value></data>
<data name="dto.StayExportFile.ExportFormat" xml:space="preserve"><value>Export Format</value></data>
<data name="dto.StayExportFile.ExportParams" xml:space="preserve"><value>Export Params</value></data>
<data name="dto.StayExportFile.ExportResult" xml:space="preserve"><value>Export Result</value></data>
<data name="dto.StayExportFile.ExportedPath" xml:space="preserve"><value>Export Path</value></data>
<data name="dto.StayExportFile.ExportDetails" xml:space="preserve"><value>Export Details</value></data>
<data name="dto.StayExportFile.ExportTime" xml:space="preserve"><value>Export Time</value></data>
<data name="dto.StayExportParams.ExportType" xml:space="preserve"><value>Export Type</value></data>
<data name="dto.StayExportParams.ExportPeriodStart" xml:space="preserve"><value>Date From</value></data>
<data name="dto.StayExportParams.ExportPeriodEnd" xml:space="preserve"><value>Date To</value></data>
<data name="tmp" xml:space="preserve"><value>TMP</value></data> <data name="tmp" xml:space="preserve"><value>TMP</value></data>
<data name="general.actions" xml:space="preserve"><value>Actions</value></data> <data name="general.actions" xml:space="preserve"><value>Actions</value></data>
@@ -177,20 +189,32 @@
<data name="general.address.state" xml:space="preserve"><value>State</value></data> <data name="general.address.state" xml:space="preserve"><value>State</value></data>
<data name="general.address.country" xml:space="preserve"><value>Country</value></data> <data name="general.address.country" xml:space="preserve"><value>Country</value></data>
<data name="general.address.zipCode" xml:space="preserve"><value>Zip Code</value></data> <data name="general.address.zipCode" xml:space="preserve"><value>Zip Code</value></data>
<!-- Common codes --> <!-- Common codes -->
<data name="resultCode.Ok" xml:space="preserve"><value>OK</value></data> <data name="enum.ResultCode.Ok" xml:space="preserve"><value>OK</value></data>
<data name="resultCode.UnknownError" xml:space="preserve"><value>Unknown Error</value></data> <data name="enum.ResultCode.UnknownError" xml:space="preserve"><value>Unknown Error</value></data>
<data name="resultCode.FailedValidation" xml:space="preserve"><value>Failed entity validation</value></data> <data name="enum.ResultCode.FailedValidation" xml:space="preserve"><value>Failed entity validation</value></data>
<data name="resultCode.NotFound" xml:space="preserve"><value>Not found</value></data> <data name="enum.ResultCode.NotFound" xml:space="preserve"><value>Not found</value></data>
<data name="enum.ResultCode.FileStorageError" xml:space="preserve"><value>File Storage Error</value></data>
<!-- Specific codes --> <!-- Specific codes -->
<data name="resultCode.GuestInStay" xml:space="preserve"><value>Guest (ID: '{0}') is in a stay.</value></data> <data name="enum.ResultCode.GuestInStay" xml:space="preserve"><value>Guest (ID: '{0}') is in a stay.</value></data>
<data name="resultCode.GuestCurrentlyInStay" xml:space="preserve"><value>Guest (ID: '{0}') is already in one stay during the period: {1}</value></data> <data name="enum.ResultCode.GuestCurrentlyInStay" xml:space="preserve"><value>Guest (ID: '{0}') is already in one stay during the period: {1}</value></data>
<data name="enum.StayExportFileResult.OK" xml:space="preserve"><value>OK</value></data>
<data name="enum.StayExportFileResult.NoData" xml:space="preserve"><value>No Data</value></data>
<data name="enum.StayExportFileResult.ExportError" xml:space="preserve"><value>Export Error</value></data>
<data name="enum.StayExportFileResult.UploadError" xml:space="preserve"><value>File Error</value></data>
<data name="enum.StayExportFormat.GuestLogJson" xml:space="preserve"><value>GuestLog JSON</value></data>
<data name="enum.StayExportFormat.SpainParteViajeros" xml:space="preserve"><value>Spain Parte Viajeros</value></data>
<data name="enum.StayExportParamType.PeriodDateIn" xml:space="preserve"><value>Stay 'Date In' Period</value></data>
<data name="navMenu.GuestDocumentList" xml:space="preserve"><value>Guests</value></data> <data name="navMenu.GuestDocumentList" xml:space="preserve"><value>Guests</value></data>
<data name="navMenu.StayEntryList" xml:space="preserve"><value>Stays</value></data> <data name="navMenu.StayEntryList" xml:space="preserve"><value>Stays</value></data>
<data name="navMenu.StayExport" xml:space="preserve"><value>Stay Export</value></data>
<data name="page.GuestDocList.pageTitle" xml:space="preserve"><value>Guest Documents</value></data> <data name="page.GuestDocList.pageTitle" xml:space="preserve"><value>Guest Documents</value></data>
@@ -205,7 +229,14 @@
<data name="page.StayEntryList.btnNewStay" xml:space="preserve"><value>New Stay</value></data> <data name="page.StayEntryList.btnNewStay" xml:space="preserve"><value>New Stay</value></data>
<data name="page.StayEntryNew.pageTitle" xml:space="preserve"><value>New Stay</value></data> <data name="page.StayEntryNew.pageTitle" xml:space="preserve"><value>New Stay</value></data>
<data name="page.StayExportList.pageTitle" xml:space="preserve"><value>Stay Export Files</value></data>
<data name="page.StayExportList.exportList" xml:space="preserve"><value>Export List</value></data>
<data name="page.StayExportList.btnNewExport" xml:space="preserve"><value>New Export</value></data>
<data name="page.StayExportNew.pageTitle" xml:space="preserve"><value>New Stay Export</value></data>
<data name="control.GuestDocForm.sectionDocument" xml:space="preserve"><value>Document Details</value></data> <data name="control.GuestDocForm.sectionDocument" xml:space="preserve"><value>Document Details</value></data>
<data name="control.GuestDocForm.sectionGuest" xml:space="preserve"><value>Guest Details</value></data> <data name="control.GuestDocForm.sectionGuest" xml:space="preserve"><value>Guest Details</value></data>
<data name="control.GuestDocForm.sectionContact" xml:space="preserve"><value>Contact Details</value></data> <data name="control.GuestDocForm.sectionContact" xml:space="preserve"><value>Contact Details</value></data>
@@ -0,0 +1,19 @@
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.Entity;
public interface IStayExportFileEntityService
{
public Task<Result> CreateStayExportAsync(StayExportFileDTO dto);
public Task<Result> UpdateStayExportAsync(StayExportFileDTO dto);
/// <summary>
/// Delete StayExport entry from DB.
/// Exported File won't be deleted from Storage.
/// </summary>
public Task<Result> DeleteStayExportAsync(StayExportFileDTO dto);
public Task<StayExportFileDTO?> GetDtoByIdAsync(long id);
//public Task<IEnumerable<StayExportFileDTO>> GetDtoListByFilterAsync(StayExportFileFilterDTO filter, int limit = 0);
public Task<IEnumerable<StayExportFileDTO>> GetDtoListAsync(int limit = 0);
}
@@ -0,0 +1,139 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Infrastructure;
using Somnia.GuestLog.Models;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Models.Entities;
using Somnia.GuestLog.Utils;
namespace Somnia.GuestLog.Services.Entity;
public class StayExportFileEntityService(
ILogger<StayExportFileEntityService> logger,
IDbContextFactory<GuestLogContext> contextFactory
) : IStayExportFileEntityService
{
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,
ExportDetails = dto.ExportDetails,
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<Result> DeleteStayExportAsync(StayExportFileDTO dto)
{
try
{
using var dbContext = contextFactory.CreateDbContext();
int deletedCount = await dbContext.StayExportFiles
.Where(e => e.Id == dto.Id)
.ExecuteDeleteAsync();
if (deletedCount == 0)
{
logger.LogWarning("StayExportFileService - DeleteStayExportAsync: Error deleting StayExport. Entity not found with ID: '{ID}'", dto.Id);
return Result.Fail(ResultCode.NotFound);
}
logger.LogInformation(
"StayExportFileService - DeleteStayExportAsync: StayExport deleted with Id: '{id}'.", dto.Id);
return Result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "StayExportFileService - DeleteStayExportAsync: Error creating GuestDocument");
return Result.FailUnknownError();
}
}
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(int limit = 0)
{
using var dbContext = contextFactory.CreateDbContext();
IQueryable<StayExportFile> query = dbContext.StayExportFiles
.OrderByDescending(e => e.ExportTime)
.WithLimit(limit);
var dbList = await query.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
}
@@ -0,0 +1,7 @@
namespace Somnia.GuestLog.Services;
public interface ILocalizerService
{
public string GetEnumValue<TEnum>(TEnum? enumValue) where TEnum : struct, Enum;
public string GetEnumValue<TEnum>(TEnum enumValue) where TEnum : struct, Enum;
}
@@ -1,5 +1,5 @@
using Somnia.GuestLog.Enums.UI; using Somnia.GuestLog.Enums.UI;
using Somnia.GuestLog.Models.DTOs; using IResult = Somnia.GuestLog.Models.DTOs.IResult;
namespace Somnia.GuestLog.Services; namespace Somnia.GuestLog.Services;
@@ -7,6 +7,6 @@ public interface IUserMessageService
{ {
public void ShowMessage(string text, MessageKind kind, params object[] parameters); public void ShowMessage(string text, MessageKind kind, params object[] parameters);
public void ShowResult(Result resultDto); public void ShowResult(IResult resultDto);
public void ShowResultWithMessage(Result resultDto, string message); public void ShowResultWithMessage(IResult resultDto, string message);
} }
@@ -0,0 +1,37 @@
using Microsoft.Extensions.Localization;
using Somnia.GuestLog.Resources;
namespace Somnia.GuestLog.Services;
public class LocalizerService(
IServiceProvider serviceProvider
) : ILocalizerService
{
private IStringLocalizer<LanguageLocale> Localizer
{
get
{
field ??= serviceProvider.GetRequiredService<IStringLocalizer<LanguageLocale>>();
return field;
}
}
public string GetEnumValue<TEnum>(TEnum? enumValue) where TEnum : struct, Enum
{
if (enumValue == null)
{
return GuestConsts.EmptyField;
}
return GetEnumValue(enumValue.Value);
}
public string GetEnumValue<TEnum>(TEnum enumValue) where TEnum : struct, Enum
{
string enumName = typeof(TEnum).Name;
string? strEnumValue = Enum.GetName(enumValue);
string localeKey = $"enum.{enumName}.{strEnumValue}";
return Localizer[localeKey];
}
}
@@ -0,0 +1,6 @@
namespace Somnia.GuestLog.Services.SpainCodigoMunicipio;
public interface ISpainCodigoMunicipioService
{
public Task<string?> GetCodigoMunicipioAsync(string municipio, string province);
}
@@ -0,0 +1,123 @@
using System.Xml.Serialization;
using Microsoft.AspNetCore.WebUtilities;
namespace Somnia.GuestLog.Services.SpainCodigoMunicipio;
public class SpainCodigoMunicipioCatastroService(
ILogger<SpainCodigoMunicipioCatastroService> logger,
IHttpClientFactory httpFactory
) : ISpainCodigoMunicipioService
{
private const string Api_Host = "https://ovc.catastro.meh.es";
private const string Api_Address = "OVCServWeb/OVCWcfCallejero/COVCCallejero.svc/rest/ObtenerMunicipios";
private const string Api_Param_Provincia = "Provincia";
private const string Api_Param_Municipio = "Municipio";
//Result Cache.
readonly Dictionary<(string provincia, string municipio), string> codigoMunicipioCache = [];
public async Task<string?> GetCodigoMunicipioAsync(string municipio, string province)
{
var cacheKey = (province.ToUpper(), municipio.ToUpper());
//Try get from cache.
if (codigoMunicipioCache.TryGetValue(cacheKey, out string? cacheCode))
{
logger.LogInformation("SpainCodigoMunicipioCatastroService - Municipio found in cache for: '{key}'", cacheKey);
return cacheCode;
}
try
{
string uri = GetRequestUri(municipio, province);
logger.LogInformation("SpainCodigoMunicipioCatastroService - Getting municipios from API with query: '{addr}'", uri);
var httpClient = httpFactory.CreateClient();
using var rsStream = await httpClient.GetStreamAsync(uri);
XmlSerializer serializer = new(typeof(CatastroApiResult));
if (serializer.Deserialize(rsStream) is not CatastroApiResult rs)
{
logger.LogError("SpainCodigoMunicipioCatastroService - Result can't be deserialized!");
return null;
}
if (rs.municipios.Count == 0)
{
logger.LogWarning("SpainCodigoMunicipioCatastroService - No municipios found for query: '{addr}'", uri);
return null;
}
if (rs.municipios.Count > 1)
{
logger.LogWarning("SpainCodigoMunicipioCatastroService - More than 1 municipio was returned. First one will be used!");
}
CatastroApiResultCodigoIne? codIne = rs.municipios.First().codigoIne;
if (codIne == null || codIne.codigoMunicipio == null || codIne.codigoProvincia == null)
{
logger.LogWarning("SpainCodigoMunicipioCatastroService - Returned Municipio without data!");
return null;
}
string finalCode = $"{codIne.codigoProvincia}{codIne.codigoMunicipio}";
codigoMunicipioCache.Add(cacheKey, finalCode);
return finalCode;
}
catch (Exception ex)
{
logger.LogError(ex, "SpainCodigoMunicipioCatastroService - Error getting codigo municipio from catastro API!");
return null;
}
}
#region Internal Methods
private static string GetRequestUri(string municipio, string province)
{
string baseAddress = $"{Api_Host}/{Api_Address}";
return QueryHelpers.AddQueryString(baseAddress, [
new KeyValuePair<string, string?>(Api_Param_Provincia, province),
new KeyValuePair<string, string?>(Api_Param_Municipio, municipio),
]);
}
#endregion
#region API Model
[XmlRoot(ElementName = "consulta_municipiero", Namespace = "http://www.catastro.meh.es/")]
public class CatastroApiResult()
{
[XmlArray(ElementName = "municipiero")]
[XmlArrayItem(ElementName = "muni")]
public required List<CatastroApiResultMunicipio> municipios;
}
public class CatastroApiResultMunicipio()
{
[XmlElement(ElementName = "nm")]
public string? municipio;
[XmlElement(ElementName = "loine")]
public CatastroApiResultCodigoIne? codigoIne;
}
public class CatastroApiResultCodigoIne
{
[XmlElement(ElementName = "cp")]
public string? codigoProvincia;
[XmlElement(ElementName = "cm")]
public string? codigoMunicipio;
}
#endregion
}
@@ -0,0 +1,19 @@
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.StayExport;
public interface IStayExportFormatProvider
{
public StayExportFormat GetFormat();
public string GetFilename(DateTime exportTime);
/// <summary>
/// Export Data with the corresponding format.
/// Data is copied to given stream (no other operations are performed to the stream).
/// </summary>
/// <param name="stayList">List of Stays to export</param>
/// <param name="dataStream">Stream to copy exported data.</param>
public Task<(StayExportFileResult fileResult, string? exportDetails)> ExportDataAsync(IEnumerable<StayEntryDTO> stayList, Stream dataStream);
}
@@ -0,0 +1,11 @@
using Somnia.GuestLog.Enums.Models;
namespace Somnia.GuestLog.Services.StayExport;
public interface IStayExportFormatProviderFactory
{
/// <summary>
/// Returns the StayExport service implementation given current configuration.
/// </summary>
public IStayExportFormatProvider GetProvider(StayExportFormat exportFormat);
}
@@ -0,0 +1,14 @@
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.StayExport;
public interface IStayExportService
{
public Task<Result<StayExportFileDTO>> ExportStaysByParamsAsync(StayExportFormat format, StayExportParamsDTO exportParams);
public Task<Result> GetExportedFileAsync(StayExportFileDTO item, Stream dataStream);
public Task<Result> DeleteExportedFileAsync(StayExportFileDTO item);
}
@@ -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 StayExportFormatProviderFactory(
IServiceProvider serviceProvider,
IOptions<StayExportConfig> config
) : IStayExportFormatProviderFactory, IFactoryDI
{
public static void RegisterFactoryItems(IServiceCollection services)
{
services.AddKeyedSingleton<IStayExportFormatProvider, StayExportProviderJson>(StayExportFormat.GuestLogJson);
services.AddKeyedSingleton<IStayExportFormatProvider, StayExportProviderSpainParteViajeros>(StayExportFormat.SpainParteViajeros);
}
public IStayExportFormatProvider GetProvider(StayExportFormat exportFormat)
{
if (config.Value.EnableStayExport == false)
{
throw new InvalidOperationException("StayExport is disabled. Enable and configure it first!");
}
return serviceProvider.GetKeyedService<IStayExportFormatProvider>(exportFormat)
?? throw new InvalidOperationException($"StayExport service not found for ExportFormat: '{exportFormat}'");
}
}
@@ -0,0 +1,30 @@
using System.Text.Json;
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.StayExport;
public class StayExportProviderJson : IStayExportFormatProvider
{
private const string fileExtension = "json";
public StayExportFormat GetFormat() => StayExportFormat.GuestLogJson;
public string GetFilename(DateTime exportTime)
=> $"{Enum.GetName(GetFormat())}_{exportTime.ToFileTimeUtc()}.{fileExtension}";
public async Task<(StayExportFileResult fileResult, string? exportDetails)> ExportDataAsync(IEnumerable<StayEntryDTO> stayList, Stream dataStream)
{
if (!stayList.Any())
{
return (fileResult: StayExportFileResult.NoData, exportDetails: null);
}
// Convert to JSON.
await JsonSerializer.SerializeAsync(dataStream, stayList);
List<string> exportDetails = [.. stayList.Where(s => s.Id != null).Select(s => s.Id?.ToString() ?? "")];
string details = JsonSerializer.Serialize(exportDetails);
return (fileResult: StayExportFileResult.OK, exportDetails: details);
}
}
@@ -0,0 +1,411 @@
using System.Diagnostics;
using System.Text.Json;
using System.Xml.Serialization;
using FluentValidation;
using Microsoft.Extensions.Options;
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.Configuration;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Services.SpainCodigoMunicipio;
namespace Somnia.GuestLog.Services.StayExport;
public class StayExportProviderSpainParteViajeros(
ILogger<StayExportProviderSpainParteViajeros> logger,
ISpainCodigoMunicipioService codigoMunicipioService,
IOptions<StayExportSpainParteViajerosConfig> configOptions
) : IStayExportFormatProvider
{
private const string fileExtension = "xml";
private const string ExportDetailsResult_Error = "Error";
private const string ExportDetailsResult_Ok = "Ok";
private const string PersonRole = "VI";
private const string PersonRelation = "OT";
private const string PersonTipoDoc_NIF = "NIF";
private const string PersonTipoDoc_NIE = "NIE";
private const string PersonTipoDoc_PAS = "PAS";
private const string PersonTipoDoc_OTRO = "OTRO";
private const string PersonDireccionPais_ESP = "ESP";
private const string XmlNamespace_Peticion = "http://www.neg.hospedajes.mir.es/altaParteHospedaje";
private readonly StayExportSpainParteViajerosConfig config = configOptions.Value;
public StayExportFormat GetFormat() => StayExportFormat.SpainParteViajeros;
public string GetFilename(DateTime exportTime)
=> $"{Enum.GetName(GetFormat())}_{exportTime.ToFileTimeUtc()}.{fileExtension}";
public async Task<(StayExportFileResult fileResult, string? exportDetails)> ExportDataAsync(IEnumerable<StayEntryDTO> stayList, Stream dataStream)
{
if (string.IsNullOrEmpty(config.CodigoEstablecimiento))
{
logger.LogError("StayExportProviderSpainParteViajeros - Config error: CodigoEstablecimiento is not configured!");
return (fileResult: StayExportFileResult.ExportError, exportDetails: null);
}
if (!stayList.Any())
{
return (fileResult: StayExportFileResult.NoData, exportDetails: null);
}
List<StayExportDetails> stayExportDetails = [];
ComunicacionValidator comunicacionValidator = new();
List<Comunicacion> comunicacionsList = [];
foreach (StayEntryDTO stay in stayList)
{
(Comunicacion? comunicacion, string errorMsg) = await GetComunicacionFromStay(stay);
if (comunicacion == null)
{
logger.LogWarning("StayExportProviderSpainParteViajeros - Stay (ID: {id}) can't be exported: Error: {code}", stay.Id, errorMsg);
stayExportDetails.Add(new(StayId: stay.Id ?? -1, ExportResult: ExportDetailsResult_Error, Details: errorMsg));
continue;
}
var errors = comunicacionValidator.Validate(comunicacion);
if (!errors.IsValid)
{
logger.LogWarning("StayExportProviderSpainParteViajeros - Stay (ID: {id}) is invalid: Errors: {errors}", stay.Id, errors.Errors);
stayExportDetails.Add(new(StayId: stay.Id ?? -1, ExportResult: ExportDetailsResult_Error, Details: errors.ToString()));
continue;
}
comunicacionsList.Add(comunicacion);
logger.LogInformation("StayExportProviderSpainParteViajeros - Stay (ID: {id}) Exported OK", stay.Id);
stayExportDetails.Add(new(StayId: stay.Id ?? -1, ExportResult: ExportDetailsResult_Ok, Details: null));
}
Peticion peticion = new()
{
solicitud = new()
{
codigoEstablecimiento = config.CodigoEstablecimiento,
comunicacion = comunicacionsList,
}
};
XmlSerializer serializer = new(typeof(Peticion));
serializer.Serialize(dataStream, peticion);
string details = JsonSerializer.Serialize(stayExportDetails);
return (fileResult: StayExportFileResult.OK, exportDetails: details);
}
#region Internal Methods
private async Task<(Comunicacion? comunicacion, string errorMsg)> GetComunicacionFromStay(StayEntryDTO stay)
{
Debug.Assert(stay.Id != null
&& stay.DateIn != null
&& stay.DateOut != null
&& stay.GuestDocuments != null
);
//Call Fn to validate Stay.
Contrato contrato = new()
{
referencia = stay.Id.Value.ToString(),
fechaContrato = stay.DateIn.Value.Date,
fechaEntrada = stay.DateIn.Value,
fechaSalida = stay.DateOut.Value,
internet = config.InternetAvailable,
numHabitaciones = stay.RoomCount ?? -1,
numPersonas = stay.GuestDocuments.Count,
pago = new()
{
tipoPago = GetTipoPagoFromStay(stay)!
}
};
List<Persona> personasList = [];
foreach (GuestDocumentDTO doc in stay.GuestDocuments)
{
Direccion dir = new()
{
direccion = doc.Address!,
codigoPostal = doc.ZipCode!,
pais = doc.AddressCountry!,
};
//Get Municipio given current country.
if (doc.AddressCountry != PersonDireccionPais_ESP)
{
List<string?> addressParts = [doc.AddressCity, doc.AddressProvince, doc.AddressState];
dir.nombreMunicipio = string.Join(", ", addressParts.Where(p => !string.IsNullOrEmpty(p)));
}
if (doc.AddressCountry == PersonDireccionPais_ESP)
{
dir.codigoMunicipio = await GetMunicipioFromGuestAddressAsync(doc);
if (dir.codigoMunicipio == null)
{
return (
comunicacion: null,
errorMsg: "Can't get codigo municio"
);
}
}
Persona persona = new()
{
rol = PersonRole,
nombre = doc.Name!,
apellido1 = doc.Surname!,
apellido2 = doc.Surname2,
tipoDocumento = GetTipoDocumentoFromGuest(doc)!,
numeroDocumento = doc.DocumentNum!,
soporteDocumento = doc.SupportNum,
fechaNacimiento = doc.BirthDate?.Date ?? DateTime.MaxValue,
nacionalidad = doc.Nationality!,
sexo = GetSexoFromGuest(doc)!,
telefono = doc.PhoneNumber,
correo = doc.EmailAddress,
parentesco = PersonRelation,
direccion = dir,
};
personasList.Add(persona);
}
return (
comunicacion: new()
{
contrato = contrato,
persona = personasList
},
errorMsg: "OK");
}
private static string? GetTipoDocumentoFromGuest(GuestDocumentDTO doc)
{
return doc.DocumentType switch
{
GuestConsts.DocumentType_DNI => PersonTipoDoc_NIF,
GuestConsts.DocumentType_NIE => PersonTipoDoc_NIE,
GuestConsts.DocumentType_PASSPORT => PersonTipoDoc_PAS,
null => null,
_ => PersonTipoDoc_OTRO
};
}
private static string? GetSexoFromGuest(GuestDocumentDTO doc)
{
return doc.Gender switch
{
GuestConsts.GenderOptions_MALE => "H",
GuestConsts.GenderOptions_FEMALE => "F",
null => null,
_ => "O"
};
}
private static string? GetTipoPagoFromStay(StayEntryDTO stay)
{
return stay.PaymentMethod;
}
private async Task<string?> GetMunicipioFromGuestAddressAsync(GuestDocumentDTO doc)
{
if (string.IsNullOrEmpty(doc.AddressCity) || string.IsNullOrEmpty(doc.AddressProvince))
{
return null;
}
//Get codMunicipio from API.
return await codigoMunicipioService.GetCodigoMunicipioAsync(doc.AddressCity, doc.AddressProvince);
}
#endregion
#region Validator
private sealed class ComunicacionValidator : AbstractValidator<Comunicacion>
{
//TODO: Validate values in list for: Pago.tipoPago, Persona.sexo, Persona.tipoDocumento
public ComunicacionValidator()
{
RuleFor(comm => comm.contrato)
.NotNull()
.ChildRules(contrato =>
{
contrato.RuleFor(p => p.referencia)
.NotEmpty()
.MaximumLength(50);
contrato.RuleFor(p => p.fechaEntrada)
.LessThan(p => p.fechaSalida);
contrato.RuleFor(p => p.fechaSalida)
.GreaterThan(p => p.fechaEntrada);
contrato.RuleFor(p => p.numHabitaciones)
.GreaterThanOrEqualTo(0);
//BLOQUE PAGO
contrato.RuleFor(p => p.pago)
.ChildRules(e =>
{
e.RuleFor(p => p.tipoPago)
.NotEmpty();
});
});
RuleForEach(comm => comm.persona)
.ChildRules(person =>
{
person.RuleFor(p => p.rol)
.Equal(PersonRole);
person.RuleFor(p => p.nombre)
.NotEmpty()
.MaximumLength(50);
person.RuleFor(p => p.apellido1)
.NotEmpty()
.MaximumLength(50);
person.RuleFor(p => p.apellido2)
.MaximumLength(50);
person.RuleFor(p => p.tipoDocumento)
.NotEmpty()
.MaximumLength(5);
person.RuleFor(p => p.numeroDocumento)
.NotEmpty()
.MaximumLength(15);
person.RuleFor(p => p.soporteDocumento)
.NotEmpty()
.When(p => p.tipoDocumento == PersonTipoDoc_NIF || p.tipoDocumento == PersonTipoDoc_NIE);
person.RuleFor(p => p.fechaNacimiento)
.NotEmpty();
person.RuleFor(p => p.sexo)
.MaximumLength(1);
person.RuleFor(p => p.telefono)
.MaximumLength(20);
person.RuleFor(p => p.correo)
.MaximumLength(250);
person.RuleFor(p => p.direccion)
.ChildRules(d =>
{
d.RuleFor(p => p.direccion)
.NotEmpty()
.MaximumLength(100);
d.RuleFor(p => p.codigoMunicipio)
.NotEmpty()
.When(p => p.pais == PersonDireccionPais_ESP)
.MaximumLength(5);
d.RuleFor(p => p.nombreMunicipio)
.NotEmpty()
.When(p => p.pais != PersonDireccionPais_ESP)
.MaximumLength(100);
d.RuleFor(p => p.codigoMunicipio)
.NotEmpty()
.MaximumLength(20);
d.RuleFor(p => p.pais)
.NotEmpty()
.Length(3);
});
});
RuleForEach(comm => comm.persona)
.Must(p => !string.IsNullOrEmpty(p.telefono) || !string.IsNullOrEmpty(p.correo))
.WithMessage($"It's required to have at least one of the following fields: '{nameof(Persona.telefono)}', '{nameof(Persona.correo)}'");
}
}
#endregion
#region Export Data Classes
private record StayExportDetails(long StayId, string ExportResult, string? Details);
[XmlRoot(ElementName = "peticion", Namespace = XmlNamespace_Peticion)]
public class Peticion
{
public required Solicitud solicitud;
}
[XmlRoot(ElementName = "solicitud")]
public class Solicitud
{
public required string codigoEstablecimiento;
public required List<Comunicacion> comunicacion;
}
[XmlRoot(ElementName = "comunicacion")]
public class Comunicacion
{
public required Contrato contrato;
public required List<Persona> persona;
}
[XmlRoot(ElementName = "contrato")]
public class Contrato
{
public required string referencia;
[XmlElement(DataType = "date")]
public required DateTime fechaContrato;
[XmlElement(DataType = "dateTime")]
public required DateTime fechaEntrada;
[XmlElement(DataType = "dateTime")]
public required DateTime fechaSalida;
public required int numPersonas;
public int? numHabitaciones;
public bool? internet;
//BLOQUE PAGO
public required Pago pago;
}
[XmlRoot(ElementName = "persona")]
public class Persona
{
public required string rol;
public required string nombre;
public required string apellido1;
public string? apellido2;
public required string tipoDocumento;
public required string numeroDocumento;
public string? soporteDocumento;
[XmlElement(DataType = "date")]
public required DateTime fechaNacimiento;
public required string nacionalidad;
public required string sexo;
public string? telefono;
public string? correo;
public required string parentesco;
// BLOQUE DIRECCION
public required Direccion direccion;
}
public class Pago
{
public required string tipoPago;
// [XmlElement(DataType = "date")]
// public required DateTime fechaPago;
public string? medioPago;
public string? titular;
public string? caducidadTarjeta;
}
public class Direccion
{
public required string direccion;
public string? codigoMunicipio;
public string? nombreMunicipio;
public required string codigoPostal;
public required string pais;
}
#endregion
}
@@ -0,0 +1,247 @@
using System.Diagnostics;
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 StayExportService(
ILogger<StayExportProviderJson> logger,
IOptions<StayExportConfig> exportConfig,
IStayExportFileEntityService stayExportEntityService,
IStayEntryEntityService stayEntityService,
IStayExportFormatProviderFactory providerFactory
) : IStayExportService
{
private static readonly StayEntryQueryConfig queryConfig =
new(IncludeGuests: true, UseSplitQueries: true, DisableTracking: true);
private readonly StayExportConfig config = exportConfig.Value;
public async Task<Result<StayExportFileDTO>> ExportStaysByParamsAsync(StayExportFormat format, 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 = format,
ExportParams = exportParams,
ExportTime = exportTime,
};
//Export data.
using Stream exportedDataStream = new MemoryStream();
//Generate data to export.
StayExportFileResult exportResult;
string? exportFilename = null;
try
{
//Create Format provider and export data to stream.
var provider = providerFactory.GetProvider(format);
(exportResult, stayExport.ExportDetails) = await provider.ExportDataAsync(stayList, exportedDataStream);
// "Rewind" stream so it can be read from the begining when uploading.
exportedDataStream.Seek(0, SeekOrigin.Begin);
exportFilename = provider.GetFilename(exportTime);
}
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
{
Debug.Assert(exportFilename != null);
string exportPathSubdir = "";
if (config.UseSubdirectoryByFormat)
{
exportPathSubdir = Enum.GetName(format) ?? "";
}
string exportPath = Path.Combine(exportPathSubdir, exportFilename);
//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);
}
public async Task<Result> GetExportedFileAsync(StayExportFileDTO item, Stream dataStream)
{
if (string.IsNullOrEmpty(item.ExportedPath))
{
logger.LogWarning("Trying to get exported file without path!! Exported file can't be loaded!");
return Result.Fail(ResultCode.NotFound);
}
try
{
IStore store = GetExportStore();
await store.GetObject(item.ExportedPath, dataStream);
}
catch (Exception ex)
{
logger.LogError(ex, "Error getting exported file '{id}' from path '{path}'", item.Id, item.ExportedPath);
return Result.FailUnknownError();
}
return Result.Ok();
}
public async Task<Result> DeleteExportedFileAsync(StayExportFileDTO item)
{
//Try to delete existing file.
if (!string.IsNullOrEmpty(item.ExportedPath))
{
bool fileDeletedFromStore = await DeleteExportFileFromStoreAsync(item);
if (!fileDeletedFromStore)
{
return Result.Fail(ResultCode.FileStorageError);
}
}
//Delete entry from DB.
Result deleteResult = await stayExportEntityService.DeleteStayExportAsync(item);
if (!deleteResult.IsSuccess)
{
return Result.Fail(deleteResult.ResultCode);
}
return Result.Ok();
}
#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<bool> DeleteExportFileFromStoreAsync(StayExportFileDTO item)
{
Debug.Assert(!string.IsNullOrEmpty(item.ExportedPath));
try
{
IStore store = GetExportStore();
bool objectExist = await store.ObjectExists(item.ExportedPath);
if (!objectExist)
{
logger.LogWarning("StayExportService - File for item {id} not found in store! Skip delete!", item.Id);
return true;
}
await store.DeleteObject(item.ExportedPath);
logger.LogInformation("StayExportService - File for item {id} deleted from path {path}", item.Id, item.ExportedPath);
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "StayExportService - Error deleting export file of item {id}", item.Id);
return false;
}
}
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
}
@@ -1,26 +1,16 @@
using Microsoft.Extensions.Localization;
using MudBlazor; using MudBlazor;
using Somnia.GuestLog.Enums.Services; using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Enums.UI; using Somnia.GuestLog.Enums.UI;
using Somnia.GuestLog.Models.DTOs; using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Resources; using IResult = Somnia.GuestLog.Models.DTOs.IResult;
namespace Somnia.GuestLog.Services; namespace Somnia.GuestLog.Services;
public class UserMessageService( public class UserMessageService(
IServiceProvider serviceProvider, ILocalizerService Localizer,
ISnackbar snackbar ISnackbar snackbar
) : IUserMessageService ) : IUserMessageService
{ {
private IStringLocalizer<LanguageLocale> _localizer
{
get
{
return serviceProvider.GetRequiredService<IStringLocalizer<LanguageLocale>>();
}
}
public void ShowMessage(string text, MessageKind kind, params object[] parameters) public void ShowMessage(string text, MessageKind kind, params object[] parameters)
{ {
string formatedMsg = GetFormatedMessage(text, parameters); string formatedMsg = GetFormatedMessage(text, parameters);
@@ -28,12 +18,12 @@ public class UserMessageService(
} }
public void ShowResult(Result resultDto) public void ShowResult(IResult resultDto)
{ {
ShowResultWithMessage(resultDto, message: null); ShowResultWithMessage(resultDto, message: null);
} }
public void ShowResultWithMessage(Result resultDto, string? message) public void ShowResultWithMessage(IResult resultDto, string? message)
{ {
string resultMsg = GetMsgForResultCode(resultDto.ResultCode); string resultMsg = GetMsgForResultCode(resultDto.ResultCode);
resultMsg = GetFormatedMessage(resultMsg, resultDto.Context); resultMsg = GetFormatedMessage(resultMsg, resultDto.Context);
@@ -61,7 +51,7 @@ public class UserMessageService(
private string GetMsgForResultCode(ResultCode resultCode) private string GetMsgForResultCode(ResultCode resultCode)
{ {
return _localizer[$"resultCode.{Enum.GetName(resultCode)}"]; return Localizer.GetEnumValue(resultCode);
} }
private static string GetFormatedMessage(string template, params object[]? parameters) private static string GetFormatedMessage(string template, params object[]? parameters)
@@ -8,6 +8,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FluentStorage" />
<PackageReference Include="FluentStorage.AWS" />
<PackageReference Include="FluentValidation" /> <PackageReference Include="FluentValidation" />
<PackageReference Include="MudBlazor" /> <PackageReference Include="MudBlazor" />
</ItemGroup> </ItemGroup>
@@ -8,4 +8,9 @@ public static class QueryExtensions
{ {
return condition ? source.Where(predicate) : source; return condition ? source.Where(predicate) : source;
} }
public static IQueryable<T> WithLimit<T>(this IQueryable<T> source, int limit)
{
return limit > 0 ? source.Take(limit) : source;
}
} }
@@ -0,0 +1,23 @@
using FluentValidation;
using Somnia.GuestLog.Enums.Models;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Validators;
public class StayExportParamsDTOValidator : ValueValidator<StayExportParamsDTO>
{
public StayExportParamsDTOValidator()
{
RuleFor(e => e.ExportType)
.NotEmpty();
RuleFor(e => e.ExportPeriodStart)
.NotEmpty()
.When(e => e.ExportType == StayExportParamType.PeriodDateIn);
RuleFor(e => e.ExportPeriodEnd)
.NotEmpty()
.When(e => e.ExportType == StayExportParamType.PeriodDateIn);
}
}
+9
View File
@@ -20,5 +20,14 @@
"ApiKey": "", "ApiKey": "",
"UserAgent": "Somnia-GuestLog-Dev", "UserAgent": "Somnia-GuestLog-Dev",
"ResultLang": "es" "ResultLang": "es"
},
"StayExport": {
"EnableStayExport": true,
"ExportStorageConnectionString": "disk://path=/SomniaGuestLog/StayExportFiles",
"UseSubdirectoryByFormat": true
},
"StayExportSpainParteViajeros": {
"InternetAvailable": true,
"CodigoEstablecimiento": ""
} }
} }
+13
View File
@@ -0,0 +1,13 @@
// Function to download files from Blazor pages
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
}