Compare commits

...
4 Commits
Author SHA256 Message Date
Daniel-Garmig 887c3d787a GuestDocument Versions - Part 1:
- Changed GuestDocument PK from `DocumentType`+`DocumentNumber` to to `ID`+`Version` for future versioning.
- Added DB field "IsLastVersion" to simplify queries where only last/current version is allowed.
- Updated GuestDocument DB fields type for `CreateTime` & `UpdateTime` to add precision.
- Updated usages of GuestDocument PK to new PK.
- Limit delete of a GuestDocument when it's currently used in a StayEntry.

Note: DB changes require recreating db tables, so all data is lost and migration "rollback" is not allowed.
2026-09-01 15:04:38 +02:00
Daniel-Garmig a01eed82e1 GuestLog - Nominatim AddressQueryService fix for Provinces.
- Small fix in Nominatim AddressQueryService to map provinces using fields "state_district" and "county" in results.
2026-09-01 11:01:05 +02:00
Daniel-Garmig b08aaf2d7b Moved and renamed Db/Entity services for better organization. 2026-08-30 20:20:03 +02:00
Daniel-Garmig 4f22cd4541 GuestLog - Moved Enums
- Enums moved to Enum folder (by type).
- ResultCode class changed to enum to ensure type safety in results.
2026-08-25 15:18:02 +02:00
37 changed files with 616 additions and 173 deletions
@@ -1,9 +1,10 @@
@using Somnia.GuestLog.Models.DTOs;
@using Somnia.GuestLog.Services
@using Somnia.GuestLog.Services.Entity
@inject ILogger<AddressQueryDialog> logger;
@inject IUserMessageService userMessage
@inject IGuestDocumentService guestDocumentService;
@inject IGuestDocumentEntityService guestDocumentService;
<MudDialog Style="max-height: 90%;">
@@ -77,7 +78,10 @@
private IMudDialogInstance MudDialog { get; set; } = null!;
private GuestDocFilterDTO filter { get; set; } = new();
private GuestDocFilterDTO filter { get; set; } = new()
{
OnlyLastVersion = true
};
private IEnumerable<GuestDocumentDTO> results = [];
private GuestDocumentDTO? SelectedResult { get; set; }
@@ -95,7 +95,7 @@
{
<MudTd DataLabel="@LanguageLocale.general_actions">
<MudIconButton Icon="@Icons.Material.Filled.Delete"
OnClick="@(() => BtnDeleteGuest(context.DocumentType!, context.DocumentNum!))" />
OnClick="@(() => BtnDeleteGuest(context.Id!.Value, context.Version!.Value))" />
</MudTd>
}
@if (ReadOnly)
@@ -229,8 +229,7 @@
//Check if this guest is already added.
if (Model.GuestDocuments.Count > 0)
{
bool alreadyAdded = Model.GuestDocuments.Any(e => e.DocumentType == resultData.DocumentType
&& e.DocumentNum == resultData.DocumentNum);
bool alreadyAdded = Model.GuestDocuments.Any(e => e.Id == resultData.Id);
if (alreadyAdded)
{
userMessage.ShowMessage("GuestDocument already added!", MessageKind.Warning);
@@ -241,13 +240,13 @@
Model.GuestDocuments.Add(resultData);
}
private void BtnDeleteGuest(string docType, string docNum)
private void BtnDeleteGuest(long guestDocId, int version)
{
Debug.Assert(Model.GuestDocuments is not null);
//Filter out given GuestDocument from model.
Model.GuestDocuments = Model.GuestDocuments
.Where(e => !(e.DocumentType == docType && e.DocumentNum == docNum))
.Where(e => !(e.Id == guestDocId && e.Version == version))
.ToList();
}
@@ -7,14 +7,14 @@
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject NavigationManager Navigation
@inject IGuestDocumentService guestDocService
@inject IStayEntryService stayService
@inject IGuestDocumentEntityService guestDocService
@inject IStayEntryEntityService stayService
<PageTitle>Somnia - Guest Docs - Details</PageTitle>
<MudStack Row="true" Class="my-4">
<MudText Typo="Typo.h4" GutterBottom="true">Guest Document - "@docId"</MudText>
<MudText Typo="Typo.h4" GutterBottom="true">Guest Document: @docId - @documentModel?.FullDocument</MudText>
<MudSpacer />
<MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small" StartIcon="@Icons.Material.Filled.Edit"
OnClick="() => BtnEdit()" Disabled>
@@ -77,7 +77,7 @@
@code {
[Parameter]
public string? docId { get; set; }
public long docId { get; set; }
GuestDocForm _form = null!;
@@ -90,23 +90,8 @@
protected override async Task OnInitializedAsync()
{
if (docId is null)
{
userMessage.ShowMessage("No GuestDocument provided!!", MessageKind.Error);
Navigation.NotFound();
return;
}
GuestDocIdDTO? docIdModel = GuestDocIdDTO.DecodeFromString(docId);
if (docIdModel is null)
{
userMessage.ShowMessage($"Provided GuestDocId can't be decoded: '{docId}'", MessageKind.Error);
Navigation.NotFound();
return;
}
//Get model from db.
documentModel = await guestDocService.GetDtoByIdAsync(docIdModel.DocumentType, docIdModel.DocumentNum);
documentModel = await guestDocService.GetLastVersionDtoByIdAsync(docId);
if (documentModel is null)
{
userMessage.ShowMessage($"GuestDocument not found with ID: '{docId}'", MessageKind.Error);
@@ -123,13 +108,13 @@
return;
}
if (documentModel is null || documentModel.DocumentType is null || documentModel.DocumentNum is null)
if (documentModel is null || documentModel.Id is null || documentModel.Version is null)
{
throw new InvalidOperationException();
}
guestStaysLoading = true;
guestStayList = await stayService.GetStaysWithGuest(documentModel.DocumentType, documentModel.DocumentNum);
guestStayList = await stayService.GetStaysWithGuest(documentModel.Id.Value);
guestStaysLoading = false;
}
@@ -3,7 +3,7 @@
@using Somnia.GuestLog.Models.DTOs;
@using Somnia.GuestLog.Services;
@inject IGuestDocumentService GuestDocService
@inject IGuestDocumentEntityService GuestDocService
@inject NavigationManager Navigation
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@@ -43,6 +43,8 @@
</MudStack>
</ToolBarContent>
<Columns>
<PropertyColumn Property="x => x.Id" Title="@LanguageLocale.dto_GuestDocument_Id" />
<PropertyColumn Property="x => x.Version" Title="@LanguageLocale.dto_GuestDocument_Version" />
<PropertyColumn Title="@LanguageLocale.dto_GuestDocument_DocumentType"
Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_DocumentTypes, x.DocumentType)"
Hideable="false" />
@@ -50,6 +52,7 @@
Title="@LanguageLocale.dto_GuestDocument_DocumentNum" />
<PropertyColumn Property="x => x.Name" Title="@LanguageLocale.dto_GuestDocument_Name" />
<PropertyColumn Property="x => x.Surname" Title="@LanguageLocale.dto_GuestDocument_Surname" />
<PropertyColumn Property="x => x.Surname2" Title="@LanguageLocale.dto_GuestDocument_Surname2" />
<PropertyColumn Title="@LanguageLocale.dto_GuestDocument_Nationality"
Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_CountryCodes, x.Nationality)" />
<PropertyColumn Property="x => x.UpdateTime" Title="@LanguageLocale.dto_GuestDocument_UpdateTime" />
@@ -126,10 +129,9 @@
private async Task BtnViewDetails(GuestDocumentDTO item)
{
GuestDocIdDTO idDto = GuestDocIdDTO.BuildFromDto(item) ?? throw new InvalidOperationException();
string strId = item.Id?.ToString() ?? throw new InvalidOperationException();
string itemId = GuestDocIdDTO.EncodeAsString(idDto);
string uri = GuestConsts.Page_GuestDocs_Detail.Replace(GuestConsts.Page_GuestDocs_Detail_Param_DocId, itemId);
string uri = GuestConsts.Page_GuestDocs_Detail.Replace(GuestConsts.Page_GuestDocs_Detail_Param_DocId, strId);
Navigation.NavigateTo(uri);
}
@@ -151,7 +153,7 @@
}
userMessage.ShowMessage($"Document {item.DocumentType}-{item.DocumentNum} deleted!", MessageKind.Success);
await LoadDataAsync();
await LoadDataAsync(showMsg: false);
}
private void BtnNewGuest()
@@ -7,7 +7,7 @@
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject NavigationManager Navigation
@inject IGuestDocumentService guestDocService
@inject IGuestDocumentEntityService guestDocService
@inject IDataListService dataListService;
@inject FluentValidation.IValidator<GuestDocIdDTO> docIdValidator;
@@ -82,6 +82,7 @@
ePageMode currentPageMode = ePageMode.selectDocId;
GuestDocIdDTO currentDocId = new() { DocumentNum = "", DocumentType = "" };
long? alreadyExistDocId = null;
GuestDocumentDTO newDocumentModel = new();
bool loadingDocId = false;
@@ -100,7 +101,8 @@
}
loadingDocId = true;
GuestDocumentDTO? dto = await guestDocService.GetDtoByIdAsync(currentDocId.DocumentType, currentDocId.DocumentNum);
GuestDocumentDTO? dto =
await guestDocService.GetLastVersionDtoByDocumentAsync(currentDocId.DocumentType, currentDocId.DocumentNum);
loadingDocId = false;
if (dto is null)
@@ -117,6 +119,7 @@
//GuestDoc already exists!
currentPageMode = ePageMode.alreadyExistDoc;
alreadyExistDocId = dto.Id;
}
private void BtnReturn()
@@ -153,14 +156,15 @@
private void BtnGoToDocument()
{
if (currentPageMode != ePageMode.alreadyExistDoc)
if (currentPageMode != ePageMode.alreadyExistDoc || alreadyExistDocId is null)
{
userMessage.ShowMessage("Invalid operation!", MessageKind.Error);
return;
}
string docId = GuestDocIdDTO.EncodeAsString(currentDocId);
string uri = GuestConsts.Page_GuestDocs_Detail.Replace("{docId}", docId);
string strId = alreadyExistDocId.Value.ToString();
string uri = GuestConsts.Page_GuestDocs_Detail.Replace(GuestConsts.Page_GuestDocs_Detail_Param_DocId, strId);
Navigation.NavigateTo(uri);
}
@@ -6,8 +6,8 @@
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject NavigationManager Navigation
@inject IGuestDocumentService guestDocService
@inject IStayEntryService stayService
@inject IGuestDocumentEntityService guestDocService
@inject IStayEntryEntityService stayService
<PageTitle>Somnia - Guest Docs - Details</PageTitle>
@@ -3,7 +3,7 @@
@using Somnia.GuestLog.Models.DTOs;
@using Somnia.GuestLog.Services;
@inject IStayEntryService StayEntryService
@inject IStayEntryEntityService StayEntryService
@inject NavigationManager Navigation
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@@ -117,7 +117,7 @@
private async Task BtnViewDetails(StayEntryDTO item)
{
string itemId = $"{item.Id ?? -1}";
string itemId = item.Id?.ToString() ?? throw new InvalidOperationException();
string uri = GuestConsts.Page_StayEntry_Detail.Replace(GuestConsts.Page_StayEntry_Detail_Param_Id, itemId);
Navigation.NavigateTo(uri);
}
@@ -7,7 +7,7 @@
@inject IUserMessageService userMessage
@inject IDialogService DialogService
@inject NavigationManager Navigation
@inject IStayEntryService stayService
@inject IStayEntryEntityService stayService
@inject IDataListService dataListService;
<PageTitle>Somnia - Stay Entries - New</PageTitle>
@@ -1 +1,2 @@
@using Somnia.GuestLog.Components.Controls
@using Somnia.GuestLog.Services.Entity;
@@ -16,4 +16,4 @@
@using Somnia.GuestLog.Components.Forms
@using Somnia.GuestLog.Components.Controls
@using Somnia.GuestLog.Resources
@using MessageKind = Somnia.GuestLog.Services.IUserMessageService.MessageKind;
@using Somnia.GuestLog.Enums.UI
@@ -0,0 +1,7 @@
namespace Somnia.GuestLog.Enums.Services;
public enum AddressQueryProvider
{
Nominatim,
GoogleApiV4
}
@@ -0,0 +1,14 @@
namespace Somnia.GuestLog.Enums.Services;
public enum ResultCode
{
//Common Codes
Ok,
UnknownError,
FailedValidation,
NotFound,
//Specific Codes
GuestInStay,
GuestCurrentlyInStay,
}
@@ -1,4 +1,4 @@
namespace Somnia.GuestLog.Components.Forms;
namespace Somnia.GuestLog.Enums.UI;
public enum FormMode
{
@@ -0,0 +1,6 @@
namespace Somnia.GuestLog.Enums.UI;
public enum MessageKind
{
Info, Warning, Error, Success, Normal
}
+3 -1
View File
@@ -6,7 +6,7 @@ public static class GuestConsts
public const string Page_GuestDocs_List = "/guest-documents";
public const string Page_GuestDocs_New = "/guest-documents/new";
public const string Page_GuestDocs_Detail = $"/guest-documents/d/{Page_GuestDocs_Detail_Param_DocId}";
public const string Page_GuestDocs_Detail_Param_DocId = "{docId}";
public const string Page_GuestDocs_Detail_Param_DocId = "{docId:long}";
public const string Page_StayEntry_List = "/stayEntries";
public const string Page_StayEntry_New = "/stayEntries/new";
@@ -28,4 +28,6 @@ public static class GuestConsts
public const string DocumentType_DNI = "DNI";
public const string DocumentType_NIE = "NIE";
public const string DocumentType_PASSPORT = "PASSPORT";
public const int GuestDocument_FirstVersion = 1;
}
@@ -11,7 +11,13 @@ public class GuestDocumentEntityConfig : IEntityTypeConfiguration<GuestDocument>
builder.ToTable("GuestDocument");
//PK
builder.HasKey(e => new { e.DocumentType, e.DocumentNum });
builder.HasKey(e => new { e.Id, e.Version });
builder.Property(e => e.Id)
.UseIdentityByDefaultColumn();
builder.Property(e => e.Version)
.IsRequired();
builder.Property(e => e.DocumentType)
.IsRequired()
@@ -48,6 +54,15 @@ public class GuestDocumentEntityConfig : IEntityTypeConfiguration<GuestDocument>
builder.Property(e => e.EmailAddress)
.HasMaxLength(256);
builder.Property(e => e.CreateTime)
.IsRequired()
.HasColumnType(DbConsts.DbType_Timestamptz_3);
builder.Property(e => e.UpdateTime)
.IsRequired()
.HasColumnType(DbConsts.DbType_Timestamptz_3);
builder.Property(e => e.IsLastVersion)
.IsRequired();
var addressBuilder = builder.ComplexProperty(e => e.AddressDetails);
@@ -0,0 +1,205 @@
// <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("20260830201743_GuestDocument_ChangePKToIdAndVersion")]
partial class GuestDocument_ChangePKToIdAndVersion
{
/// <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 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<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 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("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,101 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Somnia.GuestLog.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class GuestDocument_ChangePKToIdAndVersion : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
//Data don't really matter right now. Just get it working good.
//This migration will destry all data, but it's fine.
migrationBuilder.DropTable(
name: "GuestDocumentStayEntry"
);
migrationBuilder.Sql("""DELETE FROM "StayEntry";""");
migrationBuilder.DropTable(
name: "GuestDocument"
);
migrationBuilder.CreateTable(
name: "GuestDocument",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Version = table.Column<int>(type: "integer", nullable: false),
DocumentType = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: false),
DocumentNum = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
IssueDate = table.Column<DateOnly>(type: "date", nullable: false),
SupportNum = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: true),
Nationality = table.Column<string>(type: "character varying(3)", maxLength: 3, nullable: false),
Name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Surname = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Surname2 = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
BirthDate = table.Column<DateOnly>(type: "date", nullable: false),
Gender = table.Column<string>(type: "character varying(1)", maxLength: 1, nullable: true),
PhoneNumber = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true),
EmailAddress = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
CreateTime = table.Column<DateTime>(type: "timestamp(3) with time zone", nullable: false),
UpdateTime = table.Column<DateTime>(type: "timestamp(3) with time zone", nullable: false),
IsLastVersion = table.Column<bool>(type: "boolean", nullable: false),
AddressDetails_Address = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
AddressDetails_AddressCity = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
AddressDetails_AddressCountry = table.Column<string>(type: "character varying(3)", maxLength: 3, nullable: true),
AddressDetails_AddressProvince = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
AddressDetails_AddressState = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
AddressDetails_ZipCode = table.Column<string>(type: "character varying(12)", maxLength: 12, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_GuestDocument", x => new { x.Id, x.Version });
}
);
//Existing index for "DocType" and "DocNum" can be useful, so let's keep it.
migrationBuilder.CreateTable(
name: "GuestDocumentStayEntry",
columns: table => new
{
StayEntryId = table.Column<long>(type: "bigint", nullable: false),
GuestDocumentsId = table.Column<long>(type: "bigint", nullable: false),
GuestDocumentsVersion = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_GuestDocumentStayEntry", x => new { x.StayEntryId, x.GuestDocumentsId, x.GuestDocumentsVersion });
table.ForeignKey(
name: "FK_GuestDocumentStayEntry_GuestDocument_GuestDocumentsId_Guest~",
columns: x => new { x.GuestDocumentsId, x.GuestDocumentsVersion },
principalTable: "GuestDocument",
principalColumns: new[] { "Id", "Version" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_GuestDocumentStayEntry_StayEntry_StayEntryId",
column: x => x.StayEntryId,
principalTable: "StayEntry",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_GuestDocumentStayEntry_GuestDocumentsId_GuestDocumentsVersi~",
table: "GuestDocumentStayEntry",
columns: new[] { "GuestDocumentsId", "GuestDocumentsVersion" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
throw new NotSupportedException("Rollback is not supported for this migration!");
}
}
}
@@ -19,6 +19,9 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
#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);
@@ -28,34 +31,45 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
b.Property<long>("StayEntryId")
.HasColumnType("bigint");
b.Property<string>("GuestDocumentsDocumentType")
.HasColumnType("character varying(8)");
b.Property<long>("GuestDocumentsId")
.HasColumnType("bigint");
b.Property<string>("GuestDocumentsDocumentNum")
.HasColumnType("character varying(64)");
b.Property<int>("GuestDocumentsVersion")
.HasColumnType("integer");
b.HasKey("StayEntryId", "GuestDocumentsDocumentType", "GuestDocumentsDocumentNum");
b.HasKey("StayEntryId", "GuestDocumentsId", "GuestDocumentsVersion");
b.HasIndex("GuestDocumentsDocumentType", "GuestDocumentsDocumentNum");
b.HasIndex("GuestDocumentsId", "GuestDocumentsVersion");
b.ToTable("GuestDocumentStayEntry");
});
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.GuestDocument", b =>
{
b.Property<string>("DocumentType")
.HasMaxLength(8)
.HasColumnType("character varying(8)");
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
b.Property<string>("DocumentNum")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("Version")
.HasColumnType("integer");
b.Property<DateOnly>("BirthDate")
.HasColumnType("date");
b.Property<DateTime>("CreateTime")
.HasColumnType("timestamp with time zone");
.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)
@@ -65,6 +79,9 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
.HasMaxLength(1)
.HasColumnType("character varying(1)");
b.Property<bool>("IsLastVersion")
.HasColumnType("boolean");
b.Property<DateOnly>("IssueDate")
.HasColumnType("date");
@@ -96,7 +113,7 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
.HasColumnType("character varying(64)");
b.Property<DateTime>("UpdateTime")
.HasColumnType("timestamp with time zone");
.HasColumnType("timestamp(3) with time zone");
b.ComplexProperty(typeof(Dictionary<string, object>), "AddressDetails", "Somnia.GuestLog.Models.Entities.GuestDocument.AddressDetails#GuestAddress", b1 =>
{
@@ -126,7 +143,7 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
.HasColumnType("character varying(12)");
});
b.HasKey("DocumentType", "DocumentNum");
b.HasKey("Id", "Version");
b.ToTable("GuestDocument", (string)null);
});
@@ -178,7 +195,7 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
b.HasOne("Somnia.GuestLog.Models.Entities.GuestDocument", null)
.WithMany()
.HasForeignKey("GuestDocumentsDocumentType", "GuestDocumentsDocumentNum")
.HasForeignKey("GuestDocumentsId", "GuestDocumentsVersion")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
@@ -1,3 +1,5 @@
using Somnia.GuestLog.Enums.Services;
namespace Somnia.GuestLog.Models.Configuration;
public class AddressQueryConfig
@@ -5,18 +7,10 @@ public class AddressQueryConfig
public const string SectionName = "AddressQuery";
public bool EnableAddressQuery { get; set; }
public AddressQueryProviderEnum? Provider { get; set; }
public AddressQueryProvider? Provider { get; set; }
public string? ServiceURL { get; set; }
public string? ApiKey { get; set; }
public string? UserAgent { get; set; }
public string? ResultLang { get; set; }
public enum AddressQueryProviderEnum
{
Nominatim,
GoogleApiV4
}
}
@@ -10,6 +10,8 @@ public class GuestDocFilterDTO
public string? PhoneNumber { get; set; }
public bool OnlyLastVersion { get; set; }
public bool IsEmpty => string.IsNullOrEmpty(DocumentType)
&& string.IsNullOrEmpty(DocumentNumber)
@@ -2,6 +2,9 @@ namespace Somnia.GuestLog.Models.DTOs;
public class GuestDocumentDTO
{
public long? Id { get; set; }
public int? Version { get; set; }
public string? DocumentType { get; set; }
public string? DocumentNum { get; set; }
@@ -33,5 +36,6 @@ public class GuestDocumentDTO
public DateTime? UpdateTime { get; set; }
public string FullKey => $"{DocumentType}-{DocumentNum}";
public string FullKey => $"{Id}-{Version}";
public string FullDocument => $"{DocumentType ?? "???"}-{DocumentNum ?? "???"}";
}
+13 -11
View File
@@ -1,24 +1,26 @@
using Somnia.GuestLog.Enums.Services;
namespace Somnia.GuestLog.Models.DTOs;
public sealed record Result(bool IsSuccess, string ResultCode, params object[]? Context)
public sealed record Result(bool IsSuccess, ResultCode ResultCode, params object[]? Context)
{
public static Result Ok() => new(IsSuccess: true, ResultCode: Models.ResultCode.Ok, Context: null);
public static Result Ok() => new(IsSuccess: true, ResultCode: ResultCode.Ok, Context: null);
public static Result Fail(string resultCode) => new(IsSuccess: false, resultCode, Context: null);
public static Result FailWithContext(string resultCode, params object[] context)
public static Result Fail(ResultCode resultCode) => new(IsSuccess: false, resultCode, Context: null);
public static Result FailWithContext(ResultCode resultCode, params object[] context)
=> new(IsSuccess: false, resultCode, context);
public static Result FailUnknownError()
=> new(IsSuccess: false, ResultCode: Models.ResultCode.UnknownError, Context: null);
=> new(IsSuccess: false, ResultCode: ResultCode.UnknownError, Context: null);
public bool IsUnknownError => !IsSuccess && ResultCode == Models.ResultCode.UnknownError;
public bool IsUnknownError => !IsSuccess && ResultCode == ResultCode.UnknownError;
}
public sealed record Result<T>(bool IsSuccess, T? Value, string ResultCode, params object[]? Context)
public sealed record Result<T>(bool IsSuccess, T? Value, ResultCode ResultCode, params object[]? Context)
{
public static Result<T> Ok(T value) => new(IsSuccess: true, value, ResultCode: Models.ResultCode.Ok, Context: null);
public static Result<T> Fail(string resultCode) => new(IsSuccess: false, Value: default, resultCode, Context: null);
public static Result<T> FailWithContext(string resultCode, params object[] context)
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> FailWithContext(ResultCode resultCode, params object[] context)
=> new(IsSuccess: false, Value: default, resultCode, context);
public bool IsUnknownError => !IsSuccess && ResultCode == Models.ResultCode.UnknownError;
public bool IsUnknownError => !IsSuccess && ResultCode == ResultCode.UnknownError;
}
@@ -2,6 +2,9 @@ namespace Somnia.GuestLog.Models.Entities;
public class GuestDocument : BaseEntity
{
public long Id { get; set; }
public int Version { get; set; }
public required string DocumentType { get; set; }
public required string DocumentNum { get; set; }
@@ -26,6 +29,8 @@ public class GuestDocument : BaseEntity
public required DateTime CreateTime { get; set; }
public required DateTime UpdateTime { get; set; }
public required bool IsLastVersion { get; set; }
public override string GetFullKey() => $"{DocumentType}-{DocumentNum}";
public override string GetFullKey() => $"{Id}-{Version}";
}
@@ -10,6 +10,8 @@ internal static class EntityMapping
{
return new()
{
Id = entity.Id,
Version = entity.Version,
DocumentType = entity.DocumentType,
DocumentNum = entity.DocumentNum,
IssueDate = entity.IssueDate.ToDateTime(TimeOnly.MinValue),
-11
View File
@@ -1,11 +0,0 @@
namespace Somnia.GuestLog.Models;
public static class ResultCode
{
public const string Ok = "Ok";
public const string UnknownError = "UnknownError";
public const string FailedValidation = "FailedValidation";
public const string NotFound = "NotFound";
public const string GuestCurrentlyInStay = "GuestCurrentlyInStay";
}
+3 -2
View File
@@ -9,6 +9,7 @@ using Somnia.GuestLog.Models.Configuration;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Services;
using Somnia.GuestLog.Services.AddressQuery;
using Somnia.GuestLog.Services.Entity;
using Somnia.GuestLog.Utils;
using Somnia.GuestLog.Validators;
@@ -55,8 +56,8 @@ builder.Services.AddSingleton<IValidator<GuestDocIdDTO>, GuestDocIdDTOValidator>
builder.Services.AddSingleton<IValidator<StayEntryDTO>, StayEntryDTOValidator>();
// Add Services
builder.Services.AddSingleton<IGuestDocumentService, GuestDocumentService>();
builder.Services.AddSingleton<IStayEntryService, StayEntryService>();
builder.Services.AddSingleton<IGuestDocumentEntityService, GuestDocumentEntityService>();
builder.Services.AddSingleton<IStayEntryEntityService, StayEntryEntityService>();
builder.Services.AddSingleton<IDataListService, StaticDataListService>();
builder.Services.AddScoped<IUserMessageService, UserMessageService>();
@@ -122,6 +122,8 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="dto.GuestDocument.Id" xml:space="preserve"><value>ID</value></data>
<data name="dto.GuestDocument.Version" xml:space="preserve"><value>Version</value></data>
<data name="dto.GuestDocument.DocumentType" xml:space="preserve"><value>Document Type</value></data>
<data name="dto.GuestDocument.DocumentNum" xml:space="preserve"><value>Document Number</value></data>
<data name="dto.GuestDocument.IssueDate" xml:space="preserve"><value>Issue Date</value></data>
@@ -183,7 +185,8 @@
<data name="resultCode.FailedValidation" xml:space="preserve"><value>Failed entity validation</value></data>
<data name="resultCode.NotFound" xml:space="preserve"><value>Not found</value></data>
<!-- Specific codes -->
<data name="resultCode.GuestCurrentlyInStay" xml:space="preserve"><value>Guest ('{0}') is already in one stay during the period: {1}</value></data>
<data name="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="navMenu.GuestDocumentList" xml:space="preserve"><value>Guests</value></data>
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Options;
using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Models.Configuration;
using Somnia.GuestLog.Utils.DI;
@@ -11,8 +12,8 @@ public class ConfigFileAddressQueryFactory(
{
public static void RegisterFactoryItems(IServiceCollection services)
{
services.AddKeyedTransient<IAddressQueryService, NominatimAddressQueryService>(AddressQueryConfig.AddressQueryProviderEnum.Nominatim);
services.AddKeyedTransient<IAddressQueryService, GoogleApiAddressQueryService>(AddressQueryConfig.AddressQueryProviderEnum.GoogleApiV4);
services.AddKeyedTransient<IAddressQueryService, NominatimAddressQueryService>(AddressQueryProvider.Nominatim);
services.AddKeyedTransient<IAddressQueryService, GoogleApiAddressQueryService>(AddressQueryProvider.GoogleApiV4);
}
public IAddressQueryService GetService()
@@ -44,7 +44,7 @@ public class NominatimAddressQueryService(
HouseNumber = result.Address.House_number,
AddressRoad = result.Address.Road ?? result.Address.Square,
AddressCity = result.Address.City ?? result.Address.Municipality ?? result.Address.Town ?? result.Address.Village,
AddressProvince = result.Address.Province,
AddressProvince = result.Address.Province ?? result.Address.State_district ?? result.Address.County,
AddressState = result.Address.State,
AddressCountry = result.Address.Country,
ZipCode = result.Address.Postcode,
@@ -97,6 +97,8 @@ public class NominatimAddressQueryService(
string? Village = null,
string? Town = null,
string? Province = null,
string? State_district = null,
string? County = null,
string? State = null,
string? Country = null,
string? Postcode = null,
@@ -1,18 +1,20 @@
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;
namespace Somnia.GuestLog.Services.Entity;
public class GuestDocumentService(
ILogger<GuestDocumentService> logger,
public class GuestDocumentEntityService(
ILogger<GuestDocumentEntityService> logger,
IDbContextFactory<GuestLogContext> contextFactory,
IValidator<GuestDocumentDTO> dtoValidator
) : IGuestDocumentService
IValidator<GuestDocumentDTO> dtoValidator,
IStayEntryEntityService stayEntityService
) : IGuestDocumentEntityService
{
public async Task<Result> CreateDocumentAsync(GuestDocumentDTO dto)
{
@@ -39,6 +41,7 @@ public class GuestDocumentService(
DateTime createTime = DateTime.UtcNow;
GuestDocument dbItem = new()
{
Version = GuestConsts.GuestDocument_FirstVersion,
DocumentType = dto.DocumentType!,
DocumentNum = dto.DocumentNum!,
IssueDate = DateOnly.FromDateTime(dto.IssueDate!.Value),
@@ -54,6 +57,7 @@ public class GuestDocumentService(
AddressDetails = addressItem,
CreateTime = createTime,
UpdateTime = createTime,
IsLastVersion = true, //On creation, created entity is last version.
};
try
@@ -79,54 +83,93 @@ public class GuestDocumentService(
public Task<Result> DeleteDocumentAsync(GuestDocumentDTO dto)
{
if (dto.DocumentType is null || dto.DocumentNum is null)
if (dto.Id is null)
{
throw new InvalidOperationException("GuestDocumentService - DeleteDocument: A DTO without key can't be deleted!");
throw new InvalidOperationException("GuestDocumentService - DeleteDocument: A DTO without ID can't be deleted!");
}
return DeleteDocumentAsync(dto.DocumentType, dto.DocumentNum);
return DeleteDocumentAsync(dto.Id.Value);
}
public async Task<Result> DeleteDocumentAsync(string docType, string docNum)
public async Task<Result> DeleteDocumentAsync(long id)
{
using var dbContext = contextFactory.CreateDbContext();
GuestDocument? dbItem = await dbContext.GuestDocuments.FindAsync(docType, docNum);
if (dbItem is null)
{
logger.LogWarning("GuestDocumentService - DeleteDocument: Error deleting GuestDocument. Entity not found with key: '{key}-{key2}'", docType, docNum);
return Result.Fail(ResultCode.NotFound);
}
try
{
dbContext.GuestDocuments.Remove(dbItem);
await dbContext.SaveChangesAsync();
using var dbContext = contextFactory.CreateDbContext();
logger.LogInformation("GuestDocumentService - DeleteDocument: GuestDocument deleted: '{id}'", dbItem.GetFullKey());
//Check if GuestDocument is used in a Stay.
bool isUsed = await stayEntityService.IsGuestInStay(id);
if (isUsed)
{
logger.LogWarning("GuestDocumentService - DeleteDocument: Error deleting GuestDocument. Guest (ID: '{ID}') is in a Stay", id);
return Result.FailWithContext(ResultCode.GuestInStay, id);
}
int deletedCount = await dbContext.GuestDocuments
.Where(e => e.Id == id)
.ExecuteDeleteAsync();
if (deletedCount == 0)
{
logger.LogWarning("GuestDocumentService - DeleteDocument: Error deleting GuestDocument. Entity not found with ID: '{ID}'", id);
return Result.Fail(ResultCode.NotFound);
}
logger.LogInformation(
"GuestDocumentService - DeleteDocument: GuestDocument deleted with Id: '{id}'. Versions deleted: '{Count}'",
id, deletedCount);
return Result.Ok();
}
catch (Exception ex)
{
logger.LogError(ex, "GuestDocumentService - CreateDocument: Error deleting GuestDocument: '{id}'", dbItem.GetFullKey());
logger.LogError(ex, "GuestDocumentService - CreateDocument: Error deleting GuestDocument: '{id}'", id);
return Result.FailUnknownError();
}
}
public async Task<GuestDocumentDTO?> GetDtoByIdAsync(string docType, string docNum)
public async Task<GuestDocumentDTO?> GetLastVersionDtoByIdAsync(long id)
{
using var dbContext = contextFactory.CreateDbContext();
GuestDocument? dbItem = await dbContext.GuestDocuments.FindAsync(docType, docNum);
GuestDocument? dbItem = await dbContext.GuestDocuments
.Where(e => e.Id == id)
.OrderByDescending(e => e.Version)
.FirstOrDefaultAsync();
return dbItem is not null ? GetDtoFromDb(dbItem) : null;
}
public async Task<IEnumerable<GuestDocumentDTO>> GetDtoListAsync()
public async Task<GuestDocumentDTO?> GetLastVersionDtoByDocumentAsync(string docType, string docNum)
{
using var dbContext = contextFactory.CreateDbContext();
var dbList = await dbContext.GuestDocuments
.OrderByDescending(e => e.UpdateTime)
GuestDocument? dbItem = await dbContext.GuestDocuments
.Where(e => e.DocumentType == docType && e.DocumentNum == docNum)
.OrderByDescending(e => e.Version)
.FirstOrDefaultAsync();
return dbItem is not null ? GetDtoFromDb(dbItem) : null;
}
public async Task<IEnumerable<GuestDocumentDTO>> GetDtoListAsync(bool onlyLastVersion)
{
using var dbContext = contextFactory.CreateDbContext();
// TEMP solution
var query = dbContext.GuestDocuments.AsQueryable();
if (onlyLastVersion)
{
query = query.Where(e => e.IsLastVersion == true);
}
var dbList = await query.OrderByDescending(e => e.UpdateTime)
.ToListAsync();
// TODO: Waiting for EF Core Window function improvements:
// See expected translation: https://github.com/dotnet/efcore/issues/36380#issuecomment-3082788964
// See window function status: https://github.com/dotnet/efcore/issues/12747
// var dbList = await dbContext.GuestDocuments
// .GroupBy(e => e.Id)
// .Select(g => g.OrderByDescending(e => e.Version).First())
// .ToListAsync();
return dbList.Select(GetDtoFromDb);
}
@@ -153,8 +196,21 @@ public class GuestDocumentService(
query = query.WhereIf(!string.IsNullOrEmpty(filter.Surname),
e => EF.Functions.Like(e.Surname, filter.Surname));
// TEMP while waiting for EF Core Window function improvements
query = query.WhereIf(filter.OnlyLastVersion,
e => e.IsLastVersion == true);
query = query.OrderByDescending(e => e.UpdateTime);
// TODO: Waiting for EF Core Window function improvements:
// See: https://github.com/dotnet/efcore/issues/27470
// See window function status: https://github.com/dotnet/efcore/issues/12747
// For Ordering (or operations post-grouping), see: https://github.com/dotnet/efcore/pull/38687
// query = query
// .OrderByDescending(e => e.UpdateTime)
// .GroupBy(e => e.Id)
// .Select(g => g.OrderByDescending(e => e.Version).First());
if (limit > 0)
{
query = query.Take(limit);
@@ -0,0 +1,28 @@
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services.Entity;
public interface IGuestDocumentEntityService
{
public Task<Result> CreateDocumentAsync(GuestDocumentDTO dto);
public Task<Result> UpdateDocumentAsync(GuestDocumentDTO dto);
/// <summary>
/// Same behavior as <see cref="DeleteDocumentAsync(long)"/>
/// </summary>
public Task<Result> DeleteDocumentAsync(GuestDocumentDTO dto);
/// <summary>
/// Delete documents by ID.
/// This operation will delete all versions of a document.
/// </summary>
/// <param name="id">ID of the document to Delete</param>
public Task<Result> DeleteDocumentAsync(long id);
public Task<GuestDocumentDTO?> GetLastVersionDtoByIdAsync(long id);
public Task<GuestDocumentDTO?> GetLastVersionDtoByDocumentAsync(string docType, string docNum);
public Task<IEnumerable<GuestDocumentDTO>> GetDtoListAsync(bool onlyLastVersion);
public Task<IEnumerable<GuestDocumentDTO>> GetDtoListByFilterAsync(GuestDocFilterDTO filter, int limit = 0);
}
@@ -1,9 +1,9 @@
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Models.QueryConfigs;
namespace Somnia.GuestLog.Services;
namespace Somnia.GuestLog.Services.Entity;
public interface IStayEntryService
public interface IStayEntryEntityService
{
public Task<Result> CreateEntryAsync(StayEntryDTO dto);
public Task<Result> UpdateEntryAsync(StayEntryDTO updatedDto);
@@ -15,7 +15,8 @@ public interface IStayEntryService
public Task<IEnumerable<StayEntryDTO>> GetDtoListByFilterAsync(StayEntryFilterDTO filter, int limit = 0, StayEntryQueryConfig? queryConfig = null);
public Task<bool> IsGuestInStayInPeriod(string docType, string docNum, DateTime startTime, DateTime endTime);
public Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(string docType, string docNum, StayEntryQueryConfig? queryConfig = null);
public Task<bool> IsGuestInStay(long guestDocId);
public Task<bool> IsGuestInStayInPeriod(long guestDocId, DateTime startTime, DateTime endTime);
public Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(long guestDocId, StayEntryQueryConfig? queryConfig = null);
}
@@ -1,5 +1,6 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Infrastructure;
using Somnia.GuestLog.Models;
using Somnia.GuestLog.Models.DTOs;
@@ -7,13 +8,13 @@ using Somnia.GuestLog.Models.Entities;
using Somnia.GuestLog.Models.QueryConfigs;
using Somnia.GuestLog.Utils;
namespace Somnia.GuestLog.Services;
namespace Somnia.GuestLog.Services.Entity;
public class StayEntryService(
ILogger<StayEntryService> logger,
public class StayEntryEntityService(
ILogger<StayEntryEntityService> logger,
IDbContextFactory<GuestLogContext> contextFactory,
IValidator<StayEntryDTO> dtoValidator
) : IStayEntryService
) : IStayEntryEntityService
{
public async Task<Result> CreateEntryAsync(StayEntryDTO dto)
{
@@ -45,12 +46,13 @@ public class StayEntryService(
//Check and add GuestDocuments
foreach (GuestDocumentDTO guestDto in dto.GuestDocuments!)
{
//Get it from db.
GuestDocument? dbGuest = await dbContext.GuestDocuments.FindAsync(guestDto.DocumentType, guestDto.DocumentNum)
?? throw new InvalidOperationException($"GuestDocument not found! Id: '{guestDto.FullKey}'");
//Get guest from db.
GuestDocument dbGuest = await dbContext.GuestDocuments
.Where(gd => gd.Id == guestDto.Id && gd.Version == guestDto.Version)
.SingleAsync();
//Check if Guest is already in other stay during the same period.
bool isInOtherStay = await this.IsGuestInStayInPeriod(dbGuest.DocumentType, dbGuest.DocumentNum, dbStay.DateIn, dbStay.DateOut);
bool isInOtherStay = await this.IsGuestInStayInPeriod(dbGuest.Id, dbStay.DateIn, dbStay.DateOut);
if (isInOtherStay)
{
string period = $"{dbStay.DateIn}-{dbStay.DateOut}";
@@ -167,24 +169,34 @@ public class StayEntryService(
}
public async Task<bool> IsGuestInStayInPeriod(string docType, string docNum, DateTime startTime, DateTime endTime)
public async Task<bool> IsGuestInStay(long guestDocId)
{
using var dbContext = contextFactory.CreateDbContext();
bool rs = await dbContext.StayEntries
.AnyAsync(s => s.GuestDocuments.Any(g => g.Id == guestDocId));
return rs;
}
public async Task<bool> IsGuestInStayInPeriod(long guestDocId, DateTime startTime, DateTime endTime)
{
using var dbContext = contextFactory.CreateDbContext();
bool rs = await dbContext.StayEntries
.AnyAsync(s => s.DateIn < endTime && s.DateOut > startTime
&& s.GuestDocuments.Any(g => g.DocumentType == docType && g.DocumentNum == docNum)
&& s.GuestDocuments.Any(g => g.Id == guestDocId)
);
return rs;
}
public async Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(string docType, string docNum, StayEntryQueryConfig? queryConfig = null)
public async Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(long guestDocId, StayEntryQueryConfig? queryConfig = null)
{
using var dbContext = contextFactory.CreateDbContext();
var rs = await dbContext.StayEntries
.Where(s => s.GuestDocuments.Any(g => g.DocumentType == docType && g.DocumentNum == docNum))
.Where(s => s.GuestDocuments.Any(g => g.Id == guestDocId))
.AddQueryConfig(queryConfig)
.OrderByDescending(e => e.DateIn)
.ToListAsync();
@@ -1,16 +0,0 @@
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services;
public interface IGuestDocumentService
{
public Task<Result> CreateDocumentAsync(GuestDocumentDTO dto);
public Task<Result> UpdateDocumentAsync(GuestDocumentDTO dto);
public Task<Result> DeleteDocumentAsync(GuestDocumentDTO dto);
public Task<Result> DeleteDocumentAsync(string docType, string docNum);
public Task<GuestDocumentDTO?> GetDtoByIdAsync(string docType, string docNum);
public Task<IEnumerable<GuestDocumentDTO>> GetDtoListByFilterAsync(GuestDocFilterDTO filter, int limit = 0);
public Task<IEnumerable<GuestDocumentDTO>> GetDtoListAsync();
}
@@ -1,3 +1,4 @@
using Somnia.GuestLog.Enums.UI;
using Somnia.GuestLog.Models.DTOs;
namespace Somnia.GuestLog.Services;
@@ -8,10 +9,4 @@ public interface IUserMessageService
public void ShowResult(Result resultDto);
public void ShowResultWithMessage(Result resultDto, string message);
public enum MessageKind
{
Info, Warning, Error, Success, Normal
}
}
@@ -1,9 +1,9 @@
using Microsoft.Extensions.Localization;
using MudBlazor;
using Somnia.GuestLog.Models;
using Somnia.GuestLog.Enums.Services;
using Somnia.GuestLog.Enums.UI;
using Somnia.GuestLog.Models.DTOs;
using Somnia.GuestLog.Resources;
using MessageKind = Somnia.GuestLog.Services.IUserMessageService.MessageKind;
namespace Somnia.GuestLog.Services;
@@ -59,9 +59,9 @@ public class UserMessageService(
snackbar.Add(message: msg, severity: GetSnackbarSeveryForMessageKind(kind));
}
private string GetMsgForResultCode(string resultCode)
private string GetMsgForResultCode(ResultCode resultCode)
{
return _localizer[$"resultCode.{resultCode}"];
return _localizer[$"resultCode.{Enum.GetName(resultCode)}"];
}
private static string GetFormatedMessage(string template, params object[]? parameters)