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.
This commit is contained in:
2026-09-01 15:04:38 +02:00
parent a01eed82e1
commit 887c3d787a
21 changed files with 525 additions and 93 deletions
@@ -78,7 +78,10 @@
private IMudDialogInstance MudDialog { get; set; } = null!; 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 IEnumerable<GuestDocumentDTO> results = [];
private GuestDocumentDTO? SelectedResult { get; set; } private GuestDocumentDTO? SelectedResult { get; set; }
@@ -95,7 +95,7 @@
{ {
<MudTd DataLabel="@LanguageLocale.general_actions"> <MudTd DataLabel="@LanguageLocale.general_actions">
<MudIconButton Icon="@Icons.Material.Filled.Delete" <MudIconButton Icon="@Icons.Material.Filled.Delete"
OnClick="@(() => BtnDeleteGuest(context.DocumentType!, context.DocumentNum!))" /> OnClick="@(() => BtnDeleteGuest(context.Id!.Value, context.Version!.Value))" />
</MudTd> </MudTd>
} }
@if (ReadOnly) @if (ReadOnly)
@@ -229,8 +229,7 @@
//Check if this guest is already added. //Check if this guest is already added.
if (Model.GuestDocuments.Count > 0) if (Model.GuestDocuments.Count > 0)
{ {
bool alreadyAdded = Model.GuestDocuments.Any(e => e.DocumentType == resultData.DocumentType bool alreadyAdded = Model.GuestDocuments.Any(e => e.Id == resultData.Id);
&& e.DocumentNum == resultData.DocumentNum);
if (alreadyAdded) if (alreadyAdded)
{ {
userMessage.ShowMessage("GuestDocument already added!", MessageKind.Warning); userMessage.ShowMessage("GuestDocument already added!", MessageKind.Warning);
@@ -241,13 +240,13 @@
Model.GuestDocuments.Add(resultData); 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); Debug.Assert(Model.GuestDocuments is not null);
//Filter out given GuestDocument from model. //Filter out given GuestDocument from model.
Model.GuestDocuments = Model.GuestDocuments Model.GuestDocuments = Model.GuestDocuments
.Where(e => !(e.DocumentType == docType && e.DocumentNum == docNum)) .Where(e => !(e.Id == guestDocId && e.Version == version))
.ToList(); .ToList();
} }
@@ -14,7 +14,7 @@
<PageTitle>Somnia - Guest Docs - Details</PageTitle> <PageTitle>Somnia - Guest Docs - Details</PageTitle>
<MudStack Row="true" Class="my-4"> <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 /> <MudSpacer />
<MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small" StartIcon="@Icons.Material.Filled.Edit" <MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small" StartIcon="@Icons.Material.Filled.Edit"
OnClick="() => BtnEdit()" Disabled> OnClick="() => BtnEdit()" Disabled>
@@ -77,7 +77,7 @@
@code { @code {
[Parameter] [Parameter]
public string? docId { get; set; } public long docId { get; set; }
GuestDocForm _form = null!; GuestDocForm _form = null!;
@@ -90,23 +90,8 @@
protected override async Task OnInitializedAsync() 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. //Get model from db.
documentModel = await guestDocService.GetDtoByIdAsync(docIdModel.DocumentType, docIdModel.DocumentNum); documentModel = await guestDocService.GetLastVersionDtoByIdAsync(docId);
if (documentModel is null) if (documentModel is null)
{ {
userMessage.ShowMessage($"GuestDocument not found with ID: '{docId}'", MessageKind.Error); userMessage.ShowMessage($"GuestDocument not found with ID: '{docId}'", MessageKind.Error);
@@ -123,13 +108,13 @@
return; 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(); throw new InvalidOperationException();
} }
guestStaysLoading = true; guestStaysLoading = true;
guestStayList = await stayService.GetStaysWithGuest(documentModel.DocumentType, documentModel.DocumentNum); guestStayList = await stayService.GetStaysWithGuest(documentModel.Id.Value);
guestStaysLoading = false; guestStaysLoading = false;
} }
@@ -43,6 +43,8 @@
</MudStack> </MudStack>
</ToolBarContent> </ToolBarContent>
<Columns> <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" <PropertyColumn Title="@LanguageLocale.dto_GuestDocument_DocumentType"
Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_DocumentTypes, x.DocumentType)" Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_DocumentTypes, x.DocumentType)"
Hideable="false" /> Hideable="false" />
@@ -50,6 +52,7 @@
Title="@LanguageLocale.dto_GuestDocument_DocumentNum" /> Title="@LanguageLocale.dto_GuestDocument_DocumentNum" />
<PropertyColumn Property="x => x.Name" Title="@LanguageLocale.dto_GuestDocument_Name" /> <PropertyColumn Property="x => x.Name" Title="@LanguageLocale.dto_GuestDocument_Name" />
<PropertyColumn Property="x => x.Surname" Title="@LanguageLocale.dto_GuestDocument_Surname" /> <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" <PropertyColumn Title="@LanguageLocale.dto_GuestDocument_Nationality"
Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_CountryCodes, x.Nationality)" /> Property="x => dataListService.GetLocalizedValue(GuestConsts.DataList_CountryCodes, x.Nationality)" />
<PropertyColumn Property="x => x.UpdateTime" Title="@LanguageLocale.dto_GuestDocument_UpdateTime" /> <PropertyColumn Property="x => x.UpdateTime" Title="@LanguageLocale.dto_GuestDocument_UpdateTime" />
@@ -126,10 +129,9 @@
private async Task BtnViewDetails(GuestDocumentDTO item) 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, strId);
string uri = GuestConsts.Page_GuestDocs_Detail.Replace(GuestConsts.Page_GuestDocs_Detail_Param_DocId, itemId);
Navigation.NavigateTo(uri); Navigation.NavigateTo(uri);
} }
@@ -151,7 +153,7 @@
} }
userMessage.ShowMessage($"Document {item.DocumentType}-{item.DocumentNum} deleted!", MessageKind.Success); userMessage.ShowMessage($"Document {item.DocumentType}-{item.DocumentNum} deleted!", MessageKind.Success);
await LoadDataAsync(); await LoadDataAsync(showMsg: false);
} }
private void BtnNewGuest() private void BtnNewGuest()
@@ -82,6 +82,7 @@
ePageMode currentPageMode = ePageMode.selectDocId; ePageMode currentPageMode = ePageMode.selectDocId;
GuestDocIdDTO currentDocId = new() { DocumentNum = "", DocumentType = "" }; GuestDocIdDTO currentDocId = new() { DocumentNum = "", DocumentType = "" };
long? alreadyExistDocId = null;
GuestDocumentDTO newDocumentModel = new(); GuestDocumentDTO newDocumentModel = new();
bool loadingDocId = false; bool loadingDocId = false;
@@ -100,7 +101,8 @@
} }
loadingDocId = true; loadingDocId = true;
GuestDocumentDTO? dto = await guestDocService.GetDtoByIdAsync(currentDocId.DocumentType, currentDocId.DocumentNum); GuestDocumentDTO? dto =
await guestDocService.GetLastVersionDtoByDocumentAsync(currentDocId.DocumentType, currentDocId.DocumentNum);
loadingDocId = false; loadingDocId = false;
if (dto is null) if (dto is null)
@@ -117,6 +119,7 @@
//GuestDoc already exists! //GuestDoc already exists!
currentPageMode = ePageMode.alreadyExistDoc; currentPageMode = ePageMode.alreadyExistDoc;
alreadyExistDocId = dto.Id;
} }
private void BtnReturn() private void BtnReturn()
@@ -153,14 +156,15 @@
private void BtnGoToDocument() private void BtnGoToDocument()
{ {
if (currentPageMode != ePageMode.alreadyExistDoc) if (currentPageMode != ePageMode.alreadyExistDoc || alreadyExistDocId is null)
{ {
userMessage.ShowMessage("Invalid operation!", MessageKind.Error); userMessage.ShowMessage("Invalid operation!", MessageKind.Error);
return; 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); Navigation.NavigateTo(uri);
} }
@@ -117,7 +117,7 @@
private async Task BtnViewDetails(StayEntryDTO item) 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); string uri = GuestConsts.Page_StayEntry_Detail.Replace(GuestConsts.Page_StayEntry_Detail_Param_Id, itemId);
Navigation.NavigateTo(uri); Navigation.NavigateTo(uri);
} }
@@ -2,9 +2,13 @@ namespace Somnia.GuestLog.Enums.Services;
public enum ResultCode public enum ResultCode
{ {
//Common Codes
Ok, Ok,
UnknownError, UnknownError,
FailedValidation, FailedValidation,
NotFound, NotFound,
//Specific Codes
GuestInStay,
GuestCurrentlyInStay, GuestCurrentlyInStay,
} }
+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_List = "/guest-documents";
public const string Page_GuestDocs_New = "/guest-documents/new"; 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 = $"/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_List = "/stayEntries";
public const string Page_StayEntry_New = "/stayEntries/new"; 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_DNI = "DNI";
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 int GuestDocument_FirstVersion = 1;
} }
@@ -11,7 +11,13 @@ public class GuestDocumentEntityConfig : IEntityTypeConfiguration<GuestDocument>
builder.ToTable("GuestDocument"); builder.ToTable("GuestDocument");
//PK //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) builder.Property(e => e.DocumentType)
.IsRequired() .IsRequired()
@@ -48,6 +54,15 @@ public class GuestDocumentEntityConfig : IEntityTypeConfiguration<GuestDocument>
builder.Property(e => e.EmailAddress) builder.Property(e => e.EmailAddress)
.HasMaxLength(256); .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); 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 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "10.0.7") .HasAnnotation("ProductVersion", "10.0.7")
.HasAnnotation("Proxies:ChangeTracking", false)
.HasAnnotation("Proxies:CheckEquality", false)
.HasAnnotation("Proxies:LazyLoading", true)
.HasAnnotation("Relational:MaxIdentifierLength", 63); .HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
@@ -28,34 +31,45 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
b.Property<long>("StayEntryId") b.Property<long>("StayEntryId")
.HasColumnType("bigint"); .HasColumnType("bigint");
b.Property<string>("GuestDocumentsDocumentType") b.Property<long>("GuestDocumentsId")
.HasColumnType("character varying(8)"); .HasColumnType("bigint");
b.Property<string>("GuestDocumentsDocumentNum") b.Property<int>("GuestDocumentsVersion")
.HasColumnType("character varying(64)"); .HasColumnType("integer");
b.HasKey("StayEntryId", "GuestDocumentsDocumentType", "GuestDocumentsDocumentNum"); b.HasKey("StayEntryId", "GuestDocumentsId", "GuestDocumentsVersion");
b.HasIndex("GuestDocumentsDocumentType", "GuestDocumentsDocumentNum"); b.HasIndex("GuestDocumentsId", "GuestDocumentsVersion");
b.ToTable("GuestDocumentStayEntry"); b.ToTable("GuestDocumentStayEntry");
}); });
modelBuilder.Entity("Somnia.GuestLog.Models.Entities.GuestDocument", b => modelBuilder.Entity("Somnia.GuestLog.Models.Entities.GuestDocument", b =>
{ {
b.Property<string>("DocumentType") b.Property<long>("Id")
.HasMaxLength(8) .ValueGeneratedOnAdd()
.HasColumnType("character varying(8)"); .HasColumnType("bigint");
b.Property<string>("DocumentNum") NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
.HasMaxLength(64)
.HasColumnType("character varying(64)"); b.Property<int>("Version")
.HasColumnType("integer");
b.Property<DateOnly>("BirthDate") b.Property<DateOnly>("BirthDate")
.HasColumnType("date"); .HasColumnType("date");
b.Property<DateTime>("CreateTime") 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") b.Property<string>("EmailAddress")
.HasMaxLength(256) .HasMaxLength(256)
@@ -65,6 +79,9 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
.HasMaxLength(1) .HasMaxLength(1)
.HasColumnType("character varying(1)"); .HasColumnType("character varying(1)");
b.Property<bool>("IsLastVersion")
.HasColumnType("boolean");
b.Property<DateOnly>("IssueDate") b.Property<DateOnly>("IssueDate")
.HasColumnType("date"); .HasColumnType("date");
@@ -96,7 +113,7 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
.HasColumnType("character varying(64)"); .HasColumnType("character varying(64)");
b.Property<DateTime>("UpdateTime") 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 => 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)"); .HasColumnType("character varying(12)");
}); });
b.HasKey("DocumentType", "DocumentNum"); b.HasKey("Id", "Version");
b.ToTable("GuestDocument", (string)null); b.ToTable("GuestDocument", (string)null);
}); });
@@ -178,7 +195,7 @@ namespace Somnia.GuestLog.Infrastructure.Migrations
b.HasOne("Somnia.GuestLog.Models.Entities.GuestDocument", null) b.HasOne("Somnia.GuestLog.Models.Entities.GuestDocument", null)
.WithMany() .WithMany()
.HasForeignKey("GuestDocumentsDocumentType", "GuestDocumentsDocumentNum") .HasForeignKey("GuestDocumentsId", "GuestDocumentsVersion")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
}); });
@@ -10,6 +10,8 @@ public class GuestDocFilterDTO
public string? PhoneNumber { get; set; } public string? PhoneNumber { get; set; }
public bool OnlyLastVersion { get; set; }
public bool IsEmpty => string.IsNullOrEmpty(DocumentType) public bool IsEmpty => string.IsNullOrEmpty(DocumentType)
&& string.IsNullOrEmpty(DocumentNumber) && string.IsNullOrEmpty(DocumentNumber)
@@ -2,6 +2,9 @@ namespace Somnia.GuestLog.Models.DTOs;
public class GuestDocumentDTO public class GuestDocumentDTO
{ {
public long? Id { get; set; }
public int? Version { get; set; }
public string? DocumentType { get; set; } public string? DocumentType { get; set; }
public string? DocumentNum { get; set; } public string? DocumentNum { get; set; }
@@ -33,5 +36,6 @@ public class GuestDocumentDTO
public DateTime? UpdateTime { get; set; } public DateTime? UpdateTime { get; set; }
public string FullKey => $"{DocumentType}-{DocumentNum}"; public string FullKey => $"{Id}-{Version}";
public string FullDocument => $"{DocumentType ?? "???"}-{DocumentNum ?? "???"}";
} }
@@ -2,6 +2,9 @@ namespace Somnia.GuestLog.Models.Entities;
public class GuestDocument : BaseEntity public class GuestDocument : BaseEntity
{ {
public long Id { get; set; }
public int Version { get; set; }
public required string DocumentType { get; set; } public required string DocumentType { get; set; }
public required string DocumentNum { 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 CreateTime { get; set; }
public required DateTime UpdateTime { 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() return new()
{ {
Id = entity.Id,
Version = entity.Version,
DocumentType = entity.DocumentType, DocumentType = entity.DocumentType,
DocumentNum = entity.DocumentNum, DocumentNum = entity.DocumentNum,
IssueDate = entity.IssueDate.ToDateTime(TimeOnly.MinValue), IssueDate = entity.IssueDate.ToDateTime(TimeOnly.MinValue),
@@ -122,6 +122,8 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089</value> Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </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.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.DocumentNum" xml:space="preserve"><value>Document Number</value></data>
<data name="dto.GuestDocument.IssueDate" xml:space="preserve"><value>Issue Date</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.FailedValidation" xml:space="preserve"><value>Failed entity validation</value></data>
<data name="resultCode.NotFound" xml:space="preserve"><value>Not found</value></data> <data name="resultCode.NotFound" xml:space="preserve"><value>Not found</value></data>
<!-- Specific codes --> <!-- 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> <data name="navMenu.GuestDocumentList" xml:space="preserve"><value>Guests</value></data>
@@ -12,7 +12,8 @@ namespace Somnia.GuestLog.Services.Entity;
public class GuestDocumentEntityService( public class GuestDocumentEntityService(
ILogger<GuestDocumentEntityService> logger, ILogger<GuestDocumentEntityService> logger,
IDbContextFactory<GuestLogContext> contextFactory, IDbContextFactory<GuestLogContext> contextFactory,
IValidator<GuestDocumentDTO> dtoValidator IValidator<GuestDocumentDTO> dtoValidator,
IStayEntryEntityService stayEntityService
) : IGuestDocumentEntityService ) : IGuestDocumentEntityService
{ {
public async Task<Result> CreateDocumentAsync(GuestDocumentDTO dto) public async Task<Result> CreateDocumentAsync(GuestDocumentDTO dto)
@@ -40,6 +41,7 @@ public class GuestDocumentEntityService(
DateTime createTime = DateTime.UtcNow; DateTime createTime = DateTime.UtcNow;
GuestDocument dbItem = new() GuestDocument dbItem = new()
{ {
Version = GuestConsts.GuestDocument_FirstVersion,
DocumentType = dto.DocumentType!, DocumentType = dto.DocumentType!,
DocumentNum = dto.DocumentNum!, DocumentNum = dto.DocumentNum!,
IssueDate = DateOnly.FromDateTime(dto.IssueDate!.Value), IssueDate = DateOnly.FromDateTime(dto.IssueDate!.Value),
@@ -55,6 +57,7 @@ public class GuestDocumentEntityService(
AddressDetails = addressItem, AddressDetails = addressItem,
CreateTime = createTime, CreateTime = createTime,
UpdateTime = createTime, UpdateTime = createTime,
IsLastVersion = true, //On creation, created entity is last version.
}; };
try try
@@ -80,54 +83,93 @@ public class GuestDocumentEntityService(
public Task<Result> DeleteDocumentAsync(GuestDocumentDTO dto) 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)
{
try
{ {
using var dbContext = contextFactory.CreateDbContext(); using var dbContext = contextFactory.CreateDbContext();
GuestDocument? dbItem = await dbContext.GuestDocuments.FindAsync(docType, docNum);
if (dbItem is null) //Check if GuestDocument is used in a Stay.
bool isUsed = await stayEntityService.IsGuestInStay(id);
if (isUsed)
{ {
logger.LogWarning("GuestDocumentService - DeleteDocument: Error deleting GuestDocument. Entity not found with key: '{key}-{key2}'", docType, docNum); 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); return Result.Fail(ResultCode.NotFound);
} }
try logger.LogInformation(
{ "GuestDocumentService - DeleteDocument: GuestDocument deleted with Id: '{id}'. Versions deleted: '{Count}'",
dbContext.GuestDocuments.Remove(dbItem); id, deletedCount);
await dbContext.SaveChangesAsync();
logger.LogInformation("GuestDocumentService - DeleteDocument: GuestDocument deleted: '{id}'", dbItem.GetFullKey());
return Result.Ok(); return Result.Ok();
} }
catch (Exception ex) 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(); return Result.FailUnknownError();
} }
} }
public async Task<GuestDocumentDTO?> GetLastVersionDtoByIdAsync(long id)
public async Task<GuestDocumentDTO?> GetDtoByIdAsync(string docType, string docNum)
{ {
using var dbContext = contextFactory.CreateDbContext(); 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; 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(); using var dbContext = contextFactory.CreateDbContext();
var dbList = await dbContext.GuestDocuments GuestDocument? dbItem = await dbContext.GuestDocuments
.OrderByDescending(e => e.UpdateTime) .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(); .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); return dbList.Select(GetDtoFromDb);
} }
@@ -154,8 +196,21 @@ public class GuestDocumentEntityService(
query = query.WhereIf(!string.IsNullOrEmpty(filter.Surname), query = query.WhereIf(!string.IsNullOrEmpty(filter.Surname),
e => EF.Functions.Like(e.Surname, 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); 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) if (limit > 0)
{ {
query = query.Take(limit); query = query.Take(limit);
@@ -6,11 +6,23 @@ public interface IGuestDocumentEntityService
{ {
public Task<Result> CreateDocumentAsync(GuestDocumentDTO dto); public Task<Result> CreateDocumentAsync(GuestDocumentDTO dto);
public Task<Result> UpdateDocumentAsync(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); /// <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); public Task<IEnumerable<GuestDocumentDTO>> GetDtoListByFilterAsync(GuestDocFilterDTO filter, int limit = 0);
public Task<IEnumerable<GuestDocumentDTO>> GetDtoListAsync();
} }
@@ -15,7 +15,8 @@ public interface IStayEntryEntityService
public Task<IEnumerable<StayEntryDTO>> GetDtoListByFilterAsync(StayEntryFilterDTO filter, int limit = 0, StayEntryQueryConfig? queryConfig = null); 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<bool> IsGuestInStay(long guestDocId);
public Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(string docType, string docNum, StayEntryQueryConfig? queryConfig = null); public Task<bool> IsGuestInStayInPeriod(long guestDocId, DateTime startTime, DateTime endTime);
public Task<IEnumerable<StayEntryDTO>> GetStaysWithGuest(long guestDocId, StayEntryQueryConfig? queryConfig = null);
} }
@@ -46,12 +46,13 @@ public class StayEntryEntityService(
//Check and add GuestDocuments //Check and add GuestDocuments
foreach (GuestDocumentDTO guestDto in dto.GuestDocuments!) foreach (GuestDocumentDTO guestDto in dto.GuestDocuments!)
{ {
//Get it from db. //Get guest from db.
GuestDocument? dbGuest = await dbContext.GuestDocuments.FindAsync(guestDto.DocumentType, guestDto.DocumentNum) GuestDocument dbGuest = await dbContext.GuestDocuments
?? throw new InvalidOperationException($"GuestDocument not found! Id: '{guestDto.FullKey}'"); .Where(gd => gd.Id == guestDto.Id && gd.Version == guestDto.Version)
.SingleAsync();
//Check if Guest is already in other stay during the same period. //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) if (isInOtherStay)
{ {
string period = $"{dbStay.DateIn}-{dbStay.DateOut}"; string period = $"{dbStay.DateIn}-{dbStay.DateOut}";
@@ -168,24 +169,34 @@ public class StayEntryEntityService(
} }
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(); using var dbContext = contextFactory.CreateDbContext();
bool rs = await dbContext.StayEntries bool rs = await dbContext.StayEntries
.AnyAsync(s => s.DateIn < endTime && s.DateOut > startTime .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; 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(); using var dbContext = contextFactory.CreateDbContext();
var rs = await dbContext.StayEntries 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) .AddQueryConfig(queryConfig)
.OrderByDescending(e => e.DateIn) .OrderByDescending(e => e.DateIn)
.ToListAsync(); .ToListAsync();